繁体   English   中英

如何使用tensorflow实现类似于Conv2D的此层?

[英]How can I implement this layer similar to Conv2D using tensorflow?

我想使用tensorflow创建一个类似于Conv2D的神经网络层。 以下是我想要实现的内容。 层就像卷积层一样使用内核,但输出大于输入。

我想要实现的图层图像

但是,似乎我无法仅使用tensorflow操作来实现它。 我设法通过将张量tensorflow张量转换为numpy数组来实现下面的代码,但我仍然不知道如何将4D输出数组合并到2D数组中。

input = [[a, b],
         [c, d]]
kernel = [[1, -1],
          [2, 1]]
output = [[input[0][0] * kernel, input[0][1] * kernel],
          [input[1][0] * kernel, input[1][1] * kernel]]

#since "input[0][0] * kernel" is 2D, "output" becomes 4D array.

有没有办法只用tensorflow来实现这个? 如果没有,我应该使用什么方法?

class MyLayer(tf.keras.layers.Layer):
    def __init__(self, kernel):
        super(MyLayer, self).__init__()
        self.k = tf.constant(kernel)

    def build(self, input_shape):
        self.i = input_shape

    def call(self, input):
        x = tf.reshape(input, [-1])
        return tf.map_fn(lambda s:  tf.scalar_mul(s, self.k), x)

mylayer = MyLayer([[1.0, -1.0], [-1.0, 1.0]])
x = tf.constant([[1.0, 2.0, 3.0], [3.0, 4.0, 5.0]])

with tf.Session() as sess:
    print (sess.run(r))

输出:

[[[ 1. -1.]
  [-1.  1.]]
 [[ 2. -2.]
  [-2.  2.]]
 [[ 3. -3.]
  [-3.  3.]]
 [[ 3. -3.]
  [-3.  3.]]
 [[ 4. -4.]
  [-4.  4.]]
 [[ 5. -5.]
  [-5.  5.]]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM