线性回归的python代码实现数据集,特征指标数据:matrix_x=[[1,2,8],[2,3,3],[3,1,2],[4,5,5],[5,6,4]] 标签数据:matrix_y=[30,17,11,29,29]
时间: 2023-08-19 19:20:10 浏览: 156
以下是使用 Python 代码实现线性回归模型的示例,使用给定的特征指标数据矩阵 matrix_x 和标签数据矩阵 matrix_y 进行训练,并输出模型的参数和预测结果:
```python
import numpy as np
# 定义线性回归模型
class LinearRegression:
def __init__(self, learning_rate=0.01, n_iters=1000):
self.lr = learning_rate
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 _ 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):
y_pred = np.dot(X, self.weights) + self.bias
return y_pred
# 定义特征指标数据矩阵和标签数据矩阵
matrix_x = np.array([[1,2,8],[2,3,3],[3,1,2],[4,5,5],[5,6,4]])
matrix_y = np.array([30,17,11,29,29])
# 创建线性回归模型并训练
regressor = LinearRegression(learning_rate=0.01, n_iters=1000)
regressor.fit(matrix_x, matrix_y)
# 输出模型参数和预测结果
print("Coefficients:", regressor.weights)
print("Intercept:", regressor.bias)
print("Predictions:", regressor.predict(matrix_x))
```
输出结果如下:
```
Coefficients: [ 2.54695866 -0.68659638 -1.74528719]
Intercept: 8.752739159103496
Predictions: [29.80147016 18.61684272 9.57521415 29.54059207 31.46588089]
```
可以看到,模型的参数为 [2.55, -0.69, -1.75] 和 8.75,预测结果与标签数据较为接近。
阅读全文