为什么tensorflow不允许我写文件?

时间:2017-04-07 12:15:02

标签: python tensorflow deep-learning

我是tensorflow的新手。我已经训练了一个模型来通过张量流对图像进行分类,预测效果很好。但是,当我尝试将测试数据集的分类结果写入结果文件时,可以说 tensorflow.python.framework.errors_impl.PermissionDeniedError:文件未打开以进行写入 < / strong>即可。
这是我的python代码:

import tensorflow as tf, sys
import os

image_path = sys.argv[1]
images = os.listdir(image_path)
f = file("/tf_files/result.csv","w+")
f.write("image,ALB,BET,DOL,LAG,NoF,OTHER,SHARK,YFT\n")
for image in images:
    # Read in the image_data
    image_data = tf.gfile.FastGFile(image_path + image, 'rb').read()

    # Loads label file, strips off carriage return
    label_lines = [line.rstrip() for line
                   in tf.gfile.GFile("/tf_files/retrained_labels.txt")]

    # Unpersists graph from file
    with tf.gfile.FastGFile("/tf_files/retrained_graph.pb", 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        _ = tf.import_graph_def(graph_def, name='')

    pred = []
    with tf.Session() as sess:
        # Feed the image_data as input to the graph and get first prediction
        softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')

        predictions = sess.run(softmax_tensor, \
                               {'DecodeJpeg/contents:0': image_data})

        pred = predictions
        # Sort to show labels of first prediction in order of confidence
        top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]

        for node_id in top_k:
            human_string = label_lines[node_id]
            score = predictions[0][node_id]
            print('%s (score = %.5f)' % (human_string, score))

    f.write(image + ",")
    f.write(pred[0][4] + ",")
    f.write(pred[0][7] + ",")
    f.write(pred[0][1] + ",")
    f.write(pred[0][3] + ",")
    f.write(pred[0][2] + ",")
    f.write(pred[0][6] + ",")
    f.write(pred[0][0] + ",")
    f.write(pred[0][5] + "\n")

f.close()


当我尝试写第一行表示 f.write(“image,ALB,BET,DOL,LAG,NoF,OTHER,SHARK,YFT \ n”) ,它运作良好。但是在程序中调用tensorflow之后,语句 f.write(image +“,”) 被拒绝。
此外,我在docker上使用tensorflow。与环境有关吗?我不明白为什么tensorflow不允许我在使用它时写文件。使用张量流时,我有什么方法可以写文件吗?

1 个答案:

答案 0 :(得分:0)

注意你的行

with tf.gfile.FastGFile("/tf_files/retrained_graph.pb", 'rb') as f:

会覆盖你的命名空间中的f f.write(&#39; blah&#39;)试图写入已经关闭的文件/tf_files/retrained_graph.pb

更改为with()as some_other_f或更改您打开的初始文件的变量名称(或将它们放在2个不同的名称空间中)