编写程序实现线性回归模型要求模型中拥有五个特征值
时间: 2024-05-08 19:02:29 浏览: 11
以下是一种实现线性回归模型的 Python 代码,其中使用了五个特征值:
```python
import numpy as np
# 生成数据集
np.random.seed(0)
X = np.random.rand(100, 5)
y = np.dot(X, [2, 3, 4, 5, 6]) + np.random.randn(100)
# 定义线性回归模型
class LinearRegression:
def __init__(self, lr=0.01, n_iters=1000):
self.lr = lr
self.n_iters = n_iters
self.weights = None
self.bias = None
def fit(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
# 梯度下降求解模型参数
for i in range(self.n_iters):
y_pred = np.dot(X, self.weights) + self.bias
dw = (1/n_samples) * np.dot(X.T, (y_pred - y))
db = (1/n_samples) * np.sum(y_pred - y)
self.weights -= self.lr * dw
self.bias -= self.lr * db
def predict(self, X):
return np.dot(X, self.weights) + self.bias
# 训练模型并预测结果
model = LinearRegression()
model.fit(X, y)
y_pred = model.predict(X)
# 输出模型参数和损失值
print('Weights:', model.weights)
print('Bias:', model.bias)
print('MSE:', np.mean((y_pred - y)**2))
```
在这个例子中,我们生成了一个包含 100 个样本、每个样本有 5 个特征值的数据集。然后我们定义了一个名为 `LinearRegression` 的类来实现线性回归模型。在 `fit` 方法中使用了梯度下降算法来求解模型的参数,最终得到模型的权重和偏差。在训练完成后,我们使用 `predict` 方法对数据集进行预测,并计算了预测结果与真实值之间的均方误差(MSE)作为模型的损失值。