能写一段线性回归的python代码吗
时间: 2023-02-23 10:47:30 浏览: 118
当然可以!以下是简单的线性回归代码,使用了numpy和matplotlib库:
```python
import numpy as np
import matplotlib.pyplot as plt
# 训练数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([1, 2, 3, 4, 5])
# 假设函数的参数初始化
theta0 = 0
theta1 = 0
# 学习率
alpha = 0.01
# 迭代次数
epochs = 100
# 定义代价函数
def compute_cost(x, y, theta0, theta1):
m = x.shape[0]
J = 0
for i in range(m):
h = theta0 + theta1 * x[i]
J += (h - y[i]) ** 2
J = J / (2 * m)
return J
# 梯度下降算法
for i in range(epochs):
sum0 = 0
sum1 = 0
m = x.shape[0]
for j in range(m):
h = theta0 + theta1 * x[j]
sum0 += h - y[j]
sum1 += (h - y[j]) * x[j]
theta0 = theta0 - alpha * sum0 / m
theta1 = theta1 - alpha * sum1 / m
cost = compute_cost(x, y, theta0, theta1)
print("epoch: {0}, theta0: {1:.2f}, theta1: {2:.2f}, cost: {3:.2f}".format(i, theta0, theta1, cost))
# 绘制回归曲线
plt.plot(x, y, 'ro', label='Original data')
plt.plot(x, theta0 + theta1 * x, label='Fitted line')
plt.legend()
plt.show()
```
这是一个简单的线性回归例子,输出结果是回归曲线。代码实现了梯度下降算法,求解线性回归模型的参数。
阅读全文