张量流中fft的结果与numpy不同 [英] The result of fft in tensorflow is different from numpy

查看:145
本文介绍了张量流中fft的结果与numpy不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在tensorflow中使用fft.但是我发现分别在numpy和tensorflow中使用FFT函数时结果不同.尤其是在输入数组很大的情况下

I want to use the fft in tensorflow. But I found the result is different when use the FFT function in numpy and tensorflow respectively. Especially when the size of input array is large

import tensorflow as tf
import numpy as np

aa = tf.lin_space(1.0, 10000.0, 10000)
bb = tf.lin_space(1.0, 10000.0, 10000)
dd = tf.concat([[aa],[bb]],axis = 0)
c_input = tf.complex(dd[0,:], dd[1,:])
Spec = tf.fft(c_input)
sess = tf.Session()
uuu = sess.run(Spec)
print(uuu)

aaa = np.linspace(1.0, 10000.0, 10000)
bbb = aaa + 1j*aaa
ccc = np.fft.fft(bbb)
print(ccc)

结果是

[ 11645833.000000+11645826.j         -544529.875000 -6242453.5j
   -913097.437500  -781089.0625j   ...,     78607.218750  -108219.109375j
    103245.156250  -182935.3125j      214871.765625  -790986.0625j  ]
[ 50005000.00000000+50005000.j         -15920493.78559075+15910493.78559076j
  -7962746.10739718 +7952746.10739719j ...,
   5300163.19893340 -5310163.19893345j
   7952746.10739715 -7962746.10739723j
  15910493.78559067-15920493.78559085j]

那么,当我在tensorflow中使用fft函数时,我该怎么办才能获得相同的结果呢? 谢谢你的回答

So, what can I do to get the same result when I use the fft function in tensorflow?? Thank you for answer

我发现tf.fft输出的数据类型为complex64.但是np.fft.fft的输出是complex128.这是这个问题的关键吗?我该如何解决这个问题?

I found that the data type of the output of tf.fft is complex64. But output of np.fft.fft is complex128. Is that the key for this question? How can I solve this problem?

推荐答案

您是对的,区别只在于dtype的tensorflow和numpy.

You're right, the difference is exactly in dtype in tensorflow and numpy.

Tensorflow tf.fft强制输入张量为tf.complex64,这很可能是由于 fftpack_litemodule.c ,其中类型为NPY_CDOUBLE-128位,即np.complex128.有关详细信息,请参见此问题.

Tensorflow tf.fft forces the input tensor to be tf.complex64, most probably due to GPU op compatiblity. Numpy also hardcodes the array type for FFT. The source code is in native C, fftpack_litemodule.c, where the type is NPY_CDOUBLE - 128-bit, i.e. np.complex128. See this issue for details.

因此,恐怕没有简单的解决方案可以匹配它们.您可以尝试定义自定义张量流op (适用np.fft.fft),但这也需要您手动评估渐变.或避免将FFT应用于大向量,这样就不会出现数值误差.

So, I'm afraid there's no simple solution to match them. You can try to define the custom tensorflow op, which applies np.fft.fft, but this would require you to evaluate the gradient manually as well. Or avoid applying FFT to large vectors, so that numerical inaccuracy won't be an issue.

这篇关于张量流中fft的结果与numpy不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆