使用 tensorflow.contrib.signal 重建信号会导致放大或调制(帧、overlap_and_add、stft 等)

mem*_*emo 5 python signal-processing time-series tensorflow

更新:我已经在 librosa 中重新实现了这个进行比较,结果确实与 tensorflow 的结果非常不同。Librosa 给出了我期望的结果(但不是 tensorflow)。

我已将此作为问题发布到 tensorflow repo 上,但那里很安静,所以我在这里尝试。此外,我不确定这是 tensorflow 中的错误,还是代表我的用户错误。为了完整起见,我也将在此处包含完整的源代码和结果。

A.) 当我使用 hann 窗口(也尝试过汉明)从具有frame_length=1024frame_step=256(即 25% 跳大小,75% 重叠)的信号创建帧,然后使用 重建时overlap_and_add,我希望信号能够正确重建(因为可乐等)。但相反,它的幅度恰好是两倍。我需要将结果信号除以二才能正确。

B.) 如果我使用 STFT 创建一系列重叠的频谱图,然后使用逆 STFT 重建,再次使用frame_length=1024frame_step=256,则再次以双倍幅度重建信号。

我意识到为什么会这样(hann 重叠 50% 时的单位增益,因此 75% 重叠会使信号加倍)。但是重建功能考虑到这一点不是很正常吗?例如 librosa istft 确实以正确的幅度返回信号,而 tensorflow 返回双倍。

C.) 在任何其他 frame_step 处,都存在严重的幅度调制。请参阅下面的图片。这似乎根本不对。

更新:如果我window_fn=tf.contrib.signal.inverse_stft_window_fn(frame_step)inverse_stft输出中明确设置是正确的。所以似乎frame_stepininverse_stft没有被传递到窗口函数中(这也是结果所暗示的)。

原始数据:

在此处输入图片说明

来自帧的张量流输出+overlap_and_add:

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

stft+istft 的张量流输出:

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

stft+istft 的 librosa 输出:

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

张量流代码:

from __future__ import print_function
from __future__ import division

import numpy as np
import scipy.io.wavfile
import math
import random
import matplotlib.pyplot as plt

import tensorflow as tf
out_prefix = 'tensorflow'


def plot(data, title, do_save=True):
    plt.figure(figsize=(20,5))
    plt.plot(data[:3*frame_length])
    plt.ylim([-1, 1])
    plt.title(title)
    plt.grid()
    if do_save: plt.savefig(title + '.png')
    plt.show()


def reconstruct_from_frames(x, frame_length, frame_step):
    name = 'frame'
    frames_T = tf.contrib.signal.frame(x, frame_length=frame_length, frame_step=frame_step)
    windowed_frames_T = frames_T * tf.contrib.signal.hann_window(frame_length, periodic=True)
    output_T = tf.contrib.signal.overlap_and_add(windowed_frames_T, frame_step=frame_step)
    return name, output_T


def reconstruct_from_stft(x, frame_length, frame_step):
    name = 'stft'
    spectrograms_T = tf.contrib.signal.stft(x, frame_length, frame_step)
    output_T = tf.contrib.signal.inverse_stft(spectrograms_T, frame_length, frame_step)
    return name, output_T


def test(fn, input_data):
    print('-'*80)
    tf.reset_default_graph()
    input_T = tf.placeholder(tf.float32, [None]) 
    name, output_T = fn(input_T, frame_length, frame_step)

    title = "{}.{}.{}.l{}.s{}".format(out_prefix, sample_rate, name, frame_length, frame_step)
    print(title)

    with tf.Session():
        output_data =  output_T.eval({input_T:input_data})

#    output_data /= frame_length/frame_step/2 # tensorflow needs this to normalise amp
    plot(output_data, title)
    scipy.io.wavfile.write(title+'.wav', sample_rate, output_data)


def generate_data(duration_secs, sample_rate, num_sin, min_freq=10, max_freq=500, rnd_seed=0, max_val=0):
    '''generate signal from multiple random sin waves'''
    if rnd_seed>0: random.seed(rnd_seed)
    data = np.zeros([duration_secs*sample_rate], np.float32)
    for i in range(num_sin):
        w = np.float32(np.sin(np.linspace(0, math.pi*2*random.randrange(min_freq, max_freq), num=duration_secs*sample_rate)))
        data += random.random() * w
    if max_val>0:
        data *= max_val / np.max(np.abs(data))
    return data


frame_length = 1024
sample_rate = 22050

input_data = generate_data(duration_secs=1, sample_rate=sample_rate, num_sin=1, rnd_seed=2, max_val=0.5)

title = "{}.orig".format(sample_rate)
plot(input_data, title)
scipy.io.wavfile.write(title+'.wav', sample_rate, input_data)

for frame_step in [256, 512, 768, 1024]:
    test(reconstruct_from_frames, input_data)
    test(reconstruct_from_stft, input_data)

print('done.')
Run Code Online (Sandbox Code Playgroud)

librosa代码:

from __future__ import print_function
from __future__ import division

import numpy as np
import scipy.io.wavfile
import math
import random
import matplotlib.pyplot as plt

import librosa.core as lc
out_prefix = 'librosa'


def plot(data, title, do_save=True):
    plt.figure(figsize=(20,5))
    plt.plot(data[:3*frame_length])
    plt.ylim([-1, 1])
    plt.title(title)
    plt.grid()
    if do_save: plt.savefig(title + '.png')
    plt.show()


def reconstruct_from_stft(x, frame_length, frame_step):
    name = 'stft'
    stft = lc.stft(x, n_fft=frame_length, hop_length=frame_step)
    istft = lc.istft(stft, frame_step)
    return name, istft


def test(fn, input_data):
    print('-'*80)
    name, output_data = fn(input_data, frame_length, frame_step)

    title = "{}.{}.{}.l{}.s{}".format(out_prefix, sample_rate, name, frame_length, frame_step)
    print(title)

#    output_data /= frame_length/frame_step/2 # tensorflow needs this to normalise amp
    plot(output_data, title)
    scipy.io.wavfile.write(title+'.wav', sample_rate, output_data)


def generate_data(duration_secs, sample_rate, num_sin, min_freq=10, max_freq=500, rnd_seed=0, max_val=0):
    '''generate signal from multiple random sin waves'''
    if rnd_seed>0: random.seed(rnd_seed)
    data = np.zeros([duration_secs*sample_rate], np.float32)
    for i in range(num_sin):
        w = np.float32(np.sin(np.linspace(0, math.pi*2*random.randrange(min_freq, max_freq), num=duration_secs*sample_rate)))
        data += random.random() * w
    if max_val>0:
        data *= max_val / np.max(np.abs(data))
    return data


frame_length = 1024
sample_rate = 22050

input_data = generate_data(duration_secs=1, sample_rate=sample_rate, num_sin=1, rnd_seed=2, max_val=0.5)

title = "{}.orig".format(sample_rate)
plot(input_data, title)
scipy.io.wavfile.write(title+'.wav', sample_rate, input_data)

for frame_step in [256, 512, 768, 1024]:
    test(reconstruct_from_stft, input_data)

print('done.')
Run Code Online (Sandbox Code Playgroud)
  • Linux Ubuntu 16.04
  • Tensorflow 从二进制 v1.4.0-19-ga52c8d9, 1.4.1 安装
  • Python 2.7.14 | Anaconda 自定义(64 位)| (默认,2017 年 10 月 16 日,17:29:19)。IPython 5.4.1
  • Cuda 版本 8.0、V8.0.61、cuDNN 6
  • Geforce GTX 970M,驱动程序版本:384.111

(刚尝试过 TF1.5、Cuda9.0、cuDNN 7.0.5 以及相同的结果)。

hot*_*aw2 0

具有 50% 重叠的 Von Hann 窗口的无限序列总和达到平坦的单位增益。通过 25% 的重叠,单位时间的窗口数量加倍,从而增益加倍。

重叠相加快速卷积滤波通常没有重叠,也没有(非矩形)加窗,仅对至少滤波器函数的脉冲响应长度进行足够的零填充。任何重叠百分比不应包括任何添加的零填充长度。