- 用一條直線對一些數(shù)據(jù)點進行擬合(該線稱為最佳擬合直線),這個擬合過程就成為回歸。
- 利用Logistic回歸進行分類的主要思想是:根據(jù)現(xiàn)有數(shù)據(jù)對分類邊界建立回歸公式,以此進行分類。
- 訓練分類器時的做法是 尋找最佳擬合參數(shù),使用的是 最優(yōu)化算法。
1 基于Logistic回歸和Sigmoid函數(shù)的分類
| Logistic回歸 | |
|---|---|
| 優(yōu)點 | 計算代價不高,易于理解和實現(xiàn)。 |
| 缺點 | 容易欠擬合,分類精度可能不高。 |
| 適用數(shù)據(jù)范圍 | 數(shù)值型、標稱型。 |
- sigmoid函數(shù):σ(z) = 1/(1+e-z)
2 基于最優(yōu)化方法的最佳回歸系數(shù)確定
- z = w0x0+w1x1+w2x2+...+wnxn
- z = wTx
2.1 梯度上升法
- 思想:要找到某函數(shù)的最大值,最好的方法是沿著該函數(shù)的梯度方向探尋。
- ?f(x,y) :δf(x,y)/δx;δf(x,y)/δy
- 梯度上升算法的迭代公式:w := w+α?wf(w)。α為步長。
- 梯度下降算法的迭代公式:w := w-α?wf(w)。α為步長。
2.2 訓練算法:使用梯度上升法找到最佳參數(shù)
- 梯度上升法的偽代碼
每個回歸系數(shù)初始化為1
重復R次:
計算整個數(shù)據(jù)集的梯度
使用alpha * gradient更新回歸系數(shù)的向量
返回回歸系數(shù)
- 回歸系數(shù):確定了不同類別數(shù)據(jù)之間的分割線。
#初始化數(shù)據(jù)
def loadDataSet():
dataMat = []; labelMat = []
fr = open('testSet.txt')
for line in fr.readlines():
lineArr = line.strip().split()
dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])
labelMat.append(int(lineArr[2]))
return dataMat,labelMat
#sigmoid函數(shù)
def sigmoid(inX):
return 1.0/(1+np.exp(-inX))
#梯度上升算法
def gradAscent(dataMatIn, classLabels):
dataMatrix = np.mat(dataMatIn) #convert to NumPy matrix
labelMat = np.mat(classLabels).transpose() #convert to NumPy matrix
m,n = np.shape(dataMatrix)
alpha = 0.001
maxCycles = 500
weights = np.ones((n,1))
for k in range(maxCycles): #heavy on matrix operations
h = sigmoid(dataMatrix*weights) #matrix mult
error = (labelMat - h) #vector subtraction
weights = weights + alpha * dataMatrix.transpose()* error #matrix mult
return weights
- 測試
import logRegres
dataArr,labelMat = logRegres.loadDataSet()
logRegres.gradAscent(dataArr,labelMat)
Out[16]:
matrix([[ 4.12414349],
[ 0.48007329],
[-0.6168482 ]])
- weights = weights + alpha * dataMatrix.transpose()* error是在按照真實類別與預測類別的差值方向調整回歸系數(shù)。
2.3 分析數(shù)據(jù):畫出決策邊界
def plotBestFit(weights):
import matplotlib.pyplot as plt
dataMat,labelMat=loadDataSet()
dataArr = np.array(dataMat)
n = np.shape(dataArr)[0]
xcord1 = []; ycord1 = []
xcord2 = []; ycord2 = []
for i in range(n):
#標簽為1類的時候
if int(labelMat[i])== 1:
xcord1.append(dataArr[i,1]); ycord1.append(dataArr[i,2])
#標簽為0類的時候
else:
xcord2.append(dataArr[i,1]); ycord2.append(dataArr[i,2])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')
ax.scatter(xcord2, ycord2, s=30, c='green')
x = np.arange(-3.0, 3.0, 0.1)
y = (-weights[0]-weights[1]*x)/weights[2]
ax.plot(x, y)
plt.xlabel('X1'); plt.ylabel('X2');
plt.show()
- 測試
from numpy import *
weights = logRegres.gradAscent(dataArr,LabelMat)
logRegres.plotBestFit(weights.getA())
2.4 訓練算法:隨機梯度上升
- 一次僅用一個樣本點來更新回歸系數(shù)。
- 可以在樣本到來時對分類器進行增量學習。
- 在線學習算法。
- 與在線學習相對應,一次處理所有數(shù)據(jù)被稱作是“批處理”。
- 隨機梯度上升法的偽代碼
所有回歸系數(shù)初始化為1
對數(shù)據(jù)集中每個樣本
計算該樣本的梯度
使用alpha*gradient更新回歸系數(shù)值
返回回歸系數(shù)值
- 隨機梯度上升算法
def stocGradAscent0(dataMatrix, classLabels):
m,n = np.shape(dataMatrix)
alpha = 0.01
weights = np.ones(n) #initialize to all ones
for i in range(m):
h = sigmoid(sum(dataMatrix[i]*weights))
error = classLabels[i] - h
weights = weights + alpha * error * dataMatrix[i]
return weights
- 測試
from numpy import *
dataArr,labelMat = logRegres.loadDataSet()
weights = logRegres.stocGradAscent0(array(dataArr),labelMat)
logRegres.plotBestFit(weights)
在stocGradAscent0中,因為數(shù)據(jù)集并非線性可分,所以在每次迭代時會引發(fā)系數(shù)的劇烈改變??梢孕薷臑閟tocGradAscent1。
- alpha在每次迭代時都會調整,緩解了數(shù)據(jù)波動或高頻波動;雖然alpha會隨著迭代次數(shù)不斷減少,但永遠不會減少到0,這是因為alpha = 4/(1.0+j+i)+0.0001中存在一個常數(shù)項。必須這樣做的原因是為了保證在多次迭代之后更新數(shù)據(jù)仍然具有一定影響力。
- 使用了樣本隨機選擇機制,減少周期性波動。
def stocGradAscent1(dataMatrix, classLabels, numIter=150):
m,n = np.shape(dataMatrix)
weights = np.ones(n) #initialize to all ones
for j in range(numIter):
dataIndex = list(range(m))
for i in range(m):
alpha = 4/(1.0+j+i)+0.0001 #apha decreases with iteration, does not.常數(shù)項保證在多次迭代之后更新數(shù)據(jù)仍然具有一定影響力。
#減少周期性波動
randIndex = int(np.random.uniform(0,len(dataIndex)))#go to 0 because of the constant
h = sigmoid(sum(dataMatrix[randIndex]*weights))
error = classLabels[randIndex] - h
weights = weights + alpha * error * dataMatrix[randIndex]
del(dataIndex[randIndex])
return weights
3 示例:從疝氣病癥預測病馬的死亡率
3.1 準備數(shù)據(jù):處理數(shù)據(jù)中的缺失值
- 處理缺失值的方法
- 使用可用特征的均值來填補缺失值;
- 使用特殊值來填補缺失值,如-1;
- 忽略有缺失值的樣本;
- 使用相似樣本的均值填補缺失值;
- 使用另外的機器學習算法預測缺失值。
- logistics缺失值的處理
- 所有的缺失值必須用一個實數(shù)值來替換,因為我們使用的NumPy數(shù)據(jù)類型不允許包含缺失值。這里選擇實數(shù)0來替換所有缺失值恰好能用于logistics回歸。
- 如果在測試數(shù)據(jù)集中發(fā)現(xiàn)了一條數(shù)據(jù)的類別標簽已經(jīng)缺失,最簡單的就是將該條數(shù)據(jù)丟棄。
3.2 測試算法:用Logistic回歸進行分類
- 使用logistics回歸方法進行分類
- 把測試集上每個特征向量乘以最優(yōu)化方法得來的回歸系數(shù);
- 將該乘積求和;
- 輸入到Sigmoid函數(shù)在中。
#以回歸系數(shù)于特征向量作為輸入來計算對應的Sigmoid值
def classifyVector(inX, weights):
prob = sigmoid(sum(inX*weights))
if prob > 0.5: return 1.0
else: return 0.0
#用于打開測試集和訓練集,并對數(shù)據(jù)進行格式化處理的函數(shù)
def colicTest():
frTrain = open('horseColicTraining.txt'); frTest = open('horseColicTest.txt')
trainingSet = []; trainingLabels = []
for line in frTrain.readlines():
currLine = line.strip().split('\t')
lineArr =[]
for i in range(21):
lineArr.append(float(currLine[i]))
trainingSet.append(lineArr)
trainingLabels.append(float(currLine[21]))
trainWeights = stocGradAscent1(np.array(trainingSet), trainingLabels, 1000)
errorCount = 0; numTestVec = 0.0
for line in frTest.readlines():
numTestVec += 1.0
currLine = line.strip().split('\t')
lineArr =[]
for i in range(21):
lineArr.append(float(currLine[i]))
if int(classifyVector(np.array(lineArr), trainWeights))!= int(currLine[21]):
errorCount += 1
errorRate = (float(errorCount)/numTestVec)
print ("the error rate of this test is: %f" % errorRate)
return errorRate
#用于調用函數(shù)colicTest()10次并求結果的平均值
def multiTest():
numTests = 10; errorSum=0.0
for k in range(numTests):
errorSum += colicTest()
print ("after %d iterations the average error rate is: %f" % (numTests, errorSum/float(numTests)))
- 測試
logRegres.multiTest()
the error rate of this test is: 0.343284
the error rate of this test is: 0.328358
the error rate of this test is: 0.313433
the error rate of this test is: 0.298507
the error rate of this test is: 0.358209
the error rate of this test is: 0.238806
the error rate of this test is: 0.298507
the error rate of this test is: 0.358209
the error rate of this test is: 0.283582
the error rate of this test is: 0.388060
after 10 iterations the average error rate is: 0.320896