智能手机特定运动预测:PCA降维及模型还原原特征空间技术问询
Hey there! Let's work through this together—first, I need to point out a critical mistake in your current code, then walk you through how to properly reverse the PCA transformation.
First: Fix Your PCA Training/Testing Workflow
Right now, you're calling fit_transform() on both your training and test sets separately, which is incorrect! PCA needs to learn its principal components only from the training data—this ensures the same transformation logic is applied to both datasets, keeping your analysis consistent. Here's the corrected code:
from sklearn.decomposition import PCA # Initialize PCA to retain 95% of variance (matches your goal) pca = PCA(0.95) # Fit on training data AND transform it in one step pc_train = pca.fit_transform(data_train) # Use the already-trained PCA model to transform the test set (DO NOT fit again!) pc_test = pca.transform(data_test)
How to Reconstruct Data Back to the Original Feature Space
Scikit-learn's PCA class has a built-in inverse_transform() method that handles this exactly. It takes your reduced-dimension PCA features and projects them back into your original high-dimensional space using the principal components and mean values learned during the initial fit() on the training data.
1. Reconstruct Training Data
# Convert reduced training features back to original feature space reconstructed_train = pca.inverse_transform(pc_train)
2. Reconstruct Test Data
# Convert reduced test features back to original feature space reconstructed_test = pca.inverse_transform(pc_test)
Quick Notes on Reconstruction
- Since you set
PCA(0.95), you'll see a small amount of reconstruction error (from the 5% of variance you discarded)—this is expected and aligns with your goal of not losing too much information. - You can quantify this error easily if you want:
This will show you how much information was lost in the 5% variance cutoff.import numpy as np mse = np.mean((data_train - reconstructed_train)**2) print(f"Reconstruction Mean Squared Error: {mse:.4f}")
内容的提问来源于stack exchange,提问作者Kev

