getting error while freezing first few layers in vgg19 - python

import tensorflow as tf
from tensorflow.keras import Sequential,Model
from tensorflow.keras.layers import
Dense,Dropout,Flatten,BatchNormalization,Conv2D,MaxPool2D
from tensorflow.keras.applications.vgg19 import VGG19,preprocess_input
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import numpy as np
#defining the image size
num_classes=7
img_width=224
img_height=224
batch_size_training=32
batch_size_validation=32
data_generator=ImageDataGenerator(preprocessing_function=preprocess_inpu)
Fetching the image from directory:
train_generator=data_generator.flow_from_directory
('C:/Users/pauls/Desktop/Python Rev1/Dataset/Train/',target_size=
(224,224),batch_size=20,class_mode='categorical')
test_generator=data_generator.flow_from_directory
('C:/Users/pauls/Desktop/Python Rev1/Dataset/Test/',target_size=
(224,224),batch_size=20,class_mode='categorical')

Related

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.

ImportError: cannot import name "backend"

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.

cannot import name 'imagenet_utils' from 'tensorflow.keras.applications'

i have the following python imports with in Jupyter Notebook.
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import categorical_crossentropy
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import Model
from tensorflow.keras.applications import imagenet_utils
from sklearn.metrics import confusion_matrix
import itertools
import os
import shutil
import random
import matplotlib.pyplot as plt
%matplotlib inline
But i keep getting the following error
ImportError: cannot import name 'imagenet_utils' from 'tensorflow.keras.applications' (C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\api_v2\keras\applications_init_.py)
when i search for **cannot import name 'imagenet_utils' from 'tensorflow.keras.applications' **in google i dont get much helpful information.
Has anyone come across this at all?
change
from tensorflow.keras.applications import imagenet_utils
to
from keras.applications import imagenet_utils
i managed to solve my issue.
first i ran the following to update all modules.
conda update --all
Then i used 'from keras.applications import imagenet_utils'
instead of '#from tensorflow.keras import imagenet_utils'

Categories