C++ 多变量梯度下降法代码
时间: 2023-09-15 21:23:09 浏览: 140
梯度下降法的C代码实现方法含代码
以下是一个简单的 C++ 多变量梯度下降法的代码示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
double learning_rate = 0.01; // 学习率
int num_iterations = 1000; // 迭代次数
// 计算损失函数
double compute_cost(vector<double>& x, vector<double>& y, double theta0, double theta1) {
double cost = 0.0;
int m = x.size();
for (int i = 0; i < m; i++) {
double h = theta0 + theta1 * x[i];
cost += (h - y[i]) * (h - y[i]);
}
cost /= (2 * m);
return cost;
}
// 梯度下降法更新参数
void gradient_descent(vector<double>& x, vector<double>& y, double& theta0, double& theta1) {
int m = x.size();
double temp0 = 0.0, temp1 = 0.0;
for (int i = 0; i < m; i++) {
double h = theta0 + theta1 * x[i];
temp0 += (h - y[i]);
temp1 += (h - y[i]) * x[i];
}
theta0 -= learning_rate * temp0 / m;
theta1 -= learning_rate * temp1 / m;
}
int main() {
vector<double> x = {1.0, 2.0, 3.0, 4.0, 5.0};
vector<double> y = {2.0, 4.0, 6.0, 8.0, 10.0};
double theta0 = 0.0, theta1 = 0.0;
for (int i = 0; i < num_iterations; i++) {
double cost = compute_cost(x, y, theta0, theta1);
gradient_descent(x, y, theta0, theta1);
cout << "Iteration " << i << ", cost = " << cost << ", theta0 = " << theta0 << ", theta1 = " << theta1 << endl;
}
return 0;
}
```
该示例代码实现了一个简单的线性回归模型,使用梯度下降法来更新模型参数,以最小化损失函数。其中 `x` 和 `y` 分别表示输入和输出数据,`theta0` 和 `theta1` 表示模型参数。在每次迭代中,都会计算当前的损失函数值,并更新模型参数。
阅读全文