Keras installation error - python

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

Related

Keras not being imported

I was trying to run this code, first time using Tensorflow API in Python. Donwloaded latest version of tensorflow and pip through terminal. However, when I attempt to import from keras subpackage, an error is returned
from keras.models import Model
from keras.layers import Dense
from keras.layers import Input
ImportError: cannot import name 'pywrap_tensorflow' from partially initialized module 'tensorflow.python' (most likely due to a circular import) (/Users/macbook/Library/Python/3.9/lib/python/site-packages/tensorflow/python/__init__.py) ```

Problems importing keras

I have a functioning program on a Jupyter notebook. I downloaded it as a .py file but, for some reason, I get errors while making the imports that, in jupyter, didn't cause any problems.
The imports are:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.losses import MeanSquaredError
from tensorflow.keras.metrics import RootMeanSquaredError
from tensorflow.keras.optimizers import Adam
and I get the errors:
Import "tensorflow.keras.<name>" could not be resolved
It's so weird since the only difference is the file itself (from .ipynb to .py), it's the same environment and even the same folder.
I have tensorflow version: 2.8.0
And python version: 3.10.4

Why does %config line give me syntax error in Python 3.7?

I am creating a system in order to predict earthquakes. There's this code in which there is a line %config InlineBackend.figure_format = 'retina'.
Whenever I run my python code it gives the error as ("% invalid syntax").
Earlier I had the problem of %matplotlib statement which I figured out through google. But, this problem is sucking me.
https://www.kaggle.com/pablocastilla/predict-earthquakes-with-lstm ("The source from where the code has been taken")
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from subprocess import check_output
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential
from sklearn.cross_validation import train_test_split
import time #helper libraries
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
from numpy import newaxis
from geopy.geocoders import Nominatim
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
import warnings
warnings.filterwarnings('ignore')
%config InlineBackend.figure_format = 'retina'
# Any results you write to the current directory are saved as output.
from subprocess import check_output
print(check_output(["ls", "../input"]).decode("utf8"))
So it is showing "error invalid syntax " and the % sign before the word config has been highlighted.
The expected output is that I should not recieve an error and any results that are written to the directory are given out.
That % syntax is defining a IPython Magic Command. Read: Magic commands
Give this a try
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('retina')
Taken from Configure the backend of Ipython to use retina display mode with code
You need to install Ipython library in order to do this. Also if you get "No module named ipykernel" then install ipykernel.
pip install ipython
pip install ipykernel
Edit: but I highly recommend using jupyter notebooks for example give google colab a try : https://colab.research.google.com/notebooks/welcome.ipynb
Commands starting with % are not valid python commands, they are only supported by ipython/jupyter interpreter, not by the official python interpreter.

Import statments when using Tensorflow contrib keras

I have a bunch of code written using Keras that was installed as a separate pip install and the import statements are written like from keras.models import Sequential, etc..
On a new machine, I have Tensorflow installed which now includes Keras inside the contrib directory. In order to keep the versions consistent I thought it would be best to use what's in contrib instead of installing Keras separately, however this causes some import issues.
I can import Keras using import tensorflow.contrib.keras as keras but doing something like from tensorflow.contrib.keras.models import Sequential gives ImportError: No module named models, and from keras.models import Sequential gives a similar ImportError: No module named keras.models.
Is there a simple method to get the from x.y import z statements to work? If not it means changing all the instances to use the verbose naming (ie.. m1 = keras.models.Sequential()) which isn't my preferred syntax but is do-able.
Try this with recent versions of tensorflow:
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import LSTM, TimeDistributed, Dense, ...
Try with tensorflow.contrib.keras.python.keras:
from tensorflow.contrib.keras.python.keras.models import Sequential
Unfortunately from tensorflow.contrib.keras.python.keras.models import Sequential no longer works. It looks like they are changing the interface as of version 1.4 (currently at RC0). There is a note saying the tensorflow.contrib.keras interface is deprecated and you should use tensorflow.keras but this doesn't work either without python in the line.
The following did work for me under V1.4rc0
from tensorflow.python.keras.models import Sequential
import tensorflow.python.keras
import tensorflow.contrib.keras as keras
The following did not...
import tensorflow.python.keras as keras
Hopefully this gets cleaned up a bit more before final release.

Keras: Cannot Import Name np_utils [duplicate]

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

Categories

Resources