Logistic 梯度法进行分类

梯度上升法,求最大似然函数,见http://sbp810050504.blog.51cto.com/2799422/1608064/

梯度下降,最小二乘法结果一样,h=W'X,W=W+alfa*X'*(y-h)或者W=W+alfa*(y-h)*Xi 随机梯度法

# coding=utf-8 #

import numpy as np


def loadDataSet():
    dataMat = []; labelMat = []
    fr = open(r'C:\Users\li\Downloads\machinelearninginaction\Ch05\testSet.txt')
    for line in fr.readlines():
        lineArr = line.strip().split()
        dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])]) #list:[[x0,x1,x2],...] list
        labelMat.append(int(lineArr[2]))
    return dataMat,labelMat


def sigmoid(inX):
    return 1.0/(1+np.exp(-inX)) #overflow encountered in exp


def gradAscent(dataMatIn, classLabels):
    dataMatrix = np.mat(dataMatIn)             #convert to NumPy matrix mXn
    labelMat = np.mat(classLabels).transpose() #convert to NumPy matrix mX1
    m,n = np.shape(dataMatrix)
    alpha = 0.001
    maxCycles = 500
    weights = np.ones((n,1))                #w matrix nX1
    for k in range(maxCycles):              #heavy on matrix operations
        h = sigmoid(dataMatrix*weights)     #matrix mult h mX1
        error = (labelMat - h)              #vector subtraction (y-h) mX1
        weights = weights + alpha * dataMatrix.transpose()* error #matrix mult w=w+alfa*X'*(y-h)
    return weights


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):
        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 = np.arange(-3.0, 4.0, 1)
    y = (-weights[0]-weights[1]*x)/weights[2] # super line:w0*1+w1*x1+w2*x2=0
    ax.plot(x, y.T)                      #x array 7 [],y array 1X7[[]]:?y.T array 7X1
    plt.xlabel('X1'); plt.ylabel('X2');
    plt.show()


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 * np.array(dataMatrix[i]) #calculate only for new data,not for all data
    return weights


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 dataIndex:
            alpha = 4/(1.0+j+i)+0.01    #apha decreases with iteration, does not go to 0 because of the constant
            randIndex = int(np.random.uniform(0,len(dataIndex)))#随机选择样本进行W值计算
            h = sigmoid(sum(dataMatrix[randIndex]*weights))
            error = classLabels[randIndex] - h
            weights = weights + alpha * error * np.array(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(r'C:\Users\li\Downloads\machinelearninginaction\Ch05\horseColicTraining.txt')
    frTest = open(r'C:\Users\li\Downloads\machinelearninginaction\Ch05\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


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)))
    
dataMat,labelMat=loadDataSet()


print(dataMat,labelMat)
#weights=gradAscent(dataMat, labelMat)
#weights=stocGradAscent0(dataMat, labelMat)
weights=stocGradAscent1(dataMat, labelMat, 200)
print(weights)
plotBestFit(weights)
multiTest()        




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值