吴恩达机器学习作业(3):逻辑回归
目錄
1)數據處理
2)sigmoid函數
3)代價函數
4)梯度下降
5)預測函數
我們首先做一個練習,問題是這樣的:設想你是大學相關部分的管理者,想通過申請學生兩次測試的評分,來決定他們是否被錄取。現在你擁有之前申請學生的可以用于訓練邏輯回歸的訓練樣本集。對于每一個訓練樣本,你有他們兩次測試的評分和最后是被錄取的結果。為了完成這個預測任務,我們準備構建一個可以基于兩次測試評分來評估錄取可能性的分類模型。
1)數據處理
第三次建議,我們拿到數據之后,還是要先看看數據長什么樣子:
import numpy as np import pandas as pd import matplotlib.pyplot as pltpath = 'ex2data1.txt' data = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted']) data.head()我們創建散點圖,來是樣本可視化,其中包含正負樣本:
positive = data[data['Admitted'].isin([1])]#選取為 1的樣本 negative = data[data['Admitted'].isin([0])]#選取為 0的樣本fig, ax = plt.subplots(figsize=(12,8)) ax.scatter(positive['Exam 1'], positive['Exam 2'], s=50, c='b', marker='o', label='Admitted') ax.scatter(negative['Exam 1'], negative['Exam 2'], s=50, c='r', marker='x', label='Not Admitted') ax.legend() ax.set_xlabel('Exam 1 Score') ax.set_ylabel('Exam 2 Score') plt.show()2)sigmoid函數
g 代表一個常用的邏輯函數(logistic function)為S形函數(Sigmoid function),公式為:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
邏輯回歸模型的假設函數為:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
def sigmoid(z):return 1 / (1 + np.exp(-z))讓我們做一個快速的檢查,來確保它可以工作。
nums = np.arange(-10, 10, step=1)fig, ax = plt.subplots(figsize=(12,8)) ax.plot(nums, sigmoid(nums), 'r') plt.show()3)代價函數
代價函數:
? ? ? ? ? ? ? ? ??
def cost(theta, X, y):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)))return np.sum(first - second) / (len(X))現在我們需要對數據進行一下處理,和我們在線性回歸練習中的處理很相似
# add a ones column data.insert(0, 'Ones', 1)# set X (training data) and y (target variable) cols = data.shape[1] X = data.iloc[:,0:cols-1] y = data.iloc[:,cols-1:cols]# convert to numpy arrays and initalize the parameter array theta X = np.array(X.values) y = np.array(y.values) theta = np.zeros(3)我們可以計算初始化參數的代價函數值:(theta為0)
cost(theta, X, y)0.69314718055994534)梯度下降
形式和線性回歸的梯度下降一致:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
def gradient(theta, X, y):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])grad[i] = np.sum(term) / len(X)return grad注意在這里我們并不執行梯度下降——我們計算一個梯度步長。既然我們在用 python ,我們可以使用 SciPy 的優化 API 來實現相同功能。
我們看看用我們的數據和初始參數為0的梯度下降法的結果。
gradient(theta, X, y)array([ -0.1 , -12.00921659, -11.26284221])現在可以用SciPy's truncated newton實現尋找最優參數。
import scipy.optimize as opt result = opt.fmin_tnc(func=cost, x0=theta, fprime=gradient, args=(X, y)) result(array([-25.1613186 , 0.20623159, 0.20147149]), 36, 0)讓我們看看在這個結論下代價函數計算結果是什么個樣子。
cost(result[0], X, y)0.203497701589474645)預測函數
接下來,我們需要編寫一個函數,用我們所學的參數theta來為數據集X輸出預測。然后,我們可以使用這個函數來給我們的分類器的訓練精度打分。
當大于等于0.5時,預測 y=1
當小于0.5時,預測 y=0 。
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(result[0])#參數矩陣化 predictions = predict(theta_min, X) correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y)] accuracy = (sum(map(int, correct)) % len(correct)) print ('accuracy = {0}%'.format(accuracy))accuracy = 89%我們的邏輯回歸分類器預測正確,如果一個學生被錄取或沒有錄取,達到89%的精確度。不壞!記住,這是訓練集的準確性。我們沒有保持住了設置或使用交叉驗證得到的真實逼近,所以這個數字有可能高于其真實值(這個話題將在以后說明)。
?
在本練習的第二部分中,我們將介紹正則化邏輯回歸,這會大大提高我們模型的泛化能力。
總結
以上是生活随笔為你收集整理的吴恩达机器学习作业(3):逻辑回归的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浦发信用卡申请 支付宝申请秒批平台
- 下一篇: 详解停车位检测论文:Attentiona