正确建立Keras模型

2024-04-26 11:38:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我对神经网络和Keras还不熟悉,我想建立一个CNN来预测图像的某些值。(这三个值预测图像顶部模糊的大小、长度和宽度)。所有3个值的范围都在0到1之间,我有一个很大的数据集。你知道吗

不过,我不确定如何构建CNN来实现这一点,因为到目前为止,我构建的所有原型代码都给出了格式[1.,0.,0.]的预测,而不是每个值的范围在0到1之间。除此之外,尽管在SGD优化器中更改了epoch的数量和衰减值,但我的损失函数没有任何变化。你能告诉我哪里出了问题吗?到目前为止,我掌握的情况如下:

images, labels = load_dataset("images")   # function that loads images
images = np.asarray(images) # images are flattened 424*424 arrays (grayscale)
labels = np.asarray(labels) # Lables are 3-arrays, each value is float from 0-1

# I won't write this part but here I split into train_imgs and test_imgs

model = keras.Sequential()
# explicitly define SGD so that I can change the decay rate
sgd = keras.optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)

model.add(keras.layers.Dense(32, input_shape=(424*424,) ))
model.add(keras.layers.Activation('relu'))
model.add(keras.layers.Dense(3, activation='softmax'))

model.compile(loss='mean_squared_error',optimizer=sgd)
# note: I also tried defining a weighted binary crossentropy but it changed nothing

checkpoint_name = 'Weights-{epoch:03d}--{val_loss:.5f}.hdf5' 
checkpoint = ModelCheckpoint(checkpoint_name, monitor='val_loss', verbose = 0, save_best_only = True, mode ='auto')
callbacks_list = [checkpoint]

model.fit(train_imgs, train_labls, epochs=20, batch_size=32, validation_split = 0.2, callbacks=callbacks_list)

predictions = model.predict(test_imgs) # make predictions on same test set!

现在我知道,我正在离开辍学层,但我希望CNN过度拟合我的数据,在这一点上,我只希望它做任何事情。当我对同一组图像进行预测时,我希望得到准确的结果,不是吗?我不太确定我错过了什么。谢谢你的帮助!你知道吗


Tags: test图像addlabelsmodellayerstraincnn
1条回答
网友
1楼 · 发布于 2024-04-26 11:38:01

首先,用'sigmoid'替换'softmax'。你知道吗

Sigmoid将使三个输出的范围从0到1。还要注意,softmax是为分类而设计的。它只尝试最大化三个值中的一个,而三个值的和总是一个。你知道吗

第二,如果你的损失完全冻结,问题可能在'relu'(relu有一个恒定的零区域,没有梯度)。您可以将'relu替换为另一个对象,例如'sigmoid''tanh',也可以在relu之前添加BatchNormalization()层。你知道吗

作为一个乞丐的选择,我总是喜欢使用optimizer='adam',这是非常快的方式往往比新加坡元,你不需要太在意学习率(当然先进的模式和最好的结果可能需要调整)。你知道吗

相关问题 更多 >