import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression,Ridge,Lasso
from sklearn.neighbors import KNeighborsRegressor
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.datasets import fetch_olivetti_faces
faces=fetch_olivetti_faces()
data=faces[‘data‘]
target=faces[‘target‘]
#data.shape
#人脸补全
#人脸数据一分为二,上半部分作为数据,下半部分作为target
face_up,face_down=data[:,:2048],data[:,2048:]
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(face_up,face_down,test_size=0.1)
#5个算法分别识别
estimators={‘knn‘:KNeighborsRegressor(),
‘LinearRe‘:LinearRegression(),
‘Ridge‘:Ridge(alpha=0.1),
‘Lasso‘:Lasso(alpha=0.5),
‘ExtraTree‘:ExtraTreesRegressor()}
#face_down[2048]
result_ = {}
for key,estimator in estimators.items():
estimator.fit(x_train,y_train)
y_ = estimator.predict(x_test)
result_[key] = y_
plt.figure(figsize=(2*6,10*2))
for i in range(10):
if i :
axes=plt.subplot(10,6,i*6+1)
else:
axes=plt.subplot(10,6,1,title=‘True Face‘)
axes.axis(‘off‘)
face_up=x_test[i]
face_down=y_test[i]
face_full=np.hstack((face_up,face_down))
face_image=face_full.reshape((64,64))
axes.imshow(face_image,cmap=‘gray‘)
for j,key in enumerate(result_):
if i :
axes=plt.subplot(10,6,i*6+2+j)
else:
axes=plt.subplot(10,6,2+j,title=key)
face_up=x_test[i]
y_=result_[key]
face_down_predict=y_[i]
face_full_predict=np.hstack((face_up,face_down_predict))
face_image_predict=face_full_predict.reshape((64,64))
axes.imshow(face_image_predict,cmap=‘gray‘)