我想在Sklearn.svm
的Epsilon-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
函数中使用,我无法弄清楚核函数的输入X
和Y
及其形状。如果X
和Y
(my_kernel
方法的输入)是数据集的特征和标签,那么核函数在没有标签的测试数据上是如何工作的呢?
实际上,我想对形状为(10000, 6)
的数据集使用svm,(5列=特征,1列=标签),那么如果我想使用my_new_kernel
方法,输入和输出的形状会是什么样的?
回答:
你的具体问题不太清楚;尽管如此,以下是一些可能有帮助的评论。
我无法弄清楚核函数的输入
X
和Y
及其形状。如果X
和Y
(my_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
混淆,yy
与Y
无关)期间不使用。