【问题标题】:Evaluating tf.py_func in session.run() returns "Invalid type list"在 session.run() 中评估 tf.py_func 返回“无效类型列表”
【发布时间】:2016-06-24 11:48:46
【问题描述】:

我的数据按结构排列:

data/
  good/
  bad/

每个子文件夹都包含 jpg 文件。 我正在尝试创建一个接受basepath 作为输入并构造image_oplabel_op 的输入管道。评估这些会给我一个(图像,标签)元组,例如:

image, label = session.run([image_op, label_op])

要获得给定图像的标签,我必须查看其图像路径。一种简单的解决方案是:

label = int("good" in path)

据我所知(v0.9)在 tensorflow 中不支持这种字符串操作,所以我想在上面这样的简单函数上使用 tf.py_func 包装器。但是,虽然以这种方式评估标签操作成功,但在尝试评估图像路径操作和使用图像路径操作作为同一 session.run() 中的输入的标签操作时,我会收到错误。

这是我的 python 函数和 tf 图形代码:

def get_label(path):
    return int("good" in str(path))

class DataReadingGraph:
    """
    Graph for reading images into a data queue.
    """

    def __init__(self, base_path):
        """
        Construct the queue
        :param base_path: path to base directory that contains good images and bad images
        subdirectories. They in turn can contain further subdirectories.
        :return:
        """

        # tf can't handle recursive files matching (as of version 0.9), so
        # solve that with glob and just pass globbed paths to a constant
        pattern = os.path.join(base_path, "**/*.jpg")
        filenames = tf.constant(glob.glob(pattern, recursive=True))

        filename_queue = tf.train.string_input_producer(filenames, shuffle=True)
        reader = tf.IdentityReader()
        self.key, self.value = reader.read(filename_queue)

        self.label = tf.py_func(get_label, [self.key], [tf.int64])

现在如果我跑

label = session.run(data_reading_graph.label)

一切都很好,我得到了预期的标签。但是如果我跑

key, label = session.run([data_reading_graph.key, data_reading_graph.label])

相反,我得到了

<class 'TypeError'>
Fetch argument [<tf.Tensor 'PyFunc:0' shape=<unknown> dtype=int64>] of [<tf.Tensor 'PyFunc:0' shape=<unknown> dtype=int64>] has invalid type <class 'list'>, must be a string or Tensor. (Can not convert a list into a Tensor or Operation.)

我真的不明白这里出了什么问题,什么不应该转换成列表,以及为什么我不能在同一个session.run() 中评估关键操作和标签操作。

我可以在启动 tf graph 之前尝试在纯 Python 代码中提取标签,但问题仍然存在 - 为什么我不能评估 py_func 及其在同一 session.run() 中的输入

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    tf.py_func 返回张量的列表

    你应该得到self.label = self.label[0]:

        filename_queue = tf.train.string_input_producer(filenames, shuffle=True)
        reader = tf.IdentityReader()
        self.key, self.value = reader.read(filename_queue)
    
        self.label = tf.py_func(get_label, [self.key], [tf.int64])[0]
    

    【讨论】:

    • 天哪,你是完全正确的。我现在觉得很傻...谢谢。
    • 起初我认为这是tf.py_func 中的一个真正的错误,但不是:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2012-02-07
    • 2011-06-30
    • 1970-01-01
    • 2021-12-22
    • 2023-04-11
    相关资源
    最近更新 更多