tile&repeat api使用小结

  1. 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)>
  1. 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]])
  1. 以上述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]])
  1. 处理上面这种情况(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))  # 这几行应该用一行repeat函数就可以了
    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]])
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值