熱線電話:13121318867

登錄
首頁精彩閱讀scikit-learn的線性回歸模型
scikit-learn的線性回歸模型
2016-05-05
收藏

scikit-learn的線性回歸模型

特征選擇的方法

作為有監督學習,分類問題是預測類別結果,而回歸問題是預測一個連續的結果。

1. 使用pandas來讀取數據

Pandas是一個用于數據探索、數據處理、數據分析的Python庫

In [1]:
importpandasaspd
In [2]:
# read csv file directly from a URL and save the resultsdata=pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv',index_col=0)# display the first 5 rowsdata.head()
Out[2]:

TV Radio Newspaper Sales
1 230.1 37.8 69.2 22.1
2 44.5 39.3 45.1 10.4
3 17.2 45.9 69.3 9.3
4 151.5 41.3 58.5 18.5
5 180.8 10.8 58.4 12.9

上面顯示的結果類似一個電子表格,這個結構稱為Pandas的數據幀(data frame)。

pandas的兩個主要數據結構:SeriesDataFrame

Series類似于一維數組,它有一組數據以及一組與之相關的數據標簽(即索引)組成。

DataFrame是一個表格型的數據結構,它含有一組有序的列,每列可以是不同的值類型。DataFrame既有行索引也有列索引,它可以被看做由Series組成的字典。

In [3]:
# display the last 5 rowsdata.tail()
Out[3]:

TV Radio Newspaper Sales
196 38.2 3.7 13.8 7.6
197 94.2 4.9 8.1 9.7
198 177.0 9.3 6.4 12.8
199 283.6 42.0 66.2 25.5
200 232.1 8.6 8.7 13.4
In [4]:
# check the shape of the DataFrame(rows, colums)data.shape
Out[4]:
(200, 4)

特征

TV:對于一個給定市場中單一產品,用于電視上的廣告費用(以千為單位)

Radio:在廣播媒體上投資的廣告費用

Newspaper:用于報紙媒體的廣告費用

響應:

Sales:對應產品的銷量

在這個案例中,我們通過不同的廣告投入,預測產品銷量。因為響應變量是一個連續的值,所以這個問題是一個回歸問題。數據集一共有200個觀測值,每一組觀測對應一個市場的情況。

In [5]:
importseabornassns%matplotlibinline
In [6]:
# visualize the relationship between the features and the response using scatterplotssns.pairplot(data,x_vars=['TV','Radio','Newspaper'],y_vars='Sales',size=7,aspect=0.8)
Out[6]:
<seaborn.axisgrid.PairGrid at 0x82dd890>

seaborn的pairplot函數繪制X的每一維度和對應Y的散點圖。通過設置size和aspect參數來調節顯示的大小和比例??梢詮膱D中看出,TV特征和銷量是有比較強的線性關系的,而Radio和Sales線性關系弱一些,Newspaper和Sales線性關系更弱。通過加入一個參數kind=’reg’,seaborn可以添加一條最佳擬合直線和95%的置信帶。

In [7]:
sns.pairplot(data,x_vars=['TV','Radio','Newspaper'],y_vars='Sales',size=7,aspect=0.8,kind='reg')
Out[7]:
<seaborn.axisgrid.PairGrid at 0x83b76f0>

2. 線性回歸模型

優點:快速;沒有調節參數;可輕易解釋;可理解

缺點:相比其他復雜一些的模型,其預測準確率不是太高,因為它假設特征和響應之間存在確定的線性關系,這種假設對于非線性的關系,線性回歸模型顯然不能很好的對這種數據建模。

線性模型表達式: y=β0+β1x1+β2x2+...+βnxn 其中

y是響應

β0是截距

β1是x1的系數,以此類推

在這個案例中: y=β0+β1?TV+β2?Radio+...+βn?Newspaper

(1)使用pandas來構建X和y

scikit-learn要求X是一個特征矩陣,y是一個NumPy向量

pandas構建在NumPy之上

因此,X可以是pandasDataFrame,y可以是pandasSeries,scikit-learn可以理解這種結構

In [8]:
# create a python list of feature namesfeature_cols=['TV','Radio','Newspaper']# use the list to select a subset of the original DataFrameX=data[feature_cols]# equivalent command to do this in one lineX=data[['TV','Radio','Newspaper']]# print the first 5 rowsX.head()
Out[8]:

TV Radio Newspaper
1 230.1 37.8 69.2
2 44.5 39.3 45.1
3 17.2 45.9 69.3
4 151.5 41.3 58.5
5 180.8 10.8 58.4
In [9]:
# check the type and shape of Xprinttype(X)printX.shape
<class 'pandas.core.frame.DataFrame'> (200, 3)
In [10]:
# select a Series from the DataFramey=data['Sales']# equivalent command that works if there are no spaces in the column namey=data.Sales# print the first 5 valuesy.head()
Out[10]:
1 22.1 2 10.4 3 9.3 4 18.5 5 12.9 Name: Sales, dtype: float64
In [11]:
printtype(y)printy.shape
<class 'pandas.core.series.Series'> (200,)

(2)構造訓練集和測試集

In [12]:
fromsklearn.cross_validationimporttrain_test_splitX_train,X_test,y_train,y_test=train_test_split(X,y,random_state=1)
In [14]:
# default split is 75% for training and 25% for testingprintX_train.shapeprinty_train.shapeprintX_test.shapeprinty_test.shape
(150, 3) (150,) (50, 3) (50,)

(3)Scikit-learn的線性回歸

In [15]:
fromsklearn.linear_modelimportLinearRegressionlinreg=LinearRegression()linreg.fit(X_train,y_train)
Out[15]:
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
In [16]:
printlinreg.intercept_printlinreg.coef_
2.87696662232 [ 0.04656457 0.17915812 0.00345046]
In [17]:
# pair the feature names with the coefficientszip(feature_cols,linreg.coef_)
Out[17]:
[('TV', 0.046564567874150253), ('Radio', 0.17915812245088836), ('Newspaper', 0.0034504647111804482)]

y=2.88+0.0466?TV+0.179?Radio+0.00345?Newspaper

如何解釋各個特征對應的系數的意義?

對于給定了Radio和Newspaper的廣告投入,如果在TV廣告上每多投入1個單位,對應銷量將增加0.0466個單位

更明確一點,加入其它兩個媒體投入固定,在TV廣告上沒增加1000美元(因為單位是1000美元),銷量將增加46.6(因為單位是1000)

(4)預測

In [18]:
y_pred=linreg.predict(X_test)

3. 回歸問題的評價測度

對于分類問題,評價測度是準確率,但這種方法不適用于回歸問題。我們使用針對連續數值的評價測度(evaluation metrics)。

下面介紹三種常用的針對回歸問題的評價測度

In [21]:
# define true and predicted response valuestrue=[100,50,30,20]pred=[90,50,50,30]

(1)平均絕對誤差(Mean Absolute Error, MAE)

1n∑ni=1|yi?yi^|

(2)均方誤差(Mean Squared Error, MSE)

1n∑ni=1(yi?yi^)2

(3)均方根誤差(Root Mean Squared Error, RMSE)

1n∑ni=1(yi?yi^)2?????????????√

In [24]:
fromsklearnimportmetricsimportnumpyasnp# calculate MAE by handprint"MAE by hand:",(10+0+20+10)/4.# calculate MAE using scikit-learnprint"MAE:",metrics.mean_absolute_error(true,pred)# calculate MSE by handprint"MSE by hand:",(10**2+0**2+20**2+10**2)/4.# calculate MSE using scikit-learnprint"MSE:",metrics.mean_squared_error(true,pred)# calculate RMSE by handprint"RMSE by hand:",np.sqrt((10**2+0**2+20**2+10**2)/4.)# calculate RMSE using scikit-learnprint"RMSE:",np.sqrt(metrics.mean_squared_error(true,pred))
MAE by hand: 10.0 MAE: 10.0 MSE by hand: 150.0 MSE: 150.0 RMSE by hand: 12.2474487139 RMSE: 12.2474487139

計算Sales預測的RMSE

In [26]:
printnp.sqrt(metrics.mean_squared_error(y_test,y_pred))
1.40465142303

4. 特征選擇

在之前展示的數據中,我們看到Newspaper和銷量之間的線性關系比較弱,現在我們移除這個特征,看看線性回歸預測的結果的RMSE如何?

In [27]:
feature_cols=['TV','Radio']X=data[feature_cols]y=data.SalesX_train,X_test,y_train,y_test=train_test_split(X,y,random_state=1)linreg.fit(X_train,y_train)y_pred=linreg.predict(X_test)printnp.sqrt(metrics.mean_squared_error(y_test,y_pred))
1.38790346994

我們將Newspaper這個特征移除之后,得到RMSE變小了,說明Newspaper特征不適合作為預測銷量的特征,于是,我們得到了新的模型。我們還可以通過不同的特征組合得到新的模型,看看最終的誤差是如何的。

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢