English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

pythonでLogistic回帰を書く方法

データに対して直線でフィッティングを行うプロセスは回帰と呼ばれます。ロジスティック回帰分類の思想は、既存データに基づいて分類境界線の回帰公式を構築することです。
公式は以下の通りです:

一、勾配昇降法

各反復で全データが計算に参加します。

ループ回数:for
        トレーニング

コード如下:

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*エラー
 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.学習パラメータは反復回数に応じて調整され、パラメータの高い周波数の揺れを緩和することができます。
2.ランダムにサンプルを選択して回帰パラメータを更新することで、周期的な揺れを減少させることができます。

ループ回数:for
    サンプル数:for
        学習率を更新します
        サンプルをランダムに選択します
        トレーニング
        サンプルセットからこのサンプルを削除します

コード如下:

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*エラー*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の二つの行列型のベクトルを乗算し、結果が行列です

c = a*b
c
Out[66]: matrix([[ 6.830482])

二つのベクトル型のベクトルを乗算し、結果が二次元配列になります

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.]])

これで本稿の全てが終わり、皆様の学習に役立つことを願っています。また、呐喊教程を多くの皆様にサポートしていただけると嬉しいです。

声明:本稿の内容はインターネットから取得しており、著作権者に帰属します。インターネットユーザーが自発的に貢献し、自己でアップロードしたものであり、本サイトは所有権を有しておらず、人間による編集処理は行われていません。著作権侵害の疑いがある場合は、メール:notice#wまでご連絡ください。3codebox.com(メールを送信する際には、#を@に置き換えてください。届出を行い、関連する証拠を提供してください。一旦確認が取れましたら、本サイトは即座に侵害疑いのコンテンツを削除します。)

おすすめ