是否有使用自定义核或Sigmoid核进行2类SVM分类的Python样例代码?
下面的代码使用了3类分类。如何将其修改为2类SVM?
http://scikit-learn.org/stable/auto_examples/svm/plot_custom_kernel.html
import numpy as npimport matplotlib.pyplot as pltfrom sklearn import svm, datasetsiris = datasets.load_iris()X = iris.data[:, :2] # we only take the first two features. We could # avoid this ugly slicing by using a two-dim datasetY = iris.targetdef my_kernel(X, Y): """ We create a custom kernel: (2 0) k(X, Y) = X ( ) Y.T (0 1) """ M = np.array([[2, 0], [0, 1.0]]) return np.dot(np.dot(X, M), Y.T)h = .02 # step size in the mesh# we create an instance of SVM and fit out data.clf = svm.SVC(kernel=my_kernel)clf.fit(X, Y)# Plot the decision boundary. For that, we will assign a color to each# point in the mesh [x_min, x_max]x[y_min, y_max].x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1xx, 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()])# Put the result into a color plotZ = Z.reshape(xx.shape)plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)# Plot also the training pointsplt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k')plt.title('3-Class classification using Support Vector Machine with custom' ' kernel')plt.axis('tight')plt.show()
回答:
由于您的数据被分为3类,因此您有3个类别。您可以操作目标向量,使其仅包含两个类别。
Y = iris.targetfor index, value in enumerate(Y): Y[index] = value % 2
但这是一种不太优雅的解决方法,因为它实际上是将所有大于1的类别合并到类别1中。