温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中torch.flatten()函数怎么用

发布时间:2021-08-30 13:45:08 来源:亿速云 阅读:139 作者:小新 栏目:开发技术

这篇文章主要介绍Python中torch.flatten()函数怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

先看函数参数:

torch.flatten(input, start_dim=0, end_dim=-1)

input: 一个 tensor,即要被“推平”的 tensor。

start_dim: “推平”的起始维度。

end_dim: “推平”的结束维度。

首先如果按照 start_dim 和 end_dim 的默认值,那么这个函数会把 input 推平成一个 shape 为 [n][n] 的tensor,其中 nn 即 input 中元素个数。

如果我们要自己设定起始维度和结束维度呢?

我们要先来看一下 tensor 中的 shape 是怎么样的:

t = torch.tensor([[[1, 2, 2, 1],
                   [3, 4, 4, 3],
                   [1, 2, 3, 4]],
                  [[5, 6, 6, 5],
                   [7, 8, 8, 7],
                   [5, 6, 7, 8]]])
print(t, t.shape)
 
运行结果:
 
tensor([[[1, 2, 2, 1],
         [3, 4, 4, 3],
         [1, 2, 3, 4]],
 
        [[5, 6, 6, 5],
         [7, 8, 8, 7],
         [5, 6, 7, 8]]])
torch.Size([2, 3, 4])

我们可以看到,最外层的方括号内含两个元素,因此 shape 的第一个值是 2;类似地,第二层方括号里面含三个元素,shape 的第二个值就是 3;最内层方括号里含四个元素,shape 的第二个值就是 4。

示例代码:

x = torch.flatten(t, start_dim=1)
print(x, x.shape)
 
y = torch.flatten(t, start_dim=0, end_dim=1)
print(y, y.shape)
 
 
运行结果:
 
tensor([[1, 2, 2, 1, 3, 4, 4, 3, 1, 2, 3, 4],
        [5, 6, 6, 5, 7, 8, 8, 7, 5, 6, 7, 8]]) 
torch.Size([2, 12])
 
tensor([[1, 2, 2, 1],
        [3, 4, 4, 3],
        [1, 2, 3, 4],
        [5, 6, 6, 5],
        [7, 8, 8, 7],
        [5, 6, 7, 8]]) 
torch.Size([6, 4])

可以看到,当 start_dim = 11 而 end_dim = −1−1 时,它把第 11 个维度到最后一个维度全部推平合并了。而当 start_dim = 00 而 end_dim = 11 时,它把第 00 个维度到第 11 个维度全部推平合并了。pytorch中的 torch.nn.Flatten 类和 torch.Tensor.flatten 方法其实都是基于上面的 torch.flatten 函数实现的。

以上是“Python中torch.flatten()函数怎么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI