VGGNet 参考论文Very Deep Convolutional Networks for Large-Scale Image Recognition
VGGNet代码实现参考《Tensorflow实战》黄文坚
Fer2013图片48*48,train_set一共28708张图,测试集有两个,pub_test_set和pri_test_set各3589张图。一共7种表情,类别为0-6。
利用Google的Colab来跑模型,自己的电脑实在太慢了。
结果:
在经过41个epoch之后,模型收敛。
这时候对Fer2013 public测试集的分类精度为47.45%。对private测试集的分类精度为46.92%。
人眼分辨Fer2013的准确率为65%左右。
步骤:
1.将一整个Fer2013分为训练集和两个测试集,分别存为csv文件。
2.读入三个文件。
3.将48*48的图片resize为224*224的标准大小图片。
4.进行训练,在每次训练完成后都直接对两个测试集进行测试。
遇到的问题:
1.一开始没将图片resize为224*224,48*48的图片经过VGG的5层2*2的池化层之后,图片大小变为了1*1,特征全没了,训练失败。
2.学习速率过低,一开始的学习速率定为0.001,导致模型收敛极慢。
3.训练集过大,程序中需要将48*48的图像改成224*224的图。无论是在程序中进行resize还是读取resize之后的csv文件都特别慢,值得一提的是,resize之后的train_set的大小为7.53 GB。
---解决:使用openCV的cv2.resize来改变图像大小,速度快了很多。
---疑问:为什么openCV的resize比自己实现的resize快这么多?是不是因为openCV的resize用的不是python,是C或汇编之类的?
4.用Colab来跑也还是太慢了,跑到最后才读完数据并训练了19个epoch,目标训练100个epoch,但是Colab会把长时间占用GPU的我踢掉。
---解决:在解决了上面的问题后,时间已经够模型收敛了。
VGGNet的具体代码是直接抄书的
上代码:
#@title
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 16 10:00:07 2018
@author: Administrator
"""
from datetime import datetime
import tensorflow as tf
import pandas as pd
import numpy as np
import csv
import cv2
f_train = open("drive//fer2013//traincpy.csv", encoding = 'UTF-8')
df_train = pd.read_csv(f_train)
#f_train_resize = open("drive//fer2013//trainresize.csv", encoding = 'UTF-8')
#df_train_resize = pd.read_csv(f_train_resize)
f_test_pub = open("drive//fer2013//valcpy.csv", encoding = 'UTF-8')
df_test_pub = pd.read_csv(f_test_pub)
f_test_pri = open("drive//fer2013//testcpy.csv", encoding = 'UTF-8')
df_test_pri = pd.read_csv(f_test_pri)
print('read csv file finished')
train_featuresets = df_train.iloc[1: , 1: ]
train_emotionsets = df_train.iloc[1: , 0:1]
test_pub_featuresets = df_test_pub.iloc[0: , 1: ]
test_pub_emotionsets = df_test_pub.iloc[0: , 0:1]
test_pri_featuresets = df_test_pri.iloc[0: , 1: ]
test_pri_emotionsets = df_test_pri.iloc[0: , 0:1]
print('dataset load finished')
#train_featuresets_resize = df_train_resize.iloc[1: , 0: ]
#train_feature_resize = tf.constant(train_featuresets_resize)
#train_feature_resize = tf.reshape(train_feature_resize, [-1, 224, 224, 1])
#train_emotion = np.reshape(np.array(train_emotionsets, dtype = 'float32'), (-1))
#print(train_feature_resize.shape)
#train_feature = tf.constant(train_featuresets)
#train_emotion = tf.constant(train_emotionsets)
#train_feature = tf.reshape(train_feature, [-1, 48, 48, 1])
#train_emotion = tf.reshape(train_emotion, [-1, 1])
#双线性插值,讲48*48的图片变成224*224
def resize(src, new_size):
dst_w = 224
dst_h = 224 # 目标图像宽高
src_h = 48
src_w = 48 # 源图像宽高
if src_h == dst_h and src_w == dst_w:
return src.copy()
scale_x = float(src_w) / dst_w # x缩放比例
scale_y = float(src_h) / dst_h # y缩放比例