繁体   English   中英

在Keras上正确建立模型

[英]Building a model on Keras correctly

我是神经网络和Keras的新手,我想构建一个可预测图像某些值的CNN。 (这三个值可预测图像顶部模糊的大小,长度和宽度)。 所有3个值的范围都可以从0到1,并且我有一个很大的数据集。

但是我不确定如何构建CNN,因为到目前为止我构建的所有原型代码都为我提供了[1.,0.,0.]格式的预测,而不是0到1之间的范围。每个值。 最重要的是,尽管更改了SGD优化器中的时期数和衰减值,但我的损失函数完全没有变化。 您能告诉我我要去哪里了吗? 这是我到目前为止的内容:

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适应我的数据,这时我只想让它做任何事情。 当我对同一组图像进行预测时,希望能得到准确的结果,不是吗? 我不太确定自己缺少什么。 谢谢您的帮助!

首先,用'sigmoid'代替'softmax' 'sigmoid'

Sigmoid将使三个输出的范围从0到1。另请注意,将softmax用于分类。 它尝试仅使三个值之一最大化,并且三个值的总和将始终为1。

其次,如果您的损失被完全冻结,则问题可能出在'relu' (relu具有恒定的零区域,其中没有梯度)。 您可以用'sigmoid''tanh'类的其他东西替换'relu ”,也可以在BatchNormalization()之前添加BatchNormalization()层。

作为一个开始的选择,我总是更喜欢使用optimizer='adam' ,这通常比SGD快得多,并且您不需要太在意学习率(当然,高级模型和最佳结果可能需要调整)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM