相关函数:
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])]) #前面的一个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)) #拟合系数全部初始化为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): #画LR最佳拟合直线
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()
测试代码:
import logRegres
dataArr, labelArr = logRegres.loadDataSet()
print logRegres.gradAscent(dataArr, labelArr)
#画出数据集和LR回归最佳拟合直线
from numpy import *
weights = logRegres.gradAscent(dataArr,labelArr)
logRegres.plotBestFit(weights.getA()) #getA()函数与mat()函数的功能相反,是将一个numpy矩阵转换为数组
#作用可查看http://blog.csdn.net/douya2016/article/details/78161890?locationNum=5&fps=1
结果:
[[ 4.12414349]
[ 0.48007329]
[-0.6168482 ]]
随机梯度上升
stocGradAscent0
函数
def stocGradAscent0(dataMatrix, classLabels):
m,n = shape(dataMatrix) #m是样本个数
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
测试代码
import logRegres
from numpy import *
dataArr, labelArr = logRegres.loadDataSet()
weights = logRegres.stocGradAscent0(array(dataArr),labelArr)
logRegres.plotBestFit(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 go to 0 because of the constant
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
测试代码
#随机梯度上升
import logRegres
from numpy import *
dataArr, labelArr = logRegres.loadDataSet()
weights = logRegres.stocGradAscent0(array(dataArr),labelArr)
logRegres.plotBestFit(weights)
#改进的随机梯度上升算法
NEWweights = logRegres.stocGradAscent1(array(dataArr),labelArr)
logRegres.plotBestFit(NEWweights)
结果
效果和基于梯度上升算法的LR差不多,但随机梯度上升算法的计算量更少了
函数
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(): #10次求平均
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))
测试代码
import logRegres
logRegres.multiTest()
结果:
the error rate of this test is: 0.328358
the error rate of this test is: 0.268657
the error rate of this test is: 0.432836
the error rate of this test is: 0.283582
the error rate of this test is: 0.343284
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.313433
the error rate of this test is: 0.402985
the error rate of this test is: 0.417910
after 10 iterations the average error rate is: 0.335821