使用自定义核的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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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