上采样和下采样代码
时间: 2023-08-28 10:05:13 浏览: 53
上采样(Upsampling)和下采样(Downsampling)是在数字信号处理,图像处理和机器学习中常用的操作。下面是Python和PyTorch中的上采样和下采样代码示例:
Python代码示例:
```python
import numpy as np
from scipy import signal
# 下采样
def downsample(signal, factor):
return signal[::factor]
# 上采样
def upsample(signal, factor):
return np.repeat(signal, factor)
# 例子
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = downsample(x, 2)
z = upsample(x, 2)
print(y) # [1 3 5 7 9]
print(z) # [ 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10]
```
PyTorch代码示例:
```python
import torch
import torch.nn.functional as F
# 下采样
def downsample(x, factor):
return F.avg_pool2d(x, factor)
# 上采样
def upsample(x, factor):
return F.interpolate(x, scale_factor=factor, mode='nearest')
# 例子
x = torch.arange(1, 26).reshape(1, 1, 5, 5)
y = downsample(x, 2)
z = upsample(x, 2)
print(y)
'''
tensor([[[[ 3., 5.],
[13., 15.]]]])
'''
print(z)
'''
tensor([[[[ 1., 1., 2., 2., 3., 3., 4., 4.],
[ 1., 1., 2., 2., 3., 3., 4., 4.],
[ 6., 6., 7., 7., 8., 8., 9., 9.],
[ 6., 6., 7., 7., 8., 8., 9., 9.],
[11., 11., 12., 12., 13., 13., 14., 14.],
[11., 11., 12., 12., 13., 13., 14., 14.],
[16., 16., 17., 17., 18., 18., 19., 19.],
[16., 16., 17., 17., 18., 18., 19., 19.]]]])
'''
```
注意,PyTorch中的下采样和上采样函数默认操作在最后两个维度上。如果要在其他维度上操作,需要通过指定`dim`参数来实现。