python - 使用 fit 进行 sklearn gridsearchcv

标签 python machine-learning scikit-learn

我是 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 进行转换,出于某种其他原因(也许在这种特殊情况下,用户只需要与原始数据集中不同的标签集?)。无论哪种方式,您仍然将标签传递给您的fit方法,它们只是进行了转换。

例如,考虑一组标签['cat', 'dog'],我是否在[x1, x2, x3]上训练模型并不重要 >, ['cat', 'cat', 'dog'][x2,x3,x3], [0, 0, 1](标签索引)。

关于python - 使用 fit 进行 sklearn gridsearchcv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33618567/

相关文章:

python - 如何验证 Flask 应用程序中的 URL 参数?

python - 使用sklearn计算仅给定单词列表的tf-idf权重

tensorflow - Keras:以两种不同方式拟合 ConvNet 时结果不一致

python - 从分类器中检索训练功能名称列表

python fuzzywuzzy 的 process.extract() : how does it work?

Python 2.7 : Write to file instantly

python - 如何使用列表/字典理解在 Python 中获取唯一值

python - 神经网络 pytorch

python - 使用 sklearn 中的 minmaxScalar 缩放 NumPy 数组中具有多个特征的特定特征

python - tfidf.transform() 函数没有返回正确的值