赞
踩
本项目利用boston房价数据集联系简单的线性回归,若预测效果不够理想,可进一步进行非线性回归尝试。
- # -*- coding: utf-8 -*-
- from sklearn import datasets
- import matplotlib.pyplot as plt
- import numpy as np
- import pandas as pd
- from sklearn import linear_model
- import warnings
- warnings.filterwarnings('ignore')
- boston=datasets.load_boston()
- x=boston.data
- y=boston.target
- print(x.shape)
- print(boston.DESCR)
-
-
- '''
- #练习
- clf = linear_model.LinearRegression()
- x=np.array([2,3,5,7,6]).reshape(-1,1)
- y=np.array([6,10,14.5,21,18.5])
- print(plt.scatter(x,y,color='blue'))
- clf.fit(x,y) #训练模型
- b,a=clf.coef_, clf.intercept_
- print(b,a)
- x=[[4]]
- print(clf.predict(x))
- print(plt.plot(x, a+b*x, color = 'red'))
- '''
- #波士顿房价
- x=pd.DataFrame(boston.data, columns=boston.feature_names)
- y=pd.DataFrame(boston.target,columns=['MEDV'])
- print(plt.scatter(x['RM'],y,color='blue'))
- print(plt.scatter(x['LSTAT'],y,color='blue'))
-
- import statsmodels.api as sm
- #statsmodels中线性回归模型没有截距项,下行给训练集加上一列数值为1的特征
- x_add1=sm.add_constant(x)
- model=sm.OLS(y,x_add1).fit()
- print(model.summary())
- '''
- #输出结果
- coef std err t P>|t| [0.025 0.975]
- ------------------------------------------------------------------------------
- const 36.4595 5.103 7.144 0.000 26.432 46.487
- CRIM -0.1080 0.033 -3.287 0.001 -0.173 -0.043
- ZN 0.0464 0.014

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。