【问题标题】:How to convert a string tensor to a python string in Tensorflow?如何在 Tensorflow 中将字符串张量转换为 python 字符串?
【发布时间】:2017-07-21 21:10:23
【问题描述】:

以下代码是.mat文件的批处理数据提供者,但运行时出现以下问题:

    TypeError: expected str, bytes or os.PathLike object, not FIFOQueue

代码是:

    import numpy as np
    import tensorflow as tf
    from tensorflow.python.framework import ops
    from tensorflow.python.framework import dtypes
    import h5py

    def Reader(filename):
        with h5py.File(filename, 'r') as f:
            image = np.transpose(np.array(f.get('patch_x'), dtype=np.float32))
            label = np.transpose(np.array(f.get('patch_y'), dtype=np.float32))
        image = ops.convert_to_tensor(image, dtype=dtypes.float32)
        label = ops.convert_to_tensor(label, dtype=dtypes.float32)

        return image, label

    def Inputs(filenames, batch_size, shuffle=True):
        filenames = ops.convert_to_tensor(filenames, dtype=dtypes.string)
        filename_queue = tf.train.string_input_producer(filenames, shuffle=shuffle)
        image, label = Reader(filename_queue)
        image = tf.cast(image, tf.float32)
        label = tf.cast(label, tf.float32)

        num_preprocess_threads = 4
        if shuffle:
            image_batch, label_batch = tf.train.shuffle_batch([image, label], batch_size=batch_size, num_threads=num_preprocess_threads, capacity=5*batch_size, min_after_dequeue=2*batch_size)
        else:
            image_batch, label_batch = tf.train.batch([image, label], batch_size=batch_size, num_threads=num_preprocess_threads, capacity=5*batch_size, min_after_dequeue=2*batch_size)
        return image_batch, label_batch

有谁知道如何轻松地将 string 张量转换为 python string?谢谢。

更新 1: 使用filename.dequeue()时,报错信息为:

    TypeError: expected str, bytes or os.PathLike object, not Tensor

【问题讨论】:

  • 错误出现在哪一行?
  • @Aaron 此行with h5py.File(filename, 'r') as f:

标签: tensorflow


【解决方案1】:

要将字符串 TensorFlow 张量转换为 Python 字符串, 运行bytes.decode(string_tensor.numpy())

【讨论】:

    【解决方案2】:

    tf.train.string_input_producer() 返回一个队列,而不是一个字符串。您必须使用 Graph 操作,从该队列中获取字符串张量并从磁盘读取文件。例如,您可以使用操作链:

    image = tf.image.decode_jpeg(tf.read_file(filename_queue.dequeue()))
    

    如果你有 jpeg 文件。

    在 TensorFlow 1.2 中,有一个新的结构 Dataset 用于创建输入管道。我认为使用数据集而不是队列是个好主意。

    【讨论】:

    • 感谢您的回答。我认为pytorch中的数据加载器更简单。 [pytorch.org/tutorials/beginner/data_loading_tutorial.html]
    • 不需要使用数据集或队列。您可以将tf.placeholder 用于图形输入数据,通过现有 python 代码从文件中读取数据,并将此数据提供给图形。
    • 很多天才程序员提供了很多基于tensorflow的接口,这些让我很困惑。事实上,我们只需要一些最简单的接口,比如caffe 中的那些类,给一个输入,然后输出一个新的张量。我不知道为什么他们使用许多不同的tf 包开发了这么多孩子。
    • tfxxxx 太多了。为什么不使用官方tensorflow包中原有的类和函数?
    • 我不能问这个问题,我不是 TF 的开发者:) 但我认为只使用 TF 的“核心”部分并且不使用额外的模块没有问题。
    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 2020-12-31
    • 2021-09-19
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 2018-10-12
    相关资源
    最近更新 更多