![](/img/trans.png)
[英]Use sklearn GridSearchCV on custom class whose fit method takes 3 arguments
[英]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”都會接收訓練數據和相應的標簽。 在上面的示例中,“適合”接收訓練數據和標簽(而非標簽)的索引。 分類器如何獲取索引而不是標簽並仍然有效
標簽只是一個抽象術語。 它可以是任何東西,單詞,數字,索引等等。 在您的情況下(無論是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]
[x2,x3,x3]
[0, 0, 1]
(標簽的索引)。
顯然,您的標簽在此處編碼:
[repository.locations.keys().index(tuple(l)) for l in y_train]
除此之外,我認為值得閱讀SearchGridCV文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.