Logistic 回归主要用于分类情况,我有一堆数据,我想从某种角度或者按照他们某个特征,分成两类。于是引入分类函数。
如下,我有一堆数据点,
最终我将他们分成活跃的和非活跃的,黑线左边为非活跃的数据,黑线右边为活跃的数据,这条黑线就是目标拟合线,他用来划分将来的某个数据点应该属于左边的非活跃数据点,还是右边的活跃数据点。
用比较理论的语言就是
利用Logistic回归进行分类的主要思想是,根据现有数据对分类边界线建立回归公式,以此进行分类。
流程基本是这样的:
如何找到一个函数,无论x如何变化,y集中在0和1呢?
引入单位阶跃函数,sigmond 函数,
公式为
函数曲线为
可以看出当,z范围越大,阶跃函数分类的性质就会越明显。于是如何让z取得最大值,是分类成功或者失败的保障。
梯度上升算法,是取Z最高值的经典方法。
具体可以采用批量梯度上升算法和随机梯度上升算法
具体的流程如下,最终效果,在更迭学习速率,并且优化随机向量的基础上,计算速率大大提高了。
批量梯度下降python实现
import pandas as pd
import numpy as np
from numpy import *
def loadDataSet():
dataMat = [];
labelMat = [];
fr = open('test.txt')
for line in fr.readlines():
lineArr = line.strip().split()
dataMat.append([1.0,float(lineArr[0]),float(lineArr[1])])
#读取数据,dataMat最左侧加一列
labelMat.append(float(lineArr[2]))
#数据的最后一列是训练集的判定,y
return dataMat,labelMat
def sigmoid(inX):
return 1.0/(1+np.exp(-inX))
def gradAscent(dataMatIn,classLabels):
#转换成矩阵类型
dataMatrix = np.mat(dataMatIn)
labelMat = np.mat(classLabels).transpose()
m,n=np.shape(dataMatrix)
alpha = 0.0001
maxCycles = 50
weights = ones((n,1))
for k in range(maxCycles):
h=sigmoid(dataMatrix*weights)
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)
#labelMat = array(labelMat)
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=w0x0+w1x1+w2x2
w0=weights[0]
w1=weights[1]
w2=weights[2]
y=(w0+w1*x)/w2
ax.plot(x,y)
plt.xlabel('X1');
plt.ylabel('X2');
plt.show()
dataArr,labelMat=loadDataSet()
weights = gradAscent(dataArr,labelMat)
print(weights[1])
plotBestFit(weights.getA())
#将weights以array方式输入
效果如下
随机梯度上升算法
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
dataArr,labelMat=loadDataSet()
weights = stocGradAscent0(array(dataArr),labelMat)
print(weights[1])
plotBestFit(weights)
#将weights以array方式输入
效果如下
改进的随机梯度上升算法
def stocGradAscent1(dataMatrix,classLabels,numIter=150):
m,n= shape(dataMatrix)
weights = ones(n)
for j in range(numIter):
dataIndex = list(range(m))
#print(dataIndex)
for i in range(m):
alpha = 4/(1.0+j+i)+0.01
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
dataArr,labelMat=loadDataSet()
weights = stocGradAscent1(array(dataArr),labelMat)
#print(weights[1])
plotBestFit(weights)
#将weights以array方式输入
效果如下