inception V3用迁移学习实现代码
时间: 2023-07-11 17:52:41 浏览: 131
以下是使用Inception V3进行迁移学习实现的Python代码示例。假设你已经安装了TensorFlow和Keras,并且已经准备好了用于训练的数据集。
```python
import tensorflow as tf
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.models import Model
# 设置数据集路径
train_data_dir = 'path/to/training/dataset'
validation_data_dir = 'path/to/validation/dataset'
# 设置训练参数
batch_size = 32
epochs = 10
num_classes = 2
# 创建Inception V3模型
base_model = InceptionV3(weights='imagenet', include_top=False)
# 添加全局平均池化层
x = base_model.output
x = GlobalAveragePooling2D()(x)
# 添加全连接层和softmax激活层
x = Dense(1024, activation='relu')(x)
predictions = Dense(num_classes, activation='softmax')(x)
# 构建完整的模型
model = Model(inputs=base_model.input, outputs=predictions)
# 冻结Inception V3模型的所有层
for layer in base_model.layers:
layer.trainable = False
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 数据增强生成器
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
validation_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(299, 299),
batch_size=batch_size,
class_mode='categorical')
validation_generator = validation_datagen.flow_from_directory(
validation_data_dir,
target_size=(299, 299),
batch_size=batch_size,
class_mode='categorical')
# 训练模型
model.fit_generator(
train_generator,
steps_per_epoch=train_generator.samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=validation_generator.samples // batch_size)
# 保存模型
model.save('inceptionv3_model.h5')
```
以上代码中,我们使用了Keras中的ImageDataGenerator类来进行数据增强,以增加数据集的多样性。我们还通过调用fit_generator()方法来训练模型,并使用了save()方法将训练好的模型保存到本地。
阅读全文