python - 无法从 Google Colab 中的 keras 导入 to_categorical
问题描述
所以我一直在使用 Google Colab 上的笔记本,突然间我收到以下错误。
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-bd6ec74ccf2e> in <module>()
----> 1 from keras.utils import to_categorical
ImportError: cannot import name 'to_categorical' from 'keras.utils' (/usr/local/lib/python3.7/dist-packages/keras/utils/__init__.py)
---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.
To view examples of installing some common dependencies, click the
"Open Examples" button below.
这很奇怪,因为它工作得很好,当我重新启动会话时,这发生了。我也尝试使用另一个谷歌帐户(以防我的帐户设置可能有问题),但我仍然遇到同样的错误。
这是我用来导入函数的。
from keras.utils import to_categorical
我想知道是否有任何变化,以及是否有其他人遇到同样的问题。谢谢。
解决方案
从 TF 2.0 开始,它已随 tensorflow 一起移动。请使用这种方式:
from tensorflow.keras.utils import to_categorical
to_categorical([0, 1, 2, 3], num_classes=4)
结果会像
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]], dtype=float32)
推荐阅读
- hibernate - Hibernate envers:组合注释 @Audited 和 @AttributeOverride 不起作用
- vue.js - id passed through params get lost on page refresh
- excel - EXCEL VBA Debug: Searching through the whole workbook
- c# - JsTree Checkbox check Based on data-id
- javascript - 未实现没有 catch 块的 Promise (unhandledrejection) javascript
- entity-framework - 使用实体框架使用 fergin 键从其他表中获取数据
- python-3.x - 使用python从.txt文件中以相同的顺序仅提取多条想要的行
- java - @OneToMany 与它的自我类
- sql - 在 PostgreSQL 中按国家代码选择所有电话记录
- php - Laravel eloquent 更新记录的最小值