# 机器学习实战python实例（2）SVM

393人阅读 评论(0)

http://www.thebigdata.cn/JieJueFangAn/12661.html
http://www.wengweitao.com/zhi-chi-xiang-liang-ji-smoxu-lie-zui-xiao-zui-you-hua-suan-fa.html#fnref:calculate

# coding:utf-8
from numpy import *
import matplotlib.pyplot as plt

def loadDataSet(filename):
dataMat = []
labelMat = []
fr = open(filename)
for line in fr.readlines():
lineArr = line.strip().split('\t')
dataMat.append([float(lineArr[0]), float(lineArr[1])])
labelMat.append(float(lineArr[2]))
return dataMat, labelMat

def selectJrand(i, m):
j = i
while j == i:
j = int(random.uniform(0, m))
return j

def clipAlpha(aj, H, L):
if aj > H:
aj = H
if aj < L:
aj = L
return aj

def smoSimple(dataMatIn, classLabels, C, toler, maxIter):
dataMatrix = mat(dataMatIn)
labelMat = mat(classLabels).transpose()
b = 0
m, n = dataMatrix.shape
alphas = mat(zeros((m, 1)))
Iter = 0
while Iter < maxIter:
alphaPairsChanged = 0
for i in xrange(m):
# y = wx + b, w = ∑αyx
fXi = float(multiply(alphas, labelMat).T * dataMatrix * dataMatrix[i, :].T) + b
Ei = fXi - float(labelMat[i])
# if α needs to be adjusted or it does not satisfy the ktt
if ((labelMat[i] * Ei < -toler) and (alphas[i] < C)) or ((labelMat[i] * Ei > toler) and (alphas[i] > 0)):
j = selectJrand(i, m)
fXj = float(multiply(alphas, labelMat).T * dataMatrix * dataMatrix[j, :].T) + b
Ej = fXj - float(labelMat[j])
alphaIold = alphas[i].copy()
alphaJold = alphas[j].copy()
if labelMat[i] != labelMat[j]:
L = max(0, alphas[j] - alphas[i])
H = min(C, C + alphas[j] - alphas[i])
else:
L = max(0, alphas[j] + alphas[i] - C)
H = min(C, alphas[j] + alphas[i])
if L == H:
print "L == H"
continue
eta = 2.0 * dataMatrix[i, :] * dataMatrix[j, :].T \
- dataMatrix[i, :] * dataMatrix[i, :].T \
- dataMatrix[j, :] * dataMatrix[j, :].T
if eta >= 0:
print "eta >= 0"
continue
alphas[j] -= labelMat[j] * (Ei - Ej) / eta
alphas[j] = clipAlpha(alphas[j], H, L)
if abs(alphas[j] - alphaJold) < 0.00001:
print "j not moving enough"
continue
alphas[i] += labelMat[j] * labelMat[i] * (alphaJold - alphas[j])
b1 = b - Ei \
- labelMat[i] * (alphas[i] - alphaIold) * dataMatrix[i, :] * dataMatrix[i, :].T \
- labelMat[j] * (alphas[j] - alphaJold) * dataMatrix[j, :] * dataMatrix[i, :].T
b2 = b - Ej \
- labelMat[i] * (alphas[i] - alphaIold) * dataMatrix[i, :] * dataMatrix[j, :].T \
- labelMat[j] * (alphas[j] - alphaJold) * dataMatrix[j, :] * dataMatrix[j, :].T
if 0 < alphas[i] < C:
b = b1
elif 0 < alphas[j] < C:
b = b2
else:
b = (b1 + b2) / 2.0
alphaPairsChanged += 1
print "iter: %d i:%d, pairs changed %d" % (Iter, i, alphaPairsChanged)
if alphaPairsChanged == 0:
Iter += 1
else:
Iter = 0
print "iteration number: %d" % Iter
return b, alphas

def show(dataArr, labelArr, alphas, b):
for i in xrange(len(labelArr)):
if labelArr[i] == -1:
plt.plot(dataArr[i][0], dataArr[i][1], 'or')
elif labelArr[i] == 1:
plt.plot(dataArr[i][0], dataArr[i][1], 'Dg')
# print alphas.shape, mat(labelArr).shape, multiply(alphas, mat(labelArr)).shape
c = sum(multiply(multiply(alphas.T, mat(labelArr)), mat(dataArr).T), axis=1)
minY = min(m[1] for m in dataArr)
maxY = max(m[1] for m in dataArr)
print minY, maxY
plt.plot([sum((- b - c[1] * minY) / c[0]), sum((- b - c[1] * maxY) / c[0])], [minY, maxY])
plt.plot([sum((- b + 1 - c[1] * minY) / c[0]), sum((- b + 1 - c[1] * maxY) / c[0])], [minY, maxY])
plt.plot([sum((- b - 1 - c[1] * minY) / c[0]), sum((- b - 1 - c[1] * maxY) / c[0])], [minY, maxY])
plt.show()

import SVM
from numpy import *

dataArr, labelArr = SVM.loadDataSet('testSet.txt')
b, alphas = SVM.smoSimple(dataArr, labelArr, 0.6, 0.001, 40)
SVM.show(dataArr, labelArr, alphas, b)

http://download.csdn.net/detail/xiaonannanxn/9618859

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：12221次
• 积分：250
• 等级：
• 排名：千里之外
• 原创：13篇
• 转载：1篇
• 译文：0篇
• 评论：3条
评论排行
最新评论