亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Tensorflow 中將張量插入更大的張量

在 Tensorflow 中將張量插入更大的張量

開滿天機 2022-07-19 15:20:57
我正在使用 Tensorflow 1.15 我有一個張量,其中包含一個形狀為 (Batchsize Width Height*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 valueindex = 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 variablein_dict = {image: np.zeros([10],dtype="float")           index: 4}sess.run(...,feed_dict=in_dict)tf.where 需要兩個大小相同的張量,但我的變量和數組的大小不同。
查看完整描述

1 回答

?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

你可以用一個填充的更小的張量來做到這一點。


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)


查看完整回答
反對 回復 2022-07-19
  • 1 回答
  • 0 關注
  • 93 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號