nn.functional.interpolate实现插值和上采样
-
input (Tensor) – 输入张量
-
size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]) –
输出大小. -
scale_factor (float or Tuple[float]) – 指定输出为输入的多少倍数。如果输入为tuple,其也要制定为tuple类型
-
mode (str) – 可使用的上采样算法,有’nearest’, ‘linear’, ‘bilinear’, ‘bicubic’ , ‘trilinear’和’area’. 默认使用’nearest’
-
align_corners (bool, optional) – 几何上,我们认为输入和输出的像素是正方形,而不是点。如果设置为True,则输入和输出张量由其角像素的中心点对齐,从而保留角像素处的值。如果设置为False,则输入和输出张量由它们的角像素的角点对齐,插值使用边界外值的边值填充;当scale_factor保持不变时,使该操作独立于输入大小。仅当使用的算法为’linear’, ‘bilinear’, 'bilinear’or 'trilinear’时可以使用。默认设置为False
其中参数mode
import torch
from torch import nn
import torch.nn.functional as F
input = torch.arange(1, 5, dtype=torch.float32).view(1, 1, 2, 2)
print(input)
输出
tensor([[[[1., 2.],
[3., 4.]]]])
- mode=‘nearest’
result = F.interpolate(input, scale_factor=2, mode='nearest')
print(result)
输出
tensor([[[[1., 1., 2., 2.],
[1., 1., 2., 2.],
[3., 3., 4., 4.],
[3., 3., 4., 4.]]]])
- mode=‘linear’
NotImplementedError: Got 4D input, but linear mode needs 3D input
- mode=‘bilinear’
tensor([[[[1.0000, 1.2500, 1.7500, 2.0000],
[1.5000, 1.7500, 2.2500, 2.5000],
[2.5000, 2.7500, 3.2500, 3.5000],
[3.0000, 3.2500, 3.7500, 4.0000]]]])
- mode=‘bicubic’
tensor([[[[0.6836, 1.0156, 1.5625, 1.8945],
[1.3477, 1.6797, 2.2266, 2.5586],
[2.4414, 2.7734, 3.3203, 3.6523],
[3.1055, 3.4375, 3.9844, 4.3164]]]])
- mode=‘trilinear’
NotImplementedError: Got 4D input, but trilinear mode needs 5D input
- mode=‘area’
tensor([[[[1., 1., 2., 2.],
[1., 1., 2., 2.],
[3., 3., 4., 4.],
[3., 3., 4., 4.]]]])