数据源:https://pan.baidu.com/s/1Y7py5uSZ03SbNtL3dTKBkg
代码块:
# 简单线性回归(最小二乘法)
import numpy as np
import matplotlib.pyplot as plt
# 点
points = np.genfromtxt(r'data/data.csv',delimiter=',')
# 提取points中的两列数据分别作为X,Y
x = points[:,0]
y = points[:,1]
# 用plt画出散点图
plt.scatter(x,y)
# 显示图像
plt.show()
# 定义损失函数
# 损失函数:是系数的函数,另外还要传入数据x,y
def computer_cost(w,b,points):
total_cost = 0
M = len(points)
# 逐点计算平方损失误差,然后求平均数
for i in range(M):
x = points[i,0]
y = points[i,1]
total_cost += (y - w * x - b) ** 2
return total_cost/M
# 定义算法拟合函数
# 先定义一个求均值的函数
def average(data):
sum = 0
M = len(data)
for i in range(M):
sum += data[i]
return sum/M
# 定义核心拟合函数
def fit(poin