用Python開始機器學習(7:邏輯迴歸分類) --好!!

from : http://blog.csdn.net/lsldd/article/details/41551797html

在本系列文章中提到過用Python開始機器學習(3:數據擬合與廣義線性迴歸)中提到過迴歸算法來進行數值預測。邏輯迴歸算法本質仍是迴歸,只是其引入了邏輯函數來幫助其分類。實踐發現,邏輯迴歸在文本分類領域表現的也很優秀。如今讓咱們來一探究竟。python

一、邏輯函數

假設數據集有n個獨立的特徵,x1到xn爲樣本的n個特徵。常規的迴歸算法的目標是擬合出一個多項式函數,使得預測值與真實值的偏差最小:算法

而咱們但願這樣的f(x)可以具備很好的邏輯判斷性質,最好是可以直接表達具備特徵x的樣本被分到某類的機率。好比f(x)>0.5的時候可以表示x被分爲正類,f(x)<0.5表示分爲反類。並且咱們但願f(x)總在[0, 1]之間。有這樣的函數嗎?數據結構

sigmoid函數就出現了。這個函數的定義以下:機器學習

先直觀的瞭解一下,sigmoid函數的圖像以下所示(來自http://computing.dcu.ie/~humphrys/Notes/Neural/sigmoid.html):函數

sigmoid函數具備咱們須要的一切優美特性,其定義域在全體實數,值域在[0, 1]之間,而且在0點值爲0.5。性能

那麼,如何將f(x)轉變爲sigmoid函數呢?令p(x)=1爲具備特徵x的樣本被分到類別1的機率,則p(x)/[1-p(x)]被定義爲讓步比(odds ratio)。引入對數:學習

 

上式很容易就能把p(x)解出來獲得下式:測試

如今,咱們獲得了須要的sigmoid函數。接下來只須要和往常的線性迴歸同樣,擬合出該式中n個參數c便可。網站

二、測試數據

測試數據咱們仍然選擇康奈爾大學網站的2M影評數據集。

在這個數據集上咱們已經測試過KNN分類算法、樸素貝葉斯分類算法。如今咱們看看羅輯迴歸分類算法在處理此類情感分類問題效果如何。

一樣的,咱們直接讀入保存好的movie_data.npy和movie_target.npy以節省時間。

三、代碼與分析

邏輯迴歸的代碼以下:

 

[python]  view plain  copy
 
  1. # -*- coding: utf-8 -*-  
  2. from matplotlib import pyplot  
  3. import scipy as sp  
  4. import numpy as np  
  5. from matplotlib import pylab  
  6. from sklearn.datasets import load_files  
  7. from sklearn.cross_validation import train_test_split  
  8. from sklearn.feature_extraction.text import  CountVectorizer  
  9. from sklearn.feature_extraction.text import  TfidfVectorizer  
  10. from sklearn.naive_bayes import MultinomialNB  
  11. from sklearn.metrics import precision_recall_curve, roc_curve, auc  
  12. from sklearn.metrics import classification_report  
  13. from sklearn.linear_model import LogisticRegression  
  14. import time  
  15.   
  16. start_time = time.time()  
  17.   
  18. #繪製R/P曲線  
  19. def plot_pr(auc_score, precision, recall, label=None):  
  20.     pylab.figure(num=None, figsize=(6, 5))  
  21.     pylab.xlim([0.0, 1.0])  
  22.     pylab.ylim([0.0, 1.0])  
  23.     pylab.xlabel('Recall')  
  24.     pylab.ylabel('Precision')  
  25.     pylab.title('P/R (AUC=%0.2f) / %s' % (auc_score, label))  
  26.     pylab.fill_between(recall, precision, alpha=0.5)  
  27.     pylab.grid(True, linestyle='-', color='0.75')  
  28.     pylab.plot(recall, precision, lw=1)      
  29.     pylab.show()  
  30.   
  31. #讀取  
  32. movie_data   = sp.load('movie_data.npy')  
  33. movie_target = sp.load('movie_target.npy')  
  34. x = movie_data  
  35. y = movie_target  
  36.   
  37. #BOOL型特徵下的向量空間模型,注意,測試樣本調用的是transform接口  
  38. count_vec = TfidfVectorizer(binary = False, decode_error = 'ignore',\  
  39.                             stop_words = 'english')  
  40. average = 0  
  41. testNum = 10  
  42. for i in range(0, testNum):  
  43.     #加載數據集,切分數據集80%訓練,20%測試  
  44.     x_train, x_test, y_train, y_test\  
  45.         = train_test_split(movie_data, movie_target, test_size = 0.2)  
  46.     x_train = count_vec.fit_transform(x_train)  
  47.     x_test  = count_vec.transform(x_test)  
  48.   
  49.     #訓練LR分類器  
  50.     clf = LogisticRegression()  
  51.     clf.fit(x_train, y_train)  
  52.     y_pred = clf.predict(x_test)  
  53.     p = np.mean(y_pred == y_test)  
  54.     print(p)  
  55.     average += p  
  56.   
  57.       
  58. #準確率與召回率  
  59. answer = clf.predict_proba(x_test)[:,1]  
  60. precision, recall, thresholds = precision_recall_curve(y_test, answer)      
  61. report = answer > 0.5  
  62. print(classification_report(y_test, report, target_names = ['neg', 'pos']))  
  63. print("average precision:", average/testNum)  
  64. print("time spent:", time.time() - start_time)  
  65.   
  66. plot_pr(0.5, precision, recall, "pos")  

代碼運行結果以下:

 

0.8
0.817857142857
0.775
0.825
0.807142857143
0.789285714286
0.839285714286
0.846428571429
0.764285714286
0.771428571429
               precision    recall  f1-score   support
        neg       0.74      0.80      0.77       132
        pos       0.81      0.74      0.77       148
avg / total     0.77      0.77      0.77       280
average precision: 0.803571428571
time spent: 9.651551961898804

首先注意咱們連續測試了10組測試樣本,最後統計出準確率的平均值。另一種好的測試方法是K折交叉檢驗(K-Fold)。這樣都能更加準確的評估分類器的性能,考察分類器對噪音的敏感性。

其次咱們注意看最後的圖,這張圖就是使用precision_recall_curve繪製出來的P/R曲線(precition/Recall)。結合P/R圖,咱們能對邏輯迴歸有更進一步的理解。

前文咱們說過,一般咱們使用0.5來作劃分兩類的依據。而結合P/R分析,閾值的選取是能夠更加靈活和優秀的。

在上圖能夠看到,若是選擇的閾值太低,那麼更多的測試樣本都將分爲1類。所以召回率可以獲得提高,顯然準確率犧牲相應準確率。

好比本例中,或許我會選擇0.42做爲劃分值——由於該點的準確率和召回率都很高。

最後給一些比較好的資源:

浙大某女學霸的博客!記錄的斯坦福Andrew老師主講的LR公開課筆記:http://blog.csdn.net/abcjennifer/article/details/7716281

一個總結LR還不錯的博客:http://xiamaogeng.blog.163.com/blog/static/1670023742013231197530/

Sigmoid函數詳解:http://computing.dcu.ie/~humphrys/Notes/Neural/sigmoid.html

相關文章
相關標籤/搜索