将 fit 用于 sklearn gridsearchcv

use fit for sklearn gridsearchcv

我是 Sklearn 的新手 python;我有一个我试图破译的项目的代码片段。我希望你们能帮助我。

from repository import Repository
from configuration import config
repository = Repository(config)
dataset, labels = repository.get_dataset_and_labels()
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.svm import SVC
from sklearn.cross_validation import ShuffleSplit
from sklearn.grid_search import GridSearchCV  
# Ensure that there are no NaNs
dataset = dataset.fillna(-85)
# Split the dataset into training (90 \%) and testing (10 \%)
X_train, X_test, y_train, y_test = train_test_split(dataset, labels,      test_size = 0.1 )
cv = ShuffleSplit(X_train.shape[0], n_iter=10, test_size=0.2, random_state=0)
# Define the classifier to use
estimator = SVC(kernel='linear')
# Define parameter space
gammas = np.logspace(-6, -1, 10)
# Use Test dataset and use cross validation to find bet hyper-p  rameters.
classifier = GridSearchCV(estimator=estimator, cv=cv, param_grid=dict(gamma=gammas))
classifier.fit(X_train, [repository.locations.keys().index(tuple(l))  for l in y_train])

我无法理解的是分类器的 fit 方法的使用。我在网上找到的所有示例中,'fit' 接收训练数据和相应的标签。在上面的示例中,'fit' 接收训练数据和标签(不是标签)的索引。 分类器如何采用索引而不是标签并且仍然有效

标签只是一个抽象的术语。它可以是任何东西,单词,数字,索引,任何东西。在你的情况下(无论 repository.locations.keys().index(...),让我们假设它是一个 确定性 函数,为简单起见,我们称之为 f),你创建一个列表

 [f(tuple(l)) for l in y_train]

y_train 本身是一个列表(或更一般的 - 可迭代)。所以上面也是一个标签列表,只是通过 f 转换,出于某些其他原因(也许在这种特殊情况下,用户只需要与原始数据集中不同的标签集?)。无论哪种方式,您仍然将 labels 传递给您的 fit 方法,它们只是被转换。

考虑例如标签集 ['cat', 'dog'],我是否在 [x1, x2, x3]['cat', 'cat', 'dog'][x2,x3,x3]、[=20 上训练模型并不重要=](标签索引)。

显然你的标签在这里编码:

[repository.locations.keys().index(tuple(l))  for l in y_train]

除此之外,我认为 SearchGridCV documentation.

值得一看