Problems importing keras - python

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

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

Importing Adam and ImageDataGenerator on google colab failed

I'm implementing a UNet neural network but I'm having some issues while importing libraries. I found a solution for a couple of them, but I still have a problem with these two imports:
from tensorflow.keras.optimizers import Adam
#Import "tensorflow.keras.optimizers" could not be resolved(reportMissingImports)
from tensorflow.keras.preprocessing.image import ImageDataGenerator
#Import "tensorflow.keras.preprocessing.image" could not be resolved(reportMissingImports)
I've already imported:
import tensorflow as tf
from tensorflow import keras
from keras import layers
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
import numpy as np
Any idea? I've tried to change but it still raises an error.

ImportError: cannot import name '__version__' from partially initialized module 'keras' (most likely due to a circular import)

I have imported the following libraries for my machine learning project but have problem when I try to run my model in the command prompt...
from tensorflow.python.keras import Model
from tensorflow.python.keras.layers import Layer, Input, Conv2D, MaxPooling2D, Conv2DTranspose, concatenate, Lambda
from tensorflow.python.keras.initializers import TruncatedNormal
from keras.optimizers import Adam
from tensorflow.python.keras.callbacks import ModelCheckpoint, LearningRateScheduler, CSVLogger, Callback
from tensorflow.python.keras.models import load_model
from tensorflow.python.keras.utils import Sequence
This is the error message which I get when trying to run the model in the command prompt.
ImportError: cannot import name '__version__' from partially initialized module 'keras' (most likely due to a circular import) (C:\Users\gurun\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\__init__.py)
It is always recommend to use tensorflow.keras.* instead of tensorflow.python.*.
This is because anything under tensorflow.python.* is private, intended for development only, rather than for public use.
import tensorflow as tf
print(tf.__version__)
from tensorflow.keras import Model
from tensorflow.keras.layers import Layer, Input, Conv2D, MaxPooling2D, Conv2DTranspose, concatenate, Lambda
from tensorflow.keras.initializers import TruncatedNormal
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler, CSVLogger, Callback
from tensorflow.keras.models import load_model
from tensorflow.keras.utils import Sequence
Output:
2.5.0
You should be consistent and import keras only from one source and the recommended way, as #TFer2 said, is from tensorflow.keras . Your editor maybe can complain that tensorflow.keras cannot be resolved but usually that warning can be ignored and all works fine. If not try to uninstall keras and reinstall it accordingly to the version of your tensorflow installation.

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 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.

Categories

Resources