python編寫Logistic邏輯回歸
用一條直線對數(shù)據(jù)進行擬合的過程稱為回歸。邏輯回歸分類的思想是:根據(jù)現(xiàn)有數(shù)據(jù)對分類邊界線建立回歸公式。
公式表示為:
一、梯度上升法
每次迭代所有的數(shù)據(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)
二、隨機梯度上升法
1.學(xué)習(xí)參數(shù)隨迭代次數(shù)調(diào)整,可以緩解參數(shù)的高頻波動。
2.隨機選取樣本來更新回歸參數(shù),可以減少周期性的波動。
for 循環(huán)次數(shù):
for 樣本數(shù)量:
更新學(xué)習(xí)速率
隨機選取樣本
訓(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兩個矩陣類型的向量相乘,結(jié)果還是一個矩陣
c = a*b c Out[66]: matrix([[ 6.830482]])
兩個向量類型的向量相乘,結(jié)果為一個二維數(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.]])
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python數(shù)據(jù)分析之使用scikit-learn構(gòu)建模型
這篇文章主要介紹了Python數(shù)據(jù)分析之使用scikit-learn構(gòu)建模型,sklearn提供了model_selection模型選擇模塊、preprocessing數(shù)據(jù)預(yù)處理模塊、decompisition特征分解模塊,更多相關(guān)內(nèi)容需要朋友可以參考下面文章內(nèi)容2022-08-08Python Jupyter Notebook顯示行數(shù)問題的解決
這篇文章主要介紹了Python Jupyter Notebook顯示行數(shù)問題的解決方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02python基于json文件實現(xiàn)的gearman任務(wù)自動重啟代碼實例
這篇文章主要介紹了python基于json文件實現(xiàn)的gearman任務(wù)自動重啟代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08python2 與python3的print區(qū)別小結(jié)
這篇文章主要介紹了python2 與python3的print區(qū)別小結(jié),需要的朋友可以參考下2018-01-01Python?3.11.0下載安裝并使用help查看模塊信息的方法
本文給大家介紹Python?3.11.0下載安裝并使用help查看模塊信息的相關(guān)知識,首先給大家講解了Python?3.11.0下載及安裝緊接著介紹了在命令行使用help查看模塊信息的方法,感興趣的朋友跟隨小編一起看看吧2022-11-11