def pad_axis(x, offset, size, axis=0, name=None):
"""Pad a tensor on an axis, with a given offset and output size.
The tensor is padded with zero (i.e. CONSTANT mode). Note that the if the
`size` is smaller than existing size + `offset`, the output tensor
was the latter dimension.
Args:
x: Tensor to pad;
offset: Offset to add on the dimension chosen;
size: Final size of the dimension.
Return:
Padded tensor whose dimension on `axis` is `size`, or greater if
the input vector was larger.
"""
with tf.name_scope(name, 'pad_axis'):
shape = get_shape(x)
rank = len(shape)
# Padding description.
new_size = tf.maximum(size-offset-shape[axis], 0)
pad1 = tf.stack([0]*axis + [offset] + [0]*(rank-axis-1))
pad2 = tf.stack([0]*axis + [new_size] + [0]*(rank-axis-1))
paddings = tf.stack([pad1, pad2], axis=1)
x = tf.pad(x, paddings, mode='CONSTANT')
# Reshape, to get fully defined shape if possible.
# TODO: fix with tf.slice
shape[axis] = size
x = tf.reshape(x, tf.stack(shape))
return x
# def select_at_index(idx, val, t):
# """Return a tensor.
# """
# idx = tf.expand_dims(tf.expand_dims(idx, 0), 0)
# val = tf.expand_dims(val, 0)
# t = t + tf.scatter_nd(idx, val, tf.shape(t))
# return t
评论列表
文章目录