Logistic回归
Sigmod函数:Б(z) = 1/(1+exp(-z)) 具有可以输出0或者1的性质。
Logistic回归:任何大于0.5的数据被分为1类,小于0.5即被归为0类,所以,Logistic回归也可以被看成是一种概率估计。
import numpy as np
import matplotlib.pyplot as pp
%matplotlib inline
z = np.linspace(-60,60,10000)
y = 1/(1+np.exp(-1*z))
pp.plot(z,y)
[<matplotlib.lines.Line2D at 0x14ec0c5f9b0>]
一、基于最优化方法的最佳回归系数确定
1. 梯度上升法
最佳回归系数的确定:
z = w0*x0+w1*x1+w2*x2+...+wn*xn = W^T*X
梯度上升法的迭代公式::
w:=w+α*(f(w)的对每个w的偏导)
2. 训练算法:使用梯度上升找到最佳参数
# Logistic回归梯度上升优化算法
def loadDataSet():
dataMat = []
labelMat = []
fr = open('data/testSet.txt')
for line in fr.readlines():
lineArr = line.strip().split()
dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])]) # x0 = 1.0
labelMat.append(int(lineArr[2]))
fr.close()
return dataMat, labelMat
def sigmoid(inX):
return (1.0/(1+np.exp(-inX)))
def gradAscent(dataMatIn, classLabels):
dataMatrix = np.mat(dataMatIn) # 100*3
labelMat = np.mat(classLabels).transpose() # 1*100
m, n = np.shape(dataMatrix)
alpha = 0.001 # step
maxCycles = 500 # times
weights = np.ones((n,1)) # 3*1
for k in range(maxCycles):
h = sigmoid(dataMatrix*weights) # 100*1
error = (labelMat - h)
weights = weights + alpha * dataMatrix.transpose()*error # 按照该差值的方向调整回归系数
return weights
dataArr, labelMat = loadDataSet()
gradAscent(dataArr, labelMat)
matrix([[ 4.12414349],
[ 0.48007329],
[-0.6168482 ]])
3. 分析数据:画出决策边界
# 画出数据集和Logistic回归最佳拟合直线的函数
def plotBestFit(weights):
dataMat, labelMat = loadDataSet()
dataArr = np.array(dataMat)
n = np.shape(dataMat)[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 = pp.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, 3.0, 0.1)
y = (-weights[0]-weights[1]*x)/weights[2] # w0x0+w1x1+w2x2=0
ax.plot(x,y)
pp.xlabel('X1'); pp.ylabel('X2')
pp.show()
weights = gradAscent(dataArr, labelMat)
plotBestFit(weights.getA())
4. 训练算法:随机梯度上升
- 梯度上升算法每次更新回归系数时都需要遍历整个数据集。
- 改进方法是一次仅用一个样本点来更新回归系数,即随机梯度上升算法。
- 前一种成为“批处理”,随机梯度上升算法可以在新样本到来时对分类器进行增量式更新,是“在线学习”算法。
# 随机梯度上升算法
def stocGradAscent0(dataMatrix, classLabels):
m, n = np.shape(dataMatrix) # 100x3
alpha = 0.01
weights = np.ones(n) # 1x3 p.s.np.ones((3,1))为3x1
for i in range(m):
h = sigmoid(sum(dataMatrix[i]*weights)) # 标量
error = classLabels[i] - h
weights = weights + alpha*error*dataMatrix[i]
return weights
dataArr, labelMat = loadDataSet()
weights = stocGradAscent0(np.array(dataArr), labelMat)
plotBestFit(weights)
一个判断优化算法优劣的可靠方法是看它是否收敛。
#在整个数据集上运行200次
def stocGradAscent0_200(dataMatrix, classLabels):
m, n = np.shape(dataMatrix) # 100x3
alpha = 0.01
weights = np.ones(n) # 1x3 p.s.np.ones((3,1))为3x1
weights_all = []
for times in range(200):
for i in range(m):
h = sigmoid(sum(dataMatrix[i]*weights)) # 标量
error = classLabels[i] - h
weights = weights + alpha*error*dataMatrix[i]
#print(weights)
weights_all.append(weights)
return weights,weights_all
dataArr, labelMat = loadDataSet()
weights, weights_all = stocGradAscent0_200(np.array(dataArr), labelMat)
len(weights_all)
20000
x0 = []; x1 = []; x2 = []
for i in range(len(weights_all)):
x0.append(float(list(weights_all[i])[0]))
x1.append(float(list(weights_all[i])[1]))
x2.append(float(list(weights_all[i])[2]))
X = np.linspace(0,200,20000,endpoint=True)
fig = pp.subplot(311)
pp.plot(X,x0)
fig = pp.subplot(312)
pp.plot(X,x1)
fig = pp.subplot(313)
pp.plot(X,x2)
[<matplotlib.lines.Line2D at 0x14ec15c1eb8>]
与书上的图不太一样
x1只经过了50次迭代就达到了稳定值,但x0,x2需要更多次的迭代。另外,在大的波动停止后,还有一些小的周期性波动。
产生这种现象的原因是存在一些不能正确分类的样本点(数据集并非线性可分),在每次迭代时会引发系数的剧烈改动。
我们期望算法能避免来回波动,从而收敛到某个值。
plotBestFit(weights)
# 改进的随机梯度上升算法
def stocGradAscent1(dataMatrix, classLabels, numIter=150):
m, n = np.shape(dataMatrix)
weights = np.ones(n)
weights_all = []
for j in range(numIter):
dataIndex = list(range(m))
for i in range(m):
alpha = 4/(1.0+j+i)+0.01 # 会随着迭代次数不断减少,当j<<max(i),alpha就不是严格下降的(类似于模拟退火算法)
randIndex = int(np.random.uniform(0,len(dataIndex)))
h = sigmoid(sum(dataMatrix[randIndex]*weights))
error = classLabels[randIndex] - h
weights = weights + alpha * error * dataMatrix[randIndex]
weights_all.append(weights)
del(dataIndex[randIndex])
return weights, weights_all
dataArr, labelMat = loadDataSet()
weights, weights_all = stocGradAscent1(np.array(dataArr), labelMat)
x0 = []; x1 = []; x2 = []
for i in range(len(weights_all)):
x0.append(float(list(weights_all[i])[0]))
x1.append(float(list(weights_all[i])[1]))
x2.append(float(list(weights_all[i])[2]))
X = np.linspace(0,4000,len(weights_all),endpoint=True)
fig = pp.subplot(311)
pp.plot(X,x0)
fig = pp.subplot(312)
pp.plot(X,x1)
fig = pp.subplot(313)
pp.plot(X,x2)
[<matplotlib.lines.Line2D at 0x14ec11626d8>]
- 没有周期性波动,归功于样本随机选择机制
- 水平轴短了很多,归功于alpha,可以收敛得更快。?
plotBestFit(weights)
二、示例:从疝气病症预测病马的死亡率
1. 准备数据:处理数据中的缺失值
- 使用可用特征的均值来填补缺失值
- 使用特殊值来填补缺失值,如-1
- 忽略有缺失值的样本
- 使用相似样本的均值填补缺失值
- 使用另外的机器学习算法预测缺失值
本例选择使用实数0来替换缺失值
- 恰好能适用于Logistic回归,因为在更新时不会影响系数的值weights = weights+alpha*error*dataMatrix[randIndex]
- sigmoid(0) = 0.5,即对结果不具有任何倾向性。
如果在测试数据集中发现了一条数据的类别标签已经缺失,简单做法是丢弃
这是因为类别标签和特征不同,很难找到合适的值来替换。
2. 测试算法:用Logistic回归进行分类
# Logistic回归分类函数
def classifyVector(inX, weights):
prob = sigmoid(sum(inX*weights))
if prob > 0.5: return 1.0
else: return 0.0
def colicTest():
frTrain = open('data/horseColicTraining.txt')
frTest = open('data/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,trainWeights_all = stocGradAscent1(np.array(trainingSet), trainingLabels, 500)
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)))
multiTest()
C:\Users\daigz\Anaconda3\lib\site-packages\ipykernel_launcher.py:2: RuntimeWarning: overflow encountered in exp
the error rate of this test is: 0.328358
the error rate of this test is: 0.373134
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.313433
the error rate of this test is: 0.343284
the error rate of this test is: 0.402985
the error rate of this test is: 0.402985
the error rate of this test is: 0.417910
the error rate of this test is: 0.492537
after 10 iterations the average error rate is: 0.374627