Keras: Cannot Import Name np_utils [duplicate] - python

This question already has answers here:
ImportError: cannot import name np_utils
(16 answers)
Closed 5 years ago.
I'm using Python 2.7 and a Jupyter notebook to do some basic machine learning. I'm following along with this tutorial:
http://machinelearningmastery.com/regression-tutorial-keras-deep-learning-library-python/
I'm simply trying to import different things from Keras so I can run the tutorial. Specifically, I do this:
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
and it gets stuck at the first import, giving me a traceback of this:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-28-aae66d0fdaee> in <module>()
----> 1 from keras.models import Sequential
2 from keras.layers import Dense
3 from keras.wrappers.scikit_learn import KerasRegressor
4 from sklearn.model_selection import cross_val_score
5 from sklearn.model_selection import KFold
/Users/newscred/anaconda/lib/python2.7/site-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
/Users/newscred/anaconda/lib/python2.7/site-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've Googled around but can't seem to find out why I'm running into this problem / how to fix. Any ideas?
Thanks!

That tutorial was written on June 9th, 2016. Keras 2 was released in March 2017. Try installing the old version, using pip install keras==1.2.2.

Hi this is how it worked for me.(I am using conda)
i created a virtualenv first with conda and then install tensorflow,theano and also future. make sure numpy is updated as well...
steps to follow
conda install numpy
conda install future
conda install -c anaconda theano
conda install keras
now once all this is done. you can open jupyter from the same virtualenv or spyder(i was using spyder) or ipython notebook. this will definitely work.

import numpy in your python script before you import anything from Keras. I was facing the same issue, importing numpy before importing numpy utilities ( np_utils ) solved the issue.

try
pip install --upgrade --user keras
duplicate. Solution here
ImportError: cannot import name np_utils

Related

ModuleNotFoundError: No module named 'tensorflow' on Jupyter Notebook

when I try to import keras on a Jupyter notebook I receive this error message: ModuleNotFoundError: No module named 'tensorflow'.
I need to use keras to build an LSTM model fora project and am a beginner in python so I don't know how to get around this error. I have tried to install tenserflow and keras into an environment on anaconda but I receive the same error. For reference, I am using a Mac.
My code:
#Import libraries used
import math
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, LSTM
Any help would be greatly appreciated!

ModuleNotFoundError: No module named 'keras.backend.tensorflow_backend'

I am trying to run the code
import keras
And I am getting this stack trace.
I have tried reinstalling keras and tensorflow but nothing in working.
Here is the stack trace.
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-10-88d96843a926> in <module>
----> 1 import keras
~\Anaconda3\lib\site-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
~\Anaconda3\lib\site-packages\keras\utils\__init__.py in <module>
4 from . import data_utils
5 from . import io_utils
----> 6 from . import conv_utils
7 from . import losses_utils
8 from . import metrics_utils
~\Anaconda3\lib\site-packages\keras\utils\conv_utils.py in <module>
7 from six.moves import range
8 import numpy as np
----> 9 from .. import backend as K
10
11
~\Anaconda3\lib\site-packages\keras\backend\__init__.py in <module>
----> 1 from .load_backend import epsilon
2 from .load_backend import set_epsilon
3 from .load_backend import floatx
4 from .load_backend import set_floatx
5 from .load_backend import cast_to_floatx
~\Anaconda3\lib\site-packages\keras\backend\load_backend.py in <module>
88 elif _BACKEND == 'tensorflow':
89 sys.stderr.write('Using TensorFlow backend.\n')
---> 90 from .tensorflow_backend import *
91 else:
92 # Try and load external backend.
ModuleNotFoundError: No module named 'keras.backend.tensorflow_backend'
Try:
pip install tensorflow==2.2.0
and then
pip install Keras==2.2.0
This worked for me with Python 3.7.
instead of use something like
from keras.backend.tensorflow_backend import set_session
Try to use it like
from keras.backend import set_session
In Tensorflow 2.0.0+ versions you should just put "compat.v1" after tf and dont use "tensorflow_backend" name. Like this:
tf.keras.backend.tensorflow_backend.set_session() -> tf.compat.v1.keras.backend.set_session()
I tried to use anaconda or pip to install tensorflow and keras, and each method met the same problem.
At last I found the problem is because the version of tensorflow or keras. When I install tensorflow==2.2 and keras==2.4.3(latest), no matter which tools I used I will meet this problem.When I install tensorflow==1.14 and keras==2.2, the code works well.
My python version is 3.5.2 under ubuntu 16.04
Just install tensorflow 2.1.0 or 2.2.0 It already has Keras inside. Dont mix using pip and conda. Carry on with what you have started.
pip install tensorflow==2.2.0
or,
conda install tensorflow==2.2.0
Uninstall Keras and reinstall the version 2.2.0 in your system, it will definately work with Tensorflow 2.2. Then you won't have to downgrade you tensorflow ie. less pain of changing codes ;)
pip uninstall keras
pip install Keras==2.2.0
For my case, I had Python 3.7(latest bug fix)
for tensorflow==2.4.1 this works:
from tensorflow.python.keras.backend import set_session
In my case, it was solved by installing a given specific version of Keras.
pip install Keras==2.2.4

No module named 'sklearn.neighbors._base'

I have recently installed imblearn package in jupyter using
!pip show imbalanced-learn
But I am not able to import this package.
from tensorflow.keras import backend
from imblearn.over_sampling import SMOTE
I get the following error
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-20-f19c5a0e54af> in <module>
1 # from sklearn.utils import resample
2 from tensorflow.keras import backend
----> 3 from imblearn.over_sampling import SMOTE
4
5
~/.virtualenvs/p3/lib/python3.6/site-packages/imblearn/__init__.py in <module>
32 Module which allowing to create pipeline with scikit-learn estimators.
33 """
---> 34 from . import combine
35 from . import ensemble
36 from . import exceptions
~/.virtualenvs/p3/lib/python3.6/site-packages/imblearn/combine/__init__.py in <module>
3 """
4
----> 5 from ._smote_enn import SMOTEENN
6 from ._smote_tomek import SMOTETomek
7
~/.virtualenvs/p3/lib/python3.6/site-packages/imblearn/combine/_smote_enn.py in <module>
8 from sklearn.utils import check_X_y
9
---> 10 from ..base import BaseSampler
11 from ..over_sampling import SMOTE
12 from ..over_sampling.base import BaseOverSampler
~/.virtualenvs/p3/lib/python3.6/site-packages/imblearn/base.py in <module>
14 from sklearn.utils.multiclass import check_classification_targets
15
---> 16 from .utils import check_sampling_strategy, check_target_type
17
18
~/.virtualenvs/p3/lib/python3.6/site-packages/imblearn/utils/__init__.py in <module>
5 from ._docstring import Substitution
6
----> 7 from ._validation import check_neighbors_object
8 from ._validation import check_target_type
9 from ._validation import check_sampling_strategy
~/.virtualenvs/p3/lib/python3.6/site-packages/imblearn/utils/_validation.py in <module>
11
12 from sklearn.base import clone
---> 13 from sklearn.neighbors._base import KNeighborsMixin
14 from sklearn.neighbors import NearestNeighbors
15 from sklearn.utils.multiclass import type_of_target
ModuleNotFoundError: No module named 'sklearn.neighbors._base'
Other packages in the environment
numpy==1.16.2
pandas==0.24.2
paramiko==2.1.1
matplotlib==2.2.4
scikit-learn==0.22.1
Keras==2.2.4
tensorflow==1.12.0
tensorboard==1.12.0
tensorflow-hub==0.4.0
xlrd==1.2.0
flask==1.0.2
wtforms==2.2.1
bs4==0.0.1
gensim==3.8.1
spacy==2.2.3
nltk==3.4.5
wordcloud==1.6.0
pymongo==3.10.1
imbalanced-learn==0.6.1
I checked the sklearn package, it contains base module, not _base. But modifying it may not be the right solution. Any other solution to fix this issue.
If in case you want to persist with the latest version of scikit-learn, add the following code to your script or execute the following code in your environment before installing imblearn
import sklearn.neighbors._base
sys.modules['sklearn.neighbors.base'] = sklearn.neighbors._base
This has to be after
pip install sklearn
or in a notebook environment:
!pip install sklearn
This problem stems from the fact that certain modules are named with an underscore in the newer scikit-learn releases
Previous sklearn.neighbors.base has been renamed to sklearn.neighbors._base in version 0.22.1.
You have probably a version of scikit-learn older than that.
Installing the latest release solves the problem:
pip install -U scikit-learn
or
pip install scikit-learn==0.22.1
I had a similar problem trying to import SMOTE from imblearn.over_sampling and my version of scikit-learn was up to date (0.24.1). What worked for me was:
First I downgraded my scikit learn version to 0.22.1 using
pip install scikit-learn==0.22.1
Next, I updated the imbalanced-learn package using:
pip install -U imbalanced-learn
That uninstalled scikit-learn-0.22.1, installed the updated version (scikit-learn-0.24.1), and updated the imbalanced-learn package. Everything worked fine thereafter.
If it is in a particular env, you must copy the _base file or base file to the env from package file.
I had the same problem in my tensorflow env. I just copied _base and base file to my tensorflow env and worked.

Keras installation error

I'm using Anaconda, and I have already installed TensorFlow which works fine. Now I want to install keras. Here what i did:
activate tensorflow
pip install keras
installation seems to be successful.
after that i run
idle
and then to test correctness, i run this:
from keras.models import Sequential
and receive following error:
Warning (from warnings module):
File "C:\Users\ccc\AppData\Local\Continuum\anaconda3\envs\tensorflow\lib\site-packages\h5py__init__.py", line 36
from ._conv import register_converters as _register_converters
FutureWarning: Conversion of the second argument of issubdtype from float to np.floating is deprecated. In future, it will be treated as np.float64 == np.dtype(float).type.
Using TensorFlow backend.
I thought maybe this is just a warning, and then I run
jupyter notebook
and then try to import stuff. Error is this:
import seaborn as sns
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegressionCV
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.utils import np_utils
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-2-4f6dad112f73> in <module>()
5 from sklearn.linear_model import LogisticRegressionCV
6
----> 7 from keras.models import Sequential
8 from keras.layers.core import Dense, Activation
9 from keras.utils import np_utils
>
> ModuleNotFoundError: No module named 'keras'
EDIT
i've done cd to folder where I want to do my project.
print(sys.path)
in idle returns this:
['', 'C:\\Users\\smuminov\\Desktop\\UC\\Spring-2018\\CS504\\Project\\Prediction',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\envs\tensorflow\Scripts',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\envs\tensorflow\python35.zip',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\envs\tensorflow\DLLs',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\envs\tensorflow\lib',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\envs\tensorflow',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\envs\tensorflow\lib\site-packages',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\envs\tensorflow\lib\site-packages\uritemplate-3.0.0-py3.5.egg']
in jupyter in returns this:
['',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\python36.zip',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\DLLs',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\lib',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\lib\site-packages',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\lib\site-packages\win32',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\lib\site-packages\win32\lib',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\lib\site-packages\Pythonwin',
'C:\Users\smuminov\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\extensions',
'C:\Users\smuminov\.ipython']
They are different. Should they be the same?
Probably your python path is messed up. The message you are getting in 'idle' is just a warning you can ignore it for now. But the message you getting in your jupyter notebooks is a real error that you need to fix.
Try running the following code both in your idle environment and in Jupyter notebook. Do it before you import Keras
import sys
print sys.path
Then compare results. Probably jupyter is not picking up your virtual environment.
Continuing based on your test results:
Looks like you running Idle from virtualenv that you created called 'tensorflow', but you are running jupyter from regular anaconda environment.
If you jupyter is simply installed as a module in Anaconda environmnet. You can just install it again into your tensorflow virtual env by running the following commands
activate tensorflow
pip install jupyter
Then run
jupyter-notebook
This should fix your issue. Make sure to print out sys.path to double check

Import skflow on a Windows machine

I am trying to import skflow on my Windows PC. I have already install and used Anaconda on Python (3.5). I have no trouble to use tensorflow but when I want to use skflow I get the error:
ImportError Traceback (most recent call last)
<ipython-input-1-04faecc7c0de> in <module>()
8 import tensorflow as tf
9 from tensorflow.contrib import learn
---> 10 from tensorflow.contrib import skflow
ImportError: cannot import name 'skflow'
Does anyone know how to fix this?
Thanks in advance!
Please try this:
>>> import tensorflow as tf
>>> from tensorflow.contrib import learn as skflow
FYI, skflow is not any special package/module/... It's an alias for tensorflow.contrib.learn which is in 'sklearn' style.

Categories

Resources