import matplotlib.pyplot as plt
import pandas as pd #数据来源 http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv data=pd.read_csv('./Advertising.csv') print(data.head())
In [3]:
x=data[['TV','Radio','Newspaper']] y=data['Sales']
In [4]:
# 绘制1
plt.plot(data['TV'], y, 'ro', label='TV') plt.plot(data['Radio'], y, 'g^', label='Radio') plt.plot(data['Newspaper'], y, 'b*', label='Newspaer') # plt.legend(loc='lower right') plt.grid() plt.show()
In [5]:
plt.figure(figsize=(9,12)) plt.subplot(311) plt.plot(data['TV'], y, 'ro') plt.title('TV') plt.grid() plt.subplot(312) plt.plot(data['Radio'], y, 'g^') plt.title('Radio') plt.grid() plt.subplot(313) plt.plot(data['Newspaper'], y, 'b*') plt.title('Newspaper') plt.grid() plt.tight_layout() plt.show()
In [6]:
#构建特征向量
feature_cols = ['TV', 'Radio', 'Newspaper'] #特征向量数据 X=data[feature_cols] #目标结果 y = data['Sales']
In [8]:
#训练集 与 测试集
from sklearn.cross_validation import train_test_split
X_train,X_test, y_train, y_test = train_test_split(X, y, random_state=1) print X_train.shape,X_test.shape,y_train.shape,y_test.shape
In [9]:
#根据图目测貌似有线性相关性
from sklearn.linear_model import LinearRegression
linereg=LinearRegression() model=linereg.fit(X_train,y_train)
In [10]:
print model
In [11]:
linereg.intercept_
Out[11]:
In [12]:
linereg.coef_
Out[12]:
In [13]:
zip(feature_cols,linereg.coef_)
Out[13]:
In [14]:
y_predict=linereg.predict(X_test)
In [16]:
y_predict
Out[16]:
In [18]:
y_test
Out[18]:
In [19]:
for i in range(len(y_predict)): sum_mean+=(y_predict[i]-y_test.values[i])**2
In [20]:
sum_mean
Out[20]:
In [22]:
np.sqrt(sum_mean/len(y_predict))
Out[22]:
In [24]:
plt.plot(range(len(y_predict)),y_predict,'b',label="predict") plt.plot(range(len(y_predict)),y_test,'r',label="test")
Out[24]:
In [25]:
plt.legend(loc="upper right") plt.xlabel("the number of sales") plt.ylabel('value of sales') plt.show()
In [26]:
#根据目测Newspaper 与sales的多少并没有什么联系同时最后的参数('Newspaper', 0.0034504647111804204)] 也是及其小
#因此可以尝试移除Newspaper这个特征值
In [27]:
x=data[['TV','Radio']]
In [28]:
X_train,X_test, y_train, y_test = train_test_split(x, y, random_state=1)
In [29]:
linereg=LinearRegression()
model=linereg.fit(X_train,y_train)
In [30]:
model.intercept_
Out[30]:
In [31]:
model.coef_
Out[31]:
In [34]:
y_predict=linereg.predict(X_test)
In [35]:
y_predict
Out[35]:
In [36]:
sum_mean=0
for i in range(len(y_predict)): sum_mean+=(y_predict[i]-y_test.values[i])**2
In [37]:
np.sqrt(sum_mean/len(y_predict))
Out[37]:
In [38]:
RMES=np.sqrt(sum_mean/len(y_predict))
In [39]:
#RMES:均方根误差(Root Mean Squared Error, RMSE) 越小越接近
plt.plot(range(len(y_predict)),y_predict,'b',label="predict") plt.plot(range(len(y_predict)),y_test,'r',label="test") plt.legend(loc="upper right") plt.xlabel("the number of sales") plt.ylabel('value of sales') plt.show()
In [ ]:
#总结
'''
我们在将 Newspaper 这个特征移除之后,得到 RMSE 变小了,
说明 Newspaper 特征可能不适合作为预测销量的特征,于是,我们得到了新的模型。
我们还可以通过不同的特
征组合得到新的模型,看看最终的误差是如何的。 在机器学习中有“奥卡姆剃刀”的原理,即:如果能够用简单模型解决问题, 则不使用更为复杂的模型。 因为复杂模型往往增加了不确定性,造成过多的人力 和物力成本,且容易过拟合。 '''