欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python編寫Logistic邏輯回歸

 更新時間:2020年12月30日 10:04:34   作者:開貳錘  
這篇文章主要介紹了python編寫Logistic邏輯回歸的相關(guān)代碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

用一條直線對數(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)文章

  • PyTorch加載自己的數(shù)據(jù)集實例詳解

    PyTorch加載自己的數(shù)據(jù)集實例詳解

    這篇文章主要介紹了PyTorch加載自己的數(shù)據(jù)集,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • Python數(shù)據(jù)分析之使用scikit-learn構(gòu)建模型

    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-08
  • python和shell變量互相傳遞的幾種方法

    python和shell變量互相傳遞的幾種方法

    這篇文章主要介紹了python和shell變量互相傳遞方法,使用了環(huán)境變量、管道等方法
    2013-11-11
  • Python Jupyter Notebook顯示行數(shù)問題的解決

    Python Jupyter Notebook顯示行數(shù)問題的解決

    這篇文章主要介紹了Python Jupyter Notebook顯示行數(shù)問題的解決方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • python基于json文件實現(xiàn)的gearman任務(wù)自動重啟代碼實例

    python基于json文件實現(xiàn)的gearman任務(wù)自動重啟代碼實例

    這篇文章主要介紹了python基于json文件實現(xiàn)的gearman任務(wù)自動重啟代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • python2 與python3的print區(qū)別小結(jié)

    python2 與python3的print區(qū)別小結(jié)

    這篇文章主要介紹了python2 與python3的print區(qū)別小結(jié),需要的朋友可以參考下
    2018-01-01
  • 一文搞懂關(guān)于?sys.argv?的詳解

    一文搞懂關(guān)于?sys.argv?的詳解

    sys.argv?其實就是一個列表,里邊需要用戶傳入的參數(shù),關(guān)鍵就是要明白這參數(shù)是從程序外部輸入的,而非代碼本身的什么地方,要想看到它的效果就應(yīng)該將程序保存了,從外部來運行程序并給出參數(shù),通過本文學(xué)習(xí)你將明白?sys.argv很多知識,感興趣的朋友一起看看吧
    2023-01-01
  • 關(guān)于python中第三方庫交叉編譯的問題

    關(guān)于python中第三方庫交叉編譯的問題

    這篇文章主要介紹了python及第三方庫交叉編譯,通過交叉編譯工具,我們就可以在CPU能力很強、存儲控件足夠的主機平臺上(比如PC上)編譯出針對其他平臺的可執(zhí)行程序,需要的朋友可以參考下
    2022-09-09
  • python實現(xiàn)自定義日志的具體方法

    python實現(xiàn)自定義日志的具體方法

    在本篇文章里小編給大家整理的是一篇關(guān)于python實現(xiàn)自定義日志的具體方法,有興趣的朋友們可以學(xué)習(xí)下。
    2021-05-05
  • Python?3.11.0下載安裝并使用help查看模塊信息的方法

    Python?3.11.0下載安裝并使用help查看模塊信息的方法

    本文給大家介紹Python?3.11.0下載安裝并使用help查看模塊信息的相關(guān)知識,首先給大家講解了Python?3.11.0下載及安裝緊接著介紹了在命令行使用help查看模塊信息的方法,感興趣的朋友跟隨小編一起看看吧
    2022-11-11

最新評論