【问题标题】:2-Class Support Vector Machine using Custom Kernel使用自定义内核的 2 类支持向量机
【发布时间】:2018-07-09 13:00:40
【问题描述】:

是否有使用自定义内核或 sigmoid 内核进行 2 类 SVM 分类的示例 Python 代码?

下面的代码使用 3-class 分类。如何将其修改为 2 类 SVM?

http://scikit-learn.org/stable/auto_examples/svm/plot_custom_kernel.html

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets

iris = 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 dataset
Y = iris.target

def 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() + 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()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)

# Plot also the training points
plt.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()

【问题讨论】:

  • 只使用前两个类的数据。 iris 数据集的前 50 个样本用于 class1,接下来的 50 个用于 class2,最后 50 个用于 class3。您只能使用前 100 个样本。做X = X[:100]Y = Y[:100]

标签: python machine-learning svm sigmoid


【解决方案1】:

您有 3 个类别,因为您的数据分为 3 个类别。您可以将目标向量操作为仅包含两个类。

Y = iris.target
for index, value in enumerate(Y):
  Y[index] = value % 2

但这有点难看,因为它有效地将每个 > 1 的类合并到 1 类中。

【讨论】:

  • 哇,我运行它,它工作!但是我可以问一下,或者你能解释一下你回答的上面的代码,索引和值来自哪里?
  • 当然。 Y 是样本数据的目标标签(类)。在您的情况下,它们的值是 0、1 或 2。我的代码通过 Y 循环(您可以这样做,因为它是 ndarray。)我使用 enumerate 来跟踪索引并更新值 modulo 2最终得到一个仅包含 0 和 1 的数组。
  • 啊,好的,我明白了,谢谢。变量“M”怎么样?这样做的目的/功能是什么?如果我删除它,变量“h”将出现错误,以此类推到变量“clf”。
  • 嗨,你的内核得到了(m, 2), (n, 2) 形状的输入矩阵(因为这个例子使用了两个特征。)你想要得到(m, n) 形状的输出。 M 的形状为 (2, 2)。因此,如果您执行X * M * Y^T,您最终会得到所需的形状。你可以对输入做任何你想做的事情(这是内核技巧的关键目的)。只要你返回正确的形状。所以如果你想删除M,你可以只返回np.dot(X, Y.T),这里M是隐含的单位矩阵。
  • 另外你可能想watch this MIT OpenCourseWare video about SVMs 来获得直觉。
猜你喜欢
  • 2018-02-10
  • 2016-02-20
  • 2014-09-24
  • 2011-08-25
  • 2012-10-12
  • 1970-01-01
  • 2011-07-01
  • 2011-10-15
  • 2019-05-16
相关资源
最近更新 更多