写支持向量机分类鸢尾花数据集代码并画可以出图(不用Scikit-Learn库
时间: 2024-05-03 15:20:14 浏览: 113
)?
好的,下面是支持向量机分类鸢尾花数据集代码(不用Scikit-Learn库):
```python
import numpy as np
import matplotlib.pyplot as plt
# 加载鸢尾花数据集
f = open('iris.data', 'r')
data = f.readlines()
f.close()
X = []
Y = []
for i in range(len(data)):
line = data[i].split(',')
x = []
for j in range(len(line)-1):
x.append(float(line[j]))
X.append(x)
if line[-1].strip() == 'Iris-setosa':
Y.append(0)
else:
Y.append(1)
X = np.array(X)
Y = np.array(Y)
# 定义SVM类
class SVM:
def __init__(self, C=1.0):
self.C = C
# 计算核函数
def kernel(self, x1, x2):
return np.dot(x1, x2)
# 计算alpha
def train(self, X, Y):
n_samples, n_features = X.shape
# 初始化alpha和b
alpha = np.zeros(n_samples)
b = 0
# 计算Gram矩阵和二次规划问题的参数
K = np.zeros((n_samples, n_samples))
for i in range(n_samples):
for j in range(n_samples):
K[i,j] = self.kernel(X[i], X[j])
P = np.outer(Y, Y) * K
q = -np.ones(n_samples)
G = np.vstack((-np.eye(n_samples), np.eye(n_samples)))
h = np.hstack((np.zeros(n_samples), np.ones(n_samples) * self.C))
# 求解二次规划问题
from cvxopt import matrix, solvers
P = matrix(P)
q = matrix(q)
G = matrix(G)
h = matrix(h)
solvers.options['show_progress'] = False
sol = solvers.qp(P, q, G, h)
alpha = np.array(sol['x']).flatten()
# 计算b
for i in range(n_samples):
if alpha[i] > 1e-7:
b = Y[i] - np.sum(alpha * Y * K[i,:])
break
self.alpha = alpha
self.b = b
# 预测
def predict(self, x):
res = 0
for i in range(len(self.alpha)):
res += self.alpha[i] * self.kernel(x, X[i])
res += self.b
return np.sign(res)
# 训练模型
clf = SVM()
clf.train(X, Y)
# 画图
colors = ['red', 'blue']
for i in range(len(Y)):
plt.scatter(X[i][0], X[i][1], c=colors[Y[i]])
xlim = plt.xlim()
ylim = plt.ylim()
xx, yy = np.meshgrid(np.linspace(xlim[0], xlim[1], 50),\
np.linspace(ylim[0], ylim[1], 50))
Z = np.zeros(xx.shape)
for i in range(xx.shape[0]):
for j in range(xx.shape[1]):
Z[i,j] = clf.predict([xx[i,j], yy[i,j]])
plt.contour(xx, yy, Z, colors='black', levels=[-1, 0, 1])
plt.show()
```
我已经完成了你的第一个问题,接下来还有其它问题吗?
阅读全文