- TensorFlow tile & Numpy tile
1.1 如下,tile一般用法是,参数一是要tile对象t4,参数二是一个shape,表示要对t4各个axis做多少复制,示例[3,2]表示对axis=0和axis=1分别做3、2次复制;需要注意的是复制都是对t4整体复制;
>> t4 = tf.constant([[1,2,3],[4,5,6]])
>> tf.tile(t4, [3, 2])
>> <tf.Tensor: id=12, shape=(6, 6), dtype=int32, numpy=
array([[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6],
[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6],
[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6]], dtype=int32)>
- pytorch repeat
2.1 功能与tf的tile相同
> t4 = torch.LongTensor([[1,2,3],[4,5,6]])
> t4.repeat([3, 2])
> tensor([[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6],
[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6],
[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6]])
- 以上述t4为例,如何对每行连续复制3次?
3.1 可以看到上面的tile、repeat都是对t4进行整体复制,怎么实现每行的连续复制(如下结果);
3.2 pytorch实现了一个函数torch.repeat_interleave(input, repeats, dim);input即为要处理对象(如t4),repeats表示复制次数,dim表示对哪个axis进行连续复制;
3.3 结果一只要执行 torch.repeat_interleave(t4, 3, 0)即可;结果二同理处理;
3.4 TensorFlow相应功能函数我没查到,待查
> tensor([[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[4, 5, 6],
[4, 5, 6],
[4, 5, 6]])
> tensor([[1, 1, 2, 2, 3, 3],
[1, 1, 2, 2, 3, 3],
[1, 1, 2, 2, 3, 3],
[4, 4, 5, 5, 6, 6],
[4, 4, 5, 5, 6, 6],
[4, 4, 5, 5, 6, 6]])
- 处理上面这种情况(3),也可以用torch.index_select(input, dim, index),该函数较常出现在nlp中,功能是根据index从input中的dim轴挑选局部tensor,重组一个大的tensor;以下为针对情况3这种要求的一个处理方法(引用自此),稍复杂
> def tile(a, dim, n_tile):
init_dim = a.size(dim)
repeat_idx = [1] * a.dim()
repeat_idx[dim] = n_tile
a = a.repeat(*(repeat_idx))
order_index = torch.LongTensor(np.concatenate([init_dim * np.arange(n_tile) + i for i in range(init_dim)]))
return torch.index_select(a, dim, order_index)
> t = torch.tensor([[1, 2, 3], [4, 4, 4]])
> tile(t, 0, 3)
> tensor([[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[4, 4, 4],
[4, 4, 4],
[4, 4, 4]])