前言
上一环节预览并处理了数据,得到了训练要用的数据输入X,输出y,这里就利用一个简单的cnn网络进行训练及预测
训练
在这里尝试了用’ffill’填充和dropna两种的数据,利用这个小网络训练了120次,其结果均在2.4左右
代码
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
from tensorflow.keras import models, layers
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), input_shape=(96, 96, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(256,activation='relu'))
model.add(layers.Dropout(0.1))
model.add(layers.Dense(30))
model.summary()
model.compile(optimizer='Adam',
loss='mse',
metrics=['mae'])
model.fit(X_train, y_train, epochs=120)
model.save('model-01-drop.h5')
预测
利用测试集进行预测,大致上还是准确的
另外,由于这是对面部关键点检测,当你传入一个不是人脸面部的图片时
代码
df = pd.read_csv("../input/facial-keypoints-detection/test.zip")
df['Image'] = df['Image'].apply(lambda x: np.fromstring(x, dtype=int, sep=' ').reshape(96, 96))
X = np.asarray([df['Image']], dtype=np.float16).reshape(-1,96,96,1)
points = model.predict(X[0].reshape(1,96,96,1))
points
"""
array([[64.78511 , 35.832634, 27.615839, 35.338253, 58.57812 , 36.2881 ,
70.91475 , 37.00126 , 33.636303, 35.92947 , 21.23897 , 36.3847 ,
55.612614, 26.660004, 77.43969 , 29.050682, 36.46391 , 26.003225,
14.312644, 28.624697, 46.97079 , 49.52391 , 60.850235, 73.4968 ,
31.597683, 73.72008 , 46.38033 , 65.98983 , 46.160545, 82.430984]],
dtype=float32)
"""
img = X[0].astype(np.uint8).reshape(96, 96)
plt.imshow(img,cmap='gray')
plt.scatter(points[0][::2],points[0][1::2])
plt.show()