【问题标题】:Cannot import to_categorical from keras in Google Colab无法从 Google Colab 中的 keras 导入 to_categorical
【发布时间】:2021-08-14 03:20:08
【问题描述】:

所以我一直在使用 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 

我想知道是否有任何变化,以及是否有其他人遇到同样的问题。 谢谢。

【问题讨论】:

    标签: python keras google-colaboratory


    【解决方案1】:

    从 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)
    

    【讨论】:

      【解决方案2】:
      import tensorflow as tf
      
      y_train_one_hot = tf.keras.utils.to_categorical(y_train)
      

      【讨论】:

        【解决方案3】:
        from keras.utils import to_categorical
        

        从你的代码中删除这一行并使用它

        from tensorflow.keras.utils import to_categorical
        

        这会解决你的问题

        【讨论】:

          猜你喜欢
          • 2022-12-20
          • 1970-01-01
          • 2021-06-06
          • 2022-08-06
          • 1970-01-01
          • 2020-11-28
          • 2021-07-05
          • 1970-01-01
          • 2020-01-24
          相关资源
          最近更新 更多