多元 Huber Regression C++ 带类实现及案例
时间: 2024-03-16 20:46:09 浏览: 101
实现一个C++类
以下是一个简单的多元 Huber Regression C++ 类的实现及其使用示例:
```c++
#include <iostream>
#include <vector>
#include <cmath>
class HuberRegression {
public:
HuberRegression(double alpha = 1.0, int max_iter = 1000, double tol = 1e-6) :
alpha(alpha), max_iter(max_iter), tol(tol) {}
void fit(std::vector<std::vector<double>> X, std::vector<double> y) {
// 初始化参数
int n_samples = X.size();
int n_features = X[0].size();
std::vector<double> w(n_features, 0.0);
double b = 0.0;
// 迭代优化
for (int iter = 0; iter < max_iter; iter++) {
std::vector<double> w_new(n_features, 0.0);
double b_new = 0.0;
double loss = 0.0;
// 更新参数
for (int i = 0; i < n_samples; i++) {
double y_pred = 0.0;
for (int j = 0; j < n_features; j++) {
y_pred += X[i][j] * w[j];
}
y_pred += b;
double error = y[i] - y_pred;
double abs_error = std::abs(error);
if (abs_error <= alpha) {
loss += 0.5 * error * error;
for (int j = 0; j < n_features; j++) {
w_new[j] += X[i][j] * error;
}
b_new += error;
} else {
loss += alpha * (abs_error - 0.5 * alpha);
for (int j = 0; j < n_features; j++) {
w_new[j] += X[i][j] * alpha * error / abs_error;
}
b_new += alpha * error / abs_error;
}
}
// 判断是否收敛
bool is_converged = true;
for (int j = 0; j < n_features; j++) {
if (std::abs(w_new[j] - w[j]) > tol) {
is_converged = false;
break;
}
}
if (std::abs(b_new - b) > tol) {
is_converged = false;
}
if (is_converged) {
break;
}
// 更新参数
w = w_new;
b = b_new;
}
// 保存参数
this->w = w;
this->b = b;
}
double predict(std::vector<double> x) {
double y_pred = 0.0;
for (int j = 0; j < x.size(); j++) {
y_pred += x[j] * w[j];
}
y_pred += b;
return y_pred;
}
private:
double alpha;
int max_iter;
double tol;
std::vector<double> w;
double b;
};
int main() {
// 构造数据
std::vector<std::vector<double>> X = {
{1.0, 1.0},
{2.0, 2.0},
{3.0, 3.0},
{4.0, 4.0},
{5.0, 5.0},
{6.0, 6.0},
{7.0, 7.0},
{8.0, 8.0},
{9.0, 9.0},
{10.0, 10.0}
};
std::vector<double> y = {
2.0,
4.0,
6.0,
8.0,
10.0,
12.0,
14.0,
16.0,
18.0,
20.0
};
// 训练模型
HuberRegression model(1.0, 1000, 1e-6);
model.fit(X, y);
// 预测数据
std::vector<double> x = {5.0, 5.0};
double y_pred = model.predict(x);
std::cout << "Prediction: " << y_pred << std::endl;
return 0;
}
```
在上面的示例中,我们首先定义了一个 `HuberRegression` 类,它包含了 Huber Regression 的参数和方法。在 `fit` 方法中,我们使用迭代优化算法来训练模型。在每次迭代中,我们计算损失函数并更新参数,直到算法收敛或达到最大迭代次数。在 `predict` 方法中,我们使用训练好的模型来预测新数据。
在 `main` 函数中,我们首先构造了一些简单的数据,然后使用 `HuberRegression` 类来训练模型并进行预测。
阅读全文