When applying transformers in a cross-validation routine, it is often advised to fit the transformer to the data in your train set, and transform both the train and test set using the obtained transformer parameters. As an example, suppose we are using a standard scaler as a transformer, the cross-validation routine might look like this:
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold
scaler = StandardScaler()
cv = KFold(n_splits=5)
folds = cv.split(X=X)
for train_idx, test_idx in folds:
X_train = X[train_idx,:]
X_test = X[test_idx,:]
y_train = y[train_idx]
y_test = y[test_idx]
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
# Train & score model
This is also the behavior that Scikitlearn's pipelines implement.
What I'm interested in is the following: Why do we transform the test set based on the parameters of the train set, instead of fitting a separate transformer for the test set? If we would fit a separate standard scaler based on the test set and use the obtained parameters to transform the test set, then, as far as I see, the train and test set remain independent. As an example, we could do the following in every fold:
X_train = StandardScaler().fit_transform(X_train)
X_test = StandardScaler().fit_transform(X_test)
In case of a standard scaler, it would probably hardly matter for the performance of the resulting model. But I can imagine there to be transformers in which it matters. Is there any objection to using the second method described here?