首页 > 解决方案 > 张量流中的数组数组

问题描述

我想将张量列表写入数组m的次数(m每次迭代都会发生变化)。示例输出可能如下所示:

[
[[0, 0, 0, 0]],

[[0, 0, 0, 0],
[1, 1, 1, 1]],

[[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2]],

[[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]]
]

我正在尝试使用 while_loop 来实现这一点。这是我的代码:

i = tf.constant(1)
n = tf.constant(4)

def c(i,x):
    return tf.less(i, n)

def b(i, x):
    def _c(j,y):
        return tf.less(j, i)

    def _b(j, y):
        y = y.write(j, [j,j,j,j])
        return [tf.add(j,1), y]


    y = tf.TensorArray(dtype=tf.int32,size=1, dynamic_size=True,clear_after_read=False)
    j = tf.constant(0)
    _, y = tf.while_loop(_c, _b, (j, y))
    y = y.stack()

    x = x.write(i, y)
    return [tf.add(i,1), x]

x = tf.TensorArray(dtype=tf.int32,size=1, dynamic_size=True,clear_after_read=False,infer_shape=False)
_, out = tf.while_loop(c, b, (i, x))
out = out.stack()

with tf.compat.v1.Session() as sess:
    print(sess.run([out]))

但我收到以下错误:

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/usr/local/lib/python3.7/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1333     try:
-> 1334       return fn(*args)
   1335     except errors.OpError as e:

/usr/local/lib/python3.7/site-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
   1318       return self._call_tf_sessionrun(
-> 1319           options, feed_dict, fetch_list, target_list, run_metadata)
   1320 

/usr/local/lib/python3.7/site-packages/tensorflow/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
   1406         self._session, options, feed_dict, fetch_list, target_list,
-> 1407         run_metadata)
   1408 

InvalidArgumentError: TensorArray TensorArray_45_592: Could not read from TensorArray index 0.  Furthermore, the element shape is not fully defined: <unknown>.  It is possible you are working with a resizeable TensorArray and stop_gradients is not allowing the gradients to be written.  If you set the full element_shape property on the forward TensorArray, the proper all-zeros tensor will be returned instead of incurring this error.
     [[{{node TensorArrayStack_33/TensorArrayGatherV3}}]]

标签: pythontensorflow

解决方案


推荐阅读