python回归输出函数 python 回归( 四 )


如何解释各个特征对应的系数的意义?
对于给定了Radio和Newspaper的广告投入,如果在TV广告上每多投入1个单位 , 对应销量将增加0.0466个单位 。就是加入其它两个媒体投入固定,在TV广告上每增加1000美元(因为单位是1000美元) , 销量将增加46.6(因为单位是1000) 。但是大家注意这里的newspaper的系数居然是负数,所以我们可以考虑不使用newspaper这个特征 。这是后话,后面会提到的 。
(4)、预测
[python] view plain copy
y_pred = linreg.predict(X_test)
print y_pred
[python] view plain copy
print type(y_pred)
输出结果如下:
[ 14.586783737.9239799916.949799319.357910387.36360284
7.3535926916.083423259.1653304620.3550737412.63160058
22.833564729.662914614.1805560313.7036858411.4533557
4.1694056510.3127141323.0678686817.8046456514.53070132
15.1965668414.229696097.5469116713.4721032415.00625898
19.2853244420.731987819.7040883318.216408538.50112687
9.84937819.514257639.7327004318.1378201515.41731544
5.0741678712.2057525114.0550749310.66999267.16006245
11.8072883624.7974812110.4080916824.0522840418.44737314
20.805726319.4542480517.004817085.786341055.10594849]
type 'numpy.ndarray'
5、回归问题的评价测度
(1) 评价测度
对于分类问题,评价测度是准确率 , 但这种方法不适用于回归问题 。我们使用针对连续数值的评价测度(evaluation metrics) 。
这里介绍3种常用的针对线性回归的测度 。
1)平均绝对误差(Mean Absolute Error, MAE)
(2)均方误差(Mean Squared Error, MSE)
(3)均方根误差(Root Mean Squared Error, RMSE)
这里我使用RMES 。
[python] view plain copy
pre name="code" class="python"#计算Sales预测的RMSE
print type(y_pred),type(y_test)
print len(y_pred),len(y_test)
print y_pred.shape,y_test.shape
from sklearn import metrics
import numpy as np
sum_mean=0
for i in range(len(y_pred)):
sum_mean+=(y_pred[i]-y_test.values[i])**2
sum_erro=np.sqrt(sum_mean/50)
# calculate RMSE by hand
print "RMSE by hand:",sum_erro
最后的结果如下:
type 'numpy.ndarray' class 'pandas.core.series.Series'
50 50
(50,) (50,)
RMSE by hand: 1.42998147691
(2)做ROC曲线
[python] view plain copy
import matplotlib.pyplot as plt
plt.figure()
plt.plot(range(len(y_pred)),y_pred,'b',label="predict")
plt.plot(range(len(y_pred)),y_test,'r',label="test")
plt.legend(loc="upper right") #显示图中的标签
plt.xlabel("the number of sales")
plt.ylabel('value of sales')
plt.show()
显示结果如下:(红色的线是真实的值曲线 , 蓝色的是预测值曲线)
直到这里整个的一次多元线性回归的预测就结束了 。
6、改进特征的选择
在之前展示的数据中,我们看到Newspaper和销量之间的线性关系竟是负关系(不用惊讶,这是随机特征抽样的结果 。换一批抽样的数据就可能为正了),现在我们移除这个特征,看看线性回归预测的结果的RMSE如何?
依然使用我上面的代码,但只需修改下面代码中的一句即可:
[python] view plain copy
#create a python list of feature names
feature_cols = ['TV', 'Radio', 'Newspaper']
# use the list to select a subset of the original DataFrame
X = data[feature_cols]
# equivalent command to do this in one line
#X = data[['TV', 'Radio', 'Newspaper']]#只需修改这里即可pre name="code" class="python" style="font-size: 15px; line-height: 35px;"X = data[['TV', 'Radio']]#去掉newspaper其他的代码不变
# print the first 5 rowsprint X.head()# check the type and shape of Xprint type(X)print X.shape

推荐阅读