Gather slices from var in each batch, according to corrensponding index in indices. Currently, it only support 2d Tensor. Args: var (Variable): with shape [batch_size, ...] indices (Variable): with shape [batch_size, max_len] Returns: Variable with shape [batch_size]
(var, indices)
| 62 | |
| 63 | |
| 64 | def batch_gather_2d(var, indices): |
| 65 | """Gather slices from var in each batch, according to corrensponding |
| 66 | index in indices. Currently, it only support 2d Tensor. |
| 67 | |
| 68 | Args: |
| 69 | var (Variable): with shape [batch_size, ...] |
| 70 | indices (Variable): with shape [batch_size, max_len] |
| 71 | |
| 72 | Returns: Variable with shape [batch_size] |
| 73 | |
| 74 | Raises: NULL |
| 75 | |
| 76 | Examples: |
| 77 | var |
| 78 | [[1, 2, 3], |
| 79 | [4, 5, 6]] |
| 80 | indices |
| 81 | [[2, 0], [1, 2]] |
| 82 | |
| 83 | return |
| 84 | [[3, 1], [5, 6]] |
| 85 | |
| 86 | """ |
| 87 | if len(indices.shape) != 2: |
| 88 | raise ValueError('shape of indices error. it should be a 2-D layers. ' |
| 89 | 'but got shape = %s' % (str(indices.shape), )) |
| 90 | |
| 91 | batch_size = paddle.shape(indices)[0] |
| 92 | |
| 93 | zero = paddle.to_tensor([0], dtype='int64') |
| 94 | one = paddle.to_tensor([1], dtype='int64') |
| 95 | end = paddle.cast(batch_size, dtype='int64') |
| 96 | batch_indices_1d = paddle.unsqueeze(paddle.arange(zero, end, one, dtype=indices.dtype), [1]) |
| 97 | |
| 98 | seq_len = indices.shape[1] |
| 99 | batch_indices = paddle.expand(batch_indices_1d, [batch_size, seq_len]) |
| 100 | |
| 101 | coord_2d = paddle.concat([paddle.unsqueeze(batch_indices, [2]), paddle.unsqueeze(indices, [2])], axis=2) |
| 102 | coord_2d.stop_gradient = True |
| 103 | coord_1d = paddle.reshape(coord_2d, shape=[-1, 2]) |
| 104 | output_1d = paddle.gather_nd(var, coord_1d) |
| 105 | output_2d = paddle.reshape(output_1d, [batch_size, seq_len, var.shape[-1]]) |
| 106 | return output_2d |
| 107 | |
| 108 | |
| 109 | def sequence_mask(seq_hidden, mask, mode='zero'): |