求基于自定义核/Sigmoid核的二类SVM分类Python示例及三类转二类修改方法
当然有啦!我来帮你搞定自定义核、Sigmoid核的二类SVM分类示例,同时把你提供的三类分类代码改成二类版本。
一、把三类SVM修改为二类分类
原代码用了鸢尾花数据集的三类样本,要改成二类很简单,只需要筛选出其中两类数据即可。比如我们选取鸢尾花的前两类(setosa和versicolor),修改后的代码如下:
import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets iris = datasets.load_iris() # 筛选出前两类样本(Y=0和Y=1) mask = iris.target < 2 X = iris.data[mask, :2] # 仍取前两个特征 Y = iris.target[mask] def my_kernel(X, Y): """ 自定义核函数: (2 0) k(X, Y) = X ( ) Y.T (0 1.0) """ M = np.array([[2, 0], [0, 1.0]]) return np.dot(np.dot(X, M), Y.T) h = .02 # 网格步长 # 创建SVM实例并拟合数据(二类分类不需要额外参数,sklearn会自动处理) clf = svm.SVC(kernel=my_kernel) clf.fit(X, Y) # 绘制决策边界 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) # 绘制训练样本点 plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k') plt.title('使用自定义核函数的支持向量机二类分类') plt.axis('tight') plt.show()
修改要点:
- 用
mask = iris.target < 2筛选出前两类样本,只保留标签为0和1的数据 - 标题对应修改为二类分类的描述
- 二类SVM在sklearn中不需要额外配置,
SVC会自动处理二分类任务
二、Sigmoid核的二类SVM示例
Sigmoid核的公式为:k(x, y) = tanh(α * <x, y> + c),你可以直接使用sklearn内置的sigmoid核,也可以自定义实现。
方式1:使用sklearn内置Sigmoid核
import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets iris = datasets.load_iris() mask = iris.target < 2 X = iris.data[mask, :2] Y = iris.target[mask] h = .02 # 使用内置sigmoid核,可调整gamma(对应公式中的α)和coef0(对应公式中的c) clf = svm.SVC(kernel='sigmoid', gamma='auto', coef0=1) clf.fit(X, Y) # 绘制决策边界 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k') plt.title('使用Sigmoid核的支持向量机二类分类(内置实现)') plt.axis('tight') plt.show()
方式2:自定义实现Sigmoid核
import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets iris = datasets.load_iris() mask = iris.target < 2 X = iris.data[mask, :2] Y = iris.target[mask] def sigmoid_kernel(X, Y): """自定义Sigmoid核函数""" alpha = 0.5 # 对应公式中的α c = 1.0 # 对应公式中的c return np.tanh(alpha * np.dot(X, Y.T) + c) h = .02 clf = svm.SVC(kernel=sigmoid_kernel) clf.fit(X, Y) # 绘制决策边界 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k') plt.title('使用Sigmoid核的支持向量机二类分类(自定义实现)') plt.axis('tight') plt.show()
内容的提问来源于stack exchange,提问作者Christel Junco
相关产品推荐
相关产品推荐

