vgg16结构详细代码
时间: 2023-11-29 10:58:39 浏览: 77
以下是VGG16的详细代码,包括定义网络架构和加载预训练权重:
```python
import tensorflow as tf
def VGG16(input_shape=(224, 224, 3), num_classes=1000):
model = tf.keras.models.Sequential(name='VGG16')
# Block 1
model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=input_shape, name='block1_conv1'))
model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2'))
model.add(tf.keras.layers.MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool'))
# Block 2
model.add(tf.keras.layers.Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1'))
model.add(tf.keras.layers.Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2'))
model.add(tf.keras.layers.MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool'))
# Block 3
model.add(tf.keras.layers.Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1'))
model.add(tf.keras.layers.Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2'))
model.add(tf.keras.layers.Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3'))
model.add(tf.keras.layers.MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool'))
# Block 4
model.add(tf.keras.layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1'))
model.add(tf.keras.layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2'))
model.add(tf.keras.layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3'))
model.add(tf.keras.layers.MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool'))
# Block 5
model.add(tf.keras.layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1'))
model.add(tf.keras.layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2'))
model.add(tf.keras.layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3'))
model.add(tf.keras.layers.MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool'))
# Flatten and Dense layers
model.add(tf.keras.layers.Flatten(name='flatten'))
model.add(tf.keras.layers.Dense(4096, activation='relu', name='fc1'))
model.add(tf.keras.layers.Dense(4096, activation='relu', name='fc2'))
model.add(tf.keras.layers.Dense(num_classes, activation='softmax', name='predictions'))
return model
```
加载预训练权重:
```python
def load_weights(model, weights_path):
model.load_weights(weights_path)
weights_path = 'path/to/weights.h5'
model = VGG16()
load_weights(model, weights_path)
```
阅读全文