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)
添加回答
举报