【问题标题】:Insert Tensor into bigger tensor in Tensorflow在 Tensorflow 中将张量插入更大的张量
【发布时间】:2020-02-05 19:19:10
【问题描述】:

我使用的是 TensorFlow 1.15 我有一个张量,其中包含一个形状为 (BatchsizeWidthHeight*3)

的图像

我有一个大小为 Batchsize*50*50*3 的补丁 我想在原始图像中指定插入补丁的位置。 但是为了让它更简单,假设我有一个包含 10 个元素的一维数组并且想要 替换给定索引处的单个值 开头应该是这样的。

sess = tf.Session()
array = tf.placeholder("float32",[10]) # for easier explanation a 1d array 
variable = tf.get_variable(name=var,shape=[1],intializer=init) # This variable should replace the value
index = tf.placeholder("int32",[1]) # the value on this index should be replaced
# Here The value of the image tensor at place index should be replaced with the variable

in_dict = {image: np.zeros([10],dtype="float")
           index: 4}
sess.run(...,feed_dict=in_dict)

tf.where 需要两个大小相同的张量,但我的变量和数组的大小不同。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    您可以使用填充的较小张量来做到这一点。

    import tensorflow as tf
    import numpy as np
    
    x = tf.placeholder(tf.float32, [10])
    x_sub = tf.placeholder(tf.float32, [2])
    idx = tf.placeholder(tf.int32, ())
    
    
    def assign_slice(x, y, idx):
      '''return x with x[r:r+len(y)] assigned values from y'''
      x_l = x.shape[0]
      y_l = y.shape[0]
      #pad the smaller tensor accordingly with shapes and index using NaNs
      y_padded = tf.pad(y, [[idx, x_l-y_l-idx]], constant_values=float('NaN'))
      #if value in padded tensor is NaN, use x, else use y
      return tf.where(tf.is_nan(y_padded), x, y_padded)
    
    
    y = assign_slice(x, x_sub, idx)
    
    with tf.Session() as sess:
      print(sess.run(y, feed_dict={x:np.ones([10]), x_sub:np.zeros([2]), idx:2}))
    

    这应该打印[1. 1. 0. 0. 1. 1. 1. 1. 1. 1.]

    另一种方法可能是使用掩码提供相同大小的张量,即: out = x * mask + y * (1-mask)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      相关资源
      最近更新 更多