【问题标题】:Keras.utils fails to ImportKeras.utils 无法导入
【发布时间】:2018-07-04 05:00:12
【问题描述】:

下图显示了在 CIFAR 小图像数据集上训练简单的深度 CNN(卷积神经网络)的部分代码。 我已经导入,导入keras.utils(红色高亮)

但是,我仍然收到以下错误:

【问题讨论】:

    标签: python-3.x keras


    【解决方案1】:

    您可以在 keras 中导入to_categorical,如下所示。

    from keras.utils.np_utils import to_categorical
    

    如下图所示。

    Y = [1, 2, 1, 2, 3, 4, 1]
    
    Y = to_categorical(Y)
    
    print(Y)
    
    # output
    array([[0., 1., 0., 0., 0.],
           [0., 0., 1., 0., 0.],
           [0., 1., 0., 0., 0.],
           [0., 0., 1., 0., 0.],
           [0., 0., 0., 1., 0.],
           [0., 0., 0., 0., 1.],
           [0., 1., 0., 0., 0.]], dtype=float32)
    

    【讨论】:

      【解决方案2】:

      尝试从keras.utils 导入np_utils 并像这样使用

      from keras.utils import np_utils
      np_utils.to_categorical(y_train, num_classes)
      

      【讨论】:

        【解决方案3】:

        您在导入 python 模块时遵循了错误的做法。您应该采用以下任一做法:

        从 keras.utils.np_utils 导入到_categorical

        y_train = to_categorical(y_train, num_classes)
        y_test = to_categorical(y_test, num_classes)

                           OR
        

        从 keras.utils 导入 np_utils

        y_train = np_utils.to_categorical(y_train, num_classes)
        y_test = np_utils.to_categorical(y_test, num_classes)

        您只能调用已导入的模块/函数。说,如果你使用,
        from keras.utils.np_utils import to_categorical
        这意味着您正在从 keras.utils.np_utils 包中导入 to_categorical 函数。因此,您只能调用 to_categorical 函数。但是您尝试调用未导入的 keras.utils.to_categorical。另外,不能直接导入 to_categoricalutils 而不首先导入 np_utils

        经验法则:如果您输入 from X import Y,这意味着您必须照原样调用 Y() 而不是 X.Y()。这样做是多余的,也是错误的。

        提示:您无需在 to_categorical 中将 num_classes 作为参数提及。 Python 解释器会智能地为你做这件事。

        【讨论】:

          猜你喜欢
          • 2021-07-21
          • 2018-04-01
          • 1970-01-01
          • 2021-08-05
          • 1970-01-01
          • 2021-07-05
          • 1970-01-01
          • 2021-11-20
          • 2017-01-13
          相关资源
          最近更新 更多