Python 在使用PCA时,如何决定是使用训练数据还是测试数据?

Python 在使用PCA时,如何决定是使用训练数据还是测试数据?,python,numpy,scikit-learn,pca,dimensionality-reduction,Python,Numpy,Scikit Learn,Pca,Dimensionality Reduction,我是PCA新手,在拟合和转置时对可视化有疑问。我有两个数据,分别是训练和测试。以下是四种方法: # Method 1) pca = myPCA(n_components = 5) # Conduct myPCA with 5 principal components. pca.fit(X_train) # Calculate 5 principal components on the training dataset X_train_pca = pca.transform(X_train) #

我是PCA新手,在拟合和转置时对可视化有疑问。我有两个数据,分别是训练和测试。以下是四种方法:

# Method 1)
pca = myPCA(n_components = 5) # Conduct myPCA with 5 principal components.
pca.fit(X_train) # Calculate 5 principal components on the training dataset
X_train_pca = pca.transform(X_train)

# Method 2)
pca = myPCA(n_components = 5) # Conduct myPCA with 5 principal components.
pca.fit(X_test)
X_test_pca = pca.transform(X_test)

# Method 3)
pca = myPCA(n_components = 5) # Conduct myPCA with 5 principal components.
pca.fit(X_train)
X_test_pca = pca.transform(X_train)

# Method 4)
pca = myPCA(n_components = 5) # Conduct myPCA with 5 principal components.
pca.fit(X_train)
X_test_pca = pca.transform(X_test)
上述4种方法中哪一种是使用PCA进行可视化的正确方法?尽管PCA教程明确指出需要在测试数据上运行,但似乎我无法为此编写正确的方法

这是我的密码:

class myPCA():
"""
Principal Component Analysis (A Linear Dimension Reduction Method).
"""

def __init__(self, n_components = 2):
    """
    Conduct myPCA with 2 principal components(the principal and orthogonal modes of variation).
    """
    self.n_c = n_components


def fit(self,X):
    """
    The procedure of computing the covariance matrix.
    """
    cov_mat = np.cov(X.T) # Covariance matrix
    eig_val, eig_vec = np.linalg.eigh(cov_mat) # Eigen-values and orthogonal eigen-vectors in ascending order.
    eig_val = np.flip(eig_val) # Reverse the order, now it is descending.
    eig_vec = np.flip(eig_vec,axis=1) # reverse the order
    self.eig_values = eig_val[:self.n_c] # select the top eigen-vals
    self.principle_components = eig_vec[:,:self.n_c] # select the top eigen-vecs
    self.variance_ratio = self.eig_values/eig_val.sum() # variance explained by each PC

def transform(self,X):
    """
    Compute the score matrix.
    """
    return np.matmul(X-X.mean(axis = 0),self.principle_components) #project the data (centered) on PCs
可视化代码(仍不确定是否使用下面的X_列或X_测试):


如果任务只是将数据可视化到两个维度上,以确定观测值的分布,那么在哪个维度上进行拟合或变换并不重要。您甚至可以对整个数据集进行拟合,然后对其进行变换

但我猜您希望将其作为某些模型开发管道的一部分使用,并希望查看转换是否能在两个数据集上进行很好的泛化。如果是这种情况,您应该始终将您的转换适合于训练数据,并使用它来转换训练和测试数据


这将有助于在新的数据集上概括转换和随后的模型。

恐怕你的问题是不适定的,实际上不是关于编程,而是关于方法论。“使用PCA进行可视化”太模糊了(具体是什么可视化?)。请记住,在构建模型期间,您应该表现得好像测试数据根本不存在一样—它们仅用于评估最终模型,而不用于其他任何用途。
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
figure = plt.figure(dpi=100)
plt.scatter(X_test_pca[:, 0], X_test_pca[:, 1],c=y_test, s=15,edgecolor='none', alpha=0.5,cmap=plt.cm.get_cmap('tab10', 10))
plt.xlabel('component 1')
plt.ylabel('component 2')
plt.colorbar();