7

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?

amoeba
  • 93,463
  • 28
  • 275
  • 317
DasBoot
  • 173
  • 1
  • 5
  • 5
    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. – Scholar Jan 23 '19 at 13:38
  • 3
    @bi_scholar that's exactly my thinking, treat testing data as non-existing until the model is actually ready to be tested. – DasBoot Jan 23 '19 at 13:42

1 Answers1

6

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.

sniggatooth
  • 106
  • 2
  • 1
    +1. I voted to close this Q as a duplicate of https://stats.stackexchange.com/questions/55718/pca-and-the-train-test-split, but I fully agree with this answer. – amoeba Jan 23 '19 at 14:57
  • (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.) – amoeba Jan 23 '19 at 14:58
  • thanks @amoeba, that link provided some great insight as well as confirming my suspicion. – DasBoot Jan 23 '19 at 16:12