导入TensorFlow Federated时遭遇TypeError错误求助
问题:导入TensorFlow Federated时出现TypeError错误
尝试导入TensorFlow Federated(tff)并运行以下示例代码:
import collections import numpy as np import tensorflow as tf import tensorflow_federated as tff np.random.seed(0) tff.federated_computation(lambda: 'Hello, World!')()
运行后触发如下TypeError错误:
/usr/local/lib/python3.8/dist-packages/tensorflow_federated/python/learning/metrics/keras_utils.py in <module> 38 metrics_constructor: Union[MetricConstructor, MetricsConstructor, 39 MetricConstructors] ---> 40 ) -> Tuple[Callable[[], StateVar], Callable[[StateVar, ...], StateVar], 41 Callable[[StateVar], Any]]: 42 """Turn a Keras metric construction method into a tuple of pure functions. /usr/lib/python3.8/typing.py in __getitem__(self, params) 814 f" Got {args}") 815 params = (tuple(args), result) --> 816 return self.__getitem_inner__(params) 817 818 @_tp_cache /usr/lib/python3.8/typing.py in inner(*args, **kwds) 259 except TypeError: 260 pass # All real errors (not unhashable args) are raised below. --> 261 return func(*args, **kwds) 262 return inner 263 /usr/lib/python3.8/typing.py in __getitem_inner__(self, params) 837 return self.copy_with((_TypingEllipsis, result)) 838 msg = "Callable[[arg, ...], result]: each arg must be a type." --> 839 args = tuple(_type_check(arg, msg) for arg in args) 840 params = args + (result,) 841 return self.copy_with(params) /usr/lib/python3.8/typing.py in <genexpr>(.0) 837 return self.copy_with((_TypingEllipsis, result)) 838 msg = "Callable[[arg, ...], result]: each arg must be a type." ---> 839 args = tuple(_type_check(arg, msg) for arg in args) 840 params = args + (result,) 841 return self.copy_with(params) /usr/lib/python3.8/typing.py in _type_check(arg, msg, is_argument) 147 return arg 148 if not callable(arg): --> 149 raise TypeError(f"{msg} Got {arg!r:.100}.") 150 return arg 151 TypeError: Callable[[arg, ...], result]: each arg must be a type. Got Ellipsis.
解决方案
该错误源于Python 3.8的typing.Callable语法不支持在参数列表中直接使用省略号(...)表示可变参数,而新版TensorFlow Federated(TFF)使用了该语法,导致类型检查失败。
可通过以下两种方式解决:
- 升级Python版本:将Python升级至3.9或更高版本,新版本
typing模块兼容Callable[[StateVar, ...], StateVar]这类语法。 - 降级TFF版本:安装适配Python 3.8的旧版TFF,例如
tensorflow-federated==0.20.0,该版本的类型注解符合Python 3.8的规则。
执行降级的命令示例:
pip install tensorflow-federated==0.20.0
同时需确保TensorFlow版本与TFF版本匹配,避免出现其他兼容性问题。
内容的提问来源于stack exchange,提问作者Sully Marshall
相关产品推荐
相关产品推荐

