浅析对torch.unsqueeze()函数理解
torch.unsqueeze()函数理解
torch.unsqueeze(input, dim) 使用时等同于 input.unsqueeze(dim)
torch.unsqueeze()函数起到升维的作用,dim等于几表示在第几维度加一,比如原来x的size=([4]),x.unsqueeze(0)之后就变成了size=([1, 4]),而x.unsqueeze(1)之后就变成了size=([4, 1]),注意dim∈[-input.dim() - 1, input.dim() + 1]
例如
输入一维张量,即input.dim()=1
# 输入: x = torch.tensor([1, 2, 3, 4]) # x.dim()=1 print(x) print(x.shape) y = x.unsqueeze(0) print(y) print(y.shape) # 此时y.dim()=2 z = x.unsqueeze(1) print(z) print(z.shape) # 此时z.dim()=2
# 输出:
tensor([1, 2, 3, 4])
torch.Size([4])
tensor([[1, 2, 3, 4]])
torch.Size([1, 4])
tensor([[1],
[2],
[3],
[4]])
torch.Size([4, 1])输入二维张量,即input.dim()=2
# 输入: x = torch.tensor([[1, 2, 3], [4, 5, 6]]) # x.dim()=2 print(x) print(x.shape) y = x.unsqueeze(0) print(y) print(y.shape) # 此时y.dim()=3 z = x.unsqueeze(1) print(z) print(z.shape) # 此时z.dim()=3
# 输出:
tensor([[1, 2, 3],
[4, 5, 6]])
torch.Size([2, 3])
tensor([[[1, 2, 3],
[4, 5, 6]]])
torch.Size([1, 2, 3])
tensor([[[1, 2, 3]],
[[4, 5, 6]]])
torch.Size([2, 1, 3])输入四维张量,即input.dim()=4
# 输入:
x = torch.tensor([[[[1, 2, 3],
[4, 5, 6]],
[[0, 2, 1],
[1, 5, 2]]],
[[[1, 2, 3],
[4, 5, 6]],
[[0, 2, 1],
[1, 5, 2]]]])
print(x)
print(x.shape)
y2 = x.unsqueeze(2)
print(y2)
print(y2.shape)
y3 = x.unsqueeze(3)
print(y3)
print(y3.shape)# 输出:
tensor([[[[1, 2, 3],
[4, 5, 6]],
[[0, 2, 1],
[1, 5, 2]]],
[[[1, 2, 3],
[4, 5, 6]],
[[0, 2, 1],
[1, 5, 2]]]])
torch.Size([2, 2, 2, 3])
tensor([[[[[1, 2, 3],
[4, 5, 6]]],
[[[0, 2, 1],
[1, 5, 2]]]],
[[[[1, 2, 3],
[4, 5, 6]]],
[[[0, 2, 1],
[1, 5, 2]]]]])
torch.Size([2, 2, 1, 2, 3])
tensor([[[[[1, 2, 3]],
[[4, 5, 6]]],
[[[0, 2, 1]],
[[1, 5, 2]]]],
[[[[1, 2, 3]],
[[4, 5, 6]]],
[[[0, 2, 1]],
[[1, 5, 2]]]]])
torch.Size([2, 2, 2, 1, 3])到此这篇关于torch.unsqueeze()函数理解的文章就介绍到这了,更多相关torch.unsqueeze()函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Python web框架fastapi中间件的使用及CORS跨域问题
fastapi "中间件"是一个函数,它在每个请求被特定的路径操作处理之前,以及在每个响应之后工作,它接收你的应用程序的每一个请求,下面通过本文给大家介绍Python web框架fastapi中间件的使用及CORS跨域问题,感兴趣的朋友一起看看吧2024-03-03
Python中logging日志记录到文件及自动分割的操作代码
这篇文章主要介绍了Python中logging日志记录到文件及自动分割,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-08-08


最新评论