Numpy 的矩阵除法linalg.solve(matA, matB)

Rt

转载于:https://www.cnblogs.com/lfydeblog/p/8462606.html

为了回答这个问题,我将提供一个实现 SVM 算法的代码模板。请注意,这个模板是使用 Pythonnumpy 实现的,而不是使用 IPython。 ```python import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt class SVM: def __init__(self, C=1.0, kernel='linear', degree=3, gamma='scale', coef0=0.0): self.C = C self.kernel = kernel self.degree = degree self.gamma = gamma self.coef0 = coef0 def fit(self, X, y): # Solve the dual problem to get the optimal alphas n_samples, n_features = X.shape K = np.zeros((n_samples, n_samples)) for i in range(n_samples): for j in range(n_samples): K[i,j] = self.kernel_func(X[i], X[j]) P = np.outer(y, y) * K q = -np.ones((n_samples, 1)) G = np.vstack((-np.eye(n_samples), np.eye(n_samples))) h = np.vstack((np.zeros((n_samples, 1)), self.C*np.ones((n_samples, 1)))) A = y.reshape(1, -1) b = np.zeros(1) from cvxopt import matrix, solvers P, q, G, h, A, b = matrix(P), matrix(q), matrix(G), matrix(h), matrix(A), matrix(b) solvers.options['show_progress'] = False sol = solvers.qp(P, q, G, h, A, b) alphas = np.array(sol['x']) # Get the support vectors sv_indices = alphas > 1e-4 self.alphas = alphas[sv_indices] self.support_vectors = X[sv_indices] self.support_vector_labels = y[sv_indices] # Compute the intercept self.b = np.mean(self.support_vector_labels - np.sum(self.alphas * self.support_vector_labels * K[sv_indices], axis=0)) def predict(self, X): y_pred = np.zeros((X.shape[0],)) for i in range(X.shape[0]): s = 0 for alpha, sv_y, sv in zip(self.alphas, self.support_vector_labels, self.support_vectors): s += alpha * sv_y * self.kernel_func(X[i], sv) y_pred[i] = s return np.sign(y_pred + self.b) def kernel_func(self, x1, x2): if self.kernel == 'linear': return np.dot(x1, x2) elif self.kernel == 'poly': return (self.gamma*np.dot(x1, x2) + self.coef0)**self.degree elif self.kernel == 'rbf': return np.exp(-self.gamma*np.linalg.norm(x1-x2)**2) # Load iris dataset iris = load_iris() X = iris.data[:, [1, 3]] y = iris.target y[y==2] = -1 # Convert label 2 to -1 # Split data into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # Normalize data mean = X_train.mean(axis=0) std = X_train.std(axis=0) X_train = (X_train - mean) / std X_test = (X_test - mean) / std # Train SVM model svm = SVM(kernel='rbf') svm.fit(X_train, y_train) # Make predictions on test set y_pred = svm.predict(X_test) # Evaluate model performance accuracy = np.mean(y_pred == y_test) print(f'Accuracy: {accuracy}') # Visualize decision boundary and support vectors plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train) xlim = plt.gca().get_xlim() ylim = plt.gca().get_ylim() xx, yy = np.meshgrid(np.linspace(xlim[0], xlim[1], 100), np.linspace(ylim[0], ylim[1], 100)) Z = svm.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) plt.contour(xx, yy, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--']) plt.scatter(svm.support_vectors[:, 0], svm.support_vectors[:, 1], s=100, facecolors='none', edgecolors='k') plt.show() ``` 这个模板实现了一个 SVM 分类器,可以用于对 iris 数据集进行二分类。模板中的 SVM 类包含了 fit 和 predict 方法,用于训练模型和进行预测。在训练模型时,我们使用 cvxopt 软件包来求解 SVM 对偶问题的最优解 alpha。在预测时,我们使用训练好的模型来计算样本的决策函数值,并进行符号函数的处理,以得到样本的分类结果。 在使用这个模板时,需要注意以下几点: - 选取两个特征和两类数据进行二分类。注意:二分类标签为 1 和-1。 - 划分数据(分成训练集和数据集) - 数据归一化 - 训练模型。在这个模板中,我们使用了 RBF 核函数。如果需要使用其他核函数,可以在 SVM 类中修改 kernel_func 方法,并在初始化时指定相应的核函数和参数。 - 输出:SVM 对偶问题目标函数的最优解 alpha,决策函数的参数和截距,支持向量等。 - 可视化:通过散点图可视化训练数据样本,并画出决策面和 2 个最大间隔面,标出支持向量(包括间隔上和间隔内的样本),能够帮助检验算法正确性。 - 测试集数据进行预测,评估模型性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值