Tensorflow - 张量的块更新
Posted
技术标签:
【中文标题】Tensorflow - 张量的块更新【英文标题】:Tensorflow - Block Update of a tensor 【发布时间】:2018-05-13 08:42:47 【问题描述】:x 是一个形状为 [32,32,3] 的张量
Y 是一个形状为 [1,320,320,3] 的张量
我们可以将 Y, Y[0,:32,:32,:] = x 更新为张量流操作吗?
【问题讨论】:
【参考方案1】:是的,你可以。你测试过吗?
切片也是张量。使用:
Y[0,:32,:32,:].assign(x)
1D 示例,以便我们清楚地看到正在发生的事情:
import numpy as np
import tensorflow as tf
x = tf.Variable(np.zeros((2,)))
Y = tf.Variable(np.ones((10,)))
block_update = Y[4:6].assign(x)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print('old', Y.eval(sess))
sess.run(block_update)
print('new', Y.eval(sess))
输出:
old [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
new [ 1. 1. 1. 1. 0. 0. 1. 1. 1. 1.]
【讨论】:
【参考方案2】:gen_array_ops.inplace_update 可能是您想要的。
from tensorflow.python.ops.gen_array_ops import inplace_update
这里是官方文档
def inplace_update(x, i, v, name=None):
r"""Updates specified rows 'i' with values 'v'.
Computes `x[i, :] = v; return x`.
Originally this function is mutative however for compilation we make this
operation create / operate on a copy of `x`.
Args:
x: A `Tensor`. A tensor of type `T`.
i: A `Tensor` of type `int32`.
A vector. Indices into the left-most dimension of `x`.
v: A `Tensor`. Must have the same type as `x`.
A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `x`.
"""
【讨论】:
以上是关于Tensorflow - 张量的块更新的主要内容,如果未能解决你的问题,请参考以下文章