使用TensorFlow从头开始实现这个架构

磐创AI
关注

# 绘制模型

tf.keras.utils.plot_model(model, to_file='model.png', show_shapes=True, show_dtype=False,show_layer_names=True, rankdir='TB', expand_nested=False, dpi=96)

模型图的一个片段:

使用TensorFlow的MobileNet模型实现:

import tensorflow as tf

# 导入所有必要的层

from tensorflow.keras.layers import Input, DepthwiseConv2D

from tensorflow.keras.layers import Conv2D, BatchNormalization

from tensorflow.keras.layers import ReLU, AvgPool2D, Flatten, Dense

from tensorflow.keras import Model

# MobileNet block

def mobilnet_block (x, filters, strides):

x = DepthwiseConv2D(kernel_size = 3, strides = strides, padding = 'same')(x)

x = BatchNormalization()(x)

x = ReLU()(x)

x = Conv2D(filters = filters, kernel_size = 1, strides = 1)(x)

x = BatchNormalization()(x)

x = ReLU()(x)

return x

# 模型主干

input = Input(shape = (224,224,3))

x = Conv2D(filters = 32, kernel_size = 3, strides = 2, padding = 'same')(input)

x = BatchNormalization()(x)

x = ReLU()(x)

# 模型的主要部分

x = mobilnet_block(x, filters = 64, strides = 1)

x = mobilnet_block(x, filters = 128, strides = 2)

x = mobilnet_block(x, filters = 128, strides = 1)

x = mobilnet_block(x, filters = 256, strides = 2)

x = mobilnet_block(x, filters = 256, strides = 1)

x = mobilnet_block(x, filters = 512, strides = 2)

for _ in range (5):

x = mobilnet_block(x, filters = 512, strides = 1)

x = mobilnet_block(x, filters = 1024, strides = 2)

x = mobilnet_block(x, filters = 1024, strides = 1)

x = AvgPool2D (pool_size = 7, strides = 1, data_format='channels_first')(x)

output = Dense (units = 1000, activation = 'softmax')(x)

model = Model(inputs=input, outputs=output)

model.summary()

# 绘制模型

tf.keras.utils.plot_model(model, to_file='model.png', show_shapes=True, show_dtype=False,show_layer_names=True, rankdir='TB', expand_nested=False, dpi=96)

结论

MobileNet是最小的深度神经网络之一,它速度快、效率高,可以在没有高端GPU的设备上运行。

当使用Keras(在TensorFlow上)这样的框架时,这些网络的实现非常简单。

声明: 本文由入驻OFweek维科号的作者撰写,观点仅代表作者本人,不代表OFweek立场。如有侵权或其他问题,请联系举报。
侵权投诉

下载OFweek,一手掌握高科技全行业资讯

还不是OFweek会员,马上注册
打开app,查看更多精彩资讯 >
  • 长按识别二维码
  • 进入OFweek阅读全文
长按图片进行保存