简体   繁体   English

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

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

I want to make a neural network layer similar to Conv2D using tensorflow . 我想使用tensorflow创建一个类似于Conv2D的神经网络层。 Below is what I want to implement. 以下是我想要实现的内容。 A layer uses a kernel just like convolution layer but the output is larger than the input. 层就像卷积层一样使用内核,但输出大于输入。

The layer image that I want to implement 我想要实现的图层图像

However, it seems there is no way I can implement that using only tensorflow operations. 但是,似乎我无法仅使用tensorflow操作来实现它。 I managed to implement the below code by converting tensorflow tensors to numpy arrays but I still have no idea how to merge 4D output array into 2D array. 我设法通过将张量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.

Is there any way I can implement this using only tensorflow ? 有没有办法只用tensorflow来实现这个? If not, what method should I use instead? 如果没有,我应该使用什么方法?

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))

Output: 输出:

[[[ 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