我想在Sklearn.svm
的{{3}}模块中使用自定义的内核函数。我在Epsilon-Support Vector Regression找到了以下代码作为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))
# imagine f1,f2,f3 are functions like 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)
(5列=特征,1列=标签)的数据集使用svm,然后如果我想使用my_new_kernel
方法,输入是什么,输出及其形状。
答案 0 :(得分:1)
您的确切问题还不清楚;这里有些话可能还是有帮助的。
我不知道什么是内核的X和Y输入及其形状。如果X和Y(my_kernel方法的输入)是数据集的特征和标签,
的确如此;来自fit
的{{3}}:
参数:
X: {类似数组的稀疏矩阵},形状(n_samples,n_features)
训练向量,其中n_samples是样本数,n_features是特征数。对于kernel =“ precomputed”, X的期望形状是(n_samples,n_samples)。
y:类似数组的形状(n_samples个)
目标值(分类中的类标签,回归中的实数)
与默认可用内核一样。
那么在没有标签的情况下,内核如何处理测试数据呢?
仔细查看您提供的代码,您会发现标签Y
实际上仅在培训期间使用(fit
);它们当然不会在预测期间使用(上面的代码中的clf.predict()
-不要与yy
混淆,后者与Y
无关)。