pytorch中的numel函数用法说明

获取tensor中一共包含多少个元素

import torch
x = torch.randn(3,3)
print("number elements of x is ",x.numel())
y = torch.randn(3,10,5)
print("number elements of y is ",y.numel())

输出:

number elements of x is 9

number elements of y is 150

27和150分别位x和y中各有多少个元素或变量

补充:pytorch获取张量元素个数numel()的用法

numel就是"number of elements"的简写。

numel()可以直接返回int类型的元素个数

import torch
a = torch.randn(1, 2, 3, 4)
b = a.numel()
print(type(b)) # int
print(b) # 24

通过numel()函数,我们可以迅速查看一个张量到底又多少元素。

补充:pytorch 卷积结构和numel()函数

看代码吧~

from torch import nn
class CNN(nn.Module):
    def __init__(self, num_channels=1, d=56, s=12, m=4):
        super(CNN, self).__init__()
        self.first_part = nn.Sequential(
            nn.Conv2d(num_channels, d, kernel_size=3, padding=5//2),
            nn.Conv2d(num_channels, d, kernel_size=(1,3), padding=5//2),
            nn.Conv2d(num_channels, d, kernel_size=(3,1), padding=5//2),
            nn.PReLU(d)
        )

    def forward(self, x):
        x = self.first_part(x)
        return x

model = CNN()
for m in model.first_part:
    if isinstance(m, nn.Conv2d):
        # print('m:',m.weight.data)
        print('m:',m.weight.data[0])
        print('m:',m.weight.data[0][0])
        print('m:',m.weight.data.numel()) #numel() 计算矩阵中元素的个数

结果:
m: tensor([[[-0.2822,  0.0128, -0.0244],
         [-0.2329,  0.1037,  0.2262],
         [ 0.2845, -0.3094,  0.1443]]]) #卷积核大小为3x3
m: tensor([[-0.2822,  0.0128, -0.0244],
        [-0.2329,  0.1037,  0.2262],
        [ 0.2845, -0.3094,  0.1443]]) #卷积核大小为3x3
m: 504   # = 56 x (3 x 3)  输出通道数为56,卷积核大小为3x3
m: tensor([-0.0335,  0.2945,  0.2512,  0.2770,  0.2071,  0.1133, -0.1883,  0.2738,
         0.0805,  0.1339, -0.3000, -0.1911, -0.1760,  0.2855, -0.0234, -0.0843,
         0.1815,  0.2357,  0.2758,  0.2689, -0.2477, -0.2528, -0.1447, -0.0903,
         0.1870,  0.0945, -0.2786, -0.0419,  0.1577, -0.3100, -0.1335, -0.3162,
        -0.1570,  0.3080,  0.0951,  0.1953,  0.1814, -0.1936,  0.1466, -0.2911,
        -0.1286,  0.3024,  0.1143, -0.0726, -0.2694, -0.3230,  0.2031, -0.2963,
         0.2965,  0.2525, -0.2674,  0.0564, -0.3277,  0.2185, -0.0476,  0.0558]) bias偏置的值
m: tensor([[[ 0.5747, -0.3421,  0.2847]]]) 卷积核大小为1x3
m: tensor([[ 0.5747, -0.3421,  0.2847]]) 卷积核大小为1x3
m: 168 # = 56 x (1 x 3) 输出通道数为56,卷积核大小为1x3
m: tensor([ 0.5328, -0.5711, -0.1945,  0.2844,  0.2012, -0.0084,  0.4834, -0.2020,
        -0.0941,  0.4683, -0.2386,  0.2781, -0.1812, -0.2990, -0.4652,  0.1228,
        -0.0627,  0.3112, -0.2700,  0.0825,  0.4345, -0.0373, -0.3220, -0.5038,
        -0.3166, -0.3823,  0.3947, -0.3232,  0.1028,  0.2378,  0.4589,  0.1675,
        -0.3112, -0.0905, -0.0705,  0.2763,  0.5433,  0.2768, -0.3804,  0.4855,
        -0.4880, -0.4555,  0.4143,  0.5474,  0.3305, -0.0381,  0.2483,  0.5133,
        -0.3978,  0.0407,  0.2351,  0.1910, -0.5385,  0.1340,  0.1811, -0.3008]) bias偏置的值
m: tensor([[[0.0184],
         [0.0981],
         [0.1894]]]) 卷积核大小为3x1
m: tensor([[0.0184],
        [0.0981],
        [0.1894]]) 卷积核大小为3x1
m: 168 # = 56 x (3 x 1) 输出通道数为56,卷积核大小为3x1
m: tensor([-0.2951, -0.4475,  0.1301,  0.4747, -0.0512,  0.2190,  0.3533, -0.1158,
         0.2237, -0.1407, -0.4756,  0.1637, -0.4555, -0.2157,  0.0577, -0.3366,
        -0.3252,  0.2807,  0.1660,  0.2949, -0.2886, -0.5216,  0.1665,  0.2193,
         0.2038, -0.1357,  0.2626,  0.2036,  0.3255,  0.2756,  0.1283, -0.4909,
         0.5737, -0.4322, -0.4930, -0.0846,  0.2158,  0.5565,  0.3751, -0.3775,
        -0.5096, -0.4520,  0.2246, -0.5367,  0.5531,  0.3372, -0.5593, -0.2780,
        -0.5453, -0.2863,  0.5712, -0.2882,  0.4788,  0.3222, -0.4846,  0.2170]) bias偏置的值

'''初始化后'''
class CNN(nn.Module):
    def __init__(self, num_channels=1, d=56, s=12, m=4):
        super(CNN, self).__init__()
        self.first_part = nn.Sequential(
            nn.Conv2d(num_channels, d, kernel_size=3, padding=5//2),
            nn.Conv2d(num_channels, d, kernel_size=(1,3), padding=5//2),
            nn.Conv2d(num_channels, d, kernel_size=(3,1), padding=5//2),
            nn.PReLU(d)
        )
        self._initialize_weights()
    def _initialize_weights(self):
        for m in self.first_part:
            if isinstance(m, nn.Conv2d):
                nn.init.normal_(m.weight.data, mean=0.0, std=math.sqrt(2/(m.out_channels*m.weight.data[0][0].numel())))
                nn.init.zeros_(m.bias.data)

    def forward(self, x):
        x = self.first_part(x)
        return x

model = CNN()
for m in model.first_part:
    if isinstance(m, nn.Conv2d):
        # print('m:',m.weight.data)
        print('m:',m.weight.data[0])
        print('m:',m.weight.data[0][0])
        print('m:',m.weight.data.numel()) #numel() 计算矩阵中元素的个数

结果:
m: tensor([[[-0.0284, -0.0585,  0.0271],
         [ 0.0125,  0.0554,  0.0511],
         [-0.0106,  0.0574, -0.0053]]])
m: tensor([[-0.0284, -0.0585,  0.0271],
        [ 0.0125,  0.0554,  0.0511],
        [-0.0106,  0.0574, -0.0053]])
m: 504
m: tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0.])
m: tensor([[[ 0.0059,  0.0465, -0.0725]]])
m: tensor([[ 0.0059,  0.0465, -0.0725]])
m: 168
m: tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0.])
m: tensor([[[ 0.0599],
         [-0.1330],
         [ 0.2456]]])
m: tensor([[ 0.0599],
        [-0.1330],
        [ 0.2456]])
m: 168
m: tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0.])
 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

(0)

相关推荐

  • Pytorch Tensor基本数学运算详解

    1. 加法运算 示例代码: import torch # 这两个Tensor加减乘除会对b自动进行Broadcasting a = torch.rand(3, 4) b = torch.rand(4) c1 = a + b c2 = torch.add(a, b) print(c1.shape, c2.shape) print(torch.all(torch.eq(c1, c2))) 输出结果: torch.Size([3, 4]) torch.Size([3, 4]) tensor(1, dt

  • 详解PyTorch中Tensor的高阶操作

    条件选取:torch.where(condition, x, y) → Tensor 返回从 x 或 y 中选择元素的张量,取决于 condition 操作定义: 举个例子: >>> import torch >>> c = randn(2, 3) >>> c tensor([[ 0.0309, -1.5993, 0.1986], [-0.0699, -2.7813, -1.1828]]) >>> a = torch.ones(2,

  • PyTorch中Tensor的数据类型和运算的使用

    在使用Tensor时,我们首先要掌握如何使用Tensor来定义不同数据类型的变量.Tensor时张量的英文,表示多维矩阵,和numpy对应,PyTorch中的Tensor可以和numpy的ndarray相互转换,唯一不同的是PyTorch可以在GPU上运行,而numpy的ndarray只能在cpu上运行. 常用的不同数据类型的Tensor,有32位的浮点型torch.FloatTensor,   64位浮点型 torch.DoubleTensor,   16位整形torch.ShortTenso

  • Pytorch之contiguous的用法

    contiguous tensor变量调用contiguous()函数会使tensor变量在内存中的存储变得连续. contiguous():view只能用在contiguous的variable上.如果在view之前用了transpose, permute等,需要用contiguous()来返回一个contiguous copy. 一种可能的解释是: 有些tensor并不是占用一整块内存,而是由不同的数据块组成,而tensor的view()操作依赖于内存是整块的,这时只需要执行contiguo

  • pytorch中的numel函数用法说明

    获取tensor中一共包含多少个元素 import torch x = torch.randn(3,3) print("number elements of x is ",x.numel()) y = torch.randn(3,10,5) print("number elements of y is ",y.numel()) 输出: number elements of x is 9 number elements of y is 150 27和150分别位x和y

  • pytorch中的 .view()函数的用法介绍

    目录 一.普通用法(手动调整size) 二.特殊用法:参数-1(自动调整size) 一.普通用法 (手动调整size) view()相当于reshape.resize,重新调整Tensor的形状. import torch a1 = torch.arange(0,16) print(a1) # tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15]) a2 = a1.view(8, 2) a3 = a1.vi

  • PyTorch中反卷积的用法详解

    pytorch中的 2D 卷积层 和 2D 反卷积层 函数分别如下: class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, bias=True) class torch.nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, b

  • PyTorch中permute的基本用法示例

    目录 permute(dims) 附:permute(多维数组,[维数的组合]) 总结 permute(dims) 将tensor的维度换位. 参数:参数是一系列的整数,代表原来张量的维度.比如三维就有0,1,2这些dimension. 例: import torch import numpy    as np a=np.array([[[1,2,3],[4,5,6]]]) unpermuted=torch.tensor(a) print(unpermuted.size())  #  -->  

  • php中mt_rand()随机数函数用法

    本文实例讲述了php中mt_rand()随机数函数用法.分享给大家供大家参考.具体分析如下: mt_rand() 使用 mersenne twister 算法返回随机整数. 语法:mt_rand(min,max) 说明:如果没有提供可选参数 min 和 max,mt_rand() 返回 0 到 rand_max 之间的伪随机数,例如想要 5 到 15(包括 5 和 15)之间的随机数,用 mt_rand(5,15). 在 3.0.7 之前的版本中,max 的含义是 range,要在这些版本中得到

  • golang中strconv.ParseInt函数用法示例

    本文实例讲述了golang中strconv.ParseInt函数用法.分享给大家供大家参考,具体如下: golang strconv.ParseInt 是将字符串转换为数字的函数,功能灰常之强大. 参数1 数字的字符串形式 参数2 数字字符串的进制 比如二进制 八进制 十进制 十六进制 参数3 返回结果的bit大小 也就是int8 int16 int32 int64 func ParseInt(s string, base int, bitSize int) (i int64, err erro

  • C#多线程之Thread中Thread.Join()函数用法分析

    本文实例讲述了C#多线程之Thread中Thread.Join()函数用法.分享给大家供大家参考.具体分析如下: Thread.Join()在MSDN中的解释:Blocks the calling thread until a thread terminates 当NewThread调用Join方法的时候,MainThread就被停止执行, 直到NewThread线程执行完毕. Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));

  • 关于numpy中np.nonzero()函数用法的详解

    np.nonzero函数是numpy中用于得到数组array中非零元素的位置(数组索引)的函数.一般来说,通过help(np.nonzero)能够查看到该函数的解析与例程.但是,由于例程为英文缩写,阅读起来还是很费劲,因此,本文将其英文解释翻译成中文,便于理解. 解释 nonzero(a) 返回数组a中非零元素的索引值数组. (1)只有a中非零元素才会有索引值,那些零值元素没有索引值: (2)返回的索引值数组是一个2维tuple数组,该tuple数组中包含一维的array数组.其中,一维arra

  • C#中异步回调函数用法实例

    本文实例讲述了C#中异步回调函数用法.分享给大家供大家参考.具体如下: static void Main(string[] args) { Func<string,string> showMessage = ShowMessage; //设置了回调函数Completed,不能有返回值 IAsyncResult result = showMessage.BeginInvoke("测试异步委托",new AsyncCallback(Completed),null); //半段异

  • vc中SendMessage自定义消息函数用法实例

    本文实例讲述了vc中SendMessage自定义消息函数用法,分享给大家供大家参考.具体如下: SendMessage的基本结构如下: 复制代码 代码如下: SendMessage(     HWND hWnd,  //消息传递的目标窗口或线程的句柄.     UINT Msg, //消息类别(这里可以是一些系统消息,也可以是自己定义,下文具体介绍,)     WPARAM wParam, //参数1 (WPARAM 其实是与UINT是同种类型的,   //在vc编译器中右键有个"转到WPARA

随机推荐