用Pytorch实现FFT

2024-09-30 20:24:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Pytorch中提供的conv1d函数来实现FFT。在

产生人工信号

import numpy as np
import torch
from torch.autograd import Variable
from torch.nn.functional import conv1d

from scipy import fft, fftpack

import matplotlib.pyplot as plt

%matplotlib inline

# Creating filters

d = 4096 # size of windows

def create_filters(d):
    x = np.arange(0, d, 1)
    wsin = np.empty((d,1,d), dtype=np.float32)
    wcos = np.empty((d,1,d), dtype=np.float32)
    window_mask = 1.0-1.0*np.cos(x)
    for ind in range(d):
        wsin[ind,0,:] = np.sin(2*np.pi*((ind+1)/d)*x)
        wcos[ind,0,:] = np.cos(2*np.pi*((ind+1)/d)*x)

    return wsin,wcos

wsin, wcos = create_filters(d)
wsin_var = Variable(torch.from_numpy(wsin), requires_grad=False)
wcos_var = Variable(torch.from_numpy(wcos),requires_grad=False)

# Creating signal

t = np.linspace(0,1,4096)
x = np.sin(2*np.pi*100*t)+np.sin(2*np.pi*200*t)+np.random.normal(scale=5,size=(4096))

plt.plot(x) 

enter image description here

带Pythorch的FFT

^{pr2}$

enter image description here

带Scipy的FFT

fig = plt.figure(figsize=(20,5))
plt.plot(np.abs(fft(x).reshape(-1))[:500])

我的问题

如您所见,这两个输出在峰值特性方面非常相似。这意味着我的实现并不是完全错误的。 然而,也有一些微妙之处,比如频谱的尺度和信噪比。我不知道这里缺了什么来得到完全相同的结果。在

enter image description here


Tags: fromimportfftnumpynppiplttorch