简单线性回归模型(最小二乘法代码实现)
0.引入依赖
import numpy as np
import matplotlib.pyplot as plt
1.导入数据(data.csv)
points...# points[0,0:] # 第一行数据 array([32.50234527, 31.70700585])
x = points[:,0] # 第一列数据
y = points[:,1] # 第二列数据...2.定义损失函数
# 损失函数是模型系数的函数,还需要传入数据的 x,y
def compute_cost(w, b, points):
total_cost = 0
M = len(points...)
# 逐点计算【实际数据 yi 与 模型数据 f(xi) 的差值】的平方,然后求平均
for i in range(M):
x = points[i, 0]
... y = points[i, 1]
sum_delta += (y - w * x)
b = sum_delta / M
return w, b
4.测试:运行最小二乘算法