機器學習/邏輯回歸(logistic regression)/--附python代碼
阿新 • • 發佈:2019-01-09
一個 should 示意圖 algrithm cto python ber -- 根據 個人分類: 機器學習
本文為吳恩達《機器學習》課程的讀書筆記,並用python實現。
前一篇講了線性回歸,這一篇講邏輯回歸,有了上一篇的基礎,這一篇的內容會顯得比較簡單。
邏輯回歸(logistic regression)雖然叫回歸,但他做的事實際上是分類。這裏我們討論二元分類,即只分兩類,y屬於{0,1}。
選擇如下的假設函數:
這裏寫圖片描述
其中:
這裏寫圖片描述
上式稱為邏輯函數或S型函數,圖像如下圖:
這裏寫圖片描述
可以看到,當z趨向正無窮,g(z)趨向1,當z趨向負無窮g(z)趨向0,即g(z)取值[0,1]。
同樣,令 這裏寫圖片描述 ,
現在我們要根據訓練集,獲取上面模型的最好參數 值。同樣,可以通過最大似然函數的方法來求解。
假設:
這裏寫圖片描述
合並上面兩個式子:
這裏寫圖片描述
假設m個訓練樣本是獨立的,則似然函數:
這裏寫圖片描述
同樣,我們求其對數值以方便求解:
這裏寫圖片描述
我們的目的是最大似然函數,即max l ,可以用梯度上升法:
這裏寫圖片描述
下面我們先對g(z)進行函數求導(後面會用到):
這裏寫圖片描述
則可以求得一個樣本時的導數(第二步用到 ):
這裏寫圖片描述
則增量梯度法(上一篇線性回歸有介紹)有:
這裏寫圖片描述
m個樣本的批處理梯度法有:
這裏寫圖片描述
python 代碼:
##author:lijiayan
##data:2016/10/27
from numpy import *
import matplotlib.pyplot as plt
def loadData(filename):
data = loadtxt(filename)
x = data[:,0:2]
y = data[:,2:3]
return x,y
#the sigmoid function
def sigmoid(x):
return 1.0 / (1 + exp(-x))
#the cost function
def costfunction(y,h):
y = array(y)
h = array(h)
J = sum(y*log(h))+sum((1-y)*log(1-h))
return J
# the batch gradient descent algrithm
def gradescent(x,y):
m,n = shape(x) #m: number of training example; n: number of features
x = c_[ones(m),x] #add x0
x = mat(x) # to matrix
y = mat(y)
a = 0.002 # learning rate
maxcycle = 2000
theta = ones((n+1,1)) #initial theta
J = []
for i in range(maxcycle):
h = sigmoid(x*theta)
theta = theta + a * x.transpose()*(y-h)
cost = costfunction(y,h)
J.append(cost)
plt.plot(J)
plt.show()
return theta,cost
#the stochastic gradient descent (m should be large,if you want the result is good)
def stocGraddescent(x,y):
m,n = shape(x) #m: number of training example; n: number of features
x = c_[ones(m),x] #add x0
x = mat(x) # to matrix
y = mat(y)
a = 0.01 # learning rate
theta = ones((n+1,1)) #initial theta
J = []
for i in range(m):
h = sigmoid(x[i]*theta)
theta = theta + a * x[i].transpose()*(y[i]-h)
cost = costfunction(y,h)
J.append(cost)
plt.plot(J)
plt.show()
return theta,cost
#plot the decision boundary
def plotbestfit(x,y,theta):
plt.plot(x[:,0:1][where(y==1)],x[:,1:2][where(y==1)],‘ro‘)
plt.plot(x[:,0:1][where(y!=1)],x[:,1:2][where(y!=1)],‘bx‘)
x1= arange(-4,4,0.1)
x2 =(-float(theta[0])-float(theta[1])*x1) /float(theta[2])
plt.plot(x1,x2)
plt.xlabel(‘x1‘)
plt.ylabel((‘x2‘))
plt.show()
def classifyVector(inX,theta):
prob = sigmoid(sum(inX*theta))
print ‘the probobility is:‘,prob
if prob > 0.5:
return 1.0
else:
return 0.0
if __name__==‘__main__‘:
x,y = loadData("testSet.txt")
theta,cost = gradescent(x,y)
print ‘theta:\n‘,theta
print ‘J:‘,cost
X = [1,2,9]
print ‘the new input:‘,X
h = classifyVector(X,theta)
print ‘the predict y:‘,h
plotbestfit(x,y,theta)
這個是logL(似然函數對數值)的曲線圖,有點cost function的意思,只不過cost function取最小值,這個是取最大值,平穩了不震蕩、不發散,就說明算法正常運行:
這裏寫圖片描述
這個是兩個類的分類示意圖:
這裏寫圖片描述
這是最後的運算結果,給出了theta值,logL的最終值(最大值),以及新來一個輸入X,模型給出的預測值。註意,輸入是兩個特征x1,x2,這邊X=[1,2,9]是三個特征,其中有一個是x0=1。
這裏寫圖片描述
機器學習/邏輯回歸(logistic regression)/--附python代碼