机器学习——Logistic回归

来源:互联网 发布:用友进销存软件优缺点 编辑:程序博客网 时间:2024/05/20 04:09

前言

(1)Sigmoid函数和Logisitic回归分类器

(2)最优化理论初步

(3)梯度下降最优化算法

(4)数据中缺失项处理

利用Logistic回归进行分类的主要思想是:根据现有数据对分类边界线建立回归公式,以此进行分类。

这里的“回归”一词源于最佳拟合,表示要找到最佳拟合参数集。

训练分类器时的做法就是寻找最佳拟合参数,使用的是最优算法。

Logistic回归的一般过程

(1)收集数据:采用任意方法收集数据。

(2)准备数据:由于需要进行距离计算,因此要求数据类型为数值型。另外,结构化数据格式则最佳。

(3)分析数据:采用任意方法对数据进行分析;

(4)训练算法:大部分时间将用于训练,训练的目的是为了找到最佳的分类回归系数;

(5)测试算法:一旦训练步骤完成,分类将会很快。

(6)使用算法:首先,我们需要输入一些数据,并将其转换成对应的结构haul数值;

接着,基于训练好的回归系数就可以对这些数值进行简单的回归计算,判定它们属于哪个类别;在这之后,我们就可以在输出的类别上做一些其他方面的工作。

基于Logistic回归和Sigmoid函数的分类

任何大于0.5的数据被分入1类,小于0.5的数据被分入0类,Logistic回归也可以被看成一种概率估计。

(随着x的增大,对应的Sigmoid值将逼近于1;随着x的减小,Sigmoid值将逼近于0)

# -*- coding: utf-8 -*-__author__ = 'Mouse'from math import expfrom numpy import *def loadDataSet():    dataMat = []; labelMat = []    fr = open('testSet.txt')    for line in fr.readlines():        lineArr = line.strip().split()        #为了方便计算将X0的值设为1.0        dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])        labelMat.append(int(lineArr[2])) # 类别标签    print dataMat    return dataMat, labelMatdef 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)     #计算假设函数h        error = (labelMat - h)              #类标签和假设函数误差        weights = weights + alpha * dataMatrix.transpose()* error #对weight进行迭代更新    return weightsdef plotBestFit(wei):    import matplotlib.pyplot as plt    weights = wei.getA()    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) #x的范围    # 设定直线w0x0+w1x1+w2x2=0    y = (-weights[0]-weights[1]*x)/weights[2]    ax.plot(x, y)    plt.xlabel('X1');plt.ylabel('X2');    plt.show()if __name__ == '__main__':    dataArr, labelMat = loadDataSet()    weights = gradAscent(dataArr, labelMat)    plotBestFit(weights)

对梯度上升的算法进行改进

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 weightsdef 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
使用Logistic回归估计病马的死亡率

(1)收集数据:给定数据文件

(2)准备数据:用Python解析文本并填充缺失值

(3)分析数据:可视化并观察数据

(4)训练算法:使用优化算法,找到最佳的系数。

(5)测试算法:为了量化回归的效果,需要观察错误率。根据错误率决定是否回退到训练阶段,通过改变迭代的次数和步长等参数来得到更好的回归系数。

准备数据:处理数据中的缺失值

方法一、使用可用特征的均值来填补缺失值

方法二、使用特殊值李填充缺失值,如-1

方法三、忽略有缺失值的样本

方法四、使用相似样本的均值添补缺失值

方法五、使用另外的机器学习算法预测缺失值

# -*- coding: utf-8 -*-__author__ = 'Mouse'from math import expfrom numpy import *def loadDataSet():    dataMat = []; labelMat = []    fr = open('testSet.txt')    for line in fr.readlines():        lineArr = line.strip().split()        #为了方便计算将X0的值设为1.0        dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])        labelMat.append(int(lineArr[2])) # 类别标签    print dataMat    return dataMat, labelMatdef 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)     #计算假设函数h        error = (labelMat - h)              #类标签和假设函数误差        weights = weights + alpha * dataMatrix.transpose()* error #对weight进行迭代更新    return weightsdef 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 weightsdef plotBestFit(wei):    import matplotlib.pyplot as plt    weights = wei.getA()    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) #x的范围    # 设定直线w0x0+w1x1+w2x2=0    y = (-weights[0]-weights[1]*x)/weights[2]    ax.plot(x, y)    plt.xlabel('X1');plt.ylabel('X2');    plt.show()def plotBestFit2(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 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 weightsdef classifyVector(inX, weights):    prob = sigmoid(sum(inX*weights))    if prob > 0.5: return 1.0    else: return 0.0def 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 errorRatedef 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))if __name__ == '__main__':    # dataArr, labelMat = loadDataSet()    # #weights = gradAscent(dataArr, labelMat)    # weights2 = stocGradAscent0(array(dataArr), labelMat)    # plotBestFit2(weights2)    multiTest()
测试结果:

the error rate of this test is: 0.402985the error rate of this test is: 0.417910the error rate of this test is: 0.417910the error rate of this test is: 0.373134the error rate of this test is: 0.238806the error rate of this test is: 0.373134the error rate of this test is: 0.373134the error rate of this test is: 0.388060the error rate of this test is: 0.432836the error rate of this test is: 0.313433after 10 iterations the average error rate is: 0.373134


0 1
原创粉丝点击