我不太确定您期望什么结果,但如果我理解正确,您可以这样做:
import tensorflow as tf
a = tf.concat([tf.ones([1, 4, 3], dtype=tf.float32),
tf.ones([1, 4, 3], dtype=tf.float32) * 3,
tf.zeros([2, 4, 3], dtype=tf.float32)], axis=0)
b = tf.constant(7, dtype=tf.float32)
tensor = tf.slice(a,
begin=[1, 0, 0],
size=[1, 4, 3])
c = tensor * b
result = tf.tensor_scatter_nd_update(a, [[1]], c)
print('a -->', a, '\n')
print('c -->', c, '\n')
print('result -->', result)
a --> tf.Tensor(
[[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
[[3. 3. 3.]
[3. 3. 3.]
[3. 3. 3.]
[3. 3. 3.]]
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]], shape=(4, 4, 3), dtype=float32)
c --> tf.Tensor(
[[[21. 21. 21.]
[21. 21. 21.]
[21. 21. 21.]
[21. 21. 21.]]], shape=(1, 4, 3), dtype=float32)
result --> tf.Tensor(
[[[ 1. 1. 1.]
[ 1. 1. 1.]
[ 1. 1. 1.]
[ 1. 1. 1.]]
[[21. 21. 21.]
[21. 21. 21.]
[21. 21. 21.]
[21. 21. 21.]]
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]], shape=(4, 4, 3), dtype=float32)
更新:按照你想要的方式对数据进行切片并不是你想象的那样:
import tensorflow as tf
a = tf.concat([tf.ones([1, 2, 3], dtype=tf.float32),
tf.zeros([1, 2, 3], dtype=tf.float32)], axis=0)
b = tf.ones([2, 2, 3], dtype=tf.float32)
print(a.shape, a[...,0])
print(b.shape, b[...,0])
(2, 2, 3) tf.Tensor(
[[1. 1.]
[0. 0.]], shape=(2, 2), dtype=float32)
(2, 2, 3) tf.Tensor(
[[1. 1.]
[1. 1.]], shape=(2, 2), dtype=float32)
正如您在使用具有混合值的 (2, 2, 3) 张量时所看到的,当沿最后一个轴切片时,您不仅会得到预期的结果。