吴恩达机器学习作业(4):正则化逻辑回归
目錄
1)數據可視化
2)創建多項式特征
3)正則化成本函數
4)正則化梯度下降
4)準確度
5)Scikit-learn實現
正則化是成本函數中的一個術語,它使算法更傾向于“更簡單”的模型(在這種情況下,模型將有更小的系數)。這個理論有助于減少過擬合,提高模型的泛化能力。這樣,我們開始吧。
設想你是工廠的生產主管,你有一些芯片在兩次測試中的測試結果。對于這兩次測試,你想決定是否芯片要被接受或拋棄。為了幫助你做出艱難的決定,你擁有過去芯片的測試數據集,從其中你可以構建一個邏輯回歸模型。
和第一部分很像,從數據可視化開始吧!
1)數據可視化
我們這里使用之前導入過的庫:
path = 'ex2data2.txt' data2 = pd.read_csv(path, header=None, names=['Test 1', 'Test 2', 'Accepted']) data2.head()positive = data2[data2['Accepted'].isin([1])] negative = data2[data2['Accepted'].isin([0])]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()這個數據看起來可比前一次的復雜得多。特別地,你會注意到其中沒有線性決策界限,來良好的分開兩類數據。一個方法是用像邏輯回歸這樣的線性技術來構造從原始特征的多項式中得到的特征。讓我們通過創建一組多項式特征入手吧。
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) data2.drop('Test 2', axis=1, inplace=True)data2.head()3)正則化成本函數
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) + reg4)正則化梯度下降
現在我們來看看正則化的代價函數,只是第一項未正則化:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
對上面的算法中 j=1,2,...,n 時的更新式子進行調整可得:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
def gradientReg(theta, X, y, learningRate):theta = np.matrix(theta)X = np.matrix(X)y = np.matrix(y)parameters = int(theta.ravel().shape[1])grad = np.zeros(parameters)error = sigmoid(X * theta.T) - yfor 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 grad4)準確度
剩下的操作就像之前一樣:
# 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現在,我們來計算新的默認為0的正則化函數的值:
costReg(theta2, X2, y2, learningRate)0.6931471805599454gradientReg(theta2, X2, y2, learningRate)array([0.00847458, 0.01878809, 0.05034464, 0.01150133, 0.01835599,0.00732393, 0.00819244, 0.03934862, 0.00223924, 0.01286005,0.00309594])現在我們可以使用和第一部分相同的優化函數來計算優化后的結果。
result2 = opt.fmin_tnc(func=costReg, x0=theta2, fprime=gradientReg, args=(X2, y2, learningRate)) result2 (array([ 1.22702519e-04, 7.19894617e-05, -3.74156201e-04,-1.44256427e-04, 2.93165088e-05, -5.64160786e-05,-1.02826485e-04, -2.83150432e-04, 6.47297947e-07,-1.99697568e-04, -1.68479583e-05]), 96, 1)最后,我們可以使用第1部分中的預測函數來查看我們的方案在訓練數據上的準確度。
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))5)Scikit-learn實現
from sklearn import linear_model#調用sklearn的線性回歸包 model = linear_model.LogisticRegression(penalty='l2', C=1.0) model.fit(X2, y2.ravel())model.score(X2, y2) 0.6610169491525424這個準確度和我們剛剛實現的差了好多,不過請記住這個結果是使用默認參數下計算的結果。我們可能需要做一些參數的調整來獲得和我們之前結果相同的精確度。
總結
以上是生活随笔為你收集整理的吴恩达机器学习作业(4):正则化逻辑回归的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 节后第一天,国内油价便迎来大幅上调,8元
- 下一篇: 2017浦发信用卡进度查询平台 流程图一