前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Kaggle竞赛】AlexNet模型定义及实现

【Kaggle竞赛】AlexNet模型定义及实现

作者头像
嵌入式视觉
发布2022-09-05 13:30:42
2950
发布2022-09-05 13:30:42
举报
文章被收录于专栏:嵌入式视觉

Contents

在图像识别/目标检测领域,基本上CNN的天下,从基础的AlexNet,再到后面更深的GoogleNet、VGGNet等,再到收敛速度更快、泛化性更强ResNet等残差网络,从2012年到现在CNN网络在图像识别/目标检测领域可谓是一个很好的方法。

根据我的经验,在Kaggle竞赛中,基础的LeNet5、AlexNet等CNN模型是不够用的,我在猫狗识别竞赛中使用AlexNet模型,并进行微调,同时稍微调整了不同的超参数,最后得到的Public Score只有7.95506,排名1247/1314。cifar10竞赛稍微好些,Public Score0.27250,排名171/231。

哎,压力山大,这个排名太差了,我都不好意思说出来,可终归是自己算法工程师之路的一个阶段,写下了也是让自己有压力,现阶段还需要好好沉淀自己。

然后,我去网上查了资料,这个文章指出要选择好相应的state-of-art模型,state-of-art模型有ResNet、Inception v3、SPPNet等,只要选择好了与任务相对应的 state-of-art 模型,在代码无 bug,没有实验设置错误的情况下,排进 Top 50% 甚至 Top 15% 难度很小。

当然,实际结果我还没有验证,因为我目前还在没有实验设置错误这个阶段挣扎。

AlexNet模型概述

AlexNet模型结构示意图如下所示:

从图中可以看出,AlexNet包含输入层、5个卷积层和3个全连接层。其中有3个卷积层还进行了最大池化。AlexNet模型创新之处如下:

LRN(局部响应归一化)技术介绍:

Local Response Normalization(LRN)技术主要是深度学习训练时的一种提高准确度的技术方法。其中caffe、tensorflow等里面是很常见的方法,其跟激活函数是有区别的,LRN一般是在激活、池化后进行的一种处理方法。LRN归一化技术首次在AlexNet模型中提出这个概念。

AlexNet模型实现

环境准备

系统:Windows10/Linux系统

软件:Python3、TensorFlow框架(主要是用一些低级api,没有用高层封装(TensorFlow-Slim、TFLearn、Keras和Estimator)。

我这里把局部响应归一化放在池化层后面,但是网上有些版本放在卷积层后面。 输入的原始图像大小为224×224×3(RGB图像),在训练时会经过预处理变为227×227×3。训练集图片尺寸可能不一定是227*227,在输入前需要预处理裁剪成227*227。

代码知识点:通过 tf.get_variable 创建过滤器的权重变量和和偏执变量,权重参数是一个四维矩阵,前两维代表过滤器尺寸,第三个维度代表当前层的深度,第四个维度代表过滤器的深度。

程序设计

代码语言:javascript
复制
# coding:utf-8
# filename:alexnet.py
# Environment:windows10,python3,numpy,TensorFlow1.9,numpy,time
# Function:负责定义设计AlexNet网络

import os
import numpy as np
import tensorflow as tf
# 准备数据程序模块
import input_data

IMG_W=227
IMG_H=227
IMG_C=3
BATCH_SIZE = 20
n_epoch = 10000
n_classes = 2
# 本地电脑训练对应路径地址
train_dir = "F:/Software/Python_Project/Classification-cat-dog/train/"
logs_train_dir = "F:/Software/Python_Project/Classification-cat-dog/logs/"

# 云服务器训练对应路径地址
# train_dir = '/data/Dogs-Cats-Redux-Kernels-Edition/train/'
# logs_train_dir = '/data/Dogs-Cats-Redux-Kernels-Edition/logs/

#----------------------------------------------定义构建网络-------------------------------------
# 占位符,用于得到传递进来的真实训练样本,输入数据为猫狗识别数据集batch
# x  = tf.placeholder(tf.float32,shape=[BATCH_SIZE,IMG_W,IMG_H,IMG_C],name='x')
# y_ = tf.placeholder(tf.int32,shape=[BATCH_SIZE,],name='y_')

def inference(input_tensor,train,batch_size,regularizer,n_classes):
    # conv1,输出矩阵大小(55,55,96)
    with tf.variable_scope('layer1-conv1'):
        conv1_weights = tf.get_variable("weight",[11,11,3,96],initializer=tf.truncated_normal_initializer(stddev=0.1))
        conv1_biases = tf.get_variable("bias", [96], initializer=tf.constant_initializer(0.0))     # 定义偏置变量并初始化
        conv1 = tf.nn.conv2d(input_tensor, conv1_weights, strides=[1, 4, 4, 1], padding='SAME')   # 'VALID'不添加
        relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_biases))                                    # 使用ReLu激活函数,完成去线性化

    # pool1 && norm1,输出矩阵大小(27,27,96)
    with tf.name_scope("layer2-pool1"):
        pool1 = tf.nn.max_pool(relu1, ksize = [1,3,3,1],strides=[1,2,2,1],padding="VALID")
        norm1 = tf.nn.lrn(pool1, depth_radius=4, bias=1.0, alpha=0.001/9.0,beta=0.75, name='norm1') # lrn层,局部响应归一化
        
    # conv2,输出矩阵大小(27,27,256)
    with tf.variable_scope("layer3-conv2"):
        conv2_weights = tf.get_variable("weight",[5,5,96,256],initializer=tf.truncated_normal_initializer(stddev=0.1))
        conv2_biases = tf.get_variable("bias", [256], initializer=tf.constant_initializer(0.0))
        conv2 = tf.nn.conv2d(norm1, conv2_weights, strides=[1, 1, 1, 1], padding='SAME')
        relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_biases))                                      # 使用ReLu激活函数,完成去线性化

    # pool2 && norm2,输出矩阵大小(13,13,256)
    with tf.name_scope("layer4-pool2"):
        pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
        norm2 = tf.nn.lrn(pool2, depth_radius=4, bias=1.0, alpha=0.001/9.0,beta=0.75, name='norm1') # lrn层,局部响应归一化
        
    # conv3,输出矩阵大小(13,13,384)
    with tf.variable_scope("layer5-conv3"):
        conv3_weights = tf.get_variable("weight",[3,3,256,384],initializer=tf.truncated_normal_initializer(stddev=0.1))
        conv3_biases = tf.get_variable("bias", [384], initializer=tf.constant_initializer(0.0))
        conv3 = tf.nn.conv2d(norm2, conv3_weights, strides=[1, 1, 1, 1], padding='SAME')
        relu3 = tf.nn.relu(tf.nn.bias_add(conv3, conv3_biases))                                      # 使用ReLu激活函数,完成去线性化

    # conv4,输出矩阵大小(13,13,384)
    with tf.variable_scope("layer6-conv4"):
        conv4_weights = tf.get_variable("weight",[3,3,384,384],initializer=tf.truncated_normal_initializer(stddev=0.1))
        conv4_biases = tf.get_variable("bias", [384], initializer=tf.constant_initializer(0.0))
        conv4 = tf.nn.conv2d(relu3, conv4_weights, strides=[1, 1, 1, 1], padding='SAME')
        relu4 = tf.nn.relu(tf.nn.bias_add(conv4, conv4_biases))                                      # 使用ReLu激活函数,完成去线性化

    # conv5,输出矩阵大小(13,13,256)
    with tf.variable_scope("layer7-conv5"):
        conv5_weights = tf.get_variable("weight",[3,3,384,256],initializer=tf.truncated_normal_initializer(stddev=0.1))
        conv5_biases = tf.get_variable("bias", [256], initializer=tf.constant_initializer(0.0))
        conv5 = tf.nn.conv2d(relu4, conv5_weights, strides=[1, 1, 1, 1], padding='SAME')
        relu5 = tf.nn.relu(tf.nn.bias_add(conv5, conv5_biases))                                      # 使用ReLu激活函数,完成去线性化

    # pool5 && norm5,输出矩阵大小(6,6,256),13=(13-3)/2+1
    with tf.name_scope("layer8-pool5"):
        pool5 = tf.nn.max_pool(relu5, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='VALID')     # 'VALID'不添加

    # 将第5层池化层的输出转换为第6层全连接层的输入格式(向量)
    # pool_shape = pool5.get_shape().as_list()
    # nodes = pool_shape[1]*pool_shape[2]*pool_shape[3]    # 计算矩阵拉直成向量之后的长度,(pool_shape[1]*pool_shape[2]*pool_shape[3])=(6*6*256)

    # fc1,输出矩阵大小(-1,4096)
    with tf.variable_scope('layer9-fc1'):
        reshaped = tf.reshape(pool5,[batch_size,-1])         # 通过tf.reshaped函数将第5层池化层的输出变成一个batch的向量
        nodes = reshaped.get_shape()[1].value
        fc1_weights = tf.get_variable("weight", [nodes, 4096],
                                      initializer=tf.truncated_normal_initializer(stddev=0.1))
        if regularizer != None: tf.add_to_collection('losses', regularizer(fc1_weights))
        fc1_biases = tf.get_variable("bias", [4096], initializer=tf.constant_initializer(0.1))

        fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_weights) + fc1_biases)
        if train: fc1 = tf.nn.dropout(fc1, 0.5)                                                    # 使用丢失输出技巧dropout
    
    # fc2,输出矩阵大小(-1,4096)
    with tf.variable_scope('layer10-fc2'):
        fc2_weights = tf.get_variable("weight", [4096, 4096],
                                      initializer=tf.truncated_normal_initializer(stddev=0.1))
        if regularizer != None: tf.add_to_collection('losses', regularizer(fc2_weights))
        fc2_biases = tf.get_variable("bias", [4096], initializer=tf.constant_initializer(0.1))

        fc2 = tf.nn.relu(tf.matmul(fc1, fc2_weights) + fc2_biases)
        if train: fc2 = tf.nn.dropout(fc2, 0.5)                                                     # 使用丢失输出技巧dropout

    # fc3,输出层输出矩阵大小(-1,n_classes)=(-1,2)
    with tf.variable_scope('layer11-fc3'):
        fc3_weights = tf.get_variable("weight", [4096, n_classes],
                                      initializer=tf.truncated_normal_initializer(stddev=0.1))
        if regularizer != None: tf.add_to_collection('losses', regularizer(fc3_weights))
        fc3_biases = tf.get_variable("bias", [n_classes], initializer=tf.constant_initializer(0.1))
        logit = tf.matmul(fc2, fc3_weights) + fc3_biases

    # shape:(batch_size,num_classes)=(16,10)
    return logit

# # ------------------------------------网络结束,定义损失、评估模型-------------------------------------------------
# regularizer = tf.contrib.layers.l2_regularizer(0.0001)
# # logits是一个batch_size*10的二维数组
# logits = inference(x,True,regularizer,n_classes)
# print(logits)                                       # 仅供测试程序时用,迭代训练模型时建议注释掉
# # (小处理)将logits乘以1赋值给logits_eval,定义name,方便在后续调用模型时通过tensor名字调用输出tensor
# b = tf.constant(value=1,dtype=tf.float32)
# logits_eval = tf.multiply(logits,b,name='logits_eval') 

# #计算交叉熵作为刻画预测值和真实值之间差距的损失函数
# cross_entroy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y_)
# #计算在当前batch中所有样例的交叉熵平均值
# loss = tf.reduce_mean(cross_entroy,name='loss')+tf.add_n(tf.get_collection('losses'))
# #使用tf.train.AdamOptimizer优化算法来优化损失函数
# train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)

# #计算模型在一个batch数据上的正确率
# correct_prediction = tf.equal(tf.cast(tf.argmax(logits,1),tf.int32), y_)    
# acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# print(loss,acc)                                     # 仅供测试程序时用,迭代训练模型时建议注释掉

# 定义损失函数(labels没有进行one-hot编码)
def losses(logits, labels):
    with tf.variable_scope("loss") as scope:
        cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,
                                                                       labels=labels, name="xentropy_per_example")
        loss = tf.reduce_mean(cross_entropy, name="loss")# 计算张量的平均值
        tf.summary.scalar(scope.name + "loss", loss)     # 对loss汇总和记录
    return loss

# 定义训练函数
def trainning(loss, learning_rate):
    with tf.name_scope("optimizer"):
        # 使用Adam优化器
        optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
        # 定义训练轮数变量
        global_step = tf.Variable(0, name="global_step", trainable=False)
        # 更新参数最小化损失
        train_op = optimizer.minimize(loss, global_step=global_step)
    return train_op
# 定义评估函数,计算准确率
def evaluation(logits,labels):
    with tf.variable_scope('accuracy') as scope:
        correct = tf.nn.in_top_k(logits,labels,1)
        correct = tf.cast(correct,tf.float16)           # 将布尔型数据转换为float16
        accuracy = tf.reduce_mean(correct)              # 计算correct均值得到准确率
        tf.summary.scalar(scope.name+'/accuracy',accuracy)    # 对准确率数据进行汇总
    return accuracy

输出结果

这里还没有开始训练,所以只是加了2个printf来打印输出logits、loss、acc三个张量。输出结果如下图:

There are 12500 cats There are 12500 dogs label: 1 <matplotlib.figure.Figure at 0x1d50d0d3da0> label: 1 <matplotlib.figure.Figure at 0x1d50d0e0d68> Tensor(“layer11-fc3/add:0”, shape=(?, 2), dtype=float32) Tensor(“add:0”, shape=(), dtype=float32) Tensor(“Mean:0”, shape=(), dtype=float32)

值得注意的是,在TensorFlow框架中,我们使用tf.variable_scope和tf.get_variable定义变量,这里我发现一个坑,就是重复运行TensorFlow程序的时候会出现如下报错:

Variable layer1-conv1/weight already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope?

解决办法,如果是Jupyter运行程序,关掉Jupyter,打开再运行即不报错。

总结

这里主要使用的是TensorFlow的低级api构建AlexNet网络,如果是像VGGNet、ResNet50等这些很深的模型,建议要用TensorFLow的高级封装(TensorFlow-Slim、TFLearn、Keras和Estimator)去编写模型定义程序。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • AlexNet模型概述
  • AlexNet模型实现
    • 环境准备
      • 程序设计
        • 输出结果
        • 总结
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档