[英]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.