Reputation: 41
i am new to tensorflow programming. I want to plot training accuracy, training loss, validation accuracy and validation loss in following program.I am using tensorflow version 1.x in google colab.The code snippet is as follows.
# 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))
Upvotes: 3
Views: 29790
Reputation: 513
As Viviann commented, please use ``` when putting code because it is hard to understand it. But the following code can be helpful:
*Side note: This is using keras
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
Here you assign the values from the training and validation (for accuracy and loss). I believe you have done that part already.
The following part is for plotting those values
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()
It should give you something like these:
Upvotes: 8