【问题标题】:TensorFlow strings: what they are and how to work with themTensorFlow 字符串:它们是什么以及如何使用它们
【发布时间】:2016-12-18 13:13:36
【问题描述】:

当我用tf.read_file 读取文件时,我得到了tf.string 类型的东西。文档只说它是“可变长度字节数组。张量的每个元素都是一个字节数组。” (https://www.tensorflow.org/versions/r0.10/resources/dims_types.html)。我不知道如何解释。

我对这种类型无能为力。在通常的 python 中,您可以通过索引获取元素,例如my_string[:4],但是当我运行以下代码时会出现错误。

import tensorflow as tf
import numpy as np

x = tf.constant("This is string")
y = x[:4]


init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
result = sess.run(y)
print result

上面写着

 文件“/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_shape.py”,第 621 行,在 assert_has_rank
    raise ValueError("形状 %s 必须有等级 %d" % (self, rank))
ValueError:形状()必须具有等级 1

我也无法将我的字符串转换为tf.float32 张量。它是.flo 文件,它有魔术头“PIEH”。此 numpy 代码成功地将此类标头转换为数字(请参见此处的示例 https://stackoverflow.com/a/28016469/4744283),但我无法使用 tensorflow 做到这一点。我试过tf.string_to_number(string, out_type=tf.float32) 但它说

tensorflow.python.framework.errors.InvalidArgumentError:StringToNumberOp 无法正确转换字符串:PIEH

那么,什么是字符串?它的形状是什么?我怎样才能至少得到字符串的一部分?我想如果我能得到它的一部分,我可以跳过“PIEH”部分。

UPD:我忘了说tf.slice(string, [0], [4]) 也不会出现同样的错误。

【问题讨论】:

  • 顺便说一句,您可以使用此脚本获取接受 tf.string 数据类型的操作列表:gist.github.com/yaroslavvb/16bb81fcfb0932169087add47ecb8c3a
  • 感谢您的回答!这个脚本是针对特定版本的 TF 的吗?它至少对 0.9 不起作用。将尝试更新到 0.10。
  • 不,它也不适用于 0.10 $ python list_ops.py Traceback (most recent call last): File "list_ops.py", line 23, in <module> if arg.type == tf.string: File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/dtypes.py", line 244, in __eq__ and self._type_enum == as_dtype(other).as_datatype_enum) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/dtypes.py", line 532, in as_dtype if key == type_value: TypeError: data type not understood 你能帮我解决它吗?
  • 好像我已经修好了:) 23 行必须是if arg.type == tf.string.as_datatype_enum:
  • 我怀疑你使用的是 0.9 或更早版本的 TensorFlow,dtypes.py 中没有这样的行,并且从 0.10 版本开始就没有被触及

标签: python string numpy tensorflow tfrecord


【解决方案1】:

与 Python 不同,在 Python 中,出于切片等目的,字符串可以被视为字符列表,TensorFlow 的 tf.strings 是不可分割的值。例如,下面的x 是一个Tensor,其形状为(2,),其每个元素都是一个可变长度的字符串。

x = tf.constant(["This is a string", "This is another string"])

但是,为了实现您想要的,TensorFlow 提供了tf.decode_raw 运算符。它以tf.string 张量作为输入,但可以将字符串解码为任何其他原始数据类型。例如,要将字符串解释为字符张量,您可以执行以下操作:

x = tf.constant("This is string")
x = tf.decode_raw(x, tf.uint8)
y = x[:4]
sess = tf.InteractiveSession()
print(y.eval())
# prints [ 84 104 105 115]

【讨论】:

  • 谢谢。那么,它们是标量还是别的什么?
  • 它们是原生字符串类型。您可以在最新版本中使用 tf.string_split(s, delimiter="") 将其分解为字符(长度为 1 个字符串)
  • print("".join(map(chr, y.eval()))) 更可能是您想要的
猜你喜欢
  • 2011-07-04
  • 2011-08-03
  • 2017-10-26
  • 1970-01-01
  • 2022-08-13
  • 1970-01-01
  • 2011-10-08
  • 2014-05-27
  • 2018-01-25
相关资源
最近更新 更多