Skip to content

Commit 248721f

Browse files
添加了SVM无核函数的,注释参考有有核函数的-纯无核函数测试
1 parent c413c5f commit 248721f

2 files changed

Lines changed: 0 additions & 236 deletions

File tree

src/python/6.SVM/svm-complete.py

Lines changed: 0 additions & 120 deletions
Original file line numberDiff line numberDiff line change
@@ -531,123 +531,3 @@ def testDigits(kTup=('rbf', 10)):
531531
predict = kernelEval.T * multiply(labelSV, alphas[svInd]) + b
532532
if sign(predict) != sign(labelArr[i]): errorCount += 1
533533
print("the test error rate is: %f" % (float(errorCount) / m))
534-
535-
536-
'''#######********************************
537-
Non-Kernel VErsions below
538-
''' #######********************************
539-
540-
541-
class optStructK:
542-
def __init__(self, dataMatIn, classLabels, C, toler): # Initialize the structure with the parameters
543-
self.X = dataMatIn
544-
self.labelMat = classLabels
545-
self.C = C
546-
self.tol = toler
547-
self.m = shape(dataMatIn)[0]
548-
self.alphas = mat(zeros((self.m, 1)))
549-
self.b = 0
550-
self.eCache = mat(zeros((self.m, 2))) # first column is valid flag
551-
552-
553-
def calcEkK(oS, k):
554-
fXk = float(multiply(oS.alphas, oS.labelMat).T * (oS.X * oS.X[k, :].T)) + oS.b
555-
Ek = fXk - float(oS.labelMat[k])
556-
return Ek
557-
558-
559-
def selectJK(i, oS, Ei): # this is the second choice -heurstic, and calcs Ej
560-
maxK = -1
561-
maxDeltaE = 0
562-
Ej = 0
563-
oS.eCache[i] = [1, Ei] # set valid #choose the alpha that gives the maximum delta E
564-
validEcacheList = nonzero(oS.eCache[:, 0].A)[0]
565-
if (len(validEcacheList)) > 1:
566-
for k in validEcacheList: # loop through valid Ecache values and find the one that maximizes delta E
567-
if k == i: continue # don't calc for i, waste of time
568-
Ek = calcEk(oS, k)
569-
deltaE = abs(Ei - Ek)
570-
if (deltaE > maxDeltaE):
571-
maxK = k
572-
maxDeltaE = deltaE
573-
Ej = Ek
574-
return maxK, Ej
575-
else: # in this case (first time around) we don't have any valid eCache values
576-
j = selectJrand(i, oS.m)
577-
Ej = calcEk(oS, j)
578-
return j, Ej
579-
580-
581-
def updateEkK(oS, k): # after any alpha has changed update the new value in the cache
582-
Ek = calcEk(oS, k)
583-
oS.eCache[k] = [1, Ek]
584-
585-
586-
def innerLK(i, oS):
587-
Ei = calcEk(oS, i)
588-
if ((oS.labelMat[i] * Ei < -oS.tol) and (oS.alphas[i] < oS.C)) or (
589-
(oS.labelMat[i] * Ei > oS.tol) and (oS.alphas[i] > 0)):
590-
j, Ej = selectJ(i, oS, Ei) # this has been changed from selectJrand
591-
alphaIold = oS.alphas[i].copy()
592-
alphaJold = oS.alphas[j].copy()
593-
if (oS.labelMat[i] != oS.labelMat[j]):
594-
L = max(0, oS.alphas[j] - oS.alphas[i])
595-
H = min(oS.C, oS.C + oS.alphas[j] - oS.alphas[i])
596-
else:
597-
L = max(0, oS.alphas[j] + oS.alphas[i] - oS.C)
598-
H = min(oS.C, oS.alphas[j] + oS.alphas[i])
599-
if L == H:
600-
print("L==H")
601-
return 0
602-
eta = 2.0 * oS.X[i, :] * oS.X[j, :].T - oS.X[i, :] * oS.X[i, :].T - oS.X[j, :] * oS.X[j, :].T
603-
if eta >= 0:
604-
print("eta>=0")
605-
return 0
606-
oS.alphas[j] -= oS.labelMat[j] * (Ei - Ej) / eta
607-
oS.alphas[j] = clipAlpha(oS.alphas[j], H, L)
608-
updateEk(oS, j) # added this for the Ecache
609-
if (abs(oS.alphas[j] - alphaJold) < 0.00001):
610-
print("j not moving enough")
611-
return 0
612-
oS.alphas[i] += oS.labelMat[j] * oS.labelMat[i] * (alphaJold - oS.alphas[j]) # update i by the same amount as j
613-
updateEk(oS, i) # added this for the Ecache #the update is in the oppostie direction
614-
b1 = oS.b - Ei - oS.labelMat[i] * (oS.alphas[i] - alphaIold) * oS.X[i, :] * oS.X[i, :].T - oS.labelMat[j] * (
615-
oS.alphas[j] - alphaJold) * oS.X[i, :] * oS.X[j, :].T
616-
b2 = oS.b - Ej - oS.labelMat[i] * (oS.alphas[i] - alphaIold) * oS.X[i, :] * oS.X[j, :].T - oS.labelMat[j] * (
617-
oS.alphas[j] - alphaJold) * oS.X[j, :] * oS.X[j, :].T
618-
if (0 < oS.alphas[i]) and (oS.C > oS.alphas[i]):
619-
oS.b = b1
620-
elif (0 < oS.alphas[j]) and (oS.C > oS.alphas[j]):
621-
oS.b = b2
622-
else:
623-
oS.b = (b1 + b2) / 2.0
624-
return 1
625-
else:
626-
return 0
627-
628-
629-
def smoPK(dataMatIn, classLabels, C, toler, maxIter): # full Platt SMO
630-
oS = optStruct(mat(dataMatIn), mat(classLabels).transpose(), C, toler)
631-
iter = 0
632-
entireSet = True
633-
alphaPairsChanged = 0
634-
while (iter < maxIter) and ((alphaPairsChanged > 0) or (entireSet)):
635-
alphaPairsChanged = 0
636-
if entireSet: # go over all
637-
for i in range(oS.m):
638-
alphaPairsChanged += innerL(i, oS)
639-
print("fullSet, iter: %d i:%d, pairs changed %d" % (iter, i, alphaPairsChanged))
640-
iter += 1
641-
else: # go over non-bound (railed) alphas
642-
nonBoundIs = nonzero((oS.alphas.A > 0) * (oS.alphas.A < C))[0]
643-
for i in nonBoundIs:
644-
alphaPairsChanged += innerL(i, oS)
645-
print("non-bound, iter: %d i:%d, pairs changed %d" % (iter, i, alphaPairsChanged))
646-
iter += 1
647-
if entireSet:
648-
entireSet = False # toggle entire set loop
649-
elif (alphaPairsChanged == 0):
650-
entireSet = True
651-
print("iteration number: %d" % iter)
652-
return oS.b, oS.alphas
653-

src/python/6.SVM/svm-complete_Non-Kernel.py

Lines changed: 0 additions & 116 deletions
Original file line numberDiff line numberDiff line change
@@ -257,119 +257,3 @@ def plotfig_SVM(xArr, yArr, ws, b, alphas):
257257
# 画图
258258
ws = calcWs(alphas, dataArr, labelArr)
259259
plotfig_SVM(dataArr, labelArr, ws, b, alphas)
260-
261-
262-
263-
264-
265-
266-
267-
268-
269-
270-
271-
272-
273-
274-
275-
276-
277-
278-
279-
280-
281-
282-
283-
284-
285-
286-
287-
288-
289-
290-
291-
292-
def testRbf(k1=1.3):
293-
dataArr, labelArr = loadDataSet('testSetRBF.txt')
294-
b, alphas = smoP(dataArr, labelArr, 200, 0.0001, 10000, ('rbf', k1)) # C=200 important
295-
datMat = mat(dataArr)
296-
labelMat = mat(labelArr).transpose()
297-
svInd = nonzero(alphas.A > 0)[0]
298-
sVs = datMat[svInd] # get matrix of only support vectors
299-
labelSV = labelMat[svInd]
300-
print("there are %d Support Vectors" % shape(sVs)[0])
301-
m, n = shape(datMat)
302-
errorCount = 0
303-
for i in range(m):
304-
kernelEval = kernelTrans(sVs, datMat[i, :], ('rbf', k1))
305-
predict = kernelEval.T * multiply(labelSV, alphas[svInd]) + b
306-
if sign(predict) != sign(labelArr[i]): errorCount += 1
307-
print("the training error rate is: %f" % (float(errorCount) / m))
308-
dataArr, labelArr = loadDataSet('testSetRBF2.txt')
309-
errorCount = 0
310-
datMat = mat(dataArr)
311-
labelMat = mat(labelArr).transpose()
312-
m, n = shape(datMat)
313-
for i in range(m):
314-
kernelEval = kernelTrans(sVs, datMat[i, :], ('rbf', k1))
315-
predict = kernelEval.T * multiply(labelSV, alphas[svInd]) + b
316-
if sign(predict) != sign(labelArr[i]): errorCount += 1
317-
print("the test error rate is: %f" % (float(errorCount) / m))
318-
319-
320-
def img2vector(filename):
321-
returnVect = zeros((1, 1024))
322-
fr = open(filename)
323-
for i in range(32):
324-
lineStr = fr.readline()
325-
for j in range(32):
326-
returnVect[0, 32 * i + j] = int(lineStr[j])
327-
return returnVect
328-
329-
330-
def loadImages(dirName):
331-
from os import listdir
332-
hwLabels = []
333-
print(dirName)
334-
trainingFileList = listdir(dirName) # load the training set
335-
m = len(trainingFileList)
336-
trainingMat = zeros((m, 1024))
337-
for i in range(m):
338-
fileNameStr = trainingFileList[i]
339-
fileStr = fileNameStr.split('.')[0] # take off .txt
340-
classNumStr = int(fileStr.split('_')[0])
341-
if classNumStr == 9:
342-
hwLabels.append(-1)
343-
else:
344-
hwLabels.append(1)
345-
trainingMat[i, :] = img2vector('%s/%s' % (dirName, fileNameStr))
346-
return trainingMat, hwLabels
347-
348-
349-
def testDigits(kTup=('rbf', 10)):
350-
dataArr, labelArr = loadImages('trainingDigits')
351-
b, alphas = smoP(dataArr, labelArr, 200, 0.0001, 10000, kTup)
352-
datMat = mat(dataArr)
353-
labelMat = mat(labelArr).transpose()
354-
svInd = nonzero(alphas.A > 0)[0]
355-
sVs = datMat[svInd]
356-
labelSV = labelMat[svInd]
357-
print("there are %d Support Vectors" % shape(sVs)[0])
358-
m, n = shape(datMat)
359-
errorCount = 0
360-
for i in range(m):
361-
kernelEval = kernelTrans(sVs, datMat[i, :], kTup)
362-
predict = kernelEval.T * multiply(labelSV, alphas[svInd]) + b
363-
if sign(predict) != sign(labelArr[i]): errorCount += 1
364-
print("the training error rate is: %f" % (float(errorCount) / m))
365-
dataArr, labelArr = loadImages('testDigits')
366-
errorCount = 0
367-
datMat = mat(dataArr)
368-
labelMat = mat(labelArr).transpose()
369-
m, n = shape(datMat)
370-
for i in range(m):
371-
kernelEval = kernelTrans(sVs, datMat[i, :], kTup)
372-
predict = kernelEval.T * multiply(labelSV, alphas[svInd]) + b
373-
if sign(predict) != sign(labelArr[i]): errorCount += 1
374-
print("the test error rate is: %f" % (float(errorCount) / m))
375-

0 commit comments

Comments
 (0)