简单线性回归(最小二乘法)
0.引入依赖
import numpy as np
import matplotlib.pyplot as plt
1.导入数据(data.txt)
points = np.genfromtxt("data.txt",delimiter=",")
#points
#提取points中的两列数据,分别作为x,y
x=points[:,0]
y=points[:,1]
#x y
#用plt画出散点图
plt.scatter(x,y)
plt.show()
2.定义损失函数
def compute_costs(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
3.定义算法拟合函数 y = w * x + b
##定义一个求均值的函数
def average(data):