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

Keras Dense层自定义名称失效,出现module_wrapper命名问题

问题原因及解决办法

核心问题:混合导入不同层级的Keras组件

你代码里同时混用了**公开API路径tf.keras和内部实现路径tensorflow.python.keras**的组件:

  • 模型构建用的是tf.keras.models.Sequential(公开API)
  • 但Dense层导入的是tensorflow.python.keras.layers.Dense(内部路径)

当把内部路径的Dense层传入公开API的Sequential模型时,TensorFlow会自动将这些层包装成ModuleWrapper,导致你指定的自定义名称被覆盖,显示为module_wrapper系列名称。

另外,你的依赖版本存在冲突:TensorFlow 2.13.0自带的Keras版本是2.13.0,但你单独安装了Keras 2.11.0,版本不匹配也会加剧这类兼容性问题。

解决步骤

1. 统一Keras组件的导入路径

全部使用官方推荐的tf.keras公开API,删除内部路径的导入语句:

import tensorflow as tf
import logging

# 设置随机种子
tf.random.set_seed(1234)  
# 用tf.keras的API构建模型
model = tf.keras.models.Sequential(
    [
        tf.keras.Input(shape=(2,)),
        tf.keras.layers.Dense(3, activation='sigmoid', name='layer1'),
        tf.keras.layers.Dense(1, activation='sigmoid', name='layer2')
     ]
)
model.summary()

2. 修复依赖版本冲突

卸载单独安装的Keras,使用TensorFlow自带的Keras版本:

pip uninstall keras -y

这样TensorFlow会自动调用其内置的对应版本Keras,避免版本不兼容问题。

验证效果

运行修改后的代码,模型摘要会正常显示你指定的自定义层名称:

Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 layer1 (Dense)              (None, 3)                 9         
                                                                 
 layer2 (Dense)              (None, 1)                 4         
                                                                 
=================================================================
Total params: 13
Trainable params: 13
Non-trainable params: 0
_________________________________________________________________

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:38:28