推导过程:
代码实现(以一元为例):
# 简单线性回归(梯度下降法)
# 0. 引入依赖
import numpy as np
import matplotlib.pyplot as plt
# 1. 导入数据(data.csv)
points = np.genfromtxt('D:\学习资料\推荐系统\代码\练习代码\自己手打\data.csv', delimiter = ',')
points[0, 0]
# 提取points中的两列数据,分别作为x,y
x = points[:, 0]
y = points[:, 1]
# 用plt画出散点图
plt.scatter(x, y)
plt.show()
# 2. 定义损失函数
# 损失函数是系数的函数,另外还要传入数据的x,y
def compute_cost(w, b, points):
total_cost = 0
M = len(points)
# 逐点计算平方损失误差, 然后求平均数
for i in range(M):
x =