import torch
'''
把原先tensor中的数据按照行优先的顺序排成一个一维的数据(这里应该是因为要求地址是连续存储的),然后按照参数组合成其他维度的tensor。
参数不可为空。参数中的-1就代表这个位置由其他位置的数字来推断
'''
a=torch.Tensor([[[1,2,3],[4,5,6]]])
b=torch.Tensor([1,2,3,4,5,6])
print(a.view(1,6))
print(b.view(1,6))
#得到的结果都是tensor([[1., 2., 3., 4., 5., 6.]])
#再看一个例子:
a=torch.Tensor([[[1,2,3],[4,5,6]]])
print(a.view(3,2))
'''
max函数用法总结:
torch.max(a) 返回输入tensor a中所有元素的最大值
torch.max(a,0) 返回每一列中最大值的那个元素,且返回索引(返回最大元素在这一列的行索引)
torch.max(a,1) 返回每一行中最大值的那个元素,且返回其索引(返回最大元素在这一行的列索引)
torch.max()[0], 只返回最大值的每个数
troch.max()[1], 只返回最大值的每个索引
torch.max()[1].data 只返回variable中的数据部分(去掉Variable containing:)
torch.max()[1].data.numpy() 把数据转化成numpy ndarry
torch.max()[1].data.numpy().squeeze() 把数据条目中维度为1 的删除掉
torch.max(tensor1,tensor2) element-wise 比较tensor1 和tensor2 中的元素,返回较大的那个值
'''
a = torch.randn(3,3)
print(a)#返回生成的随机tensor(3*3)
print(torch.max(a,0))#返回每一列中最大值的那个元素,且返回索引(返回最大元素在这一列的行索引)
print(torch.max(a,1))#返回每一行中最大值的那个元素,且返回其索引(返回最大元素在这一行的列索引)
print(torch.max(a))#返回tensor a 中的最大值
print(torch.max(a,0)[0] )# 只返回最大值的每个数
print(torch.max(a,0)[1])#只返回最大值的每个索引
'''
cat是concatnate的意思:拼接,联系在一起。
按维数0拼接(竖着拼)
C = torch.cat( (A,B),0 )
按维数1拼接(横着拼)
C = torch.cat( (A,B),1 )
'''
A=torch.ones(2,3) #2x3的张量(矩阵)
print(A)
B=2*torch.ones(4,3) #4x3的张量(矩阵)
print(B)
C=torch.cat((A,B),0) #按维数0(行)拼接
print(C)
'''
torch.Tensor.permute (Python method, in torch.Tensor)
作用:将tensor的维度换位。
'''
x = torch.randn(2,3,4)
print(x.size())
x_p = x.permute(1,0,2) # 将原来第1维变为0维,同理,0→1,2→2 print(x_p.size())
print(x_p.size())
'''
torch.unsqueeze(input, dim, out=None)
作用:扩展维度
返回一个新的张量,对输入的既定位置插入维度 1
tensor (Tensor) – 输入张量
dim (int) – 插入维度的索引
out (Tensor, optional) – 结果张量
'''
x = torch.Tensor([1, 2, 3, 4])
print(torch.unsqueeze(x, 0)) # tensor([[1., 2., 3., 4.]])
print(torch.unsqueeze(x, 0).size()) # torch.Size([1, 4])
print(torch.unsqueeze(x, 0).dim()) # 2
print(torch.unsqueeze(x, 0).numpy()) # [[1. 2. 3. 4.]]
print(torch.unsqueeze(x, 1))
# tensor([[1.],
# [2.],
# [3.],
# [4.]])
print(torch.unsqueeze(x, -1))
# tensor([[1.],
# [2.],
# [3.],
# [4.]])
print(torch.unsqueeze(x, -2)) # tensor([[1., 2., 3., 4.]])
'''
作用:降维
将输入张量形状中的1 去除并返回。 如果输入是形如(A×1×B×1×C×1×D),那么输出形状就为: (A×B×C×D)
当给定dim时,那么挤压操作只在给定维度上。例如,输入形状为: (A×1×B), squeeze(input, 0) 将会保持张量不变,
只有用 squeeze(input, 1),形状会变成 (A×B)。
'''
m = torch.zeros(2, 1, 2, 1, 2)
print(m.size()) # torch.Size([2, 1, 2, 1, 2])
n = torch.squeeze(m)
print(n.size()) # torch.Size([2, 2, 2])
n = torch.squeeze(m, 0) # 当给定dim时,那么挤压操作只在给定维度上
print(n.size()) # torch.Size([2, 1, 2, 1, 2])
n = torch.squeeze(m, 1)
print(n.size()) # torch.Size([2, 2, 1, 2])
n = torch.squeeze(m, 2)
print(n.size()) # torch.Size([2, 1, 2, 1, 2])
n = torch.squeeze(m, 3)
print(n.size()) # torch.Size([2, 1, 2, 2])
x=[1,2,3,4]
print(*x) #相当于迭代出1,2,3,4
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交