ImportError: cannot import name "backend" - python

Below the written code,
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from keras.layers import backend as k
batch_size = 128
num_classes = 10
epochs = 12
and below the issue,
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-d1183f2cea73> in <module>
8 from tensorflow.keras.layers import Conv2D
9 from tensorflow.keras.layers import MaxPooling2D
---> 10 from keras.layers import backend as k
11
12
ImportError: cannot import name 'backend'
Need help to solve this issue
Note: I am using Python 3.6.0.

You can use the keras backend lib
import keras.backend as k
or directelly from tensorflow
from tensorflow.keras import backend as k

Try uninstalling Tensor Flow and keras and removing their directories in site-packages then reinstalling them.

Related

TypeError: 'module' object is not callable when using Keras

I've been having lots of imports issues when it comes to TensorFlow and Keras and now I stumbled upon this error:
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17880/703187089.py in <module>
75 #model.compile(loss="categorical_crossentropy",optimizers.rmsprop(lr=0.0001),metrics=["accuracy"])
76
---> 77 model.compile(optimizers.rmsprop_v2(lr=0.0001, decay=1e-6),loss="categorical_crossentropy",metrics=["accuracy"])
78
79 STEP_SIZE_TRAIN=train_generator.n//train_generator.batch_size
TypeError: 'module' object is not callable
These are the imports:
from tensorflow import keras
from keras_preprocessing.image import ImageDataGenerator
from keras.layers import Dense, Activation, Flatten, Dropout, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras import regularizers, optimizers
from keras.models import Sequential
from keras import optimizers
from keras.optimizers import rmsprop_v2, adadelta_v2
kerns.optimizers.rmsprop_v2 and kerns.optimizers.adadelta_v2 are the modules. You want:
from keras.optimizers import RMSprop, Adadelta
And:
optimizers.RMSprop(lr=0.0001, decay=1e-6) (or just RMSprop(lr=0.0001, decay=1e-6)) instead of optimizers.rmsprop_v2(lr=0.0001, decay=1e-6)

ImportError: cannot import name 'LayerNormalization' from 'tensorflow.python.keras.layers.normalization' mismatch versions fix?

Have not posted much on stackoverflow and new to tensorflow. I followed this tutorial on how to install tensorflow for use on jupyter notebooks (https://github.com/jeffheaton/t81_558_deep_learning/blob/master/install/tensorflow-install-mac-jan-2021.ipynb).
When testing the environment I get Python 3.8.11, Tensor Flow 2.5.1 and Keras 2.5.0
Code I am trying to run:
import pandas as pd
import numpy as np
import tensorflow as tf
import re
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklearn.metrics import median_absolute_error as mae
from sklearn.metrics import mean_squared_error as mse
from sklearn.metrics import accuracy_score as acc
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras import initializers
from keras.layers import Dropout, Activation, Embedding, Convolution1D, MaxPooling1D, Input, Dense, Merge, \
BatchNormalization, Flatten, Reshape, Concatenate
from keras.layers.recurrent import LSTM, GRU
from keras.callbacks import Callback, ModelCheckpoint, EarlyStopping, ReduceLROnPlateau
from keras.models import Model
from keras.optimizers import Adam, SGD, RMSprop
from keras import regularizers
The error I get is
ImportError Traceback (most recent call last)
<ipython-input-4-3a64b96c6d78> in <module>
10 import matplotlib.pyplot as plt
11
---> 12 from keras.models import Sequential
13 from keras import initializers
14 from keras.layers import Dropout, Activation, Embedding, Convolution1D, MaxPooling1D, Input, Dense, Merge, \
/opt/miniconda3/envs/tensorflow/lib/python3.8/site-packages/keras/__init__.py in <module>
23
24 # See b/110718070#comment18 for more details about this import.
---> 25 from keras import models
26
27 from keras.engine.input_layer import Input
/opt/miniconda3/envs/tensorflow/lib/python3.8/site-packages/keras/models.py in <module>
18 import tensorflow.compat.v2 as tf
19 from keras import backend
---> 20 from keras import metrics as metrics_module
21 from keras import optimizer_v1
22 from keras.engine import functional
/opt/miniconda3/envs/tensorflow/lib/python3.8/site-packages/keras/metrics.py in <module>
25
26 import numpy as np
---> 27 from keras import activations
28 from keras import backend
29 from keras.engine import base_layer
/opt/miniconda3/envs/tensorflow/lib/python3.8/site-packages/keras/activations.py in <module>
18
19 from keras import backend
---> 20 from keras.layers import advanced_activations
21 from keras.utils.generic_utils import deserialize_keras_object
22 from keras.utils.generic_utils import serialize_keras_object
/opt/miniconda3/envs/tensorflow/lib/python3.8/site-packages/keras/layers/__init__.py in <module>
146
147 # Normalization layers.
--> 148 from keras.layers.normalization import LayerNormalization
149 from keras.layers.normalization_v2 import SyncBatchNormalization
150
ImportError: cannot import name 'LayerNormalization' from 'keras.layers.normalization' (/opt/miniconda3/envs/tensorflow/lib/python3.8/site-packages/keras/layers/normalization/__init__.py)
I am aware that there have been posts about mismatch versions being the reason for this not working but not sure how I would go about independently changing the versions for tensorflow etc.. to make this work.
Try again with Tensorflow 2.5 and Keras 2.4.3 .
providing gist for reference

KeyError: 'input_1_ib-0' when i save my autoencoder model

I get the error when save my Autoencoder model.
This is my code. I have searched about this error but no solution help me solve this problem.
The error photo:
.
Probably it is due to mixing keras and tesnorflow libraries. Use from tensorflow.keras.optimizers import Adam and from tensorflow.keras.models import Model, load_model instead of keras ones.
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Conv2D, Input, BatchNormalization, MaxPooling2D, UpSampling2D, Dropout, BatchNormalization
#from keras.models import Model, load_model
from tensorflow.keras.models import Model, load_model # tensorflow.keras
from tensorflow.keras.callbacks import ModelCheckpoint
from google.colab.patches import cv2_imshow
from tensorflow.keras.preprocessing.image import ImageDataGenerator
#from keras.optimizers import Adam
from tensorflow.keras.optimizers import Adam # tensorflow.keras

Attribute Error: module 'no tf2 attribute' (Running TF1 code with TF2 with all compatibility)

tf.compat.v1.disable_eager_execution()
tf.disable_v2_behavior()
from keras.models import Sequential
from keras.layers import Dense, Activation
This is the code block where I am encountering such an issue:
import keras
from keras.datasets import cifar10
from keras.models import Sequential, Model
from keras.optimizers import Adam
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.applications.resnet50 import ResNet50
from keras.callbacks import EarlyStopping
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
keras.__version__
The output is:
AttributeError Traceback (most recent call last)
"ipython-input-3-005a85517711" in "module" <br/>
----> 1 import keras
2 from keras.datasets import cifar10
3 from keras.models import Sequential, Model
4 from keras.optimizers import Adam
5 from keras.layers import Dense, Dropout, Activation, Flatten
~\.conda\envs\weapon\lib\site-packages\keras\__init__.py in "module" <br/>
18 from . import callbacks
19 from . import constraints
---> 20 from . import initializers
21 from . import metrics
22 from . import models
~\.conda\envs\weapon\lib\site-packages\keras\initializers\__init__.py in "module" <br/>
122 # from ALL_OBJECTS. We make no guarantees as to whether these objects will
123 # using their correct version.
--> 124 populate_deserializable_objects()
125 globals().update(LOCAL.ALL_OBJECTS)
126
~\.conda\envs\weapon\lib\site-packages\keras\initializers\__init__.py in populate_deserializable_objects() <br/>
47
48 LOCAL.ALL_OBJECTS = {}
---> 49 LOCAL.GENERATED_WITH_V2 = tf.__internal__.tf2.enabled()
50
51 # Compatibility aliases (need to exist in both V1 and V2).
AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'tf2'
From comments
Issue has been resolved by adding tf.disable_v2_behavior() at the
begining (paraphrased from Lescurel)
I would recommend one more solution, instead of import keras, you should try from tensorflow import keras or import tensorflow as tf and use tf.keras as shown below
from tensorflow import keras
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.callbacks import EarlyStopping
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
For more information you can refer this solution.

Is there a shorter way to import classes of a submodule?

Currently, I do this:
import tensorflow as tf
keras = tf.contrib.keras
Sequential = keras.models.Sequential
Dense = keras.layers.Dense
Dropout = keras.layers.Dropout
Flatten = keras.layers.Flatten
Conv2D = keras.layers.Conv2D
MaxPooling2D = keras.layers.MaxPooling2D
I would like to do something like this:
import tensorflow as tf
keras = tf.contrib.keras
from tf.contrib.keras import (Sequential, Dense, Dropout, Flatten,
Conv2D, MaxPooling2D)
but when I try this I get
ImportError: No module named tf.contrib.keras
Is there a shorter way than the first code block to import those classes?
Other tries
>>> from tensorflow.contrib.keras import (Sequential, Dense, Dropout, Flatten)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name Sequential
Nr 2
>>> import tensorflow
>>> from tensorflow.contrib.keras.models import Sequential
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named models
>>> tensorflow.contrib.keras.models.Sequential
<class 'tensorflow.contrib.keras.python.keras.models.Sequential'>
First, you need to import using the actual name of the tensorflow module, not the tf alias you used for it:
Second, the package structure of tensorflow.contrib.keras is kind of weird. The names
tensorflow.contrib.keras.models
tensorflow.contrib.keras.layers
are actually aliases for the more deeply nested modules
tensorflow.contrib.keras.api.keras.models
tensorflow.contrib.keras.api.keras.layers
and the way these aliases are created doesn't allow you to use from imports to import their contents. You can use the "real" names directly:
from tensorflow.contrib.keras.api.keras.models import Sequential
from tensorflow.contrib.keras.api.keras.layers import (
Dense, Dropout, Flatten, Conv2D, MaxPooling2D)
(There's even more aliasing here - the tensorflow.contrib.keras.api.keras.* modules pull most of their contents from tensorflow.contrib.keras.python.keras - but we don't need to worry about that.)
Try this:
from tensorflow.contrib.keras.models import Sequential
from tensorflow.contrib.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D

Categories