Python实现DenseNet模型详解:结构、代码与复现
本文详细解析DenseNet模型的核心原理,对比其与ResNet在连接方式上的差异。通过Python代码复现DenseBlock和Transition Layer,讲解特征重用机制及通道数调整方法,并提供完整的网络实现与预测代码,帮助开发者深入理解并应用该模型。
DenseNet模型概述
鉴于DenseNet在性能上被认为优于ResNet,值得深入学习和研究。
ResNet的提出使得构建更深的深度学习神经网络成为可能,从而显著提升了模型的准确度。
ResNet的核心机制在于引入短路连接(shortcuts),将前面层与后面层直接相连,这有助于训练过程中梯度的反向传播,从而支持训练更深的卷积神经网络(CNN)。
DenseNet的基本思路与ResNet相似,同样建立前面层与后面层的连接,但其区别在于建立了前面所有层与当前层的密集连接。
DenseNet的另一个显著特点是实现了特征的重用。
凭借这些特性,DenseNet能够在参数和计算成本更低的情况下,实现比ResNet更优越的性能表现。
DenseNet的整体结构示意图如下所示:

相关代码已下载备查。
DenseNet模型详解
DenseNet的整体架构主要由DenseBlock和中间的过渡模块Transition Layer构成。

如示意图所示,DenseNet由DenseBlock和Transition Layer组成。
DenseBlock是DenseNet特有的模块,如示意图所示,其中前面所有层与当前层之间存在密集连接。在同一个DenseBlock内部,特征层的高度和宽度保持不变,但通道数会发生变化。

Transition Layer是连接不同DenseBlock的模块,主要功能是整合前一个DenseBlock提取的特征,并缩小其宽高。在Transition Layer中,通常使用步长为2的AveragePooling2D来减小特征层的空间尺寸。
DenseBlock的具体实现
DenseBlock的实现流程如示意图所示:

之前获得的特征在保留后会被不断堆叠起来。
以下通过一个简单示例说明DenseBlock的具体工作流程:
假设输入的特征层为X0。
首先,对X0进行1x1卷积以调整通道数至4*32,随后利用3x3卷积获得一个32通道的特征层,此时得到形状为(h,w,32)的特征层x1。
接着,将获得的x1与初始的x0进行堆叠,生成一个新的特征层。该层同时保留了初始x0的特征以及经过卷积处理后的特征。
反复执行上述步骤1和2,原始特征得以持续保留,经过卷积处理后的特征也被保留。随着网络深度的增加,实现了前面所有层与当前层的密集连接。

对应的实现代码如下:
def dense_block(x, blocks, name):
for i in range(blocks):
x = conv_block(x, 32, name=name + '_block' + str(i + 1))
return x
def conv_block(x, growth_rate, name):
bn_axis = 3
x1 = layers.BatchNormalization(axis=bn_axis,
epsilon=1.001e-5,
name=name + '_0_bn')(x)
x1 = layers.Activation('relu', name=name + '_0_relu')(x1)
x1 = layers.Conv2D(4 * growth_rate, 1,
use_bias=False,
name=name + '_1_conv')(x1)
x1 = layers.BatchNormalization(axis=bn_axis, epsilon=1.001e-5,
name=name + '_1_bn')(x1)
x1 = layers.Activation('relu', name=name + '_1_relu')(x1)
x1 = layers.Conv2D(growth_rate, 3,
padding='same',
use_bias=False,
name=name + '_2_conv')(x1)
x = layers.Concatenate(axis=bn_axis, name=name + '_concat')([x, x1])
return x
Transition Layer的实现
Transition Layer用于连接不同的DenseBlock,主要功能是整合前一个DenseBlock获得的特征,并缩小其宽高。在Transition Layer中,通常使用步长为2的AveragePooling2D来减小特征层的宽高。
Transition Layer的实现代码如下:
def transition_block(x, reduction, name):
bn_axis = 3
x = layers.BatchNormalization(axis=bn_axis, epsilon=1.001e-5,
name=name + '_bn')(x)
x = layers.Activation('relu', name=name + '_relu')(x)
x = layers.Conv2D(int(backend.int_shape(x)[bn_axis] * reduction), 1,
use_bias=False,
name=name + '_conv')(x)
x = layers.AveragePooling2D(2, strides=2, name=name + '_pool')(x)
return x
完整的网络实现代码
from keras.preprocessing import image
from keras.models import Model
from keras import layers
from keras.applications import imagenet_utils
from keras.applications.imagenet_utils import decode_predictions
from keras.utils.data_utils import get_file
from keras import backend
import numpy as np
BASE_WEIGTHS_PATH = (
'https://github.com/keras-team/keras-applications/'
'releases/download/densenet/')
DENSENET121_WEIGHT_PATH = (
BASE_WEIGTHS_PATH +
'densenet121_weights_tf_dim_ordering_tf_kernels.h5')
DENSENET169_WEIGHT_PATH = (
BASE_WEIGTHS_PATH +
'densenet169_weights_tf_dim_ordering_tf_kernels.h5')
DENSENET201_WEIGHT_PATH = (
BASE_WEIGTHS_PATH +
'densenet201_weights_tf_dim_ordering_tf_kernels.h5')
def dense_block(x, blocks, name):
for i in range(blocks):
x = conv_block(x, 32, name=name + '_block' + str(i + 1))
return x
def conv_block(x, growth_rate, name):
bn_axis = 3
x1 = layers.BatchNormalization(axis=bn_axis,
epsilon=1.001e-5,
name=name + '_0_bn')(x)
x1 = layers.Activation('relu', name=name + '_0_relu')(x1)
x1 = layers.Conv2D(4 * growth_rate, 1,
use_bias=False,
name=name + '_1_conv')(x1)
x1 = layers.BatchNormalization(axis=bn_axis, epsilon=1.001e-5,
name=name + '_1_bn')(x1)
x1 = layers.Activation('relu', name=name + '_1_relu')(x1)
x1 = layers.Conv2D(growth_rate, 3,
padding='same',
use_bias=False,
name=name + '_2_conv')(x1)
x = layers.Concatenate(axis=bn_axis, name=name + '_concat')([x, x1])
return x
def transition_block(x, reduction, name):
bn_axis = 3
x = layers.BatchNormalization(axis=bn_axis, epsilon=1.001e-5,
name=name + '_bn')(x)
x = layers.Activation('relu', name=name + '_relu')(x)
x = layers.Conv2D(int(backend.int_shape(x)[bn_axis] * reduction), 1,
use_bias=False,
name=name + '_conv')(x)
x = layers.AveragePooling2D(2, strides=2, name=name + '_pool')(x)
return x
def DenseNet(blocks,
input_shape=None,
classes=1000,
**kwargs):
img_input = layers.Input(shape=input_shape)
bn_axis = 3
# 224,224,3 -> 112,112,64
x = layers.ZeroPadding2D(padding=((3, 3), (3, 3)))(img_input)
x = layers.Conv2D(64, 7, strides=2, use_bias=False, name='conv1/conv')(x)
x = layers.BatchNormalization(
axis=bn_axis, epsilon=1.001e-5, name='conv1/bn')(x)
x = layers.Activation('relu', name='conv1/relu')(x)
# 112,112,64 -> 56,56,64
x = layers.ZeroPadding2D(padding=((1, 1), (1, 1)))(x)
x = layers.MaxPooling2D(3, strides=2, name='pool1')(x)
# 56,56,64 -> 56,56,64+32*block[0]
# Densenet121 56,56,64 -> 56,56,64+32*6 == 56,56,256
x = dense_block(x, blocks[0], name='conv2')
# 56,56,64+32*block[0] -> 28,28,32+16*block[0]
# Densenet121 56,56,256 -> 28,28,32+16*6 == 28,28,128
x = transition_block(x, 0.5, name='pool2')
# 28,28,32+16*block[0] -> 28,28,32+16*block[0]+32*block[1]
# Densenet121 28,28,128 -> 28,28,128+32*12 == 28,28,512
x = dense_block(x, blocks[1], name='conv3')
# Densenet121 28,28,512 -> 14,14,256
x = transition_block(x, 0.5, name='pool3')
# Densenet121 14,14,256 -> 14,14,256+32*block[2] == 14,14,1024
x = dense_block(x, blocks[2], name='conv4')
# Densenet121 14,14,1024 -> 7,7,512
x = transition_block(x, 0.5, name='pool4')
# Densenet121 7,7,512 -> 7,7,256+32*block[3] == 7,7,1024
x = dense_block(x, blocks[3], name='conv5')
x = layers.BatchNormalization(axis=bn_axis, epsilon=1.001e-5, name='bn')(x)
x = layers.Activation('relu', name='relu')(x)
x = layers.GlobalAveragePooling2D(name='avg_pool')(x)
x = layers.Dense(classes, activation='softmax', name='fc1000')(x)
inputs = img_input
if blocks == [6, 12, 24, 16]:
model = Model(inputs, x, name='densenet121')
elif blocks == [6, 12, 32, 32]:
model = Model(inputs, x, name='densenet169')
elif blocks == [6, 12, 48, 32]:
model = Model(inputs, x, name='densenet201')
else:
model = Model(inputs, x, name='densenet')
return model
def DenseNet121(input_shape=[224,224,3],
classes=1000,
**kwargs):
return DenseNet([6, 12, 24, 16],
input_shape, classes,
**kwargs)
def DenseNet169(input_shape=[224,224,3],
classes=1000,
**kwargs):
return DenseNet([6, 12, 32, 32],
input_shape, classes,
**kwargs)
def DenseNet201(input_shape=[224,224,3],
classes=1000,
**kwargs):
return DenseNet([6, 12, 48, 32],
input_shape, classes,
**kwargs)
def preprocess_input(x):
x /= 255.
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
x[..., 0] -= mean[0]
x[..., 1] -= mean[1]
x[..., 2] -= mean[2]
if std is not None:
x[..., 0] /= std[0]
x[..., 1] /= std[1]
x[..., 2] /= std[2]
return x
if __name__ == '__main__':
# model = DenseNet121()
# weights_path = get_file(
# 'densenet121_weights_tf_dim_ordering_tf_kernels.h5',
# DENSENET121_WEIGHT_PATH,
# cache_subdir='models',
# file_hash='9d60b8095a5708f2dcce2bca79d332c7')
model = DenseNet169()
weights_path = get_file(
'densenet169_weights_tf_dim_ordering_tf_kernels.h5',
DENSENET169_WEIGHT_PATH,
cache_subdir='models',
file_hash='d699b8f76981ab1b30698df4c175e90b')
# model = DenseNet201()
# weights_path = get_file(
# 'densenet201_weights_tf_dim_ordering_tf_kernels.h5',
# DENSENET201_WEIGHT_PATH,
# cache_subdir='models',
# file_hash='1ceb130c1ea1b78c3bf6114dbdfd8807')
model.load_weights(weights_path)
model.summary()
img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
print('Input image shape:', x.shape)
preds = model.predict(x)
print(np.argmax(preds))
print('Predicted:', decode_predictions(preds))
以上即为Python神经网络DenseNet模型复现的详细内容,更多关于DenseNet模型复现的资料请持续关注本站其他相关文章。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









