gpt4 book ai didi

python - 如何在 Tensorflow 中为张量切片赋值?

转载 作者:太空宇宙 更新时间:2023-11-03 20:53:08 24 4
gpt4 key购买 nike

我想使用以下代码更新“centers”

centers = tf.zeros((batch, H, W, B, 2))

for row in range(H):
for col in range(W):
centers[:, row, col, :, 0] = (col + centers[:, row, col, :, 0]) / W * 364
centers[:, row, col, :, 1] = (row + centers[:, row, col, :, 1]) / H * 205

错误:

TypeError: 'Tensor' object does not support item assignment

我该怎么办?如果有人提供帮助,我将非常感激。

最佳答案

张量是不可变的。一般来说,您需要做的是计算将为您提供所需输出的张量。在这种情况下,你可以这样做:

import tensorflow as tf
import numpy as np

# Make random input data
np.random.seed(100)
batch = 10
H = 100
W = 200
B = 5
centers = np.random.rand(batch, H, W, B, 2).astype(np.float32)

# Compute result with NumPy
centers_np = centers.copy()
for row in range(H):
for col in range(W):
centers_np[:, row, col, :, 0] = (col + centers_np[:, row, col, :, 0]) / W * 364
centers_np[:, row, col, :, 1] = (row + centers_np[:, row, col, :, 1]) / H * 205

# Compute result with TensorFlow and check result is equal
with tf.Graph().as_default(), tf.Session() as sess:
dt = tf.float32
centers_ph = tf.placeholder(dt, [None, None, None, None, 2])
s = tf.shape(centers_ph)
H = s[1]
W = s[2]
row = tf.cast(tf.range(H)[:, tf.newaxis, tf.newaxis], dt)
col = tf.cast(tf.range(W)[:, tf.newaxis], dt)
c0, c1 = tf.unstack(centers_ph, num=2, axis=-1)
centers_tf = tf.stack([(col + c0) / tf.cast(W, dt) * 364,
(row + c1) / tf.cast(H, dt) * 205], axis=-1)
centers_val = sess.run(centers_tf, feed_dict={centers_ph: centers})
print(np.allclose(centers_val, centers_np))
# True

关于python - 如何在 Tensorflow 中为张量切片赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56188546/

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