gpt4 book ai didi

python - 当 Variable 的第一个维度为 None 时使用 tf.unpack()

转载 作者:太空狗 更新时间:2023-10-29 17:16:03 26 4
gpt4 key购买 nike

我正在使用以下方法输入动态形状的张量:

x = tf.placeholder(tf.int32, shape=[None, vector_size])

我需要将其转换为具有 shape=[1, vector_size] 的张量列表使用 x_list = tf.unpack(x, 0)

但它引发了一个 ValueError因为第一维的长度未知,即它是 None .

我一直在尝试使用另一个 tf.placeholder 来解决这个问题动态提供 x 的形状但是参数 shape不能是张量。

如何使用 tf.unpack()在这个情况下?

或者是否有另一个函数也可以将我输入的变量转换为张量列表?

提前致谢。

最佳答案

我不认为你可以unpack 参数num 未指定且不可推断的张量。作为他们的documentation说:

Raises ValueError if num is unspecified and cannot be inferred.

这与TensorFlow内部如何设计unpack等操作有关。在这个other tread , Yaroslav Bulatov 解释说

Operations like unpack compile into "tensor-in/tensor-out" ops during graph construction time.

因此TensorFlow需要知道num的具体值才能通过编译。

不过,我会尝试使用 TensorArray 来解决这个问题。 (请参见以下代码进行说明)。

import tensorflow as tf
import numpy as np
sess = tf.InteractiveSession()
# assume vector_size=2 for simplicity
x = tf.placeholder(tf.int32, shape=[None, 2])
TensorArr = tf.TensorArray(tf.int32, 1, dynamic_size=True, infer_shape=False)
x_array = TensorArr.unpack(x)

TensorArray is a class for wrapping dynamically sized arrays of Tensors .在本应用中初始化一个TensorArray对象时,TensorArr = tf.TensorArray(tf.int32, 1, dynamic_size=True, infer_shape=False),设置dynamic_size= Trueinfer_shape=False 因为占位符 x 的形状仅部分定义。

访问每个解包的元素:

# access the first element
x_elem0 = x_array.read(0)
# access the last element
last_idx = tf.placeholder(tf.int32)
x_last_elem = x_array.read(last_idx)

然后在评估时:

# generate random numpy array
dim0 = 4
x_np = np.random.randint(0, 25, size=[dim0, 2])
print x_np
# output of print x_np
[[17 15]
[17 19]
[ 3 0]
[ 4 13]]

feed_dict = {x : x_np, last_idx : dim0-1} #python 0 based indexing
x_elem0.eval(feed_dict=feed_dict)
array([17, 15], dtype=int32) #output of x_elem0.eval(feed_dict)

x_last_elem.eval(feed_dict=feed_dict)
array([ 4, 13], dtype=int32) #output of x_last_elem.eval(feed_dict)
sess.close()

请注意,当尝试访问每个解压缩的元素时,如果 index 值超出范围,您将能够通过编译,但在运行时会出现错误,提示 index out的约束。此外,解压缩张量的形状将为 TensorShape(None),因为 x 的形状在被评估之前仅部分确定。

关于python - 当 Variable 的第一个维度为 None 时使用 tf.unpack(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39446313/

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