python - 如何在 TensorFlow 中将信号与一维内核进行卷积?

标签 python tensorflow

我正在尝试过滤形状为 (N_batch, N_data) 的 TensorFlow 张量,其中 N_batch 是批量大小(例如 32),N_data 是(嘈杂的)时间序列数组的大小。我有一个高斯核(取自 here ),它是一维的。然后我想使用 tensorflow.nn.conv1d将此内核与我的信号进行卷积。

我早上的大部分时间都在尝试获得正确的输入信号和内核的尺寸,但显然没有成功。根据我从互联网上收集到的信息,输入信号和内核的尺寸都需要以某种挑剔的方式对齐,而我只是不知道那是哪种方式。 TensorFlow 错误消息也不是特别有意义(Shape 必须为等级 4,但对于“conv1d/Conv2D”(操作:“Conv2D”)为等级 3,输入形状:[?,1,1000], [1 ,81])。下面我添加了一小段代码来重现这种情况:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# Based on: https://stackoverflow.com/a/52012658/1510542
# Credits to @zephyrus


def gaussian_kernel(size, mean, std):
    d = tf.distributions.Normal(tf.cast(mean, tf.float32), tf.cast(std, tf.float32))
    vals = d.prob(tf.range(start=-size, limit=size+1, dtype=tf.float32))

    kernel = vals   # Some reshaping is required here

    return kernel / tf.reduce_sum(kernel)


def gaussian_filter(input, sigma):
    size = int(4*sigma + 0.5)

    x = input   # Some reshaping is required here

    kernel = gaussian_kernel(size=size, mean=0.0, std=sigma)
    conv = tf.nn.conv1d(x, kernel, stride=1, padding="SAME")
    return conv


def run_filter():

    tf.reset_default_graph()

    # Define size of data, batch sizes
    N_batch = 32
    N_data = 1000

    noise = 0.2 * (np.random.rand(N_batch, N_data) - 0.5)
    x = np.linspace(0, 2*np.pi, N_data)
    y = np.tile(np.sin(x), N_batch).reshape(N_batch, N_data)
    y_noisy = y + noise

    input = tf.placeholder(tf.float32, shape=[None, N_data])
    smooth_input = gaussian_filter(input, sigma=10)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        y_smooth = smooth_input.eval(feed_dict={input: y_noisy})

        plt.plot(y_noisy[0])
        plt.plot(y_smooth[0])
        plt.show()


if __name__ == "__main__":
    run_filter()

有什么想法吗?

最佳答案

您需要向输入/内核添加 channel 维度,因为 TF 卷积通常用于多 channel 输入/输出。当您使用简单的 1 channel 输入/输出时,这相当于仅添加一些尺寸为 1 的“虚拟”轴。
由于默认情况下卷积期望 channel 出现在最后,因此您的占位符应具有形状 [None, N_data, 1] 并且您的输入应修改为

y_noisy = y + noise
y_noisy = y_noisy[:, :, np.newaxis] 

同样,您需要将输入和输出 channel 维度添加到过滤器:

kernel = gaussian_kernel(size=size, mean=0.0, std=sigma)
kernel = kernel[:, tf.newaxis, tf.newaxis]

也就是说,过滤器的形状预计为[width, in_channels, out_cannels]

关于python - 如何在 TensorFlow 中将信号与一维内核进行卷积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55237112/

相关文章:

python - 如何在Python中加载带有日期和时间的文件作为日期时间对象?

tensorflow - 将外部优化器与 tensorflow 和随机网络元素一起使用

python - 在张量中分配行会抛出 "None values not supported"

python - 如何在同时具有 64 位和 32 位版本的情况下 pip 安装 64 位包?

python - 如何将列表加入字符串(警告)?

python - 测试 python 类对象实例

python - 如何使用opencv填充整个内部轮廓

python - 如何通过唯一索引对 pandas 列求和,然后重置总和?

tensorflow softmax总是返回1

python - 如何在 Tensorflow 中更新二维张量的子集?