Tin*_*pic 5 python python-2.7 tensorflow
我正在为 tensorflow RNN 准备输入张量。
目前我正在做以下事情
rnn_format = list()
for each in range(batch_size):
rnn_format.append(tf.slice(input2Dpadded,[each,0],[max_steps,10]))
lstm_input = tf.stack(rnn_format)
Run Code Online (Sandbox Code Playgroud)
是否可以使用一些 tensorflow 函数在没有循环的情况下立即执行此操作?
正如 Peter Hawkins 所建议的,您可以使用gather_nd适当的索引来实现这一目标。
您可以在调用 之前简单地对内部维度进行统一裁剪gather_nd。
例子:
\n\nimport tensorflow as tf\nimport numpy as np\n\nsess = tf.InteractiveSession()\n\n# integer image simply because it is more readable to me\nim0 = np.random.randint(10, size=(20,20))\nim = tf.constant(im0)\n\nmax_steps = 3\nbatch_size = 10\n\n# create the appropriate indices here\nindices = (np.arange(max_steps) +\n np.arange(batch_size)[:,np.newaxis])[...,np.newaxis]\n# crop then call gather_nd\nres = tf.gather_nd(im[:,:10], indices).eval()\n\n# check that the resulting tensors are equal to what you had previously\nfor each in range(batch_size):\n assert(np.all(tf.slice(im, [each,0],[max_steps,10]).eval() == res[each]))\nRun Code Online (Sandbox Code Playgroud)\n\n编辑
\n\n如果您的切片索引位于张量中,则在创建时只需将 numpy 的操作替换为 tensorflow 的操作indices:
# indices stored in a 1D array\nmy_indices = tf.constant([1, 8, 3, 0, 0])\nindices = (np.arange(max_steps) +\n my_indices[:,tf.newaxis])[...,tf.newaxis]\nRun Code Online (Sandbox Code Playgroud)\n\n进一步说明:
\n\nindices是通过在加法过程中利用广播来创建的:数组实际上是平铺的,以便它们的尺寸匹配。numpy 和tensorflow 以类似的方式支持广播。...是标准numpy 切片符号的一部分,它基本上填充了其他切片索引留下的所有剩余维度。所以[..., newaxis]基本上相当于expand_dims(\xc2\xb7, -1)。| 归档时间: |
|
| 查看次数: |
2875 次 |
| 最近记录: |