天天看點

Python機器學習實戰之邏輯回歸

有關邏輯回歸模型的理論知識: 邏輯回歸模型(logistic regression)

簡要回顧一下邏輯回歸進行分類任務:邏輯回歸使用函數y = sigmoid(wx+b)  (通常把b包含在w向量内,直接寫成y = g(z),z = wx)。 對于輸入樣本xi,若yi>0.5則判讀為正例,否則為反例。

是以最重要的就是确認模型參數w。常用方法是寫出代價函數,使用梯度下降法,核心公式如下:

Python機器學習實戰之邏輯回歸

《機器學習實戰》代碼 書中為梯度上升法,與梯度下降法原理相同,前者向正梯度方向修改參數,用來求極大值。後者向負梯度方向修改參數,用來求極小值。 PS: 書中使用梯度上升法求解的原因是因為其梯度公式中為(y-h(x)),而不像上圖中為(h(x)-y),是以“-”号變正号,梯度下降變梯度上升。

(1)普通梯度上升法

def gradAscent(dataMatIn, classLabels):
    dataMatrix = mat(dataMatIn)             #轉換為numpy矩陣
    labelMat = mat(classLabels).transpose() #轉換為numpy矩陣并轉置
    m,n = shape(dataMatrix)
    alpha = 0.001     #更新步長
    maxCycles = 500   #最大更新次數
    weights = ones((n,1))
    for k in range(maxCycles):              
        h = sigmoid(dataMatrix*weights)     #邏輯回歸預測
        error = (labelMat - h)              #誤差,文中圖誤差為(h - labelMat)
        weights = weights + alpha * dataMatrix.transpose()* error
        #梯度更新公式(矩陣形式),和文中圖給出不同的就是差個-号
    return weights
           

用梯度上升法訓練資料:

import log_reg
dataArr,labelMat = log_reg.loadDataSet()
weights = log_reg.gradAscent(dataArr,labelMat)  #梯度上升算法
weights
matrix([[ 4.12414349],
        [ 0.48007329],
        [-0.6168482 ]])
log_reg.plotBestFit(weights.getA())   #繪制決策分界
           
Python機器學習實戰之邏輯回歸

(2)随機梯度上升法

從weights(或者叫theta)更新公式中可以看出,每一個weights更新都需要周遊所有樣本(1~m),當樣本資料巨大時(10^6以上),計算量是十分恐怖的,是以随機梯度法就是随機選取某一樣本計算梯度,計算量大大減少。

但很顯然,隻選擇一個樣本進行模型更新,模型會更加符合該樣本,而不一定符合所有樣本,是以更常用的做法是每次取出少量的資料樣本進行模型更新(例如16,32,64等,速度并不會比隻計算一個樣本慢太多)。 此外,在接近極值處,如果步長較大,可能出現反複振蕩,始終達不到要求的精度範圍,是以,還可以随着疊代次數的增加逐漸減小步長。

def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    m,n = shape(dataMatrix)
    weights = ones(n)   #全部初始化為1
    for j in range(numIter):
        dataIndex = range(m) #1~m随機數
        for i in range(m):
            alpha = 4/(1.0+j+i)+0.0001
            #步長逐漸減小,但不會等于0(等于0将無法更新)
            randIndex = int(random.uniform(0,len(dataIndex)))#從1~m中随機選取一個樣本
            h = sigmoid(sum(dataMatrix[randIndex]*weights))
            error = classLabels[randIndex] - h
            weights = weights + alpha * error * dataMatrix[randIndex]
            del(dataIndex[randIndex]) #已選過的樣本不會再選
    return weights
           

(3)分類函數 這個簡單,不多說了

def classifyVector(inX, weights):
    prob = sigmoid(sum(inX*weights))
    if prob > 0.5: return 1.0
    else: return 0.0
           

(4)分類實驗

預測患有‘疝’病的馬的存活問題(二分類任務),輸入的樣本資料(299*21),測試樣本為(67*21),使用所給函數預測錯誤率0.37,效果不太好,具體問題還是得畫學習曲線分析:機器學習模型評價

Python機器學習實戰之邏輯回歸

完整代碼

'''
Created on Oct 27, 2010
Logistic Regression Working Module
@author: Peter
'''
from numpy import *

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

def sigmoid(inX):
    return 1.0/(1+exp(-inX))

def gradAscent(dataMatIn, classLabels):
    dataMatrix = mat(dataMatIn)             #convert to NumPy matrix
    labelMat = mat(classLabels).transpose() #convert to NumPy matrix
    m,n = shape(dataMatrix)
    alpha = 0.001
    maxCycles = 500
    weights = 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

def plotBestFit(weights):
    import matplotlib.pyplot as plt
    dataMat,labelMat=loadDataSet()
    dataArr = array(dataMat)
    n = shape(dataArr)[0]
    xcord1 = []; ycord1 = []
    xcord2 = []; ycord2 = []
    for i in range(n):
        if int(labelMat[i])== 1:
            xcord1.append(dataArr[i,1]); ycord1.append(dataArr[i,2])
        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 = 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()

def stocGradAscent0(dataMatrix, classLabels):
    m,n = shape(dataMatrix)
    alpha = 0.01
    weights = 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

def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    m,n = shape(dataMatrix)
    weights = ones(n)   #initialize to all ones
    for j in range(numIter):
        dataIndex = range(m)
        for i in range(m):
            alpha = 4/(1.0+j+i)+0.0001    #apha decreases with iteration, does not
            randIndex = int(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

def classifyVector(inX, weights):
    prob = sigmoid(sum(inX*weights))
    if prob > 0.5: return 1.0
    else: return 0.0

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(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(array(lineArr), trainWeights))!= int(currLine[21]):
            errorCount += 1
    errorRate = (float(errorCount)/numTestVec)
    print "the error rate of this test is: %f" % errorRate
    return errorRate

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