使用python代码对梯度下降算法实现线性回归
时间: 2024-01-31 14:02:10 浏览: 35
好的,以下是使用Python代码对梯度下降算法实现线性回归的示例:
首先,我们需要导入所需的包:
```python
import numpy as np
import matplotlib.pyplot as plt
```
然后,我们定义一个函数来计算误差,即损失函数:
```python
def compute_cost(X, y, theta):
m = len(y)
predictions = X.dot(theta)
square_err = (predictions - y) ** 2
J = 1 / (2 * m) * np.sum(square_err)
return J
```
其中,X是一个m行n列的特征矩阵,y是一个m行1列的目标向量,theta是一个n行1列的参数向量,m是样本数量,n是特征数量。
接下来,我们定义一个函数来执行梯度下降算法:
```python
def gradient_descent(X, y, theta, alpha, num_iters):
m = len(y)
J_history = np.zeros((num_iters, 1))
for i in range(num_iters):
predictions = X.dot(theta)
errors = np.subtract(predictions, y)
delta = (alpha / m) * X.transpose().dot(errors)
theta = theta - delta
J_history[i] = compute_cost(X, y, theta)
return theta, J_history
```
其中,alpha是学习率,num_iters是迭代次数,J_history记录了每次迭代后的损失函数值。
最后,我们可以使用上述函数来拟合一个简单的线性模型:
```python
# 生成随机数据
np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)
# 对特征矩阵X添加一列全为1的向量,以便于计算截距
X_b = np.c_[np.ones((100, 1)), X]
# 初始化参数向量theta
theta = np.random.randn(2, 1)
# 执行梯度下降算法
alpha = 0.1
num_iters = 1000
theta, J_history = gradient_descent(X_b, y, theta, alpha, num_iters)
# 绘制拟合直线
plt.scatter(X, y)
plt.plot(X, X_b.dot(theta), 'r')
plt.show()
```
这里我们生成了一个简单的一维数据集,然后对其进行线性回归拟合并绘制出拟合直线。
完整代码如下: