Код: Выделить всё
#include <iostream>
#include <vector>
class LinearRegression {
public:
LinearRegression(float learningRate, int iterations)
: learningRate(learningRate), iterations(iterations), weight(0), bias(0) { }
void train(const std::vector<float>& x, const std::vector<float>& y) {
int n = x.size();
for (int i = 0; i < iterations; ++i) {
float weightGradient = 0;
float biasGradient = 0;
// Обновляем градиенты
for (int j = 0; j < n; ++j) {
float prediction = predict(x[j]);
weightGradient += (prediction - y[j]) * x[j];
biasGradient += (prediction - y[j]);
}
// Обновляем веса
weight -= (weightGradient / n) * learningRate;
bias -= (biasGradient / n) * learningRate;
}
}
float predict(float x) {
return weight * x + bias;
}
private:
float learningRate;
int iterations;
float weight;
float bias;
};
int main() {
std::vector<float> x = {1, 2, 3, 4, 5}; // Примеры входных данных
std::vector<float> y = {2, 3, 4, 5, 6}; // Соответствующие выходные данные
LinearRegression model(0.01, 1000);
model.train(x, y);
// Предсказание
float testInput = 6;
std::cout << "Предсказание для " << testInput << ": " << model.predict(testInput) << std::endl;
return 0;
}