Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何返回Keras中验证丢失的历史记录_Python_Neural Network_Nlp_Deep Learning_Keras - Fatal编程技术网

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

Python 如何返回Keras中验证丢失的历史记录,python,neural-network,nlp,deep-learning,keras,Python,Neural Network,Nlp,Deep Learning,Keras,使用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)) m

使用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方法返回一个历史回调,它有一个历史属性,包含连续损失列表和其他度量

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)
它回来了

{}

即使我运行了一次迭代

具有“acc”、“loss”等历史记录的词典可用,并保存在
hist.history
变量中。

已解决

这些损失只是历代历史的一部分。我运行的是迭代,而不是使用Keras内置的epochs选项

因此,我现在没有进行4次迭代

model.fit(......, nb_epoch = 4)
现在,它返回每个历元运行的损失:

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

这只是一个例子

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'])

另一个选项是CSVLogger:。
它创建一个csv文件,附加每个历元的结果。即使你中断了训练,你也可以看到它是如何演变的。

我还发现,你可以使用
verbose=2
让keras打印出损失:

history = model.fit(X, Y, validation_split=0.33, nb_epoch=150, batch_size=10, verbose=2)
这样就可以打印出这样漂亮的线条:

Epoch 1/1
 - 5s - loss: 0.6046 - acc: 0.9999 - val_loss: 0.4403 - val_acc: 0.9999
根据他们的意见:


以下简单代码对我来说非常有用:

    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
确保将拟合函数指定给输出变量。然后,您可以非常轻松地访问该变量

# 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)
希望这有帮助。
来源:

实际上,你也可以用迭代法来做。因为有时我们可能需要使用迭代方法而不是内置的epochs方法来可视化每次迭代后的训练结果

history = [] #Creating a empty list for holding the loss later
for iteration in range(1, 3):
    print()
    print('-' * 50)
    print('Iteration', iteration)
    result = model.fit(X, y, batch_size=128, nb_epoch=1) #Obtaining the loss after each training
    history.append(result.history['loss']) #Now append the loss after the training to the list.
    start_index = random.randint(0, len(text) - maxlen - 1)
print(history)

通过这种方式,您可以在保持迭代方法的同时获得所需的损失。

要直接绘制损失,请执行以下操作:

import matplotlib.pyplot as plt
...    
model_ = model.fit(X, Y, epochs= ..., verbose=1 )
plt.plot(list(model_.history.values())[0],'k-o')

那些像我一样仍然犯错误的人:

借助Alloush,将model.fit_generator()转换为model.fit()

以下参数必须包含在
model.fit()中。

如果未定义,
val_acc
val_loss
将不会
在输出时存在。

如果我在控制台中键入“hist”,它只会给我运行此会话的代码。hist.history呢?嗨,Marcin,我解决了它。问题是,当我运行外部迭代时,损失只会在不同的时期内节省。所以,在每次迭代中,我的历史记录都被清除了。您是否可以指定是从控制台运行此代码,还是从命令行(或IDE)运行脚本?训练后你有权限访问hist变量吗?我正在用Anaconda运行它。我找到了一个解决方案,可以访问hist变量。但它总是返回一个空的卷曲括号。欢迎使用SO!当你要回答一个已经有公认答案的老问题(这个问题已经超过4年了)(这里就是这种情况)时,请扪心自问:我真的有实质性的改进吗?如果不是,请考虑不要回答。恭敬地说,“TIMUS,代码在4年内发生了显著的变化,以前的解决方案在2016中可能已经很好地工作了,但不能保证在2020版本的TunSoFalm上工作。因此,我认为,以一种能够与最新版本的框架协同工作的方式回答一个老问题,实际上确实提供了一个实质性的改进。@JohnnyUtah我没有对提供的解决方案进行评判,我从来没有想过否决权(我不知道)!我只是想指出,答案实际上应该提供一些新的东西。当我这样做时,我只得到'acc'和'loss',我没有看到'val_loss'@taga如果你给了模型一个训练集和一个验证集来学习,你会得到一个“train_loss”和一个“val_loss”:,验证集可用于评估每个历元后未知数据的模型,并在验证损失停止减少时停止拟合。
import matplotlib.pyplot as plt
...    
model_ = model.fit(X, Y, epochs= ..., verbose=1 )
plt.plot(list(model_.history.values())[0],'k-o')
validation_data = (x_test, y_test)