tensorflow - 在迁移学习:InceptionV3 中,我的损失是“nan”,准确度是“0.0000e+00”
问题描述
我正在研究迁移学习。我的用例是对两类图像进行分类。我使用 InceptionV3 对图像进行分类。在训练我的模型时,我得到nan作为损失和0.0000e+00作为每个时期的准确度。我使用了 20 个 epoch,因为我的数据量很小:我有 1000 张图像用于训练,100 张用于测试,每批 5 条记录。
from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing import image
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from keras import backend as K
# create the base pre-trained model
base_model = InceptionV3(weights='imagenet', include_top=False)
# add a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)
# let's add a fully-connected layer
x = Dense(1024, activation='relu')(x)
x = Dense(512, activation='relu')(x)
x = Dense(32, activation='relu')(x)
# and a logistic layer -- we have 2 classes
predictions = Dense(1, activation='softmax')(x)
# this is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)
for layer in base_model.layers:
layer.trainable = False
# we chose to train the top 2 inception blocks, i.e. we will freeze
# the first 249 layers and unfreeze the rest:
for layer in model.layers[:249]:
layer.trainable = False
for layer in model.layers[249:]:
layer.trainable = True
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
training_set = train_datagen.flow_from_directory(
'C:/Users/Desktop/Transfer/train/',
target_size=(64, 64),
batch_size=5,
class_mode='binary')
test_set = test_datagen.flow_from_directory(
'C:/Users/Desktop/Transfer/test/',
target_size=(64, 64),
batch_size=5,
class_mode='binary')
model.fit_generator(
training_set,
steps_per_epoch=1000,
epochs=20,
validation_data=test_set,
validation_steps=100)
解决方案
听起来你的渐变正在爆炸。这可能有几个原因:
- 检查您的输入是否正确生成。例如使用
save_to_dir
参数flow_from_directory
- 由于您的批量大小为 5,请修复
steps_per_epoch
from1000
到1000/5=200
- 使用
sigmoid
激活而不是softmax
- 在 Adam 中设置较低的学习率;为此,您需要单独创建优化器
adam = Adam(0.0001)
并将其传入model.compile(..., optimizer=adam)
- 尝试
VGG16
代替InceptionV3
当您尝试上述所有方法时,请告诉我们。
推荐阅读
- c++ - 表达式:使用 vector.erase() 时矢量擦除迭代器超出范围
- r - 自动将系列拆分为相等重叠的子系列,而无需在 R 中设置子集
- selenide - 如何使用 Selenide 检查页面 url
- sql - 我正在尝试找到一种将 IN() 与 LIKE() 一起用于多种条件的方法
- python - 如何使用 Asyncio 避免错误 429 (Too Many Requests) python
- node.js - 如何使用 Puppeteer 遍历具有相同类的 div
- sql-server - Azure SQL - 将 ****** 值“******”转换为数据类型 ****** 失败
- javascript - 打破'滚动'事件Javascript
- python - 如何使用 pandas 从 Azure Blob 读取 .xlsx 格式文件而不创建临时文件
- python - 为什么 Pytorch 给我一个数据类型错误:Float vs Double?