通过python调用不同的模型去预测人脸
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 09:26:18 2020
@author: guangjie2333
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.utils.validation import check_random_state
from sklearn.datasets import fetch_olivetti_faces
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.linear_model import LinearRegression
from sklearn.neural_network import MLPRegressor
from sklearn.ensemble import RandomForestRegressor
data, targets = fetch_olivetti_faces(return_X_y = True)
train = data[targets < 30]
test = data[targets >= 30]
#test on face data
n_faces = 5;
rng = check_random_state(4);
face_ids = rng.randint(test.shape[0],size = (n_faces,));
test = test[face_ids,:];
n_pixels = data.shape[1]
x_train = train[:,:(n_pixels + 1)//2]
y_train = train[:,n_pixels//2:];
x_test = test[:,:(n_pixels + 1)//2]
y_test = test[:,n_pixels//2:]
# Fit estimators
ESTIMATORS = {
"Extra trees": ExtraTreesRegressor(n_estimators=10, max_features=32,
random_state=0),
"K-nn": KNeighborsRegressor(),
"Linear regression": LinearRegression(),
"MLP": MLPRegressor(),
"Random Tree": RandomForestRegressor(n_estimators=10,max_features=5, max_depth=5,min_samples_split=2)
}
y_test_predict = dict()
for name, estimator in ESTIMATORS.items():
estimator.fit(x_train, y_train)
y_test_predict[name] = estimator.predict(x_test)
#plot face
image_shape = (64, 64)
n_cols = 1 + len(ESTIMATORS)
plt.figure(figsize=(10, 10))
plt.suptitle("Face completion with multi-output estimators", size=30)
for i in range(n_faces):
true_face = np.hstack((x_test[i], y_test[i]))
#画真脸
if i:
sub = plt.subplot(n_faces, n_cols, i * n_cols + 1)
else:
#第0行加标题
sub = plt.subplot(n_faces, n_cols, i * n_cols + 1,
title="true faces")
sub.axis("off")
sub.imshow(true_face.reshape(image_shape),#照片大小
cmap=plt.cm.gray,#灰度图
interpolation="nearest")#内差值方式
#画预测脸
for j, est in enumerate(sorted(ESTIMATORS)): #j代表元素下标, est代表元素
completed_face = np.hstack((x_test[i], y_test_predict[est][i]))
if i: #j用来控制图像的位置
sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j)
else: #第0行加标题
sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j,
title=est)
sub.axis("off")
sub.imshow(completed_face.reshape(image_shape),
cmap=plt.cm.gray,
interpolation="nearest")
plt.show()
讨论RandomForestRegressor模型n_estimators, max_depth,max_features对结果的影响
n_estimators取10,20,30,40
max_depth取 3,6,9,12
max_features取 5,8,11,14