Elizabeth Fons
Elizabeth Fons

Reputation: 511

ImportError: cannot import name np_utils

I'm trying to run the following example from keras

but I get this error:

ImportError
Traceback (most recent call last)
<ipython-input-58-50de27eea0f8> in <module>()   
      8 import numpy as np  
      9 import matplotlib.pyplot as plt  
---> 10 from keras.models import Sequential  
     11 from keras.layers import Dense, LSTM  
     12   

/usr/local/lib/python2.7/dist-packages/keras/__init__.py in <module>()  
      1 from __future__ import absolute_import  
      2   
----> 3 from . import utils  
      4 from . import activations  
      5 from . import applications  

/usr/local/lib/python2.7/dist-packages/keras/utils/__init__.py in <module>()  
      1 from __future__ import absolute_import  
----> 2 from . import np_utils  
      3 from . import generic_utils  
      4 from . import data_utils  
      5 from . import io_utils  

ImportError: cannot import name np_utils  

I'm using Ubuntu and I installed keras with:

sudo pip install keras 

This question was already asked but there was no answer: Keras: Cannot Import Name np_utils

Upvotes: 51

Views: 196450

Answers (21)

Prosper Asiimwe
Prosper Asiimwe

Reputation: 1

keras.utils.np_utils module is no longer available in the latest version of Keras. The to_categorical function has been moved to the tensorflow.keras.utils module.

To fix this issue, you can use the following import statement instead:

from keras.utils import to_categorical

or:

from tensorflow.keras.utils import to_categorical

Upvotes: 0

aft123
aft123

Reputation: 1

For me, np_utils can be accessed by:

from keras.src.utils.np_utils import to_categorical

to get a specific package.

Upvotes: 0

Andrey
Andrey

Reputation: 1626

This works for me now

from keras.src.utils.np_utils import to_categorical

Upvotes: 0

Tharath Dev
Tharath Dev

Reputation: 1

this work for me keras version (2.13.1)

from keras import utils

Y_train = utils.to_categorical(y_train, n_classes)

Upvotes: 0

Asha Choudhary
Asha Choudhary

Reputation: 165

this worked for me

from tensorflow.python.keras.utils import np_utils

Upvotes: 1

muninn
muninn

Reputation: 483

I ran into the same issue. You need to do pip install np_utils and then restart your terminal. Make sure everything is up to date.

Upvotes: 8

Poornachandra Kashi
Poornachandra Kashi

Reputation: 101

This works in Google Colab:

import tensorflow as tf

y_train=tf.keras.utils.to_categorical(y_train,num_classes=7)

Upvotes: 1

Soheil Sarabandi
Soheil Sarabandi

Reputation: 11

Here is my solution:

from keras import utils

utils.to_categorical(...)

Upvotes: 1

Anas
Anas

Reputation: 819

I was actually having similar issue while using

from keras.utils import to_categorical

But I managed to solve it with:

from tensorflow.keras.utils import to_categorical

Upvotes: 9

Ibrahim
Ibrahim

Reputation: 322

In tf 2.x or higher, Keras has been packed into TensorFlow, you now call everything from TensorFlow. np_utils has been moved to util you can simply use it by doing:

tf.keras.utils.to_categorical(
y, num_classes=None, dtype='float32'
)

Upvotes: 0

D.Dimanov
D.Dimanov

Reputation: 175

They moved everything to just utils, so if you are using tf 2.x or higher version of keras it is just tf.keras.utils or keras.utils.

So for example: keras.utils.np_utils.to_categorical -> keras.utils.to_categorical

Upvotes: 13

gopalreddy lakki
gopalreddy lakki

Reputation: 11

from tensorflow.python.keras.utils import tf_utils ImportError: cannot import name 'tf_utils'

pip install keras==2.1.5 -i https://pypi.tuna.tsinghua.edu.cn/simple

https://blog.csdn.net/CLOUD_J/article/details/103101247

Upvotes: 1

Matthieu
Matthieu

Reputation: 125

This problem seems to have different solutions depending on the situation. Here's yet another solution that helped me when I had those exact symptoms:

pip install enum34

Installing np_utils, future or a different version of numpy or Theano didn't help for me. The problem was due to Keras that use enum, that only exists in Python3. Enum34 is a backport of Python3's enum to Python2.

I was using:

  • python2.7
  • Keras==2.3.0
  • Theano==1.0.4 as a backend

Upvotes: 0

Italo Gervasio
Italo Gervasio

Reputation: 388

If you are using TensorFlow backend with Keras make sure your keras.json file states its backend is Tensorflow. The code below worked for me:

import os
os.environ['KERAS_BACKEND']='tensorflow'
#Anything from keras

Cheers hope I helped somebody. OBS: I was using Anaconda and Spyder.

Upvotes: 0

shinemu
shinemu

Reputation: 11

Open Anaconda Prompt --> Write this command : **conda install keras**



(base) C:\>conda `enter code here`install keras
Collecting package metadata: done
Solving environment: done

## Package Plan ##

  environment location: C:\Users\sinem.secgin\AppData\Local\Continuum\anaconda3

  added / updated specs:
    - keras


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    _tflow_select-2.3.0        |              mkl           3 KB
    absl-py-0.7.1              |           py37_0         158 KB
    astor-0.7.1                |           py37_0          44 KB
    ca-certificates-2019.5.15  |                0         166 KB
    certifi-2019.6.16          |           py37_0         155 KB
    conda-4.7.5                |           py37_0         3.0 MB
    conda-package-handling-1.3.10|           py37_0         280 KB
    gast-0.2.2                 |           py37_0         138 KB
    grpcio-1.16.1              |   py37h351948d_1         947 KB
    keras-2.2.4                |                0           5 KB
    keras-applications-1.0.8   |             py_0          33 KB
    keras-base-2.2.4           |           py37_0         489 KB
    keras-preprocessing-1.1.0  |             py_1          36 KB
    libmklml-2019.0.3          |                0        21.4 MB
    libprotobuf-3.8.0          |       h7bd577a_0         2.2 MB
    markdown-3.1.1             |           py37_0         132 KB
    mock-3.0.5                 |           py37_0          47 KB
    openssl-1.1.1c             |       he774522_1         5.7 MB
    protobuf-3.8.0             |   py37h33f27b4_0         581 KB
    tensorboard-1.13.1         |   py37h33f27b4_0         3.3 MB
    tensorflow-1.13.1          |mkl_py37h9463c59_0           4 KB
    tensorflow-base-1.13.1     |mkl_py37hcaf7020_0        49.4 MB
    tensorflow-estimator-1.13.0|             py_0         205 KB
    termcolor-1.1.0            |           py37_1           7 KB
    ------------------------------------------------------------
                                           Total:        88.4 MB

The following NEW packages will be INSTALLED:

  _tflow_select      pkgs/main/win-64::_tflow_select-2.3.0-mkl
  absl-py            pkgs/main/win-64::absl-py-0.7.1-py37_0
  astor              pkgs/main/win-64::astor-0.7.1-py37_0
  conda-package-han~ pkgs/main/win-64::conda-package-handling-1.3.10-py37_0
  gast               pkgs/main/win-64::gast-0.2.2-py37_0
  grpcio             pkgs/main/win-64::grpcio-1.16.1-py37h351948d_1
  keras              pkgs/main/win-64::keras-2.2.4-0
  keras-applications pkgs/main/noarch::keras-applications-1.0.8-py_0
  keras-base         pkgs/main/win-64::keras-base-2.2.4-py37_0
  keras-preprocessi~ pkgs/main/noarch::keras-preprocessing-1.1.0-py_1
  libmklml           pkgs/main/win-64::libmklml-2019.0.3-0
  libprotobuf        pkgs/main/win-64::libprotobuf-3.8.0-h7bd577a_0
  markdown           pkgs/main/win-64::markdown-3.1.1-py37_0
  mock               pkgs/main/win-64::mock-3.0.5-py37_0
  protobuf           pkgs/main/win-64::protobuf-3.8.0-py37h33f27b4_0
  tensorboard        pkgs/main/win-64::tensorboard-1.13.1-py37h33f27b4_0
  tensorflow         pkgs/main/win-64::tensorflow-1.13.1-mkl_py37h9463c59_0
  tensorflow-base    pkgs/main/win-64::tensorflow-base-1.13.1-mkl_py37hcaf7020_0
  tensorflow-estima~ pkgs/main/noarch::tensorflow-estimator-1.13.0-py_0
  termcolor          pkgs/main/win-64::termcolor-1.1.0-py37_1

Proceed ([y]/n)? y
Y

Upvotes: 0

stenlytw
stenlytw

Reputation: 958

Try to install the old version using Anaconda:

conda install tensorflow-gpu==1.2.1

Upvotes: 0

Nabeel Ahmed
Nabeel Ahmed

Reputation: 19252

np_utils is a separate package (and a keras dependency - which doesn't get install with it). Can be installed using pip:

pip install np_utils

using - Keras==2.0.6


Suggestion: For some odd (and still unknown) reasons, even after installing the import

from keras.utils.np_utils import to_categorical

didn't work - I had to restart the notebook (first restart even didn't work), and once it worked, I got stuck again for same import call (gave exception for no module named tensorflow) - as in utils there's another import from . import conv_utils, which required the tensorflow.

I did try installing tensorflow using pip install tensorflow gave:

Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow

even this gist didn't work for me.


Finally, I installed Anaconda - which have all the scientific packages (numpy, scipy, scikit-learn,..) pre-installed. Installed keras:

conda install keras

Best thing was, it even installed tensorflow as its dependency.

Upvotes: 45

mohaseeb
mohaseeb

Reputation: 389

I had a similar issue in a build system:

  • Keras throwing: ImportError: cannot import name np_utils
  • But also tensorflow assertion failure: AttributeError: type object 'NewBase' has no attribute 'is_abstract'

The problem in my case was the build environment, for some reason I didn't investigate, had an old six version (six 1.5.0) (compared to my local env). The issue was solved by installing the most recent six version (1.11.0 when writing this).

pip install six -U

Upvotes: 0

MCheng
MCheng

Reputation: 1200

For keras > 2.0, please use from keras.utils import to_categorical instead.

Example of usage will be to_categorical(y, num_classes=None)

Upvotes: 41

Daniel McLean
Daniel McLean

Reputation: 451

I had to install tensorflow to solve this problem. (From virtualenv):

 pip install tensorflow

Upvotes: 2

Kunal Goswami
Kunal Goswami

Reputation: 41

Try importing numpy before you import something from keras (I see that you have already done so, am adding this just to document the solution which worked for me). I faced the same error and when I tried:

import numpy as np
from __future__ import absolute_import
#Anything from keras

It seemed to work just fine with me. Try installing the latest stable packages of future and numpy beforehand through:

pip install future
pip install numpy

Sometimes its possible that conda and other installations of python might be interfering with each other. I had everything managed through brew beforehand, but when I installed conda many of the packages which I previously installed gave me an import error (because of the PYTHONPATH variable).

Upvotes: 4

Related Questions