7
$\begingroup$

I've read so many contradicting opinions that I feel like I need to ask the question myself.

Say I use PCA on a dataset with 60 variables and find that I can explain 98% of variance with 6 principal components and I get a decent model predicting what I want.

Now I get some new data (testing), this data should then be translated to the same "PCA space" in order for my model to interpret it right? So I would scale it using the same scaling used on my training data and then use the loading scores from the original PCA to translate my new data to "PCA space"?

The reason I'm asking is that I've seen tons of people doing PCA before doing test/train splits so their testing data is already "transformed", this seems like a mistake to me? Shouldn't the PCA be used on the training data exclusively and then using the loadings from that PCA translate the testing data to the same dimensionality?

$\endgroup$
2
  • 5
    $\begingroup$ I think you are rightfully concerned about the later approach. For test data, it is best practice to simply pretend it doesn't exist during model build and only use it at the very end. $\endgroup$
    – Scholar
    Commented Jan 23, 2019 at 13:38
  • 3
    $\begingroup$ @bi_scholar that's exactly my thinking, treat testing data as non-existing until the model is actually ready to be tested. $\endgroup$
    – DasBoot
    Commented Jan 23, 2019 at 13:42

1 Answer 1

6
$\begingroup$

Yes this is a common way of overfitting your model to the test data. In NLP a similar mistake is to do vocabulary selection and bag-of-words vectorization on the full train/test data.

This is a bit insidious since doing model selection is a lot easier with most tools once you got your feature matrix. In addition the "boost" you get is not alarmingly big so it is tempting to just think your model is great and pat yourself on the back.

On a positive note I think this was a lot more common 5-10 ten years ago and most practitioners are wise to this error today.

$\endgroup$
3
  • 1
    $\begingroup$ +1. I voted to close this Q as a duplicate of stats.stackexchange.com/questions/55718/…, but I fully agree with this answer. $\endgroup$
    – amoeba
    Commented Jan 23, 2019 at 14:57
  • $\begingroup$ (If you want, you can post a version of this answer in that thread which is our "canonical" thread on this topic -- lots of questions get closed as duplicate of that one.) $\endgroup$
    – amoeba
    Commented Jan 23, 2019 at 14:58
  • $\begingroup$ thanks @amoeba, that link provided some great insight as well as confirming my suspicion. $\endgroup$
    – DasBoot
    Commented Jan 23, 2019 at 16:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.