python編寫Logistic邏輯回歸
用一條直線對(duì)數(shù)據(jù)進(jìn)行擬合的過程稱為回歸。邏輯回歸分類的思想是:根據(jù)現(xiàn)有數(shù)據(jù)對(duì)分類邊界線建立回歸公式。
公式表示為:

一、梯度上升法
每次迭代所有的數(shù)據(jù)都參與計(jì)算。
for 循環(huán)次數(shù):
訓(xùn)練
代碼如下:
import numpy as np
import matplotlib.pyplot as plt
def loadData():
labelVec = []
dataMat = []
with open('testSet.txt') as f:
for line in f.readlines():
dataMat.append([1.0,line.strip().split()[0],line.strip().split()[1]])
labelVec.append(line.strip().split()[2])
return dataMat,labelVec
def Sigmoid(inX):
return 1/(1+np.exp(-inX))
def trainLR(dataMat,labelVec):
dataMatrix = np.mat(dataMat).astype(np.float64)
lableMatrix = np.mat(labelVec).T.astype(np.float64)
m,n = dataMatrix.shape
w = np.ones((n,1))
alpha = 0.001
for i in range(500):
predict = Sigmoid(dataMatrix*w)
error = predict-lableMatrix
w = w - alpha*dataMatrix.T*error
return w
def plotBestFit(wei,data,label):
if type(wei).__name__ == 'ndarray':
weights = wei
else:
weights = wei.getA()
fig = plt.figure(0)
ax = fig.add_subplot(111)
xxx = np.arange(-3,3,0.1)
yyy = - weights[0]/weights[2] - weights[1]/weights[2]*xxx
ax.plot(xxx,yyy)
cord1 = []
cord0 = []
for i in range(len(label)):
if label[i] == 1:
cord1.append(data[i][1:3])
else:
cord0.append(data[i][1:3])
cord1 = np.array(cord1)
cord0 = np.array(cord0)
ax.scatter(cord1[:,0],cord1[:,1],c='red')
ax.scatter(cord0[:,0],cord0[:,1],c='green')
plt.show()
if __name__ == "__main__":
data,label = loadData()
data = np.array(data).astype(np.float64)
label = [int(item) for item in label]
weight = trainLR(data,label)
plotBestFit(weight,data,label)
二、隨機(jī)梯度上升法
1.學(xué)習(xí)參數(shù)隨迭代次數(shù)調(diào)整,可以緩解參數(shù)的高頻波動(dòng)。
2.隨機(jī)選取樣本來(lái)更新回歸參數(shù),可以減少周期性的波動(dòng)。

for 循環(huán)次數(shù):
for 樣本數(shù)量:
更新學(xué)習(xí)速率
隨機(jī)選取樣本
訓(xùn)練
在樣本集中刪除該樣本
代碼如下:
import numpy as np
import matplotlib.pyplot as plt
def loadData():
labelVec = []
dataMat = []
with open('testSet.txt') as f:
for line in f.readlines():
dataMat.append([1.0,line.strip().split()[0],line.strip().split()[1]])
labelVec.append(line.strip().split()[2])
return dataMat,labelVec
def Sigmoid(inX):
return 1/(1+np.exp(-inX))
def plotBestFit(wei,data,label):
if type(wei).__name__ == 'ndarray':
weights = wei
else:
weights = wei.getA()
fig = plt.figure(0)
ax = fig.add_subplot(111)
xxx = np.arange(-3,3,0.1)
yyy = - weights[0]/weights[2] - weights[1]/weights[2]*xxx
ax.plot(xxx,yyy)
cord1 = []
cord0 = []
for i in range(len(label)):
if label[i] == 1:
cord1.append(data[i][1:3])
else:
cord0.append(data[i][1:3])
cord1 = np.array(cord1)
cord0 = np.array(cord0)
ax.scatter(cord1[:,0],cord1[:,1],c='red')
ax.scatter(cord0[:,0],cord0[:,1],c='green')
plt.show()
def stocGradAscent(dataMat,labelVec,trainLoop):
m,n = np.shape(dataMat)
w = np.ones((n,1))
for j in range(trainLoop):
dataIndex = range(m)
for i in range(m):
alpha = 4/(i+j+1) + 0.01
randIndex = int(np.random.uniform(0,len(dataIndex)))
predict = Sigmoid(np.dot(dataMat[dataIndex[randIndex]],w))
error = predict - labelVec[dataIndex[randIndex]]
w = w - alpha*error*dataMat[dataIndex[randIndex]].reshape(n,1)
np.delete(dataIndex,randIndex,0)
return w
if __name__ == "__main__":
data,label = loadData()
data = np.array(data).astype(np.float64)
label = [int(item) for item in label]
weight = stocGradAscent(data,label,300)
plotBestFit(weight,data,label)
三、編程技巧
1.字符串提取
將字符串中的'\n', ‘\r', ‘\t', ' ‘去除,按空格符劃分。
string.strip().split()
2.判斷類型
if type(secondTree[value]).__name__ == 'dict':
3.乘法
numpy兩個(gè)矩陣類型的向量相乘,結(jié)果還是一個(gè)矩陣
c = a*b c Out[66]: matrix([[ 6.830482]])
兩個(gè)向量類型的向量相乘,結(jié)果為一個(gè)二維數(shù)組
b Out[80]: array([[ 1.], [ 1.], [ 1.]]) a Out[81]: array([1, 2, 3]) a*b Out[82]: array([[ 1., 2., 3.], [ 1., 2., 3.], [ 1., 2., 3.]]) b*a Out[83]: array([[ 1., 2., 3.], [ 1., 2., 3.], [ 1., 2., 3.]])
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python從入門到精通之條件語(yǔ)句和循環(huán)結(jié)構(gòu)詳解
Python中提供了強(qiáng)大而靈活的條件語(yǔ)句和循環(huán)結(jié)構(gòu),本文將從入門到精通地介紹它們的使用方法,并通過相關(guān)代碼進(jìn)行講解,希望對(duì)大家深入了解Python有一定的幫助2023-07-07
基于python 二維數(shù)組及畫圖的實(shí)例詳解
下面小編就為大家分享一篇基于python 二維數(shù)組及畫圖的實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2018-04-04
Python2及Python3如何實(shí)現(xiàn)兼容切換
這篇文章主要介紹了Python2及Python3如何實(shí)現(xiàn)兼容切換,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09

