pytorch中一些维度变换(小白自学笔记,大佬跳过)
主要是 torch.cat函数 和repeat函数
代码和运行结果
import random
import numpy as np
import torch
img=torch.ones(3,10,10)
print(img)
noise_level1 = torch.zeros(1).float()
print(noise_level1)
print(noise_level1.size()
#tensor([0.])
#torch.Size([1])
noise_level2 = torch.FloatTensor([np.random.uniform(0, 50)])/255.0
print(noise_level2)
print(noise_level2.size())
#tensor([0.1507])
#torch.Size([1])
noise = torch.randn(img.size()).mul_(noise_level2).float()
print(noise.size())
img.add_(noise)
print(img.size())
#torch.Size([3, 10, 10])
#torch.Size([3, 10, 10])
k_reduced=torch.ones(15)
M_vector = torch.cat((k_reduced, noise_level1), 0).unsqueeze(1).unsqueeze(1)
print(k_reduced)
print(M_vector)
print(M_vector.size())
M = M_vector.repeat(1, img.size()[-2], img.size()[-1])
print(M.size())
print(img.size()[-2])
print(img.size()[-1])
#tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
#tensor([[[1.]],
[[1.]],
[[1.]],
[[1.]],
[[1.]],
[[1.]],
[[1.]],
[[1.]],
[[1.]],
[[1.]],
[[1.]],
[[1.]],
[[1.]],
[[1.]],
[[1.]],
[[0.]]])
#torch.Size([16, 1, 1])
#torch.Size([16, 10, 10])
#10
#10