美文网首页
numpy和tensor增加、删除一个维度

numpy和tensor增加、删除一个维度

作者: 一位学有余力的同学 | 来源:发表于2021-03-20 19:39 被阅读0次

numpy

1.增加维度

import numpy as np
a = np.ones((3,4))
print(a.shape)

输出a的形状:(3,4)

现在变量a为二维数组,在图形计算中有时需要将图像处理成(length, width, channel)的形式,我们需要将a处理成三维,第三维的形状为1,方式如下:

b = np.expand_dims(a, 2)
print(b.shape)

输出的形状为:(3,4,1)

2.压缩维度

如果我们想要将b再变回二维,需要用到如下方法:

c = np.squeeze(b)
print(c.shape)

输出的形状为:(3,4)
我们也可以指定要压缩的维度

c = np.squeeze(b, axis=2)
print(c.shape)

输出为:(3,4)

Tensor

1.增加维度

import torch
a = torch.ones((3,4))
print(a.shape)

输出的形状为:torch.Size([3,4])
现在,我们要让它增加一个维度,变成[1,3,4]

b = torch.unsqueeze(a, 0)
print(b.shape)

输出结果为:torch.Size([1,3,4])
现在我们要把它再压缩到三维:

c = torch.squeeze(b, 0)
print(c.shape)

输出结果为:torch.Size([3,4])[1]


  1. Numpy , Tensor , Variable 增删一个值为1的维度

相关文章

网友评论

      本文标题:numpy和tensor增加、删除一个维度

      本文链接:https://www.haomeiwen.com/subject/vngwcltx.html