gpt4 book ai didi

python - TensorFlow 字符串 : what they are and how to work with them

转载 作者:太空狗 更新时间:2023-10-29 17:30:00 27 4
gpt4 key购买 nike

当我使用 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

它说

  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_shape.py", line 621, in assert_has_rank    raise ValueError("Shape %s must have rank %d" % (self, rank))ValueError: Shape () must have rank 1

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

tensorflow.python.framework.errors.InvalidArgumentError: StringToNumberOp could not correctly convert string: PIEH

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

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

最佳答案

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

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]

关于python - TensorFlow 字符串 : what they are and how to work with them,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38902433/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com