如何在Keras中返回验证丢失的历史记录

2024-04-25 04:30:18 发布

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

使用Anaconda Python 2.7 Windows 10。

我正在使用Keras exmaple培训语言模型:

print('Build model...')
model = Sequential()
model.add(GRU(512, return_sequences=True, input_shape=(maxlen, len(chars))))
model.add(Dropout(0.2))
model.add(GRU(512, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(len(chars)))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy', optimizer='rmsprop')

def sample(a, temperature=1.0):
    # helper function to sample an index from a probability array
    a = np.log(a) / temperature
    a = np.exp(a) / np.sum(np.exp(a))
    return np.argmax(np.random.multinomial(1, a, 1))


# train the model, output generated text after each iteration
for iteration in range(1, 3):
    print()
    print('-' * 50)
    print('Iteration', iteration)
    model.fit(X, y, batch_size=128, nb_epoch=1)
    start_index = random.randint(0, len(text) - maxlen - 1)

    for diversity in [0.2, 0.5, 1.0, 1.2]:
        print()
        print('----- diversity:', diversity)

        generated = ''
        sentence = text[start_index: start_index + maxlen]
        generated += sentence
        print('----- Generating with seed: "' + sentence + '"')
        sys.stdout.write(generated)

        for i in range(400):
            x = np.zeros((1, maxlen, len(chars)))
            for t, char in enumerate(sentence):
                x[0, t, char_indices[char]] = 1.

            preds = model.predict(x, verbose=0)[0]
            next_index = sample(preds, diversity)
            next_char = indices_char[next_index]

            generated += next_char
            sentence = sentence[1:] + next_char

            sys.stdout.write(next_char)
            sys.stdout.flush()
        print()

根据Keras文档,model.fit方法返回一个History回调,它有一个History属性,包含连续损失和其他度量的列表。

hist = model.fit(X, y, validation_split=0.2)
print(hist.history)

在训练我的模型之后,如果我运行print(model.history),就会得到错误:

 AttributeError: 'Sequential' object has no attribute 'history'

使用上述代码训练模型后,如何返回模型历史记录?

更新

问题是:

必须首先定义以下内容:

from keras.callbacks import History 
history = History()

必须调用回调选项

model.fit(X_train, Y_train, nb_epoch=5, batch_size=16, callbacks=[history])

但现在如果我打印

print(history.History)

它又回来了

{}

即使我运行了一个迭代。


Tags: 模型addforindexmodellennphistory
3条回答

举个例子

history = model.fit(X, Y, validation_split=0.33, nb_epoch=150, batch_size=10, verbose=0)

你可以用

print(history.history.keys())

列出历史上的所有数据。

然后,您可以按如下方式打印验证丢失的历史记录:

print(history.history['val_loss'])

已经解决了。

这些损失只会保存到各个时代的历史上。我在运行迭代,而不是使用Keras内置的epochs选项。

所以我现在没有做4次迭代

model.fit(......, nb_epoch = 4)

现在它返回每个历元运行的损失:

print(hist.history)
{'loss': [1.4358016599558268, 1.399221191623641, 1.381293383180471, h1.3758836857303727]}

下面的简单代码对我很有用:

    seqModel =model.fit(x_train, y_train,
          batch_size      = batch_size,
          epochs          = num_epochs,
          validation_data = (x_test, y_test),
          shuffle         = True,
          verbose=0, callbacks=[TQDMNotebookCallback()]) #for visualization

确保将fit函数分配给输出变量。然后你可以很容易地访问这个变量

# visualizing losses and accuracy
train_loss = seqModel.history['loss']
val_loss   = seqModel.history['val_loss']
train_acc  = seqModel.history['acc']
val_acc    = seqModel.history['val_acc']
xc         = range(num_epochs)

plt.figure()
plt.plot(xc, train_loss)
plt.plot(xc, val_loss)

希望这有帮助。 来源:https://keras.io/getting-started/faq/#how-can-i-record-the-training-validation-loss-accuracy-at-each-epoch

相关问题 更多 >