Боюсь, что я сделал что-то не так, потому что точность моей проверки подозрительно высока. Я думаю, что ошибаюсь: я разделяю данные обучения на наборы для разработки и проверки, тренируюсь на наборе для разработки и записываю оценку перекрестной проверки в набор для проверки. Моя точность может быть завышена, потому что на самом деле я тренируюсь на наборах для разработки и проверки, а затем тестирую на наборе для проверки. Я не уверен, правильно ли я использую модуль PredefineSplit scikit-learn. Подробности ниже:
После этого ответа я сделал следующее:
Код: Выделить всё
import numpy as np
from sklearn.model_selection import train_test_split, PredefinedSplit
from sklearn.grid_search import GridSearchCV
# I split up my data into training and test sets.
X_train, X_test, y_train, y_test = train_test_split(
data[training_features],
data[training_response],
test_size=0.2,
random_state=550
)
# sanity check - dimensions of training and test splits
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
# dimensions of X_train and x_test are (323430, 26) and (323430,1) respectively
# dimensions of X_test and y_test are (80858, 26) and (80858, 1)
'''Now, I define indices for a pre-defined split.
this is a 323430 dimensional array, where the indices for the development
set are set to -1, and the indices for the validation set are set to 0.'''
validation_idx = np.repeat(-1, y_train.shape)
np.random.seed(550)
validation_idx[
np.random.choice(
validation_idx.shape[0],
int(round(0.2*validation_idx.shape[0])),
replace = False
)
] = 0
# Now, create a list which contains a single tuple of two elements,
# which are arrays containing the indices for the development and
# validation sets, respectively.
validation_split = list(PredefinedSplit(validation_idx).split())
# sanity check
print(len(validation_split[0][0])) # outputs 258744
print(len(validation_split[0][0]))/float(validation_idx.shape[0])) # outputs .8
print(validation_idx.shape[0] == y_train.shape[0]) # True
print(set(validation_split[0][0]).intersection(set(validation_split[0][1]))) # set([])
Код: Выделить всё
# a vanilla XGboost model
model1 = XGBClassifier()
# create a parameter grid for the number of trees and depth of trees
n_estimators = range(300, 1100, 100)
max_depth = [8, 10]
param_grid = dict(max_depth=max_depth, n_estimators=n_estimators)
# A grid search.
# NOTE: I'm passing a PredefinedSplit object as an argument to the `cv` parameter.
grid_search = GridSearchCV(
model1,
param_grid,
scoring='neg_log_loss',
n_jobs=-1,
cv=validation_split,
verbose=1
)
Код: Выделить всё
# accurracy score on the validation set. This yields .89207865
accuracy_score(
y_pred=grid_result2.predict(X_train.iloc[validation_split[0][1]]),
y_true=y_train[validation_split[0][1]]
)
# accuracy score when applied to the development set. This yields .8929559
accuracy_score(
y_pred=grid_result2.predict(X_train.iloc[validation_split[0][0]]),
y_true=y_train[validation_split[0][0]]
)
# finally, the score when applied to the test set. This yields .783
accuracy_score(
y_pred=grid_result2.predict(X_test),
y_true=y_test
)
Кажется, я не могу найти, в чем я ошибся - в основном потому, что не знаю, в чем GridSearchCV работает скрытно, когда получает объект PredefineSplit в качестве аргумента параметра cv.
Есть идеи, где я ошибся? Если вам нужна более подробная информация/уточнение, пожалуйста, дайте мне знать. Код также находится в этом блокноте на github.
Спасибо!
Подробнее здесь: https://stackoverflow.com/questions/468 ... split-susp
Мобильная версия