使用自定义核的2类支持向量机

是否有使用自定义核或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中。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注