程序本地地址:ex2data2_regularized.py
編者注:本文采用梯度下降法來求解的logistic回歸,關於其思想以及編程原理見本人之前文章《梯度下降法求解線性回歸的python實現及其結果可視化》(https://zhuanlan.zhihu.com/p/30562194),在這里不再贅述。
01 非線性決策邊界的logistic回歸擬合
常規的logistic回歸在解決分類問題時,通常是用於線性決策邊界的分類(如下圖-左圖),因為logistic回歸可以視為線性回歸的一種轉化,其回歸模型為 (sigmoid函數):


但是,這種處理方式相比較於線性函數表達式會產生很多的項數,因而其變量(特征)也比較多,如果我們沒有足夠的數據集(訓練集)去約束這個變量過多的模型,那么就會發生過擬合。如上圖中的最右邊圖形,其分類結果完全正確,但這個分類模型似乎太過完美了吧?連交叉部分的類別也划分出來了。過擬合就是表示它的分類只是適合於自己這個測試用例,對需要分類的真實樣本(例如測試集)而言,特別是針對新的數據樣本,實用性反倒可能會低很多。
02 正則化優化logistic回歸過擬合
正則化(Regularized)是解決過擬合問題的一種方法,它將保留所有的特征變量,但是會減小特征變量的數量級(參數數值的大小θ(j)),當我們有很多特征變量時,其中每一個變量都能對預測產生一點影響,每一個變量都是有用的,因此我們不希望把它們刪掉,但是我們可以通過正則化方式增加它們的成本cost,來減小我們的函數中的一些項的權重,其意義在於平滑函數曲線,使得預測函數相對簡單一些,避免過度復雜函數的過擬合問題。
其處理方法為:對某些θ(j)加入懲罰項:

三、Regularized Logistic Regression實例
(1)假設有這樣一個非線性決策邊界的分類數據,(數據來自
https://github.com/jdwittenauer/ipython-notebooks/tree/master/data 中的ex2data2.txt):
import numpy as np import pandas as pd import matplotlib.pyplot as plt path = '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設定為positive negative = data2[data2['Accepted'].isin([0])] #Accepted列中的0設定為positive fig, 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 = 5 x1 = 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 theta X2 = 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 opt result2 = 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
作者:博觀厚積
鏈接:https://www.jianshu.com/p/f9adf1621016
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。