相当于 TensorFlow 中的 np.resize
Equivalent of np.resize in TensorFlow
我有一个一维数组 x
并且想按照 np.resize 正在做的相同方式将其重新整形为请求的形状,即如果 x
中的元素太多它们被丢弃,如果太少,它们被循环添加,例如
x = np.array([1, 2, 3, 4, 5, 6])
y = np.resize(x, shape=(2, 2))
assert y == np.array([[1, 2], [3, 4]])
z = np.resize(x, shape=(3, 3))
assert z == np.array([[1, 2, 3], [4, 5, 6], [1, 2, 3]])
我想知道如何仅使用 TensorFlow 中的张量运算符来做到这一点。
我不确定这是否可以在 TF 中的单个操作中实现,但可以使用 crops 或 tf.tile
编写一个函数,然后重塑结果。
感谢 Poe Dator's 我最终得到了以下解决方案:
def tf_resize(t, shape):
"""
Args:
t: a `Tensor`
shape: requested output shape
"""
input_size = tf.size(t)
output_size = tf.reduce_prod(shape)
t_flatten = tf.reshape(t, [input_size])
result = tf.tile(t_flatten, [output_size // input_size + 1])
return tf.reshape(result[0:output_size], shape=shape)
我有一个一维数组 x
并且想按照 np.resize 正在做的相同方式将其重新整形为请求的形状,即如果 x
中的元素太多它们被丢弃,如果太少,它们被循环添加,例如
x = np.array([1, 2, 3, 4, 5, 6])
y = np.resize(x, shape=(2, 2))
assert y == np.array([[1, 2], [3, 4]])
z = np.resize(x, shape=(3, 3))
assert z == np.array([[1, 2, 3], [4, 5, 6], [1, 2, 3]])
我想知道如何仅使用 TensorFlow 中的张量运算符来做到这一点。
我不确定这是否可以在 TF 中的单个操作中实现,但可以使用 crops 或 tf.tile
编写一个函数,然后重塑结果。
感谢 Poe Dator's
def tf_resize(t, shape):
"""
Args:
t: a `Tensor`
shape: requested output shape
"""
input_size = tf.size(t)
output_size = tf.reduce_prod(shape)
t_flatten = tf.reshape(t, [input_size])
result = tf.tile(t_flatten, [output_size // input_size + 1])
return tf.reshape(result[0:output_size], shape=shape)