import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression,Ridge,Lasso
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn import datasets
from sklearn.model_selection import train_test_split
faces=datasets.fetch_olivetti_faces()
X=faces.data
images=faces.images
y=faces.target
print(X.shape,y.shape,images.shape)
index=np.random.randint(0,400,size=1)[0]
img=images[index]
plt.imshow(img,cmap=plt.cm.gray)
X_up=X[:,:2048]
X_down=X[:,2048:]
index=np.random.randint(0,400,size=1)[0]
axes=plt.subplot(1,3,1)
up_face=X_up[index].reshape(32,64)
axes.imshow(up_face,cmap='gray')
axes=plt.subplot(1,3,2)
down_face=X_down[index].reshape(32,64)
axes.imshow(down_face,cmap='gray')
axes=plt.subplot(1,3,3)
face=X[index].reshape(64,64)
axes.imshow(face,cmap='gray')
X=X_up.copy()
y=X_down.copy()
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=30)
estimators={}
estimators['linear']=LinearRegression()
estimators['ridge']=Ridge(alpha=0.1)
estimators['lasso']=Lasso(alpha=1)
estimators['knn']=KNeighborsRegressor(n_neighbors=5)
estimators['tree']=DecisionTreeRegressor()
result={}
for key,model in estimators.items():
model.fit(X_train,y_train)
y_=model.predict(X_test)
result[key]=y_
plt.figure(figsize=(7*2,10*2.5))
for i in range(0,10):
axes=plt.subplot(10,7,i*7+1)
up_face=X_test[i].reshape(32,64)
axes.imshow(up_face,cmap=plt.cm.gray)
axes.axis('off')
if i==0:
axes.set_title('Up_face')
axes=plt.subplot(10,7,i*7+7)
down_face=y_test[i].reshape(32,64)
true_face=np.concatenate([up_face,down_face])
axes.imshow(true_face,cmap=plt.cm.gray)
axes.axis('off')
if i==0:
axes.set_title('True_face')
for j,key in enumerate(result):
axes=plt.subplot(10,7,i*7+2+j)
y_=result[key]
predict_down_face=y_[i].reshape(32,64)
predict_face=np.concatenate([up_face,predict_down_face])
axes.imshow(predict_face, cmap=plt.cm.gray)
axes.axis('off')
if i == 0:
axes.set_title(key)
plt.show()