使用 Anaconda Python 2.7 Windows 10。
我正在使用 Keras 示例训练语言模型:
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)
它返回
{}
即使我运行了一个迭代。
model.fit()
。我可以以某种方式获得损失历史还是必须重复整个训练过程
只是一个例子开始于
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)
现在它返回每个 epoch 运行的损失:
print(hist.history)
{'loss': [1.4358016599558268, 1.399221191623641, 1.381293383180471, 1.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
确保将拟合函数分配给输出变量。然后您可以非常轻松地访问该变量
# 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)
具有“acc”、“loss”等历史记录的字典可用并保存在 hist.history
变量中。
我还发现您可以使用 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
根据他们的documentation:
verbose: 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch.
为了直接绘制损失,以下工作:
import matplotlib.pyplot as plt
...
model_ = model.fit(X, Y, epochs= ..., verbose=1 )
plt.plot(list(model_.history.values())[0],'k-o')
另一个选项是 CSVLogger:https://keras.io/callbacks/#csvlogger。它创建一个 csv 文件,附加每个 epoch 的结果。即使你中断训练,你也能看到它是如何演变的。
实际上,您也可以使用迭代方法来做到这一点。因为有时我们可能需要使用迭代方法而不是内置的 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)
这种方式可以让你在保持迭代方法的同时获得你想要的损失。
感谢阿洛什,
model.fit()
中必须包含以下参数:
validation_data = (x_test, y_test)
如果未定义,则 val_acc
和 val_loss
将不存在于输出中。
那些像我一样仍然出错的人:
将 model.fit_generator()
转换为 model.fit()
您可以获得如下损失和指标:返回的历史对象是字典,您可以访问模型损失(val_loss)或准确性(val_accuracy),如下所示:
model_hist=model.fit(train_data,train_lbl,epochs=my_epoch,batch_size=sel_batch_size,validation_data=val_data)
acc=model_hist.history['accuracy']
val_acc=model_hist.history['val_accuracy']
loss=model_hist.history['loss']
val_loss=model_hist.history['val_loss']
不要忘记,要获得 val_loss 或 val_accuracy,您应该在“fit”函数中指定验证数据。
不定期副业成功案例分享