我的神经网络预测代码有什么问题?所有的预测都为每个图像返回相同的类名



以下是我的训练代码:

def train():

#START
img_input = layers.Input(shape=(150, 150, 3))
x = layers.Conv2D(16, 3, activation='relu')(img_input)
x = layers.MaxPooling2D(2)(x)
x = layers.Conv2D(32, 3, activation='relu')(x)
x = layers.MaxPooling2D(2)(x)
x = layers.Conv2D(64, 3, activation='relu')(x)
x = layers.MaxPooling2D(2)(x)
x = layers.Flatten()(x)
x = layers.Dense(512, activation='relu')(x)

output = layers.Dense(1, activation='sigmoid')(x)
model = Model(img_input, output)
model.compile(loss='binary_crossentropy',
optimizer=RMSprop(lr=0.001),
metrics=['acc'])

#END
# All images will be rescaled by 1./255
train_datagen = ImageDataGenerator(rescale=1./255)
val_datagen = ImageDataGenerator(rescale=1./255)
bs = 20
# Flow training images in batches of 20 using train_datagen generator
train_generator = train_datagen.flow_from_directory(
train_dir,  # This is the source directory for training images
target_size=(150, 150),  # All images will be resized to 150x150
batch_size=bs,
# Since we use binary_crossentropy loss, we need binary labels
class_mode='binary')
# Flow validation images in batches of 20 using val_datagen generator
validation_generator = val_datagen.flow_from_directory(
validation_dir,
target_size=(150, 150),
batch_size=bs,
class_mode='binary')

history = model.fit(
train_generator,
steps_per_epoch=train_steps, 
epochs=4,
validation_data=validation_generator,
validation_steps=val_steps,  
verbose=1)     



model.save_weights("trained_weights.h5")

这是我的预测代码:

def evaluate(imgpath):
if not os.path.isfile(imgpath):
print("No such file: {}".format(imgpath))
sys.exit(-1)

# START
img_input = layers.Input(shape=(150, 150, 3))

x = layers.Conv2D(16, 3, activation='relu')(img_input)
x = layers.MaxPooling2D(2)(x)
x = layers.Conv2D(32, 3, activation='relu')(x)
x = layers.MaxPooling2D(2)(x)
x = layers.Conv2D(64, 3, activation='relu')(x)
x = layers.MaxPooling2D(2)(x)

x = layers.Flatten()(x)
x = layers.Dense(512, activation='relu')(x)
output = layers.Dense(1, activation='sigmoid')(x)
model = Model(img_input, output)
model.compile(loss='binary_crossentropy',
optimizer=RMSprop(lr=0.001),
metrics=['acc'])

# END
model.load_weights("trained_weights.h5")
img = image.load_img(path=imgpath,grayscale=False,target_size=(150,150),color_mode='rgb')
img_arr = image.img_to_array(img)
test_img = np.expand_dims(img_arr, axis=0)
y_prob = model.predict(test_img)

classname = y_prob.argmax(axis=-1)
print("Class: ",classname)
return classname  

我有一种感觉,错误是在评估函数的最后5-6行某处,我正在加载图像。问题是,每当我对任何图像运行评估函数时,我的输出是[0]。尽管训练进行得很顺利,如下图所示。
输入图片描述

我是不是犯了什么愚蠢的错误?

因为你有一个单一的神经元作为顶层,当你做预测时,你会得到一个单一的预测。因为使用argmax只有一个预测,所以总是返回0。您需要做的是为预测设置一个阈值,例如

if yprob>=.5:
klass=1 
else:
klass=0

也正如史努比博士指出的,你应该把你的图像缩放到1/255。

最新更新