1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
| # -*- coding: utf-8 -*-
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])])
labelMat.append(int(lineArr[2]))
return dataMat,labelMat
#计算sigmoid函数
def sigmoid(inX):
return 1.0/(1+exp(-inX))
#梯度上升算法-计算回归系数
def gradAscent(dataMatIn, classLabels):
dataMatrix = mat(dataMatIn) #转换为numpy数据类型
labelMat = mat(classLabels).transpose()
m,n = shape(dataMatrix)
alpha = 0.01
maxCycles = 500
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(wei):
import matplotlib.pyplot as plt
weights = wei.getA()
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()
#随机梯度上升算法
def stocGradAscent0(dataMatrix, classLabels,numInter = 150):
dataMatrix = array(dataMatrix)
m,n = shape(dataMatrix)
alpha = 0.1
weights = ones(n)
for j in range(numInter):
for i in range(m):
h = sigmoid(sum(dataMatrix[i] * weights))
error = classLabels[i] - h
weights = weights + alpha * error * dataMatrix[i]
return weights
#改进的随机梯度上升算法
def stocGradAscent1(dataMatrix, classLabels, numInter = 150):
dataMatrix = array(dataMatrix)
m,n = shape(dataMatrix)
weights = ones(n)
for j in range(numInter):
dataIndex = range(m)
for i in range(m):
alpha = 4 / (1.0+j+i) + 0.01 #alpha值每次迭代时都进行调整
randIndex = int(random.uniform(0, len(dataIndex))) #随机选取更新
h = sigmoid(sum(dataMatrix[randIndex] * weights))
error = classLabels[randIndex] - h
#print "alpha:"+ str(alpha) + "\trandIndex:" + str(randIndex) + "\th:" + str(h),
#print "\terror:" + str(error)
#weights = weights + alpha * error * dataMatrix[randIndex]
mlambda = 10
weights = weights*(1-alpha*(mlambda/m)) + alpha * error * dataMatrix[randIndex]
del[dataIndex[randIndex]]
return weights
#案例-从疝气病症预测病马的死亡率
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(trainingSet, trainingLabels, 10)
#trainWeights = stocGradAscent0(trainingSet, trainingLabels,5000)
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)
return (errorRate,trainWeights)
def multiTest():
numTests = 6000;errorSum = 0.0
min_error = 1
for k in range(numTests):
(er,wt) = colicTest()
errorSum += er
if er < min_error :
min_error = er
print "er:%f,wt:%s"%(er,str(wt))
print 'after %d iterations the mini error rate is: %f' %(numTests, min_error)
def trainRight():
myWeights = [8.19655178, 11.12727104 , 9.85693272, -3.77115778 , 0.4234126,
-7.12006621 , -9.03044278, -15.09789776 ,-2.62982192 ,-16.55003638,
-2.37763633 ,-14.36786141 , 18.78190262 , 0.37877785 , -8.16171466,
15.0932786, -8.45941768, -0.38117651 , 2.02203557 , -8.77960815,
-3.62265693]
frTrain = open('horseColicTraining.txt')
trainingSet = []; trainingLabels = []
errorCount = 0; numTestVec = 0.0
for line in frTrain.readlines():
numTestVec += 1.0
currLine = line.strip().split('\t')
lineArr =[]
for i in range(21):
lineArr.append(float(currLine[i]))
trainingSet.append(lineArr)
trainingLabels.append(float(currLine[21]))
if classifyVector(array(lineArr), myWeights) - float(currLine[21]) != 0:
errorCount += 1
print 'Right:'+str(1-(float(errorCount)/numTestVec))
#plotBestFit()
#colicTest()
multiTest()
#trainRight()
|