使用VGG-19模型训练自己的数据集

前言:

上一节介绍的图像识别中一个经典的模型AlexNet,今天介绍的是图像识别领域另一个经典的模型VGG-19。VGG-19是由牛津大学的Oxford Visual Geometry Group实验室发明的。因为不像是AlexNet是由Alex一个人完成的。所以这个模型就按照实验室的名称的缩写命名。VGG-19和AlexNet的整体架构是相似的,只是在AlexNet进行了一些改进,具体的有。

第一: VGG16相比AlexNet的一个改进是采用连续的几个3x3的卷积核代替AlexNet中的较大卷积核(11x11,7x7,5x5)

第二: VGGNet的结构非常简洁,整个网络都使用了同样大小的卷积核尺寸(3x3)和最大池化尺寸(2x2)

VGG-19的架构图:

首先让我们看一下VGG的发展历程,第三行表示VGG不同版本的卷积层数,从11层到13再到16最后达到19层。

首先同样是本程序的主程序:

和上一节的AlexNet几乎一毛一样。所以只把代码公布一下,就不做解释了。

# -*- coding: utf-8 -*-
# @Time    : 2019/7/2 16:07
# @Author  : YYLin
# @Email   : [email protected]
# @File    : VGG_19_Train.py
# 定义一些模型中所需要的参数
from VGG_19 import VGG19
import tensorflow as tf
import os
import cv2
import numpy as np
from keras.utils import to_categorical

batch_size = 64
img_high = 100
img_width = 100
Channel = 3
label = 9

# 定义输入图像的占位符
inputs = tf.placeholder(tf.float32, [batch_size, img_high, img_width, Channel], name='inputs')
y = tf.placeholder(dtype=tf.float32, shape=[batch_size, label], name='label')
keep_prob = tf.placeholder("float")
is_train = tf.placeholder(tf.bool)

model = VGG19(inputs, keep_prob, label)
score = model.fc8
softmax_result = tf.nn.softmax(score)

# 定义损失函数 以及相对应的优化器
cross_entropy = -tf.reduce_sum(y*tf.log(softmax_result))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

# 显示最后预测的结果
correct_prediction = tf.equal(tf.argmax(softmax_result, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))


# 现在的我只需要加载图像和对应的label即可 不需要加载text中的内容
def load_satetile_image(batch_size=128, dataset='train'):
    img_list = []
    label_list = []
    dir_counter = 0

    if dataset == 'train':
        path = '../Dataset/baidu/train_image/train'

        # 对路径下的所有子文件夹中的所有jpg文件进行读取并存入到一个list中
        for child_dir in os.listdir(path):
            child_path = os.path.join(path, child_dir)
            for dir_image in os.listdir(child_path):
                img = cv2.imread(os.path.join(child_path, dir_image))
                img = img / 255.0
                img_list.append(img)
                label_list.append(dir_counter)

            dir_counter += 1
    else:
        path = '../Dataset/baidu/valid_image/valid'

        # 对路径下的所有子文件夹中的所有jpg文件进行读取并存入到一个list中
        for child_dir in os.listdir(path):
            child_path = os.path.join(path, child_dir)
            for dir_image in os.listdir(child_path):
                img = cv2.imread(os.path.join(child_path, dir_image))
                img = img / 255.0
                img_list.append(img)
                label_list.append(dir_counter)

            dir_counter += 1

    # 返回的img_list转成了 np.array的格式
    X_train = np.array(img_list)
    Y_train = to_categorical(label_list, 9)
    # print('to_categorical之后Y_train的类型和形状:', type(Y_train), Y_train.shape)

    # 加载数据的时候 重新排序
    data_index = np.arange(X_train.shape[0])
    np.random.shuffle(data_index)
    data_index = data_index[:batch_size]
    x_batch = X_train[data_index, :, :, :]
    y_batch = Y_train[data_index, :]

    return x_batch, y_batch


# 开始feed 数据并且训练数据
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(500000//batch_size):
        # 加载训练集和验证集
        img, img_label = load_satetile_image(batch_size, dataset='train')
        img_valid, img_valid_label = load_satetile_image(batch_size, dataset='vaild')
        # print('使用 mnist.train.next_batch加载的数据集形状', img.shape, type(img))

        # print('模型使用的是dropout的模型')
        dropout_rate = 0.5
        # print('经过 tf.reshape之后数据的形状以及类型是:', img.shape, type(img))
        if i % 20 == 0:
            train_accuracy = accuracy.eval(feed_dict={inputs: img, y: img_label, keep_prob: dropout_rate})
            print("step %d, training accuracy %g" % (i, train_accuracy))
        train_step.run(feed_dict={inputs: img, y: img_label, keep_prob: dropout_rate})

        # 输出验证集上的结果
        if i % 50 == 0:
            dropout_rate = 1
            valid_socre = accuracy.eval(feed_dict={inputs: img_valid, y: img_valid_label, keep_prob: dropout_rate})
            print("step %d, valid accuracy %g" % (i, valid_socre))

本节的核心代码 VGG-19:

从图中我们可以看到VGG-19有16个卷积层,卷积层的通道数分别是64、128、256、512。最后有三个全连接层通道数分别是4096,4096,1000。

第一: VGG-19所有的卷积核大小都是 3 * 3,  步长为1 * 1。 代码中满足要求

第二: VGG-19所有最大池化层的卷积核大小为2 * 2, 步长为1 * 1  代码中满足要求

第三: 根据上图查看一下每层卷积操作的通道数是否与代码对应    显然代码满足要求。

第四: 在第一节的时候我们向模型中增加一些优化技巧,我们发现使用batch normalize的话,能够极大的提高模型的准确率。但是VGG-19中并没有增加。 尝试增加batch normalize。而且也没有使用一些激活函数,所以说这个模型可以尝试的优化方案还是很多的。

# -*- coding: utf-8 -*-
# @Time    : 2019/7/2 8:18
# @Author  : YYLin
# @Email   : [email protected]
# @File    : VGG_19.py
# 本模型为VGG-19参考代码链接
import tensorflow as tf


def maxPoolLayer(x, kHeight, kWidth, strideX, strideY, name, padding="SAME"):
    return tf.nn.max_pool(x, ksize=[1, kHeight, kWidth, 1],
                          strides=[1, strideX, strideY, 1], padding=padding, name=name)


def dropout(x, keepPro, name=None):
    return tf.nn.dropout(x, keepPro, name)


def fcLayer(x, inputD, outputD, reluFlag, name):
    with tf.variable_scope(name) as scope:
        w = tf.get_variable("w", shape=[inputD, outputD], dtype="float")
        b = tf.get_variable("b", [outputD], dtype="float")
        out = tf.nn.xw_plus_b(x, w, b, name=scope.name)
        if reluFlag:
            return tf.nn.relu(out)
        else:
            return out


def convLayer(x, kHeight, kWidth, strideX, strideY, featureNum, name, padding = "SAME"):

    channel = int(x.get_shape()[-1])
    with tf.variable_scope(name) as scope:
        w = tf.get_variable("w", shape=[kHeight, kWidth, channel, featureNum])
        b = tf.get_variable("b", shape=[featureNum])
        featureMap = tf.nn.conv2d(x, w, strides=[1, strideY, strideX, 1], padding=padding)
        out = tf.nn.bias_add(featureMap, b)
        return tf.nn.relu(tf.reshape(out, featureMap.get_shape().as_list()), name=scope.name)


class VGG19(object):
    def __init__(self, x, keepPro, classNum):
        self.X = x
        self.KEEPPRO = keepPro
        self.CLASSNUM = classNum
        self.begin_VGG_19()

    def begin_VGG_19(self):
        """build model"""
        conv1_1 = convLayer(self.X, 3, 3, 1, 1, 64, "conv1_1" )
        conv1_2 = convLayer(conv1_1, 3, 3, 1, 1, 64, "conv1_2")
        pool1 = maxPoolLayer(conv1_2, 2, 2, 2, 2, "pool1")

        conv2_1 = convLayer(pool1, 3, 3, 1, 1, 128, "conv2_1")
        conv2_2 = convLayer(conv2_1, 3, 3, 1, 1, 128, "conv2_2")
        pool2 = maxPoolLayer(conv2_2, 2, 2, 2, 2, "pool2")

        conv3_1 = convLayer(pool2, 3, 3, 1, 1, 256, "conv3_1")
        conv3_2 = convLayer(conv3_1, 3, 3, 1, 1, 256, "conv3_2")
        conv3_3 = convLayer(conv3_2, 3, 3, 1, 1, 256, "conv3_3")
        conv3_4 = convLayer(conv3_3, 3, 3, 1, 1, 256, "conv3_4")
        pool3 = maxPoolLayer(conv3_4, 2, 2, 2, 2, "pool3")

        conv4_1 = convLayer(pool3, 3, 3, 1, 1, 512, "conv4_1")
        conv4_2 = convLayer(conv4_1, 3, 3, 1, 1, 512, "conv4_2")
        conv4_3 = convLayer(conv4_2, 3, 3, 1, 1, 512, "conv4_3")
        conv4_4 = convLayer(conv4_3, 3, 3, 1, 1, 512, "conv4_4")
        pool4 = maxPoolLayer(conv4_4, 2, 2, 2, 2, "pool4")

        conv5_1 = convLayer(pool4, 3, 3, 1, 1, 512, "conv5_1")
        conv5_2 = convLayer(conv5_1, 3, 3, 1, 1, 512, "conv5_2")
        conv5_3 = convLayer(conv5_2, 3, 3, 1, 1, 512, "conv5_3")
        conv5_4 = convLayer(conv5_3, 3, 3, 1, 1, 512, "conv5_4")
        pool5 = maxPoolLayer(conv5_4, 2, 2, 2, 2, "pool5")
        print('最后一层卷积层的形状是:', pool5.shape)

        fcIn = tf.reshape(pool5, [-1, 4*4*512])
        fc6 = fcLayer(fcIn, 4*4*512, 4096, True, "fc6")
        dropout1 = dropout(fc6, self.KEEPPRO)

        fc7 = fcLayer(dropout1, 4096, 4096, True, "fc7")
        dropout2 = dropout(fc7, self.KEEPPRO)

        self.fc8 = fcLayer(dropout2, 4096, self.CLASSNUM, True, "fc8")


VGG-19增加batch normalize: 亲测是可以使用的,但是需要将batch_size修改成32不然GPU显存溢出

# -*- coding: utf-8 -*-
# @Time    : 2019/7/2 16:57
# @Author  : YYLin
# @Email   : [email protected]
# @File    : VGG_19_BN.py
import tensorflow as tf


# 相对于第一个版本 增加的批量正则化 2019 7 2
def bn(x, is_training):
    return tf.layers.batch_normalization(x, training=is_training)


def maxPoolLayer(x, kHeight, kWidth, strideX, strideY, name, padding="SAME"):
    return tf.nn.max_pool(x, ksize=[1, kHeight, kWidth, 1],
                          strides=[1, strideX, strideY, 1], padding=padding, name=name)


def dropout(x, keepPro, name=None):
    return tf.nn.dropout(x, keepPro, name)


def fcLayer(x, inputD, outputD, reluFlag, name):
    with tf.variable_scope(name) as scope:
        w = tf.get_variable("w", shape=[inputD, outputD], dtype="float")
        b = tf.get_variable("b", [outputD], dtype="float")
        out = tf.nn.xw_plus_b(x, w, b, name=scope.name)
        if reluFlag:
            return tf.nn.relu(out)
        else:
            return out


def convLayer(x, kHeight, kWidth, strideX, strideY, featureNum, name, padding = "SAME"):

    channel = int(x.get_shape()[-1])
    with tf.variable_scope(name) as scope:
        w = tf.get_variable("w", shape=[kHeight, kWidth, channel, featureNum])
        b = tf.get_variable("b", shape=[featureNum])
        featureMap = tf.nn.conv2d(x, w, strides=[1, strideY, strideX, 1], padding=padding)
        out = tf.nn.bias_add(featureMap, b)
        return tf.nn.relu(tf.reshape(out, featureMap.get_shape().as_list()), name=scope.name)


class VGG19(object):
    def __init__(self, x, keepPro, classNum, is_training):
        self.X = x
        self.KEEPPRO = keepPro
        self.CLASSNUM = classNum
        self.is_training = is_training
        self.begin_VGG_19()

    def begin_VGG_19(self):
        """build model"""
        conv1_1 = convLayer(self.X, 3, 3, 1, 1, 64, "conv1_1" )
        conv1_1 = bn(conv1_1, self.is_training)

        conv1_2 = convLayer(conv1_1, 3, 3, 1, 1, 64, "conv1_2")
        conv1_2 = bn(conv1_2, self.is_training)
        pool1 = maxPoolLayer(conv1_2, 2, 2, 2, 2, "pool1")

        conv2_1 = convLayer(pool1, 3, 3, 1, 1, 128, "conv2_1")
        conv2_1 = bn(conv2_1, self.is_training)

        conv2_2 = convLayer(conv2_1, 3, 3, 1, 1, 128, "conv2_2")
        conv2_2 = bn(conv2_2, self.is_training)
        pool2 = maxPoolLayer(conv2_2, 2, 2, 2, 2, "pool2")

        conv3_1 = convLayer(pool2, 3, 3, 1, 1, 256, "conv3_1")
        conv3_1 = bn(conv3_1, self.is_training)

        conv3_2 = convLayer(conv3_1, 3, 3, 1, 1, 256, "conv3_2")
        conv3_2 = bn(conv3_2, self.is_training)

        conv3_3 = convLayer(conv3_2, 3, 3, 1, 1, 256, "conv3_3")
        conv3_3 = bn(conv3_3, self.is_training)

        conv3_4 = convLayer(conv3_3, 3, 3, 1, 1, 256, "conv3_4")
        conv3_4 = bn(conv3_4, self.is_training)
        pool3 = maxPoolLayer(conv3_4, 2, 2, 2, 2, "pool3")

        conv4_1 = convLayer(pool3, 3, 3, 1, 1, 512, "conv4_1")
        conv4_1 = bn(conv4_1, self.is_training)

        conv4_2 = convLayer(conv4_1, 3, 3, 1, 1, 512, "conv4_2")
        conv4_2 = bn(conv4_2, self.is_training)
        
        conv4_3 = convLayer(conv4_2, 3, 3, 1, 1, 512, "conv4_3")
        conv4_3 = bn(conv4_3, self.is_training)
        
        conv4_4 = convLayer(conv4_3, 3, 3, 1, 1, 512, "conv4_4")
        conv4_4 = bn(conv4_4, self.is_training)
        pool4 = maxPoolLayer(conv4_4, 2, 2, 2, 2, "pool4")

        conv5_1 = convLayer(pool4, 3, 3, 1, 1, 512, "conv5_1")
        conv5_1 = bn(conv5_1, self.is_training)
        
        conv5_2 = convLayer(conv5_1, 3, 3, 1, 1, 512, "conv5_2")
        conv5_2 = bn(conv5_2, self.is_training)
        
        conv5_3 = convLayer(conv5_2, 3, 3, 1, 1, 512, "conv5_3")
        conv5_3 = bn(conv5_3, self.is_training)
        
        conv5_4 = convLayer(conv5_3, 3, 3, 1, 1, 512, "conv5_4")
        conv5_4 = bn(conv5_4, self.is_training)
        
        pool5 = maxPoolLayer(conv5_4, 2, 2, 2, 2, "pool5")
        print('最后一层卷积层的形状是:', pool5.shape)

        fcIn = tf.reshape(pool5, [-1, 4*4*512])
        fc6 = fcLayer(fcIn, 4*4*512, 4096, True, "fc6")
        dropout1 = dropout(fc6, self.KEEPPRO)

        fc7 = fcLayer(dropout1, 4096, 4096, True, "fc7")
        dropout2 = dropout(fc7, self.KEEPPRO)

        self.fc8 = fcLayer(dropout2, 4096, self.CLASSNUM, True, "fc8")


 

VGG-19模型运行的结果分析:

VGG-19 增加BN之后的结果分析:

猜你喜欢

转载自blog.csdn.net/qq_41776781/article/details/94452085