Python 作为数组Tensorflow在张量上迭代

Python 作为数组Tensorflow在张量上迭代,python,python-3.x,numpy,matplotlib,tensorflow,Python,Python 3.x,Numpy,Matplotlib,Tensorflow,我正试图将预测的图像保存在我用Tensorflow编写的CNN网络上。在我的代码y_pred_cls中,包含我的预测标签,y_pred_cls是尺寸为1 x批次大小的张量。现在,我想将y_pred_cls作为一个数组进行迭代,生成一个文件名,包括pred class、true class和一些索引号,然后找出与预测标签相关的图像,并使用imsave保存为图像 with tf.Session() as sess: sess.run(tf.global_variables_initializer()

我正试图将预测的图像保存在我用Tensorflow编写的CNN网络上。在我的代码
y_pred_cls
中,包含我的预测标签,
y_pred_cls
是尺寸为1 x批次大小的张量。现在,我想将y_pred_cls作为一个数组进行迭代,生成一个文件名,包括pred class、true class和一些索引号,然后找出与预测标签相关的图像,并使用
imsave
保存为图像

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))
将tf.Session()作为sess的
:
sess.run(tf.global\u variables\u initializer())
训练写入器添加图形(sess.graph)
打印(“{}开始培训…”格式(datetime.now().strftime(“%Y-%m-%d%H:%m:%S”))
打印(“{}打开Tensorboard at--logdir{}”。格式(datetime.now().strftime(“%Y-%m-%d%H:%m:%S”),Tensorboard_dir))
对于范围内的历元(FLAGS.num_历元):
打印(“{}历元编号:{}”。格式(datetime.now().strftime(“%Y-%m-%d%H:%m:%S”),历元+1))
步骤=1
#开始训练
当步骤
batch_tx,batch_ty分别是我的RGB数据和标签


提前感谢。

要将数据从张量提取到python变量中,请使用

label=sess.run(y\u pred\u cls)

这将为单热向量标签提供一个数组,或为标量标签提供一个int变量

要将阵列保存到图像,可以使用PIL库

from PIL import Image
img = Image.fromarray(data, 'RGB')
img.save('name.png')
剩下的应该是直截了当的

  • 从batch_tx、batch_ty和y_pred_cls张量中提取数据
  • 迭代每个三元组
  • 用当前的
    x
  • 创建一个字符串,格式为
    name=str(y)+“y”+str(y_-hat)
  • 保存您的图像

  • 如果您在应用这些步骤时遇到问题,我可以帮助您进一步解决

    您应该在外循环之前创建
    tf.conflusion\u矩阵(y\u true\u cls,y\u pred\u cls,FLAGS.num\u class)
    一次,否则您将在图中创建同一操作的多个实例。嘿@jdehesa,我应该在哪里准确创建tf.conflusion\u matrix()
    ?因为如果我在循环后创建混淆矩阵,我将只获得每个批次的混淆矩阵,并且对于混淆矩阵,我必须输入
    x:batch\u tx,y\u true:batch\u ty
    ,否则我将得到一个错误。您应该能够执行类似
    conf\u mat=tf.conflusion\u矩阵的操作(y\u true\u cls,y\u pred\u cls,FLAGS.num\u classes)
    在定义了
    y\u-true\u-cls
    y\u-pred\u-cls
    之后的图形构建时间(在任何训练循环之前)。然后在循环中只需执行
    acc,loss,conf_m=sess.run([accurity,cost,conf_mat],feed_dict={x:batch_tx,y_true:batch_ty})
    (除非我不理解一些东西…)在开始我的
    tf.Session()会话之前,我按照你说的那样添加了
    conf_mat=tf.conflusion_矩阵(y_真的,y pred_cls,FLAGS.num类)
    在循环中,我做了
    acc,loss,conf\u m=sess.run([精度,成本,conf\u mat],feed\u dict={x:batch\u tx,y\u true:batch\u ty})
    但是仍然要得到一批的混淆矩阵,我需要将所有批次的混淆矩阵相加,得到一个完整的混淆矩阵,结果与我之前所做的完全相同。啊,好吧,这就是你的意思,对,是的,你仍然必须这样做,我想说的是,如果你一直在循环中调用
    tf.conflusion\u matrix
    ,你会创建同一个TensorFlow op的多个副本,这些副本会留在你的图中,所以最好只创建一次并重用它。但是你的代码是正确的。也许你也需要
    label=sess.run(y\u pred\u cls,feed\u dict={x:batch\u tx})
    ,或者只是将现有的调用扩展到
    .run
    来计算
    y\u pred\u cls
    。是的,如果你从当前的程序流中执行,这是真的。嘿@JonathanR,你能帮我更多吗。我将像您所说的那样,使用这行代码
    label=sess.run(y_pred_cls,feed_dict={x