I am trying to save the predicted images on my CNN network which I wrote with Tensorflow. In my code y_pred_cls
contain my predicted labels and the y_pred_cls
is a tensor of dimensions 1 x batch size. Now, I want to iterate over y_pred_cls as an array and make a file name including pred class, true class, and some index number, then find out images relate to predicted labels and use imsave
to save as image.
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
train_writer.add_graph(sess.graph)
print("{} Start training...".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
print("{} Open Tensorboard at --logdir {}".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), tensorboard_dir))
for epoch in range(FLAGS.num_epochs):
print("{} Epoch number: {}".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), epoch + 1))
step = 1
# Start training
while step < train_batches_per_epoch:
batch_xs, batch_ys = train_preprocessor.next_batch(FLAGS.batch_size)
opt, train_acc = sess.run([optimizer, accuracy], feed_dict={x: batch_xs, y_true: batch_ys})
# Logging
if step % FLAGS.log_step == 0:
s = sess.run(sum, feed_dict={x: batch_xs, y_true: batch_ys})
train_writer.add_summary(s, epoch * train_batches_per_epoch + step)
step += 1
# Epoch completed, start validation
print("{} Start validation".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
val_acc = 0.
val_count = 0
cm_running_total = None
for _ in range(val_batches_per_epoch):
batch_tx, batch_ty = val_preprocessor.next_batch(FLAGS.batch_size)
acc, loss , conf_m= sess.run([accuracy, cost, tf.confusion_matrix(y_true_cls, y_pred_cls, FLAGS.num_classes)],
feed_dict={x: batch_tx, y_true: batch_ty})
if cm_running_total is None:
cm_running_total = conf_m
else:
cm_running_total += conf_m
val_acc += acc
val_count += 1
val_acc /= val_count
s = tf.Summary(value=[
tf.Summary.Value(tag="validation_accuracy", simple_value=val_acc),
tf.Summary.Value(tag="validation_loss", simple_value=loss)
])
val_writer.add_summary(s, epoch + 1)
print("{} -- Training Accuracy = {:.4%} -- Validation Accuracy = {:.4%} -- Validation Loss = {:.4f}".format(
datetime.now().strftime('%Y-%m-%d %H:%M:%S'), train_acc, val_acc, loss))
# Reset the dataset pointers
val_preprocessor.reset_pointer()
train_preprocessor.reset_pointer()
print("{} Saving checkpoint of model...".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
# save checkpoint of the model
checkpoint_path = os.path.join(checkpoint_dir, 'model_epoch.ckpt' + str(epoch+1))
save_path = saver.save(sess, checkpoint_path)
print("{} Model checkpoint saved at {}".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), checkpoint_path))
batch_tx, batch_ty is my RGB data and labels respectively.
Thanks in advance.
To extract data from a tensor into a python-variable use
label = sess.run(y_pred_cls)
This will give you an array for a one-hot-vector label or an int variable for a scalar label.
To save arrays to images you can use the PIL-library
from PIL import Image
img = Image.fromarray(data, 'RGB')
img.save('name.png')
The rest should be straight forward,
x
name = str(y)+'_'+str(y_hat)
If you have trouble applying these steps I can help you out further
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.