机器学习之sklearn工具包(回归算法补全人脸)

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(人脸数据)分成上半张人脸和下半zhangrenlian
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')
    # 绘制第二列到第六列,算法预测的数据resul,字典,key算法,value 预测人脸
    for j,key in enumerate(result): #j 0,1,2,3,4
        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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值