TensorFlow/Keras 中的自定义层

问题描述 投票:0回答:1

我是张量流新手,我正在尝试构建一个接受多个输入(即 x,y,A)并返回 z 的自定义层。在这一层中,w是可训练参数。我的代码是:

import tensorflow as tf
import tensorflow.keras as tfK
from keras import backend as K
import numpy as np

class MyLayer(tfK.layers.Layer):
    def __init__(self, x, y, A):
        super().__init__()

    def build(self, x.shape, y.shape, A.shape):
        self.w= self.add_weight(
            shape=(x.shape[-1]),
            initializer="random_normal",
            trainable=True,
        )

    def call(self, x, y, A):
        alpha = K.abs(tf.matmul(A,x) - y)/tf.matmul(A,(x_w))
        beta = K.abs(tf.matmul(A,x) - y)/tf.matmul(A,(x-w))
        LHS = tf.matmul(A,x)
        cond  = K.abs(LHS) < y
        lowerProj = (1-beta) * x + beta * w
        upperProj  = (1-alpha) * x + alpha * w
        z = tf.where(cond, upperProj, lowerProj)
        return z

当我运行上面的代码(只是想检查它是否有效)时

A = tf.convert_to_tensor(np.array([[1,2],[2,-1]]), dtype=tf.float32)
y = tf.constant(1, shape= (2,1), dtype=tf.float32)
x = tf.constant(0.5, shape= (2,1), dtype=tf.float32)

inputs = x,y,A
NN = MyLayer(x.shape[0],y.shape[0],A.shape)
output = NN(inputs)
print(output)

我收到以下错误: TypeError:MyLayer.build() 缺少 2 个必需的位置参数:'y_shape'、'A_shape'

如何正确构建这一层?我非常感谢任何反馈。

python-3.x keras tensorflow2.0 tf.keras keras-layer
1个回答
0
投票

当调用方法采用多个参数时,构建方法签名采用一个列表,而不是多个参数。试试这个。

def build(self, shapes):
  assert len(shapes) == 
  x_shape, y_shape, A_shape = *shapes 
  self.w= self.add_weight(shape=(x_shape[-1]),
                          initializer="random_normal",
                          trainable=True,
                          )

另外,不要单独导入 Keras - 只需使用 tf.keras。

© www.soinside.com 2019 - 2024. All rights reserved.