You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建具备可切换输入层的Keras模型?

实现Keras中基于二进制信号切换的双输入模型

要实现同一时间仅激活一个输入层的需求,我们可以新增一个开关输入来控制两个输入的启用状态,核心思路是通过加权融合的方式,让开关信号决定哪个输入层的输出进入后续网络。具体实现如下:

实现思路

  • 新增开关输入层,接收二进制组合信号(如[1, 0]表示启用input_A,[0, 1]表示启用input_B)
  • 使用Lambda层对两个输入进行加权求和,未被选中的输入会被乘以0,相当于被屏蔽
  • 复用原有全连接层结构,保证模型主体逻辑不变

完整代码

from tensorflow.keras import Model
from tensorflow.keras.layers import Dense, Input, Lambda
from tensorflow.keras.optimizers import Adam

def switchable_input_model():
    # 定义两个输入层(input_B形状可根据实际需求调整)
    input_A = Input(shape=(6,), name="input_A")
    input_B = Input(shape=(6,), name="input_B")
    # 开关输入:接收[1,0]或[0,1]的二进制控制信号
    switch_input = Input(shape=(2,), name="switch_input")
    
    # 根据开关信号加权融合输入,未选中的输入会被置0
    merged_input = Lambda(
        lambda x: x[0] * x[2][:, 0:1] + x[1] * x[2][:, 1:2],
        name="input_selector"
    )([input_A, input_B, switch_input])
    
    # 原有网络结构
    out = Dense(64, activation="relu")(merged_input)
    out = Dense(32, activation="relu")(out)
    outputs = Dense(1, activation="tanh")(out)
    
    # 定义包含三个输入的模型
    model = Model(
        inputs=[input_A, input_B, switch_input],
        outputs=outputs,
        name="switchable_inputs_model"
    )
    model.compile(loss="mse", optimizer=Adam(), metrics=["accuracy"])
    return model

使用示例

训练或推理时,需要传入三组数据:输入A的数据集、输入B的数据集,以及对应的开关控制信号:

import numpy as np

# 生成示例数据
data_A = np.random.rand(100, 6)  # input_A的训练数据
data_B = np.random.rand(100, 6)  # input_B的训练数据
# 开关信号:前50条用input_A,后50条用input_B
switches = np.array([[1,0]]*50 + [[0,1]]*50)
labels = np.random.rand(100, 1)  # 标签数据

# 初始化模型并训练
model = switchable_input_model()
model.fit([data_A, data_B, switches], labels, epochs=10, batch_size=8)

内容的提问来源于stack exchange,提问作者goldfinch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:50:30