在实验8支持向量机中,绘制在简化版的SMO算法下生成的分类超平面,以及绘制在完整版的SMO算法下生成的分类超平面;数据集仍然用实验8中的“testSet.txt”python代码怎么写?
时间: 2024-03-17 12:47:50 浏览: 137
首先,我们需要导入必要的库:numpy和matplotlib。然后,我们可以使用以下代码来读取数据并绘制散点图:
```python
import numpy as np
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
dataArr, labelArr = loadDataSet('testSet.txt')
dataArr = np.array(dataArr)
n = np.shape(dataArr)[0]
xcord1 = []
ycord1 = []
xcord2 = []
ycord2 = []
for i in range(n):
if int(labelArr[i]) == 1:
xcord1.append(dataArr[i,0])
ycord1.append(dataArr[i,1])
else:
xcord2.append(dataArr[i,0])
ycord2.append(dataArr[i,1])
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')
plt.xlabel('X1')
plt.ylabel('X2')
plt.show()
```
接下来,我们可以使用以下代码来绘制简化版本SMO算法和完整版本SMO算法的分类超平面:
```python
from svmMLiA import smoSimple, smoP
# 简化版SMO算法
b, alphas = smoSimple(dataArr, labelArr, 0.6, 0.001, 40)
w = np.zeros((2,))
for i in range(n):
w += alphas[i] * labelArr[i] * dataArr[i]
x1 = np.min(dataArr[:,0])
x2 = np.max(dataArr[:,0])
y1 = (-b - w[0]*x1) / w[1]
y2 = (-b - w[0]*x2) / w[1]
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')
ax.plot([x1, x2], [y1, y2])
plt.xlabel('X1')
plt.ylabel('X2')
plt.show()
# 完整版SMO算法
b, alphas = smoP(dataArr, labelArr, 0.6, 0.001, 40)
w = np.zeros((2,))
for i in range(n):
w += alphas[i] * labelArr[i] * dataArr[i]
x1 = np.min(dataArr[:,0])
x2 = np.max(dataArr[:,0])
y1 = (-b - w[0]*x1) / w[1]
y2 = (-b - w[0]*x2) / w[1]
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')
ax.plot([x1, x2], [y1, y2])
plt.xlabel('X1')
plt.ylabel('X2')
plt.show()
```
注意,在以上代码中,我们使用了“svmMLiA.py”文件中的“smoSimple”和“smoP”函数来计算分类超平面。这两个函数实现了简化版SMO算法和完整版SMO算法。此外,我们还需要注意,在使用完整版SMO算法时,需要将核函数设置为线性核函数。
阅读全文