使用一个线性回归模型来拟合身高-体重的数据

1、创建数据集

#引用sklearn库,为了使用其中的线性回归模块
from sklearn.linear_model import LinearRegression
#引用numpy库,做科学计算
import numpy as np  
#引用matplotlib库,用来画图
import matplotlib.pyplot as plt

#创建数据集,把数据写入到numpy数组
data = np.array([[152,51],[156,53],[160,54],[164,55],
		[168,57],[172,60],[176,62],[180,65],
		[184,69],[188,72]])
#打印出数组的大小
print(data.shape)

2、对数据进行变形
由于在调用的sklearn里封装好的一些模型来建模时,对训练数据的输入x要求是二维数组,所以需要对数据进行变形。如下所示:

x,y = data[:,0].reshape(-1,1),data[:,1]

reshape(行数,列数)常用来更改数据的行列数目
-1是指未设定行数,程序随机分配
reshape(-1,1)表示(任意行,1列)
相当于:

x = data[:,0].reshape(-1,1)
y = data[:,1]

3、利用线性回归来拟合数据

#实例化一个线性回归的模型
regr = LinearRegression().fit(x,y) # fit() 用来分析模型参数
#在x,y上训练一个线性回归模型。若训练顺利,则regr会存储训练完成后的结果模型
regr.score(x,y)

4、画出身高与体重之间的关系

# 画出已训练好的线条
plt.plot(x, regr.predict(x), color='blue')
#画x,y轴的标题
plt.xlabel('height (cm)')
plt.ylabel('weight (kg)')
plt.show() # 展示

5、预测体重
利用训练好的模型输入身高去预测体重

height = int(input("Input your height>>>"))
print ("Standard weight for person with %d is %.2f"%(height, regr.predict([[height]])))

贪心学院机器学习课程笔记

你可能感兴趣的:(机器学习,机器学习,python)