## 1. 基于logistic回归和sigmoid函数的分类

``````import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-5,5,200)
y = 1./(1+np.exp(-x))

plt.figure()
plt.plot(x,y)
plt.xlabel('x')
plt.ylabel('sigmiod(x)')
plt.show()``````

![1]()

## 2. 基于最优化方法的最佳回归系数确定

sigmiod函数的输入记为z，公式：z = w0x0+w1x1+w2x2+...+wnxn (这里0，1，2，...,n都代表下标系数)，简单写就是 z = wTx （T代表转置）

![2]()

![3]()

### 2.2 训练算法 :使用梯度上升找到最佳参数

``````每个回归系数初始化为1

计算整个数据集的梯度

``````def loadDataSet():
dataMat = []; labelMat = []
fr = open('testSet.txt')
lineArr = line.strip().split()
dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])
labelMat.append(int(lineArr[2]))
return dataMat,labelMat

def sigmoid(inX):
return 1.0/(1+exp(-inX))

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)     #matrix mult
error = (labelMat - h)              #vector subtraction
weights = weights + alpha * dataMatrix.transpose()* error #matrix mult
return weights``````

![4]()

`cd 桌面/machinelearninginaction/Ch05`
/home/fangyang/桌面/machinelearninginaction/Ch05
`import logRegres`
`dataMat , labelMat = logRegres.loadDataSet()`
`logRegres.gradAscent(dataMat,labelMat)`

![5]()

### 2.3 分析数据：画出决策边界

``````def plotBestFit(weights):
import matplotlib.pyplot as plt
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.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()``````

`from numpy import *`
`weights = logRegres.gradAscent(dataMat,labelMat)`
`logRegres.plotBestFit(weights.getA()) # the function of getA is used to transform matrix into array`

![6]()

### 2.4 训练算法：随机梯度上升

``````所有回归系数初始化为 1

计算该样本的梯度

``````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 weights``````

`weights = logRegres.stocGradAscent0(array(dataMat),labelMat)`
`logRegres.plotBestFit(weights)`

![7]()

``````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)))
h = sigmoid(sum(dataMatrix[randIndex]*weights))
error = classLabels[randIndex] - h
weights = weights + alpha * error * dataMatrix[randIndex]
del(dataIndex[randIndex])
return weights``````

`weights = logRegres.stocGradAscent1(array(dataMat),labelMat)`
`logRegres.plotBestFit(weights)`

![8]()

## 3. 示例:从疝气病症预测病马的死亡率

### 3.1 准备数据：处理数据中的缺失值

• 使用可用特征的均值来填补缺失值;
• 使用特殊值来补缺失值,如 -1;
• 忽略有缺失值的样本;
• 使用相似样本的均值添补缺失值;
• 使用另外的机器学习算法预测缺失值。

### 3.2 测试算法 :用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('horseColicTraining.txt'); frTest = open('horseColicTest.txt')
trainingSet = []; trainingLabels = []
currLine = line.strip().split('\t')
lineArr =[]
for i in range(21):
lineArr.append(float(currLine[i]))
trainingSet.append(lineArr)
trainingLabels.append(float(currLine[21]))
errorCount = 0; numTestVec = 0.0
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.0
for k in range(numTests):
errorSum += colicTest()
print "after %d iterations the average error rate is: %f" % (numTests, errorSum/float(numTests))``````

`logRegres.multiTest()`

![9]()

## 小结

1. logistic回归的目的是寻找一个非线性函数sigmiod的最佳拟合参数,求解过程可以由最优化算法来完成。在最优化算法中,最常用的就是梯度上升算法, 而梯度上升算法又可以简化为随机梯度上升算法。

2. 随机梯度上升算法与梯度上升算法的效果相当, 但占用更少的计算资源。此 外 ,随机梯度上升是一个在线算法, 它可以在新数据到来时就完成参数更新, 而不需要重新读取整个数据集来进行批处理运算。