Logistic回归简介

算法,机器学习 2016-01-27

  参考:Logistic回归

  Logister回归是一种最优化算法,所谓回归就是假设你有一些数据点,用一条直线对它们进行拟合,这个拟合过程就是回归。   基于梯度上升的最优化方法,梯度上升的思想就是找到某函数的最大值,最好的函数沿该函数的梯度方向探寻。详细解释可以看wiki百科:参考链接。    为了便于理解,可以看下图    2.png

        路径是沿‘最弯曲处’前进

      具体实现,数据下载 testSet.txt

#ecoding:utf-8

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)             #转换为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)              #矢量减法
        weights = weights + alpha * dataMatrix.transpose()* error #matrix mult
    return weights

#画出数据集和Logister回归最佳拟合直线的函数(图二)

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)   #初始化
    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)   #初始化
    for j in range(numIter):
        dataIndex = range(m)
        for i in range(m):
            alpha = 4/(1.0+j+i)+0.0001    #apha每次迭代时调整 
            randIndex = int(random.uniform(0,len(dataIndex))) #常量为0
            h = sigmoid(sum(dataMatrix[randIndex]*weights))
            error = classLabels[randIndex] - h
            weights = weights + alpha * error * dataMatrix[randIndex]
            del(dataIndex[randIndex])
    return weights

       1.png

          图一

       3.png              图二

       4.png

          图三

     应用:

      从疝气病预测病马的死亡率,数据处理后保存为horseColicTest.txt && horseColicTraining.txt,对于缺失数据用0代替。

   #Logister回归分类测试,用到horseColicTraining.txt和horseColicTest.txt

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

    Logistic回归的基本实现如上,图形的表示代码就不给出了。


本文由 Tony 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

赏个馒头吧