问题描述
根据人脸上半脸预测下班脸,数据集在
from sklearn.datasets import fetch_olivetti_faces
代码实现
一开始,我用了库里面的标准线性回归模型进行预测,结果发现效果不太好,以下为一开始的代码与效果
import matplotlib.pyplot as plt
import tensorflow as tf
tf = tf.compat.v1
tf.disable_v2_behavior()
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import r2_score
from sklearn.datasets import fetch_olivetti_faces
import numpy as np
from sklearn.linear_model import LinearRegression
def process_feature(X):
scaler=StandardScaler()
X=scaler.fit_transform(X)
scaler=MinMaxScaler(feature_range=(-1,1))
X=scaler.fit_transform(X)
return X
data=fetch_olivetti_faces()
images=data.images
plt.imshow(images[0])
plt.show()
data=images.reshape((len(data.images),-1))
n_pixels=data.shape[1]
n_samples=data.shape[0]
X_lode=data[:,:(n_pixels+1)//2]
y_lode=data[:,n_pixels//2:]
X_train,X_test,y_train,y_test=train_test_split(X_lode,y_lode,test_size=0.2,random_state=0)
X_train=process_feature(X_train)
X_test=process_feature(X_test)
model=LinearRegression()
reg=model.fit(X_train,y_train)
y_pred=model.predict(X_test)
coef=model.coef_
r2=r2_score(y_test,y_pred)
print("coef{}".format(coef))
print("r2={}".format(r2))
id=6
true_face=np.hstack((X_test[id],y_test[id]))
pred_face=np.hstack((X_test[id],y_pred[id]))
plt.figure()
image_shape=(64,64)
plt.figure(0)
plt.imshow(true_face.reshape(image_shape),interpolation="nearest")
plt.figure(1)
plt.imshow(pred_face.reshape(image_shape),interpolation="nearest")
plt.show()
下面的效果图还挺可怕的,尽量不要在晚上看
发现这个图是真的不大对,看着只有上面出问题了,想着是不是因为我做了标准化的原因,去掉标准化之后果然图片正确了起来
以下是正确运行代码
import matplotlib.pyplot as plt
import tensorflow as tf
tf = tf.compat.v1
tf.disable_v2_behavior()
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import r2_score
from sklearn.datasets import fetch_olivetti_faces
import numpy as np
from sklearn.linear_model import LinearRegression
data=fetch_olivetti_faces()
images=data.images
plt.imshow(images[0])
plt.show()
data=images.reshape((len(data.images),-1))
n_pixels=data.shape[1]
n_samples=data.shape[0]
X_lode=data[:,:(n_pixels+1)//2]
y_lode=data[:,n_pixels//2:]
X_train,X_test,y_train,y_test=train_test_split(X_lode,y_lode,test_size=0.2,random_state=0)
model=LinearRegression()
reg=model.fit(X_train,y_train)
y_pred=model.predict(X_test)
coef=model.coef_
r2=r2_score(y_test,y_pred)
print("coef{}".format(coef))
print("r2={}".format(r2))
id=6
true_face=np.hstack((X_test[id],y_test[id]))
pred_face=np.hstack((X_test[id],y_pred[id]))
plt.figure()
image_shape=(64,64)
plt.figure(0)
plt.imshow(true_face.reshape(image_shape),interpolation="nearest")
plt.figure(1)
plt.imshow(pred_face.reshape(image_shape),interpolation="nearest")
plt.show()
结果图为