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

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

Related

how to solve ''looks like you are trying to use a version of multi-backend Keras that does not support TensorFlow 2.0''

I am using tensorflow 2 version for running a sequentional model. I am not sure why it does not support tensorflow2. I also checked the same question, but it doesn't help. can anyone help me to correct the code?
from sklearn.model_selection import train_test_split
import tensorflow
import keras
from tensorflow.keras import layers
from tensorflow.keras import optimizers
from tensorflow.keras import callbacks
from tensorflow.python.keras.layers import Input, Dense, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import BatchNormalization
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D, AveragePooling2D
from keras.layers.core import Activation
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Input
from tensorflow.keras import optimizers
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras import datasets, layers, models
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import plot_model
from tensorflow.keras.models import load_model, Model
from tensorflow.keras.callbacks import EarlyStopping
model = Sequential()
model.add(Conv2D(input_shape=(32,32,4),filters=64,kernel_size=(3,3),padding="same", activation="relu"))
model.add(Conv2D(filters=64,kernel_size=(3,3),padding="same", activation="relu"))
model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2)))
model.add(Conv2D(filters=128, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=128, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2)))
model.add(Flatten())
model.add(Dense(units=1024,activation="relu"))
model.add(Dense(units=1024,activation="relu"))
model.add(Dense(units=1, activation="linear"))
#compile model
optimizer = tensorflow.keras.optimizers.Adam(learning_rate=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
model.compile(loss='mean_squared_error',
optimizer=optimizer,
metrics=['mae'])
error:
Traceback (most recent call last):
File "/appl/soft/ai/miniconda3/envs/tensorflow-2.0.0/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py", line 66, in _get_default_graph
return tf.get_default_graph()
AttributeError: module 'tensorflow' has no attribute 'get_default_graph'
During handling of the above exception, another exception occurred:
RuntimeError: It looks like you are trying to use a version of multi-backend Keras that does not support TensorFlow 2.0. We recommend using `tf.keras`, or alternatively, downgrading to TensorFlow 1.14.
I managed to run the code by editing the section for importing the libraries:
from tensorflow.python.keras.layers import Input, Dense, Flatten, Dropout, Conv2D, MaxPooling2D
from tensorflow.python.keras.models import Model
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import BatchNormalization
from tensorflow.python.keras import optimizers from tensorflow.python.keras.callbacks import EarlyStopping
import tensorflow as tf

getting error while freezing first few layers in vgg19

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

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.

No module named 'tensorflow.python.keras.engine.base_layer_v1' in python code with tensor flow keras

hi i'm doing this code in google colab and i have this error No module named 'tensorflow.python.keras.engine.base_layer_v1' in python code with tensor flow keras
i did use tensorflow.keras instead of keras since i use tensorflow v=2.1.0
and keras v=2.3.0-tf
i tried both tensorflow v=2.1.0 and v=2.2.0-rc2
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.layers import Dense, Embedding, LSTM, SpatialDropout1D
from sklearn.model_selection import train_test_split
MAX_NB_WORDS=50000
EMBEDDING_DIM=100
model = tf.keras.Sequential()
model.add(Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_length=train.shape[1]))
model.add(SpatialDropout1D(0.2))
model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(13, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
epochs = 5
batch_size = 64
history = model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.1, callbacks=[EarlyStopping(monitor='val_loss', patience=3, min_delta=0.0001)])
accr = model.evaluate(x_test,y_test)
print('Test set\n Loss: {:0.3f}\n Accuracy: {:0.3f}'.format(accr[0],accr[1]))
I had similar error while working with gaborNet-CNN. I tired following and it worked in my case.
import numpy as np
from matplotlib import pyplot as plt
from tqdm import tqdm
import keras
from keras import backend as K
from keras import activations, initializers, regularizers, constraints, metrics
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, Model
from keras.layers import (Dense, Dropout, Activation, Flatten, Reshape, Layer,
BatchNormalization, LocallyConnected2D,
ZeroPadding2D, Conv2D, MaxPooling2D, Conv2DTranspose,
GaussianNoise, UpSampling2D, Input)
from keras.utils import conv_utils, multi_gpu_model
from keras.layers import Lambda
from keras.engine import Layer, InputSpec
from keras.legacy import interfaces
in my case, I just reinstall keras and it works

Categories