如何在给定程序中绘制 TensorFlow 版本 v1.x 中相对于历元的训练准确性、训练损失

raj*_*pal 3 python plot graph loss tensorflow

我是张量流编程的新手。我想在下面的程序中绘制训练准确性、训练损失、验证准确性和验证损失。我在google colab中使用tensorflow版本1.x。代码片段如下。

# hyperparameters
n_neurons = 128  
learning_rate = 0.001  
batch_size = 128
n_epochs = 5
# parameters
n_steps = 32   
n_inputs = 32  
n_outputs = 10   
# build a rnn model
X = tf.placeholder(tf.float32, [None, n_steps, n_inputs])  
y = tf.placeholder(tf.int32, [None])  
cell = tf.nn.rnn_cell.BasicRNNCell(num_units=n_neurons)  
output, state = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)  
logits = tf.layers.dense(state, n_outputs)  
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits)  
loss = tf.reduce_mean(cross_entropy)  
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)  
prediction = tf.nn.in_top_k(logits, y, 1)  
accuracy = tf.reduce_mean(tf.cast(prediction, tf.float32))  
# input data
x_test = x_test.reshape([-1, n_steps, n_inputs]) 
# initialize the variables
init = tf.global_variables_initializer()
# train the model
with tf.Session() as sess:    sess.run(init)  
    n_batches = 100  
    for epoch in range(n_epochs):  
        for batch in range(n_batches):  
            sess.run(optimizer, feed_dict={X: x_train, y: y_train})  
            loss_train, acc_train = sess.run([loss, accuracy], feed_dict={X: 
            x_train, y: y_train})  
            print('Epoch: {}, Train Loss: {:.3f}, Train Acc: 
            {:.3f}'.format(epoch + 1, loss_train, acc_train))  
            loss_test, acc_test = sess.run([loss, accuracy], feed_dict={X: 
            x_test, y: y_test})  
            print('Test Loss: {:.3f}, Test Acc: {:.3f}'.format(loss_test, 
            acc_test))
Run Code Online (Sandbox Code Playgroud)

小智 8

正如 Viviann 评论的那样,在放置代码时请使用 ```,因为它很难理解。但以下代码可能会有所帮助:

*旁注:这是使用 keras

acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']

Run Code Online (Sandbox Code Playgroud)

您可以在此处分配训练和验证中的值(用于准确性和损失)。我相信你已经完成了那部分。

以下部分用于绘制这些值

import matplotlib.pyplot as plt

epochs = range(1, len(acc) + 1)

plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()

plt.figure()

plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()

plt.show()
Run Code Online (Sandbox Code Playgroud)

它应该给你这样的东西:

绘图值示例(训练、验证 acc 和损失)

  • 只是一个旁注。如果您训练模型,然后决定训练更多时期,则历史对象不会保留,并且仅包含第二次训练会话的数据。因此,如果您想要完整的数据集,您需要保存第一个训练会话中的数据,然后将新数据附加到其中。 (3认同)