python 线性回归代码
时间: 2023-10-15 18:19:57 浏览: 30
以下是使用Python实现的线性回归代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成数据
np.random.seed(0)
X = np.random.rand(100, 1)
y = 2 + 3 * X + np.random.rand(100, 1)
# 绘制数据点
plt.scatter(X, y, s=10)
plt.xlabel('X')
plt.ylabel('y')
plt.show()
# 线性回归模型
class LinearRegression:
def __init__(self, learning_rate=0.01, iterations=1000):
self.learning_rate = learning_rate
self.iterations = iterations
def fit(self, X, y):
# 初始化参数
self.theta = np.zeros((X.shape[1], 1))
self.bias = 0
self.costs = []
# 梯度下降更新参数
for i in range(self.iterations):
y_pred = np.dot(X, self.theta) + self.bias
error = y_pred - y
cost = np.mean(error ** 2)
self.costs.append(cost)
self.theta -= self.learning_rate * np.dot(X.T, error) / X.shape[0]
self.bias -= self.learning_rate * np.mean(error)
def predict(self, X):
return np.dot(X, self.theta) + self.bias
# 训练模型
model = LinearRegression()
model.fit(X, y)
# 绘制拟合直线
plt.scatter(X, y, s=10)
plt.plot(X, model.predict(X), color='r')
plt.xlabel('X')
plt.ylabel('y')
plt.show()
```
这个示例代码中,我们使用了Numpy和Matplotlib库来生成数据、绘制图形和实现线性回归模型。首先,我们生成了100个数据点,然后使用LinearRegression类来拟合线性回归模型。在fit方法中,我们使用梯度下降算法来更新模型参数,并在每次迭代中计算损失函数的值。在predict方法中,我们使用训练好的模型来预测新的数据点。最后,我们绘制了原始数据点和拟合直线的图形。