【机器学习】六种算法在人脸补全中的应用比较(K紧邻,线性,决策树,岭回归,套索回归,ElasticNet)
生活随笔
收集整理的這篇文章主要介紹了
【机器学习】六种算法在人脸补全中的应用比较(K紧邻,线性,决策树,岭回归,套索回归,ElasticNet)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需求:
根據人的上半邊臉預測下半邊臉,用各種算法取得的結果與原圖比較
-
思考:
這是一個回歸問題,不是分類問題(人臉數據不固定) 數據集一共包含40個人,每一個人10張照片,分布規律
每一個人取出8張照片作為訓練數據,2張照片作為測試數據 樣本特征和樣本標簽如何拆分?上半邊臉作為樣本特征,下半邊臉作為特征標簽
————————————————
人臉圖像補全的方法用途及研究
導包
import numpy as np import matplotlib.pyplot as plt %matplotlib inline #構建方程 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導入datasets中400位人臉數據數據
faces = datasets.fetch_olivetti_faces() X = faces.data images = faces.images y = faces.targetdisplay(X.shape) display(images.shape) display(y.shape)(400, 4096)
(400, 64, 64)
(400,)
plt.figure(figsize=(2,2)) index = np.random.randint(0,400,size =1)[0] img = images[index] plt.imshow(img,cmap = plt.cm.gist_gray)將X(人臉數據)分成上半張人臉和下半張人臉
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 = plt.cm.gray)axes = plt.subplot(1,3,2) down_face = X_down[index].reshape(32,64) axes.imshow(down_face,cmap = plt.cm.gray)axes = plt.subplot(1,3,3) face = X[index].reshape(64,64) axes.imshow(face,cmap = plt.cm.gray) X = X_up.copy() y = X_down.copy() display(X.shape,y.shape)(400, 2048)
(400, 2048)
2048
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['knn'] = KNeighborsRegressor(n_neighbors=5) estimators['lasso'] = Lasso(alpha=0.1) estimators['ElasticNet'] = ElasticNet()estimators['tree'] = DecisionTreeRegressor()#決策樹費時間 2048個樣本特征 #criterion = 'mse' 線性的是gini 和熵 都是越小越好分別調用這六個每個算法
result = {} for key,model in estimators.items():model.fit(X_train,y_train)y_ = model.predict(X_test)#預測的是下班長人臉result[key] = y_結果可視化
plt.figure(figsize=(8*2,2*10,))for i in range(0,10):#繪制第一列,上班張人臉axes = plt.subplot(10,8,i*8+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('upface')#第七列繪制整張人臉axes = plt.subplot(10,8,i*8+8)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('trueface')#繪制第二列到第六列 ,算法預測的數據result,#字典 key 算法value 預測人臉#用enumerate 循環增加了個jfor j , key in enumerate(result): #j,0,1,2,3,4axes = plt.subplot(10,8,i*8+2+j)y_ = result[key]pre_downface = y_[i].reshape(32,64)pre_face = np.concatenate([up_face,pre_downface])axes.imshow(pre_face,cmap = plt.cm.gray)axes.axis('off')if i == 0:axes.set_title(key)總結
以上是生活随笔為你收集整理的【机器学习】六种算法在人脸补全中的应用比较(K紧邻,线性,决策树,岭回归,套索回归,ElasticNet)的全部內容,希望文章能夠幫你解決所遇到的問題。