pytorch中view()函数的用法

本文介绍了PyTorch中view函数的使用,它等价于NumPy的reshape。view(-1,4)将数据按4列重塑,-1表示行数由程序自动计算。示例中,将1到20的序列reshape为5行4列的张量。尝试view(-1,3)时,由于无法整除导致运行时错误。
摘要由CSDN通过智能技术生成

pytorch中view的用法相当于numpy中的reshape,即对数据维度进行重新定义,view(-1, 4)其中4代表分成4列,-1代表不确定行大小,即能分成多少行让程序自行计算,如果不能整除,则程序报错。

import torch
a = torch.arange(1, 21)
print(a)

输出结果:
tensor([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
        19, 20])
---------------------------------------------------------------------------
b = a.view(-1, 4)
print(b)

输出结果:
tensor([[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12],
        [13, 14, 15, 16],
        [17, 18, 19, 20]])
---------------------------------------------------------------------------
c = a.view(-1, 2, 5)
print(c)

输出结果:
tensor([[[ 1,  2,  3,  4,  5],
         [ 6,  7,  8,  9, 10]],

        [[11, 12, 13, 14, 15],
         [16, 17, 18, 19, 20]]])

         [16, 17, 18, 19, 20]]])
---------------------------------------------------------------------------
d = a.view(-1, 3)
print(d)

输出结果:
RuntimeError                              Traceback (most recent call last)
Input In [9], in <cell line: 1>()
----> 1 d = a.view(-1, 3)
      2 print(d)

RuntimeError: shape '[-1, 3]' is invalid for input of size 20

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值