【问题标题】:Why TensorFlow do not support strides = [1,0] or [0,1] for conv2d?为什么 TensorFlow 不支持 conv2d 的 strides = [1,0] 或 [0,1]?
【发布时间】:2021-02-19 03:51:56
【问题描述】:

这意味着内核只向一个方向移动。

我想让内核在文本序列上移动。

还有其他方法吗?

代码如下:

import tensorflow as tf
import numpy as np

batch_size = 2
sequence_len = 5
hidden_size = 16
kernel_len = 2
in_channel = 1
out_channel = hidden_size
a1 = np.array(np.arange(1, 1 + sequence_len * hidden_size).reshape([sequence_len, hidden_size, in_channel]),
              dtype=np.float32)

inputX = np.stack([a1, a1], axis=0)

kernel = np.array(np.arange(1, 1 + kernel_len * hidden_size * in_channel * out_channel), dtype=np.float32).reshape(
    [kernel_len, hidden_size, in_channel, out_channel])

conv2d = tf.nn.conv2d(inputX, kernel, strides=[1,0], padding='VALID')

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    print(sess.run(tf.shape(conv2d)))
    print(sess.run(conv2d))

【问题讨论】:

  • 不清楚您需要什么。你能详细说明一下吗?
  • 我添加代码。 @thushv89

标签: python tensorflow keras deep-learning conv-neural-network


【解决方案1】:

我们知道卷积的原理:

比例公式可以写成: 跨内核(ks1,ks2)的二维数组(W1,W2),Stride(S1,S2)和Padding(P1,P2)

看来你想让内核移动到另一个字符,这意味着卷积后的数组行或列都应该是1,所以楼层内的数字应该小于1。

有两种方法可以达到目标。我们假设原始数组是 10*20。

  1. 将内核映射设置为与您的列一样大。例如:(10*3)
  2. 将步幅设置得更大。如果 S>(W+2pad-ks),则公式等于 1。

在你的情况下,只需要改变:

kernel = np.array(np.arange(1, 1 + (kernel_len-1) * hidden_size * in_channel *out_channel),
    dtype=np.float32).reshape([kernel_len-1, hidden_size, in_channel, out_channel])

tf.shape(a1) 是 (5,16,1)

tf.shape(kernel) 为 (2,16,1,16)

根据公式,得到 [2,floor(5-2)+1,floor(16-16)+1,16] (stride=1) = [2,4,1,16]

当内核变为 (1,16,1,16) 时,卷积数组将为 [2,5,1,16]

【讨论】:

  • 您的输入形状是 (2,5,16,1),但内核形状是 (2,16,1,16)。不匹配。
  • 谢谢,但它可以运行。 @CodingPeter
  • 输出形状为(2,4,1,16),你希望得到哪个形状?
  • (2,5,1,16) 更好。 :) @CodingPeter
  • 我已经改变了答案,它给了我一个 (2,5,1,16) 数组。再试一次。
猜你喜欢
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-07
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多