可能和数据预处理混在一起了,将就吧。
一,代码
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import Normalizer
from sklearn.datasets import make_blobs
from sklearn.neural_network import MLPClassifier
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.datasets import fetch_lfw_people
'''
wine = load_wine()
scaler = StandardScaler()
X = wine.data
y = wine.target
X_scaled = scaler.fit_transform(X)
pca = PCA(n_components=2)
pca.fit(X_scaled)
X_pca = pca.transform(X_scaled)
X0 = X_pca[wine.target == 0]
X1 = X_pca[wine.target == 1]
X2 = X_pca[wine.target == 2]
plt.scatter(X0[: ,0], X0[:, 1], c='b', s=60, edgecolors='k')
plt.scatter(X1[: ,0], X1[:, 1], c='g', s=60, edgecolors='k')
plt.scatter(X2[: ,0], X2[:, 1], c='r', s=60, edgecolors='k')
plt.legend(wine.target_names, loc='best')
plt.xlabel('component 1')
plt.ylabel('component 2')
plt.show()
plt.matshow(pca.components_, cmap='plasma')
plt.yticks([0, 1], ['component 1', 'component 2'])
plt.colorbar()
plt.xticks(range(len(wine.feature_names)), wine.feature_names, rotation=60, ha='left')
plt.show()
'''
faces = fetch_lfw_people(min_faces_per_person=20, resize=0.8)
X_train, X_test, y_train, y_test = train_test_split(
faces.data/255, faces.target, random_state=62
)
# 使用PCA的白化功能处理人脸数据
pca = PCA(whiten=True, n_components=0.9, random_state=62).fit(X_train)
X_train_whiten = pca.transform(X_train)
X_test_whiten = pca.transform(X_test)
print('白化后的数据形态:{}'.format(X_train_whiten.shape))
mlp = MLPClassifier(hidden_layer_sizes=[100, 100], random_state=62, max_iter=400)
mlp.fit(X_train_whiten, y_train)
print('模型识别准确率: {:.2f}'.format(mlp.score(X_test_whiten, y_test)))
'''
image_shape = faces.images[0].shape
fig, axes = plt.subplots(3, 4, figsize=(12, 9),
subplot_kw={'xticks':(), 'yticks':()})
for target, image,ax in zip(faces.target, faces.images, axes.ravel()):
ax.imshow(image, cmap=plt.cm.gray)
ax.set_title(faces.target_names[target])
plt.show()
'''
二,效果
2022-04-26 21_44_40-MessageCenterUI.png 2022-04-26 19_22_02-Figure 1.png
网友评论