PCA 重建 Fashion_mnist 數據集

import tensorflow as tf
from tensorflow import keras
import numpy as np
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
from PIL import Image

讀取數據

(x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data()
print(x_train.shape, y_train.shape)
(60000, 28, 28) (60000,)
# [60000, 28, 28] => [60000, 28 * 28]
x_train_reshape = x_train.reshape(-1, 28 * 28)
print(x_train_reshape.shape)
(60000, 784)
def printImage(images):
    plt.figure(figsize=(10, 10))
    for i in range(100):
        plt.subplot(10,10,i+1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(images[i], cmap=plt.cm.binary)
# 保留圖片 95% 的特徵
pca = PCA(0.95)
pca.fit(x_train_reshape)
PCA(copy=True, iterated_power='auto', n_components=0.95, random_state=None,
    svd_solver='auto', tol=0.0, whiten=False)
# 需要 壓縮到 187 個特徵
pca.n_components_
187
# 提取圖片主成分
x_train_reduction = pca.transform(x_train_reshape)
x_train_reduction.shape
(60000, 187)
# 由提取後的主成分還原圖片
x_train_inverse = pca.inverse_transform(x_train_reduction)
# [60000, 28 * 28] => [60000, 28, 28]
x_train_inverse = x_train_inverse.reshape(-1, 28, 28)
# 輸入的前 50 張+重建的前 50 張圖片合併
x_concat = np.vstack([x_train[:50], x_train_inverse[:50]])
x_concat.shape
(100, 28, 28)
# x_concat.dtype='int32'
printImage(x_concat)
# 上面 5 行是原始圖片, 下面 5 行是經過 PCA 提取主成分還原後的圖片

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章