1. 程式人生 > 其它 >【Python環境】scikit-learn的線性迴歸模型

【Python環境】scikit-learn的線性迴歸模型

內容概要

  • 如何使用pandas讀入資料
  • 如何使用seaborn進行資料的視覺化
  • scikit-learn的線性迴歸模型和使用方法
  • 線性迴歸模型的評估測度
  • 特徵選擇的方法

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

1. 使用pandas來讀取資料

Pandas是一個用於資料探索、資料處理、資料分析的Python庫

In [1]:

import pandas as pd

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的兩個主要資料結構:Series和DataFrame:

  • 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]:

import seaborn as sns%matplotlib inline

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引數來調節顯示的大小和比例。可以從圖中看出,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可以是pandas的DataFrame,y可以是pandas的Series,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 Xprint type(X)print X.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]:

print type(y)print y.shape
<class 'pandas.core.series.Series'>
(200,)

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

In [12]:

from sklearn.cross_validation import train_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 testingprint X_train.shapeprint y_train.shapeprint X_test.shapeprint y_test.shape
(150, 3)
(150,)
(50, 3)
(50,)

(3)Scikit-learn的線性迴歸

In [15]:

from sklearn.linear_model import LinearRegressionlinreg = LinearRegression()linreg.fit(X_train, y_train)

Out[15]:

LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

In [16]:

print linreg.intercept_print linreg.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]:

from sklearn import metricsimport numpy as np# 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]:

print np.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)print np.sqrt(metrics.mean_squared_error(y_test, y_pred))
1.38790346994

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