import numpy as np
import matplotlib.pyplot as plt
##导入数据
points = np.genfromtxt('data.csv',delimiter=',')
## points 二维数组
##[[ 32.50234527, 31.70700585],
##[ 53.42680403, 68.77759598]]
## 提取points 中的两列数据,分别作为x,y
x=points[:,0]##第一列
y=points[:,1]##第二列
print(x)
print(y)
## 用plt画出散点图
plt.scatter(x,y)
plt.show()
#损失函数是系数的函数,另外还要传入数据的x,y
def compute_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
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
x_new =x.reshape(-1,1) # reshape改变形状 -1 表示行数不限制 1 表示列数
y_new =y.reshape(-1,1)
lr.fit(x_new,y_new) #做拟合 传入的参数需要是二维的举证 python机器学习库的线性回归用的是最小二乘法
w = lr.coef_[0][0] #拿出系数
b = lr.intercept_[0] #拿出截距 常数项
print("w is :",w)
print("b is :",b)
cost = compute_cost(w,b,points)
print("cost is ",cost)
## 图形展示
plt.scatter(x,y) ##散点图
# 针对每一个x,计算出预测的y值
pred_y = w * x + b
plt.plot(x,pred_y,c='r') ##点图
plt.show()