我需要在维数据集(5000,26421)上执行内核pca以获得较低维度表示。为了选择组件的数量(比如说k)参数,我将数据和重构数据减少到原始空间,得到不同k值的重建和原始数据的均方误差。Scikit-Learn GridSearch自定义评分函数
我遇到了sklearn的网格搜索功能,并希望将其用于上述参数估计。由于内核pca没有评分函数,我实现了一个自定义评分函数并将其传递给Gridsearch。
from sklearn.decomposition.kernel_pca import KernelPCA
from sklearn.model_selection import GridSearchCV
import numpy as np
import math
def scorer(clf, X):
Y1 = clf.inverse_transform(X)
error = math.sqrt(np.mean((X - Y1)**2))
return error
param_grid = [
{'degree': [1, 10], 'kernel': ['poly'], 'n_components': [100, 400, 100]},
{'gamma': [0.001, 0.0001], 'kernel': ['rbf'], 'n_components': [100, 400, 100]},
]
kpca = KernelPCA(fit_inverse_transform=True, n_jobs=30)
clf = GridSearchCV(estimator=kpca, param_grid=param_grid, scoring=scorer)
clf.fit(X)
但是,它会导致下面的错误:
/usr/lib64/python2.7/site-packages/sklearn/metrics/pairwise.py in check_pairwise_arrays(X=array([[ 2., 2., 1., ..., 0., 0., 0.],
...., 0., 1., ..., 0., 0., 0.]], dtype=float32), Y=array([[-0.05904257, -0.02796719, 0.00919842, .... 0.00148251, -0.00311711]], dtype=float32), precomp
uted=False, dtype=<type 'numpy.float32'>)
117 "for %d indexed." %
118 (X.shape[0], X.shape[1], Y.shape[0]))
119 elif X.shape[1] != Y.shape[1]:
120 raise ValueError("Incompatible dimension for X and Y matrices: "
121 "X.shape[1] == %d while Y.shape[1] == %d" % (
--> 122 X.shape[1], Y.shape[1]))
X.shape = (1667, 26421)
Y.shape = (112, 100)
123
124 return X, Y
125
126
ValueError: Incompatible dimension for X and Y matrices: X.shape[1] == 26421 while Y.shape[1] == 100
有人能指出我究竟做错了什么?
首先,PCA具有[score()](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html#sklearn.decomposition.PCA.score)函数。第二次使用['make_scorer()'](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html)将自定义分数函数传递给gridSearch。 –
我在这种情况下不使用PCA,而是使用没有得分功能的内核PCA。还尝试使用make_scorer函数,但该方法无效。 – user1683894