gpt4 book ai didi

python - Tensorflow:使用 tf.slice 分割输入

转载 作者:太空狗 更新时间:2023-10-29 19:34:37 25 4
gpt4 key购买 nike

我正在尝试将我的输入层分成不同大小的部分。我正在尝试使用 tf.slice 来执行此操作,但它不起作用。

一些示例代码:

import tensorflow as tf
import numpy as np

ph = tf.placeholder(shape=[None,3], dtype=tf.int32)

x = tf.slice(ph, [0, 0], [3, 2])

input_ = np.array([[1,2,3],
[3,4,5],
[5,6,7]])

with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print sess.run(x, feed_dict={ph: input_})

输出:

[[1 2]
[3 4]
[5 6]]

这行得通并且大致是我想要发生的事情,但我必须指定第一个维度(在本例中为 3)。我不知道我将输入多少向量,这就是为什么我首先使用 placeholderNone 的原因!

是否有可能以这样一种方式使用 slice,即当维度在运行时未知时它可以工作?

我试过使用从 ph.get_shape()[0] 中获取值的 placeholder,如下所示:x = tf.slice(ph , [0, 0], [num_input, 2])。但这也不起作用。

最佳答案

您可以在tf.slicesize 参数中指定一个负维度。负维度告诉 Tensorflow 根据其他维度的决定动态确定正确的值。

import tensorflow as tf
import numpy as np

ph = tf.placeholder(shape=[None,3], dtype=tf.int32)

# look the -1 in the first position
x = tf.slice(ph, [0, 0], [-1, 2])

input_ = np.array([[1,2,3],
[3,4,5],
[5,6,7]])

with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print(sess.run(x, feed_dict={ph: input_}))

关于python - Tensorflow:使用 tf.slice 分割输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39054414/

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