构建自己的VGG16网络模型(不使用官方模板),并进行猫狗分类。写出此代码
时间: 2023-09-17 07:07:23 浏览: 67
深度学习作业-基于resnet50和vgg16网络pytorch框架实现猫狗分类完整源码+代码注释+实验报告.zip
好的,以下是构建自己的VGG16网络模型并进行猫狗分类的代码示例:
```python
import tensorflow as tf
from tensorflow.keras import layers, models
# 构建VGG16网络模型
def VGG16():
model = models.Sequential()
# 第一段卷积层
model.add(layers.Conv2D(64, (3, 3), padding='same', input_shape=(224, 224, 3), activation='relu'))
model.add(layers.Conv2D(64, (3, 3), padding='same', activation='relu'))
model.add(layers.MaxPooling2D((2, 2), strides=(2, 2)))
# 第二段卷积层
model.add(layers.Conv2D(128, (3, 3), padding='same', activation='relu'))
model.add(layers.Conv2D(128, (3, 3), padding='same', activation='relu'))
model.add(layers.MaxPooling2D((2, 2), strides=(2, 2)))
# 第三段卷积层
model.add(layers.Conv2D(256, (3, 3), padding='same', activation='relu'))
model.add(layers.Conv2D(256, (3, 3), padding='same', activation='relu'))
model.add(layers.Conv2D(256, (3, 3), padding='same', activation='relu'))
model.add(layers.MaxPooling2D((2, 2), strides=(2, 2)))
# 第四段卷积层
model.add(layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(layers.MaxPooling2D((2, 2), strides=(2, 2)))
# 第五段卷积层
model.add(layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(layers.MaxPooling2D((2, 2), strides=(2, 2)))
# 全连接层
model.add(layers.Flatten())
model.add(layers.Dense(4096, activation='relu'))
model.add(layers.Dense(4096, activation='relu'))
model.add(layers.Dense(2, activation='softmax'))
return model
# 加载数据集并进行预处理
train_data = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, validation_split=0.2)
train_generator = train_data.flow_from_directory('data/train', target_size=(224, 224), batch_size=32, class_mode='categorical', subset='training')
validation_generator = train_data.flow_from_directory('data/train', target_size=(224, 224), batch_size=32, class_mode='categorical', subset='validation')
# 编译模型并进行训练
model = VGG16()
model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.001), loss='categorical_crossentropy', metrics=['acc'])
history = model.fit(train_generator, epochs=10, validation_data=validation_generator)
# 保存模型
model.save('vgg16_model.h5')
```
在上述代码中,我们首先定义了一个VGG16网络模型,然后加载并预处理了猫狗分类的训练数据集,接着编译模型并进行训练,最后保存了模型。需要注意的是,训练数据集需要按照猫和狗分别放置在不同的文件夹中,并且文件夹名称需要分别为“cat”和“dog”。
阅读全文