我是Sklearn和Python的新手;我有一个项目中的代码片段需要解读。希望你们能帮我解答。
from repository import Repositoryfrom configuration import configrepository = Repository(config)dataset, labels = repository.get_dataset_and_labels()import numpy as npfrom sklearn.cross_validation import train_test_splitfrom sklearn.svm import SVCfrom sklearn.cross_validation import ShuffleSplitfrom sklearn.grid_search import GridSearchCV # Ensure that there are no NaNsdataset = 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 useestimator = SVC(kernel='linear')# Define parameter spacegammas = 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]
(标签的索引),这实际上没有太大区别。