如何在 Tensorflow 中将字符串张量转换为 python 字符串? [英] How to convert a string tensor to a python string in Tensorflow?

查看:67
本文介绍了如何在 Tensorflow 中将字符串张量转换为 python 字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following code is a batch data provider for .mat files, but has the following problem when running it:

    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?谢谢.

Does anyone know how to convert a string tensor to a python string easily? Thanks.

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

UPDATED 1: when using the filename.dequeue(), the error information is:

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

推荐答案

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

tf.train.string_input_producer() return a queue, not a string. You have to use Graph operation, which get string tensor from this queue and read file from disk. For example you can use chain of operation:

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

如果您有 jpeg 文件.

if you have jpeg files.

在 TensorFlow 1.2 中有新的结构 Dataset 用于创建输入管道.我认为使用 Dataset 代替队列是个好主意.

In TensorFlow 1.2 there is new structure Dataset for creating input pipeline. I think it is good idea to use Dataset instead queues.

这篇关于如何在 Tensorflow 中将字符串张量转换为 python 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆