NJU1healer的个人博客分享 http://blog.sciencenet.cn/u/NJU1healer

博文

[Pytorch函数] .masked_fill_()与Numpy数组中None的作用

已有 5035 次阅读 2020-11-19 16:42 |个人分类:Pytorch|系统分类:科研笔记

(一).masked_fill_()

masked_fill_(mask, value)
掩码操作
用value填充tensor中与mask中值为1位置相对应的元素。mask的形状必须与要填充的tensor形状一致。

a = torch.randn(5,6)


x = [5,4,3,2,1]

mask = torch.zeros(5,6,dtype=torch.float)

for e_id, src_len in enumerate(x):

    mask[e_id, src_len:] = 1

mask = mask.to(device = 'cpu')

print(mask)

a.data.masked_fill_(mask.byte(),-float('inf'))

print(a)

----------------------------输出

tensor([[0., 0., 0., 0., 0., 1.],

        [0., 0., 0., 0., 1., 1.],

        [0., 0., 0., 1., 1., 1.],

        [0., 0., 1., 1., 1., 1.],

        [0., 1., 1., 1., 1., 1.]])

tensor([[-0.1053, -0.0352,  1.4759,  0.8849, -0.7233,    -inf],

        [-0.0529,  0.6663, -0.1082, -0.7243,    -inf,    -inf],

        [-0.0364, -1.0657,  0.8359,    -inf,    -inf,    -inf],

        [ 1.4160,  1.1594,    -inf,    -inf,    -inf,    -inf],

        [ 0.4163,    -inf,    -inf,    -inf,    -inf,    -inf]])

(二)Numpy数组中None的作用

>>> import numpy as np

>a=[1,2,3,4]

>>> a=np.array(a)

>>> a

array([1, 2, 3, 4])

>>> b=a[:,None]

>>> b

array([[1],

       [2],

       [3],

       [4]])

>>> c=a[:,None,None]

>>> c

array([[[1]],


       [[2]],


       [[3]],


       [[4]]])


>>> a=np.ones((2,3))

>>> a

array([[1., 1., 1.],

       [1., 1., 1.]])

>>> b=a[:,None,:]

>>> b

array([[[1., 1., 1.]],


       [[1., 1., 1.]]])

>>> b=a[None,:,:]

>>> b

array([[[1., 1., 1.],

        [1., 1., 1.]]])



在pytorch中:

>>> import torch as t

>>> a=t.from_numpy(a)

>>> a

tensor([[1., 1., 1.],

        [1., 1., 1.]], dtype=torch.float64)

>>> b=a[:,None,:]

>>> b

tensor([[[1., 1., 1.]],


        [[1., 1., 1.]]], dtype=torch.float64)

可以看出,在数组索引中,加入None就相当于在对应维度加一维
但是这种方法只是在ndarray和tensor类型使用,python的list并不适用(会报错)

点滴分享,福泽你我!Add oil!



https://blog.sciencenet.cn/blog-3428464-1259051.html

上一篇:[转载]Python numpy模块:transpose以及swapaxes函数(矩阵理解及性能)
下一篇:[转载]Pollutant 和 Contaminant的区别
收藏 IP: 211.162.81.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

全部作者的其他最新博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-23 22:33

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部