微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我是 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_train还是X_test):

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();

解决方法

如果任务只是将 2 维数据可视化以识别观察值的分布,那么拟合或转换哪个都无关紧要。您甚至可以拟合整个数据集,然后对其进行转换。

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。