使用自定义核函数的`sklearn.svm`回归器时的模糊性

我想在Sklearn.svmEpsilon-Support Vector Regression模块中使用自定义核函数。我在scikit-learn文档中找到了一个用于svc的自定义核函数的示例代码:

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

# import some data to play with
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()

我想定义一些类似于下面的函数:

def my_new_kernel(X):
    a,b,c = (random.randint(0,100) for _ in range(3))
    # 假设f1,f2,f3是类似于sin(x), cos(x)的函数
    ans = a*f1(X) + b*f2(X) + c*f3(X)
    return ans

我对核方法的理解是,它是一个接受特征矩阵X)作为输入并返回一个形状为(n,1)的矩阵的函数。然后svm返回的矩阵附加到特征列上,并使用它来分类标签Y

在上面的代码中,核函数在svm.fit函数中使用,我无法弄清楚核函数的输入XY及其形状。如果XYmy_kernel方法的输入)是数据集的特征和标签,那么核函数在没有标签的测试数据上是如何工作的呢?

实际上,我想对形状为(10000, 6)的数据集使用svm,(5列=特征,1列=标签),那么如果我想使用my_new_kernel方法,输入和输出的形状会是什么样的?


回答:

你的具体问题不太清楚;尽管如此,以下是一些可能有帮助的评论。

我无法弄清楚核函数的输入XY及其形状。如果XYmy_kernel方法的输入)是数据集的特征和标签,

确实如此;根据fit文档

参数:

X : {array-like, sparse matrix}, shape (n_samples, n_features)

训练向量,其中n_samples是样本数,n_features是特征数。对于kernel=”precomputed”,X的预期形状为(n_samples, n_samples)。

y : array-like, shape(n_samples,)

目标值(分类中的类标签,回归中的实数)

这与默认可用的核函数完全一样。

那么没有标签的测试数据上的核函数是如何工作的呢?

仔细查看你提供的代码会发现,标签Y确实只在训练(fit)期间使用;当然,它们在预测(上面的代码中的clf.predict() – 不要与yy混淆,yyY无关)期间不使用。

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中创建了一个多类分类项目。该项目可以对…

发表回复

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