Google Colab导入tensorflow_federated报TypeError解决方案
导入TensorFlow Federated触发
TypeError: 'type' object is not subscriptable报错解决方案 问题场景
在Google Colab平台运行《Federated Learning for Image Classification(图像分类联邦学习)》官方教程示例代码时,执行导入tensorflow_federated的语句触发报错。
触发报错的示例代码如下:
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 - 报错提示:'type' object is not subscriptable
- 错误定位:报错栈指向
tensorflow_federated包内structure.py文件的collections.OrderedDict[str, Any]类型标注行
完整报错信息如下:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-35-a23308ec3f7c> in <module>() 3 import numpy as np 4 import tensorflow as tf ----> 5 import tensorflow_federated as tff 6 7 np.random.seed(0) 6 frames /usr/local/lib/python3.7/dist-packages/tensorflow_federated/python/common_libs/structure.py in <module>() 263 264 def to_odict(struct: Struct, --> 265 recursive: bool = False) -> collections.OrderedDict[str, Any]: 266 """Returns `struct` as an `OrderedDict`, if possible. 267 TypeError: 'type' object is not subscriptable
无效尝试方案
- 参考公开方案将Python版本升级至3.9,问题未解决。
可行解决步骤
在Colab单元格中执行以下代码,指定安装0.20.0版本的tensorflow-federated,升级nest-asyncio并启用异步嵌套适配,执行完成后重启运行时即可正常导入使用TFF:
!pip install --quiet tensorflow-federated==0.20.0 # 不要直接安装最新版tensorflow-federated,会触发版本兼容问题 #!pip install --quiet --upgrade tensorflow-federated !pip install --quiet --upgrade nest-asyncio import nest_asyncio nest_asyncio.apply()
内容的提问来源于stack exchange,提问作者CodingTheVerse
相关产品推荐
相关产品推荐

