用途:分类问题
假设函数:
我们就是要通过训练样本来确定theta的取值
z=Theta^t*x在样本的图像上即是分类的分界曲线,即求得theta就可以判断实验样本的分类
theta^*x表示边界图像
代价函数:
一般来说代价函数为误差的平方和
但对于h(x)误差的平方和为非凸函数所以
将其写成一个式子:
通过梯度下降算法求theta:
代码:
1 | from numpy import * |
def stocGradAscent0(dataMatrix,classLabels):
#注意这里的dataMatrix是array数组不是矩阵
m,n=shape(dataMatrix)
alpha=0.01
weight=ones(n)
for i in range(m):
error=classLabels[i]-sigmoid(sum(weightdataMatrix[i]))
weight=weight+erroralpha*dataMatrix[i]
return weight
1 |
|
def stocGradAscent1(dataMatrix,classLabels,numIter=150):
m,n=shape(dataMatrix)
weight=ones(n)
for i in range(numIter):
dataIndex=range(m)
for j in range(m):
alpha=4.0/(1.0+i+j)
randIndex=int(random.uniform(0,len(dataIndex)))
error=classLabels[randIndex]-sigmoid(sum(weightdataMatrix[randIndex]))
weight=weight+alphaerror*dataMatrix[randIndex]
return weight
1 |
|
from logRegres import *
def classifyVector(inX,weight):
prob=sigmoid(sum(inX*weight))
if prob>0.5:return 1.0
else: return 0.0
def colicTest():
trainLabels =[]
trainSet=[]
with open(‘horseColicTraining.txt’) as frTrian:
for line in frTrian.readlines():
currLine=line.strip().split(‘\t’)
n=int(len(currLine))-1
Arr=[float(i) for i in currLine[0:n]]
trainSet.append(Arr)
trainLabels.append(float(currLine[-1]))
trianWeights=stocGradAscent1(array(trainSet),trainLabels,1000)
with open('horseColicTest.txt') as frTest:
lineArr=[]
errorCount=0.0
numTestVect = 0.0
for line in frTest.readlines():
numTestVect+=1
currline=line.strip().split('\t')
Arr=[float(i) for i in currline[0:len(currline)-1]]
lineArr.append(Arr)
if int(classifyVector(array(lineArr),trianWeights))!=int(currline[-1]):
errorCount+=1
errorRate=float(errorCount)/float(numTestVect)
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()`
注:1.书上读取文件时写的代码比较繁琐,自己简化了一下。
注在用切片时想进行类型转换:Arr=[float(i) for i in currline[0:len(currline)-1]]
2.在随机梯度增加时 有一句del(dataIndex[randIndex])在python3中出错,应该将dataIndex=rand(m)改为dataIndex=list(rand(m)),这样更改之后错误率明显上升,个人理解这个语句的作用应该是删除已经被删选过的数据,避免重复选择一些数据进行学习,但是为什么效果更差了很奇怪,待解决