1 回答

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超5個(gè)贊
你可以用一個(gè)填充的更小的張量來做到這一點(diǎn)。
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}))
這應(yīng)該打印[1. 1. 0. 0. 1. 1. 1. 1. 1. 1.]。
另一種方法可能是用掩碼提供相同大小的張量,即: out = x * mask + y * (1-mask)
添加回答
舉報(bào)