scikit中的特征面与训练图像不对应

2024-09-29 23:20:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个基于PCA的基于一些在线代码的特征约简小程序,我的源代码如下:

import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import fetch_lfw_people
from sklearn.decomposition import PCA

def main():
    lfw_dataset = fetch_lfw_people(min_faces_per_person=100)
    n_samples, h, w = lfw_dataset.images.shape
    X = lfw_dataset.data
    y = lfw_dataset.target
    target_names = lfw_dataset.target_names
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
    n_components = 100
    pca = PCA(n_components=n_components, whiten=True).fit(X_train)
    X_train_pca = pca.transform(X_train)
    plot(X_train,h,w)
    eigenfaces = pca.components_
    X_train_recover = pca.inverse_transform(X_train_pca)
    plot(eigenfaces,h,w)
    plot(X_train_recover,h,w)

def plot(images,h,w):
    n_row=2
    n_col=5
    plt.figure(figsize=(1.5 * n_col, 2.2 * n_row))
    plt.subplots_adjust(0.6, 0.5, 1.5, 1.5)
    for i in range(n_row * n_col):
        plt.subplot(n_row, n_col, i + 1)
        plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
    plt.tight_layout()
    plt.show()

if __name__=="__main__":
    main()

我的问题是,当我执行以下代码行时:

eigenfaces = pca.components_
X_train_recover = pca.inverse_transform(X_train_pca)
plot(eigenfaces,h,w)

为什么绘制的图像,即特征面,与训练图像集或逆变换后绘制的图像集不对应?我可以看到,如果我们考虑到我们应用了主成分分析,原始的训练图像和来自逆变换的图像是“相同的”

据我所知,pca.components会给我一个n\u components x n\u特征的数组,但我看不到与原始图像或显示的变换图像的关系

有什么帮助吗


Tags: test图像importplotcomponentstrainpltcol

热门问题