我想使用以下代码更新“中心”
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
我该怎么办?如果有人提供帮助,我将非常感谢。
答案 0 :(得分:0)
张量是不变的。通常,您要做的是计算张量,该张量将为您提供所需的输出。在这种情况下,您可以这样操作:
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