我正在使用 1d 信号的 torch 数据集,并且希望在进一步处理数据之前将向量标准化为 0、std 1。如果我要处理图像,我可以使用 torchvision.transforms:
import torchvision.transforms as transforms
import torch
data_2d = torch.rand(1, 100,100)
normalized_data_2d = transforms.Normalize(mean = (data_2d.mean(),), std = (data_2d.std(),))(data_2d)
print(f'mean: {normalized_data_2d.mean()} ~ 0 , std: {normalized_data_2d.std()} ~ 1, ok')
我得到:
mean: -4.1373571235681084e-08 ~ 0 , std: 0.9999999403953552 ~ 1, ok
当我以同样的方式使用一维数据时:
data_1d = torch.rand(100)
normalized_data_1d = transforms.Normalize(mean = (data_1d.mean(),), std = (data_1d.std(),))(data_1d)
我收到
TypeError: Tensor is not a torch image
错误:
有没有一种优雅的方法使用火炬变换来标准化一维向量?
atleast_3d
使输入张量达到预期的形状,然后使用 squeeze
输出单维,使其再次为 1d,例如,
normalized_data_1d = Normalize(
mean=(data_1d.mean(),),
std=(data_1d.std(),)
)(
torch.atleast_3d(data_1d) # make shape "at least 3d"
).squeeze() # squeeze out singleton dimensions