Skip to main content
 首页 » 编程设计

python之用列表切片张量之TensorFlow

2024年08月19日31davidwang456

有没有办法在 Tensorflow 中完成这种切片方法(使用 numpy 显示的示例)?

z = np.random.random((3,7,7,12)) 
x = z[...,[0,5]] 

这样

x_hat = np.concatenate([z[...,[0]], z[...,[5]]], 3) 
assert np.all(x == x_hat) 
x.shape # (3, 7, 7, 2) 

在Tensorflow中,这个操作

tfz = tf.constant(z) 
i = np.array([0,5] dtype=np.int32) 
tfx = tfz[...,i] 

抛出错误

ValueError: Shapes must be equal rank, but are 0 and 1 
From merging shape 0 with other shapes. for 'strided_slice/stack_1' (op: 'Pack') with input shapes: [], [2]. 

请您参考如下方法:

怎么样:

x = tf.stack([tfz[..., i] for i in [0,5]], axis=-1)  

这对我有用:

z = np.random.random((3,7,7,12)) 
tfz = tf.constant(z) 
x = tf.stack([tfz[..., i] for i in [0,5]], axis=-1) 
 
x_hat = np.concatenate([z[...,[0]], z[...,[5]]], 3) 
 
with tf.Session() as sess: 
    x_run = sess.run(x) 
 
assert np.all(x_run == x_hat)