我正在学习转学。我的用例是对图像进行两类分类。我使用InceptionV3对图像进行分类。训练模型时,在每个时期我都会得到 nan 作为损失,而得到 0.0000e + 00 。我使用20个纪元是因为我的数据量很小:我得到了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)
答案 0 :(得分:1)
听起来您的梯度正在爆炸。可能有几个原因:
save_to_dir
flow_from_directory
参数
steps_per_epoch
从1000
固定为1000/5=200
sigmoid
激活代替softmax
adam = Adam(0.0001)
一样分别创建优化器并将其传递到model.compile(..., optimizer=adam)
VGG16
代替InceptionV3
当您尝试以上所有方法时,请告知我们。
答案 1 :(得分:1)
使用Softmax进行激活对于单班没有意义。您的输出值将始终由其自身归一化,因此等于1。softmax的目的是使这些值的总和为1。在单个值的情况下,您将得到它==1。我相信您有时会得到零作为预测值,导致零除和NaN损失值。
您应该通过以下方式将类数更改为2:
predictions = Dense(2, activation='softmax')(x)
class_mode='categorical'
中的{li> flow_from_directory
loss="categorical_crossentropy"
或在最后一层使用S型激活功能。