用python语言使用批量梯度下降算法拟合直线。待拟合的二维平面数据点:(1, 3), (2, 6.2), (4, 12.1),(10,29.9),(16,47.7),并展示代码。
时间: 2023-02-25 11:56:30 浏览: 84
使用Python语言实现批量梯度下降算法拟合给定的二维平面数据点:(1, 3), (2, 6.2), (4, 12.1),(10,29.9),(16,47.7),下面是代码:import numpy as np
# 设置学习率
lr = 0.1
# 初始化参数
b = 0
w = 0
# 迭代次数
epochs = 50
# 数据
x_data = np.array([1, 2, 4, 10, 16])
y_data = np.array([3, 6.2, 12.1, 29.9, 47.7])
# 计算损失函数
def compute_cost(x, y, b, w):
total_cost = 0
m = len(x)
for i in range(m):
total_cost += (y[i] - (w * x[i] + b)) ** 2
return total_cost / m# 批量梯度下降更新参数
for epoch in range(epochs):
# 计算梯度
b_grad = 0.0
w_grad = 0.0
m = len(x_data)
for i in range(m):
b_grad = b_grad - 2.0 * (y_data[i] - (w * x_data[i] + b)) * 1.0
w_grad = w_grad - 2.0 * (y_data[i] - (w * x_data[i] + b)) * x_data[i]
# 更新参数
b = b - lr * b_grad
w = w - lr * w_grad
# 计算损失
loss = compute_cost(x_data, y_data, b, w)
print("epoch={}, loss={}, w={}, b={}".format(epoch, loss, w, b))# 拟合直线
x = np.linspace(0, 17, 100)
y = w * x + b
# 画图
plt.plot(x_data, y_data, 'bo')
plt.plot(x, y, 'r-')
plt.show()
阅读全文