I have optimized RandomForest, using GridSearch with a nested cross-validation. After that, I know that with the best parameters, I have to train the whole dataset before making predictions on out-of sample data.
Do I have to fit the model twice? One to find the accuracy estimate by nested cross validation and then with the out-of-sample data?
Please check my code:
#Load data
for name in ["AWA"]:
for el in ['Fp1']:
X=sio.loadmat('/home/TrainVal/{}_{}.mat'.format(name, el))['x']
s_y=sio.loadmat('/home/TrainVal/{}_{}.mat'.format(name, el))['y']
y=np.ravel(s_y)
print(name, el, x.shape, y.shape)
print("")
#Pipeline
clf = Pipeline([('rcl', RobustScaler()),
('clf', RandomForestClassifier())])
#Optimization
#Outer loop
sss_outer = StratifiedShuffleSplit(n_splits=2, test_size=0.1, random_state=1)
#Inner loop
sss_inner = StratifiedShuffleSplit(n_splits=2, test_size=0.1, random_state=1)
# Use a full grid over all parameters
param_grid = {'clf__n_estimators': [10, 12, 15],
'clf__max_features': [3, 5, 10],
}
# Run grid search
grid_search = GridSearchCV(clf, param_grid=param_grid, cv=sss_inner, n_jobs=-1)
#FIRST FIT!!!!!
grid_search.fit(X, y)
scores=cross_val_score(grid_search, X, y, cv=sss_outer)
#Show best parameter in inner loop
print(grid_search.best_params_)
#Show Accuracy average of all the outer loops
print(scores.mean())
#SECOND FIT!!!
y_score = grid_search.fit(X, y).score(out-of-sample, y)
print(y_score)