Python機器學習隨筆之非線性分類的logistic回歸擬合及正則化

01 非線性決策邊界的logistic回歸擬合

常規的logistic回歸在解決分類問題時,通常是用於線性決策邊界的分類(如下圖-左圖),因為logistic回歸可以視為線性回歸的一種轉化,其回歸模型為 (sigmoid函數):

式中的z=θTx(i)就是不同x的線性表達式f(x) = g(w0+w1x1+w2x2)。那麼,對於線性決策邊界的分類,如何用logistic回歸預測、擬合呢?這時候就需要將f(x) = g(w0+w1x1+w2x2)的線性函數式轉化成多項式:f(x) = g(w0+w1x1+w2x2+w3x12+w4x22+w5x1x2)去擬合(如下圖-中圖)。

但是,這種處理方式相比較於線性函數表達式會產生很多的項數,因而其變數(特徵)也比較多,如果我們沒有足夠的數據集(訓練集)去約束這個變數過多的模型,那麼就會發生過擬合。如上圖中的最右邊圖形,其分類結果完全正確,但這個分類模型似乎太過完美了吧?連交叉部分的類別也劃分出來了。過擬合就是表示它的分類只是適合於自己這個測試用例,對需要分類的真實樣本(例如測試集)而言,特別是針對新的數據樣本,實用性反倒可能會低很多。

Advertisements

02 正則化優化logistic回歸過擬合

正則化(Regularized)是解決過擬合問題的一種方法,它將保留所有的特徵變數,但是會減小特徵變數的數量級(參數數值的大小θ(j)),當我們有很多特徵變數時,其中每一個變數都能對預測產生一點影響,每一個變數都是有用的,因此我們不希望把它們刪掉,但是我們可以通過正則化方式增加它們的成本cost,來減小我們的函數中的一些項的權重,其意義在於平滑函數曲線,使得預測函數相對簡單一些,避免過度複雜函數的過擬合問題。

其處理方法為:對某些θ(j)加入懲罰項:

在這裡λ稱作正則化參數,它通過平衡擬合訓練的目標和保持參數值較小的目標。從而來保持假設的形式相對簡單,來避免過度的擬合。

Advertisements

03 Regularized Logistic Regression實例

(1)假設有這樣一個非線性決策邊界的分類數據,(數據來自

https://github.com/jdwittenauer/ipython-notebooks/tree/master/data 中的ex2data2.txt):

import numpy as npimport pandas as pdimport matplotlib.pyplot as pltpath = 'D:\python\ml data\ex2data2.txt' #路徑要設置為你自己的路徑data2 = pd.read_csv(path, header=None, names=['Test 1', 'Test 2', 'Accepted'])data2.head()

(2)其數據可視化為:

positive = data2[data2['Accepted'].isin([1])] #Accepted列中的1設定為positivenegative = data2[data2['Accepted'].isin([0])] #Accepted列中的0設定為positivefig, ax = plt.subplots(figsize=(12,8))ax.scatter(positive['Test 1'], positive['Test 2'], s=50, c='b', marker='o', label='Accepted')ax.scatter(negative['Test 1'], negative['Test 2'], s=50, c='r', marker='x', label='Rejected')ax.legend()ax.set_xlabel('Test 1 Score')ax.set_ylabel('Test 2 Score')plt.show()

(3)構建多項式特徵值

上圖的可視化結果可以看到該數據類別是明顯的非線性決策邊界,對此我們首先構建變數'Test 1', 'Test 2'的多項式特徵值,如下:

degree = 5x1 = data2['Test 1']x2 = data2['Test 2']data2.insert(3, 'Ones', 1)for i in range(1, degree): for j in range(0, i): data2['F' + str(i) + str(j)] = np.power(x1, i-j) * np.power(x2, j)data2.drop('Test 1', axis=1, inplace=True) #刪除Text1列並進行替換data2.drop('Test 2', axis=1, inplace=True) #刪除Text2列並進行替換data2.head()

其中degree表示多項式的冪數,range(1, degree)表示了從1次到4次,即由data2['F' + str(i) + str(j)] = np.power(x1, i-j) * np.power(x2, j)命令可知,每一列列名的F第一個數代表了x1的冪值,第二個數代表了x2的冪值,如F31則表示x13x2,以此類推。

(4)構建加入懲罰項的cost函數

def sigmoid(z): return 1 / (1 + np.exp(-z)) #構建sigmoid函數def costReg(theta, X, y, learningRate): theta = np.matrix(theta) X = np.matrix(X) y = np.matrix(y) first = np.multiply(-y, np.log(sigmoid(X * theta.T))) second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T))) reg = (learningRate / 2 * len(X)) * np.sum(np.power(theta[:,1:theta.shape[1]], 2))return np.sum(first - second) / (len(X)) + reg

reg就是懲罰項,構建思路參考正則化優化logistic回歸過擬合部分的懲罰項設置規則。

(5)採用梯度下降法求解

def gradientReg(theta, X, y, learningRate): theta = np.matrix(theta) #轉化為矩陣 X = np.matrix(X) y = np.matrix(y) parameters = int(theta.ravel().shape[1]) #計算參數theta的個數 grad = np.zeros(parameters) error = sigmoid(X * theta.T) - y for i in range(parameters): term = np.multiply(error, X[:,i]) #兩矩陣相乘 if (i == 0): grad[i] = np.sum(term) / len(X) #一般來說第一個參數不需要正則化 else: grad[i] = (np.sum(term) / len(X)) + ((learningRate / len(X)) * theta[:,i])return grad

具體的梯度下降法思路可以參考之前本人寫的關於梯度下降法求解線性回歸的文章,只是在這裡加了一個懲罰項的梯度下降求解,其構造思路如下圖所示。

(6)將變數代入進行擬合

基於表格數據構建x、y變數並轉化成數組,這部分內容可以參考之前本人寫的關於梯度下降法求解線性回歸的文章。然後用梯度下降法函數求解並計算cost。

# set X and y (remember from above that we moved the label to column 0)cols = data2.shape[1]X2 = data2.iloc[:,1:cols]y2 = data2.iloc[:,0:1]# convert to numpy arrays and initalize the parameter array thetaX2 = np.array(X2.values)y2 = np.array(y2.values)theta2 = np.zeros(11)learningRate = 1 #設置學習率gradientReg(theta2, X2, y2, learningRate)costReg(theta2, X2, y2, learningRate)

得到的cost值為0.6931471805599454。

值得注意的是,在這裡我們並沒有在這個函數中執行梯度下降,而是基於梯度下降計算結果加入梯度項來實現的一個漸變步驟,因此,在這裡我們還可以調用octave的內建函數fminunc();來獲得最優的theta和最小的cost。在Python,我們可以使用SciPy的優化API來完成

import scipy.optimize as optresult2 = opt.fmin_tnc(func=costReg, x0=theta2, fprime=gradientReg, args=(X2, y2, learningRate))result2

(7)計算預測結果精度

def predict(theta, X): probability = sigmoid(X * theta.T)return [1 if x >= 0.5 else 0 for x in probability]theta_min = np.matrix(result2[0])predictions = predict(theta_min, X2)correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y2)]accuracy = (sum(map(int, correct)) % len(correct))print 'accuracy = {0}%'.format(accuracy)

首先構建預測值函數,然後將該值與原始類別值0,1比較,計算其正確的精度,結果為91%。

寫作不易,特別是技術類的寫作,請大家多多支持,關注、點贊、轉發等等..

參考文獻:

Machine Learning Exercises In Python, Part 1,

http://www.johnwittenauer.net/machine-learning-exercises-in-python-part-1/

(吳恩達筆記 1-3)——損失函數及梯度下降

http://blog.csdn.net/wearge/article/details/77073142?locationNum=9&fps=1

斯坦福機器學習視頻筆記 Week3 邏輯回歸與正則化 Logistic

https://www.cnblogs.com/yangmang/p/6352118.html

詳解機器學習中的「正則化」(Regularization)

http://makaidong.com/baimafujinji/1/5017_10306169.html

Advertisements

你可能會喜歡