Keras 自定义层:__init__takes 1 个位置参数,但给出了 2 个

Keras Custom Layer: __init__takes 1 positional argument but 2 were given

我正在尝试创建一个图层,将 [3,5] 张量的列分别拆分为 [3,2] 和 [3,3] 张量。例如,

[[0., 1., 0.,  0., 0.],
 [1., 0., -1., 0., 0.],
 [1., 0., 1.,  1., 0.]]

进入,

[[0., 1.],
 [1., 0.],
 [1., 0.]]

[[0.,  0., 0.],
 [-1., 0., 0.],
 [1.,  1., 0.]]

这是我尝试构建的自定义层,

import tensorflow as tf
from tensorflow.keras.layers import Layer

class NodeFeatureSplitter(Layer):
    def __init__(self):
        super(NodeFeatureSplitter, self).__init__()
        
    def call(self, x):
        h_feat = x[...,:2]
        x_feat = x[...,-3:]
        
        return h_feat, x_feat

然而,当我在下面的例子中调用这一层时,我得到了上述错误,

x = tf.constant([[0., 1., 0., 0., 0.],[1., 0., -1., 0., 0.],[1., 0., 1., 1., 0.]])

h_feat, x_feat = NodeFeatureSplitter(x)
print(h_feat)
print(x_feat)

TypeError: __ init __() takes 1 positional argument but 2 were given

谁能指出我做错了什么?

谢谢 <3

你的NodeFeatureSplitterclass只接收一个参数,self:

class NodeFeatureSplitter(Layer):

但是你提供了两个,selfx:

h_feat, x_feat = NodeFeatureSplitter(x)

你不想在定义图层时传递x,而只在调用它时传递:

my_layer = NodeFeatureSplitter()
h_feat, x_feat = my_layer(x)  # This is executing __call__, we're using our layer instance as a callable