如何将固定权重矩阵乘以keras图层输出

2024-09-30 06:14:16 发布

您现在位置:Python中文网/ 问答频道 /正文

当我打算将keras输出乘以常数张量时,遇到了一个问题? 这是我的密码

a = tf.constant(ws, "float32") output4 = AveragePooling3D(pool_size=(X_shape[0], 1, 1), strides = None, padding='valid')(output3) output5 = Conv3D(filters=X_shape[3], kernel_size=(1, 1, 1),padding='same',data_format='channels_last')(output4) output6 = Lambda( tf.multiply(output5, a))(output5)

这是我的错误“

ValueError: Tensor("Const:0", shape=(1, 1, 21, 27, 3), dtype=float32) must be from the same graph as Tensor("conv3d_1/add:0", shape=(None, 1, 21, 27, 3), dtype=float32).

提前感谢您的帮助


Tags: none密码sizetf常数kerassametensor
1条回答
网友
1楼 · 发布于 2024-09-30 06:14:16

由于您使用的是函数式API,因此需要提供常量张量作为模型的输入,或者作为继承Layer的对象的构造函数的输入

方法1(首选)-作为自定义图层的输入:

class ConstMul(tf.keras.layers.Layer):
    def __init__(self, const_val, *args, **kwargs):
        ....
        self.const = const_val

    def call(self, inputs, **kwargs):
        return inputs * self.const

....
output6 = ConstMul(ws)(output5)

方法2-作为单独的输入层:

const_inp = Input(shape)
....
output6 = tf.multiply(output5, const_inp)

然后将const_inp添加到模型的输入列表中。但这不是最好的办法

相关问题 更多 >

    热门问题