通用范例 General Examples - Ex 7: Face completion with a multi-output estimators

优质
小牛编辑
124浏览
2023-12-01

通用范例/范例七: Face completion with a multi-output estimators

http://scikit-learn.org/stable/auto_examples/plot_multioutput_face_completion.html

这个范例用来展示scikit-learn如何用 extremely randomized trees, k nearest neighbors, linear regressionridge regression 演算法来完成人脸估测。

(一)引入函式库及内建影像资料库

引入之函式库如下

  1. sklearn.datasets: 用来绘入内建之影像资料库
  2. sklearn.utils.validation: 用来取乱数
  3. sklearn.ensemble
  4. sklearn.neighbors
  5. sklearn.linear_model

使用 datasets.load_digits() 将资料存入, data 为一个dict型别资料,我们看一下资料的内容。

  1. from sklearn.datasets import fetch_olivetti_faces
  2. data = fetch_olivetti_faces()
  3. targets = data.target
  4. data = data.images.reshape((len(data.images), -1))
显示说明
(‘images’, (400, 64, 64))共有40个人,每个人各有10张影像,共有 400 张影像,影像大小为 64x64
(‘data’, (400, 4096))data 则是将64x64的矩阵摊平成4096个元素之一维向量
(‘targets’, (400,))说明400张图与40个人之分类对应 0-39,记录每张影像是哪一个人
DESCR资料之描述

前面30个人当训练资料,之后当测试资料

  1. train = data[targets < 30]
  2. test = data[targets >= 30]

测试影像从100张乱数选5张出来,变数test的大小变成(5,4096)

  1. # Test on a subset of people
  2. n_faces = 5
  3. rng = check_random_state(4)
  4. face_ids = rng.randint(test.shape[0], size=(n_faces, ))
  5. test = test[face_ids, :]

把每张训练影像和测试影像都切割成上下两部分:

X人脸上半部分,
Y
人脸下半部分。

  1. n_pixels = data.shape[1]
  2. X_train = train[:, :np.ceil(0.5 * n_pixels)]
  3. y_train = train[:, np.floor(0.5 * n_pixels):]
  4. X_test = test[:, :np.ceil(0.5 * n_pixels)]
  5. y_test = test[:, np.floor(0.5 * n_pixels):]

(二)资料训练

分别用以下四种演算法来完成人脸下半部估测

  1. extremely randomized trees (绝对随机森林演算法)
  2. k nearest neighbors (K-邻近演算法)
  3. linear regression (线性回归演算法)
  4. ridge regression (脊回归演算法)
  1. ESTIMATORS = {
  2. "Extra trees": ExtraTreesRegressor(n_estimators=10, max_features=32,random_state=0),
  3. "K-nn": KNeighborsRegressor(),
  4. "Linear regression": LinearRegression(),
  5. "Ridge": RidgeCV(),
  6. }

分别把训练资料人脸上、下部分放入estimator.fit()中进行训练。上半部分人脸为条件影像,下半部人脸为目标影像。

y_test_predict为一个dict型别资料,存放5位测试者分别用四种演算法得到的人脸下半部估计结果。

  1. y_test_predict = dict()
  2. for name, estimator in ESTIMATORS.items():
  3. estimator.fit(X_train, y_train)
  4. y_test_predict[name] = estimator.predict(X_test)

(三)matplotlib.pyplot画出结果

每张影像都是64*64,总共有5位测试者,每位测试者分别有1张原图,加上使用4种演算法得到的估测结果。

  1. image_shape = (64, 64)
  2. n_cols = 1 + len(ESTIMATORS)
  3. plt.figure(figsize=(2. * n_cols, 2.26 * n_faces))
  4. plt.suptitle("Face completion with multi-output estimators", size=16)
  5. for i in range(n_faces):
  6. true_face = np.hstack((X_test[i], y_test[i]))
  7. if i:
  8. sub = plt.subplot(n_faces, n_cols, i * n_cols + 1)
  9. else:
  10. sub = plt.subplot(n_faces, n_cols, i * n_cols + 1,
  11. title="true faces")
  12. sub.axis("off")
  13. sub.imshow(true_face.reshape(image_shape),
  14. cmap=plt.cm.gray,
  15. interpolation="nearest")
  16. for j, est in enumerate(sorted(ESTIMATORS)):
  17. completed_face = np.hstack((X_test[i], y_test_predict[est][i]))
  18. if i:
  19. sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j)
  20. else:
  21. sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j,
  22. title=est)
  23. sub.axis("off")
  24. sub.imshow(completed_face.reshape(image_shape),
  25. cmap=plt.cm.gray,
  26. interpolation="nearest")
  27. plt.show()

Ex 7: Face completion with a multi-output estimators - 图1