sklearn是python的一个包,也是机器学习中常用的一个模块,里面封装了很多机器学习的算法,不需要对机器学习算法的实现,只需要简单地调用sklearn里相对应的模块即可。
波士顿房价数据是sklearn里经典的回归数据集。使用sklearn linear_regression 模型拟合boston房价datasets。并使用pyplot画出预测价格和真实价格的对比图。
from sklearn import datasets
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
##1 数据的加载,使用数据集进行线性回归(这里是波士顿房价数据)
loaded_data = datasets.load_boston()
data_X = loaded_data.data
data_y = loaded_data.target
print('-------data description of this dataset: ', loaded_data.DESCR)
##2 模型的加载
model = LinearRegression()
##3 模型的训练
model.fit(data_X, data_y)
#前四个预测值
print('prediction: ',model.predict(data_X[:4]))
y_pred=model.predict(data_X)
#前四个真实值
print('reality: ',data_y[:4])
'''----------图形化预测结果-----------'''
#只显示前50个预测结果,太多的话看起来不直观
plt.xlim([0,50])
plt.plot( range(len(data_y)), data_y, 'r', label='y_reality')
plt.plot( range(len(y_pred)), y_pred, 'g--', label='y_predict')
plt.title('sklearn: Linear Regression')
plt.legend()
plt.title('house price prediction')
plt.show()
备注:
再找实例和数据集的时候,读取csv数据的时候,遇到一个转义符问题,例如C:\Users\...里\u被当做unicode编码相关而报错...建议python在描述路径时,采取下面几种方式:
方式一:转义的方式
'd:\\a.txt'
方式二:显式声明字符串不用转义
'd:r\a.txt'
方式三:使用Linux的路径/
'd:/a.txt'
推荐第三种写法,这在Linux和window下都是行的通的。
reference:
1.Scikit-learn快速入门教程和实例(一) https://blog.youkuaiyun.com/linxid/article/details/79104130
2.scikit-learn linear regression reference: https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html
3. https://dataconomy.com/2015/02/linear-regression-implementation-in-python/