python - 使用 Keras 回调保存最佳 val_loss

标签 python machine-learning neural-network keras autoencoder

根据此处讨论的内容,我为 mnist 数据集建立了一个去噪自动编码器: https://blog.keras.io/building-autoencoders-in-keras.html

我试图了解输入图像的重建如何随时间变化;我注意到有时 DAE 的损失会出现峰值(无论是训练还是验证),例如损失从 ~0.12 到 ~3.0。为了避免在训练过程中使用这些“失误”,我尝试使用 Keras 的回调,保存最佳权重(val_loss 明智的)并在训练的每个“片段”之后加载它们(在我的例子中= 10 epoch)。

但是,我收到一条错误消息:

File "noise_e_mini.py", line 71, in <module> callbacks=([checkpointer])) File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1650, in fit validation_steps=validation_steps) File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1145, in _fit_loop callbacks.set_model(callback_model) File "/usr/local/lib/python2.7/dist-packages/keras/callbacks.py", line 48, in set_model callback.set_model(model) AttributeError: 'tuple' object has no attribute 'set_model'

我的代码是:

from keras.layers import Input, Dense
from keras.models import Model
from keras import regularizers
from keras.callbacks import ModelCheckpoint
input_img = Input(shape=(784,))

filepath_for_w='denoise_by_AE_weights_1.h5'


def autoencoder_block(input,l1_score_encode,l1_score_decode):


    #    encoder:
    encoded = Dense(256, activation='relu',activity_regularizer=regularizers.l1(l1_score_encode))(input_img)
    encoded = Dense(128, activation='relu',activity_regularizer=regularizers.l1(l1_score_encode))(encoded)
    encoded = Dense(64, activation='relu',activity_regularizer=regularizers.l1(l1_score_encode))(encoded)
    encoded = Dense(32, activation='relu',activity_regularizer=regularizers.l1(l1_score_encode))(encoded)

    encoder = Model (input=input_img, output=encoded)

    #    decoder:
    connection_layer= Input(shape=(32,))
    decoded = Dense(64, activation='relu',activity_regularizer=regularizers.l1(l1_score_decode))(connection_layer)
    decoded = Dense(128, activation='relu',activity_regularizer=regularizers.l1(l1_score_decode))(decoded)
    decoded = Dense(256, activation='relu',activity_regularizer=regularizers.l1(l1_score_decode))(decoded)
    decoded = Dense(784, activation='sigmoid',activity_regularizer=regularizers.l1(l1_score_decode))(decoded)

    decoder = Model (input=connection_layer , output=decoded)

    crunched = encoder(input_img)
    final = decoder(crunched)

    autoencoder = Model(input=input_img, output=final)
    autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
    return (autoencoder)



from keras.datasets import mnist
import numpy as np
(x_train, y_train), (x_test, y_test) = mnist.load_data()


x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
print x_train.shape
print x_test.shape

noise_factor = 0.5

x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape) 
x_test_noisy = np.clip(x_test_noisy, 0., 1.)



autoencoder=autoencoder_block(input_img,0,0)

for i in range (10):

    x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape) 
    x_train_noisy = np.clip(x_train_noisy, 0., 1.)
    checkpointer=ModelCheckpoint(filepath_for_w, monitor='val_loss', verbose=0, save_best_only=True, save_weights_only=True, mode='auto', period=1),

    autoencoder.fit(x_train_noisy, x_train,
                epochs=10,
                batch_size=256,            
                shuffle=True,
                validation_data=(x_test_noisy, x_test),
                callbacks=([checkpointer]))
    autoencoder.load_weights(filepath_for_w)  # load weights from the best in the run

    decoded_imgs = autoencoder.predict(x_test_noisy) # save results for this stage for presentation
    np.save('decoded'+str(i)+'.npy',decoded_imgs)    ####

np.save('tested.npy',x_test_noisy)
np.save ('true_catagories.npy',y_test)
np.save('original.npy',x_test)


autoencoder.save('denoise_by_AE_model_1.h5')

我做错了什么? 非常感谢:)

最佳答案

您的问题可能在这一行内

callbacks=([checkpointer]))

您需要删除括号,因为回调需要列表,而不是元组,尝试:

callbacks=[checkpointer]

我还注意到您的检查指针以逗号结尾,您也应该将其删除。

checkpointer=ModelCheckpoint(filepath_for_w, monitor='val_loss', verbose=0, save_best_only=True, save_weights_only=True, mode='auto', period=1),

关于python - 使用 Keras 回调保存最佳 val_loss,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47769181/

相关文章:

machine-learning - 大多数机器学习技术是否源自线性回归和 kNN?

python - 如何在Python中以表格形式查看系列

python - 在 Django 模板中隐藏重复迭代

python-3.x - 逻辑回归成本 = nan

machine-learning - 交叉熵和遗传算法有什么区别?

language-agnostic - 液态状态机的实现

python - 监听简单表上的插入/更新事件

python - 如何运行子进程命令以在后台 Python 中启动 nodejs 服务器

python - Theano:使用 CSV 文件中的数据训练 theano 神经网络

python - 如何将字符串转换为 float ?值错误: could not convert string to float: '0,25691372'