使用WeightNormalization附加层时出现TypeError问题求助
TensorFlow Addons WeightNormalization 触发TypeError问题解决
问题复现
以下代码在Colab环境中执行时触发TypeError,单独使用Dense层无异常,问题出在WeightNormalization包装器:
import numpy as np import tensorflow as tf import tensorflow_addons as addon_layers x = np.random.rand(1, 10, 10, 1) dense = addon_layers.WeightNormalization(tf.keras.layers.Dense(10), data_init=False) y = dense(x) y.shape
报错信息
完整报错堆栈:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-47-a2d44c85c018> in <module> 2 3 x = np.random.rand(1, 10, 10, 1) ----> 4 dense = addon_layers.WeightNormalization(tf.keras.layers.Dense(10)) 5 y = dense(x) 6 y.shape 2 frames /usr/local/lib/python3.9/dist-packages/tensorflow_addons/layers/wrappers.py in __init__(self, layer, data_init, **kwargs) 57 58 @typechecked ---> 59 def __init__(self, layer: tf.keras.layers, data_init: bool = True, **kwargs): 60 super().__init__(layer, **kwargs) 61 self.data_init = data_init /usr/local/lib/python3.9/dist-packages/typeguard/_functions.py in check_argument_types(memo) 111 value = memo.arguments[argname] 112 try: --> 113 check_type_internal(value, expected_type, memo=memo) 114 except TypeCheckError as exc: 115 qualname = qualified_name(value, add_class_prefix=True) /usr/local/lib/python3.9/dist-packages/typeguard/_checkers.py in check_type_internal(value, annotation, memo) 668 return 669 --> 670 if not isinstance(value, origin_type): 671 raise TypeCheckError(f"is not an instance of {qualified_name(origin_type)}") 672 TypeError: isinstance() arg 2 must be a type or tuple of types
问题原因
错误根源是TensorFlow Addons的WeightNormalization类在__init__方法的类型注解中,错误地将layer参数的类型指定为tf.keras.layers(模块),而非正确的tf.keras.layers.Layer(层类)。这导致typeguard库在执行类型检查时,无法用isinstance验证实例是否属于一个模块,从而抛出TypeError。
解决方法
方法一:降级TensorFlow Addons版本
该bug在0.20.0及以上版本出现,降级到0.19.0版本即可修复:
pip install tensorflow-addons==0.19.0
方法二:临时禁用类型检查
如果需要保留当前版本,可在代码开头添加以下语句关闭typeguard的类型检查:
from typeguard import typechecked typechecked.off()
内容的提问来源于stack exchange,提问作者Bhavesh
相关产品推荐
相关产品推荐

