logistic回归预测病马死亡率

Posted Aaron12

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了logistic回归预测病马死亡率相关的知识,希望对你有一定的参考价值。

logistic回归实现预测病马死亡率

python3已经实现 代码还在更新中 写完全部注释以后在贴上来

# -*- coding: 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
#定义sigmoid函数
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):              #循环500次
        h = sigmoid(dataMatrix*weights)     #向量相乘 h也是向量
        error = (labelMat - h)              #向量相减
        weights = weights + alpha * dataMatrix.transpose()* error #调整回归系数
    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)  #出初始回归系数
    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 = list(range(m))#此处注意Python2和python3的区别
        for i in range(m):
            alpha = 4/(1.0+j+i)+0.0001    #动态调整步长
            randIndex = int(random.uniform(0,len(dataIndex)))#随机选取样本
            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;
    for k in range(numTests):
        errorSum+=colicTest()
    print (after %d iterations the average error rate is: %f  %(numTests,errorSum/float(numTests)))

 结果如下:

the error rate of this test is: 0.313433
the error rate of this test is: 0.358209
the error rate of this test is: 0.358209
the error rate of this test is: 0.402985
the error rate of this test is: 0.253731
the error rate of this test is: 0.417910
the error rate of this test is: 0.283582
the error rate of this test is: 0.283582
the error rate of this test is: 0.328358
the error rate of this test is: 0.417910
after 10 iterations the average error rate is: 0.341791 

考虑到数据缺失问题,这个结果并不差

 

注意几个方法和概念

分类函数,梯度上升法,随机梯度上升法,改进的随机梯度上升法

以上是关于logistic回归预测病马死亡率的主要内容,如果未能解决你的问题,请参考以下文章

《机器学习实战》之逻辑回归--基于Python3--02

《机器学习实战》之逻辑回归--基于Python3--01

R语言广义线性模型Logistic回归模型C Statistics计算

[机器学习实战-Logistic回归]使用Logistic回归预测各种实例

如何解读logistic回归分析

R语言广义线性模型Logistic回归案例代码