基于tensorflow的vgg16
时间: 2023-06-27 14:07:40 浏览: 147
VGG16是深度学习中非常经典的模型之一,其使用了16层卷积神经网络来进行图像分类任务。下面是基于TensorFlow实现VGG16的代码:
```python
import tensorflow as tf
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense
def vgg16(input_shape=(224, 224, 3), num_classes=1000):
inputs = Input(shape=input_shape)
# Block 1
x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(inputs)
x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)
# Block 2
x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)
x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)
# Block 3
x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)
x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)
x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)
# Block 4
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)
# Block 5
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)
# Classification block
x = Flatten(name='flatten')(x)
x = Dense(4096, activation='relu', name='fc1')(x)
x = Dense(4096, activation='relu', name='fc2')(x)
outputs = Dense(num_classes, activation='softmax', name='predictions')(x)
# Create model
model = tf.keras.Model(inputs, outputs)
return model
```
以上代码定义了一个名为`vgg16`的函数,它接受输入的图像大小和输出类别数,并返回一个完整的模型。模型的实现与VGG16论文中所描述的架构一致,包括5个卷积块和一个分类块。
你可以通过调用`vgg16()`函数来创建一个新的VGG16模型,如下所示:
```python
model = vgg16(input_shape=(224, 224, 3), num_classes=1000)
```
其中,`input_shape`指定了输入图像的大小,`num_classes`指定了模型输出的类别数。你可以根据自己的需要来调整这些参数。
阅读全文