01_有监督学习--简单线性回归模型(最小二乘法代码实现)
有监督学习–简单线性回归模型(最小二乘法代码实现)
0.引入依赖
import numpy as np
import matplotlib.pyplot as plt
1.导入数据(data.csv)
points = np.genfromtxt('data.csv', delimiter=',')
# points
# 提取 points 中的两对数据,分别作为 x, y
# points[0][0] 等价于
# points[0,0] # 第一行第一列数据
# points[0,0:1] # array([32.50234527])
# points[0,0:2] # 第一行数据 array([32.50234527, 31.70700585])
# points[0,0:] # 第一行数据 array([32.50234527, 31.70700585])
x = points[:,0] # 第一列数据
y = points[:,1] # 第二列数据
# 用 scatter 画出散点图
plt.scatter(x, y)
plt.show()
# 10/3 # 3.3333333333333333
# 10//3 # 3 向下取整(地板除)
作图如下:
[外链图片转存失败(img-veReoaSa-1569159842226)(https://s2.ax1x.com/2019/05/18/ELjCGT.png)]
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]
total_cost += (y - w * x - b) ** 2
return total_cost / M
3.定义模型拟合函数
# 先定义一个求均值的函数
def average(data):
sum = 0
num = len(data)
for i in range(num):
sum += data