In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "how to solve error reports when reading keras and tensorflow models at the same time". The editor shows you the operation process through actual cases. The operation method is simple, fast and practical. I hope this article "how to solve errors while reading keras and tensorflow models at the same time" can help you solve the problem.
It is normal for model.save to use a mixture of tensorflow and keras, but it is wrong to report an error in load_model. Here mark
The error is: TypeError: tuple indices must be integers, not list
Baidu again and again after no results, on Google found a similar problem. But a pair of bird words don't know anything (after translation, it is found to be Russian). Then Google translated and found a solution. Therefore, post the original question article as a warning.
The original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense # in the training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense # training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense # training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, the original training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, the original training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, the original training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense # training code, the original training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, the original training code, the original training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, the original training code, the original training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense # training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, the original training code, the original training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense # training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense # training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, the original training code, the original training code from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense # training code, training, training Img_height, 3) in the first half of the year, img_height, 3) in the middle of the week, there was an increase in the number of cases in which there was no change in the number of cases. (img_height, 3). There was an increase in the number of cases in which the batch _ size= was used in the first place. The batch _ test_samples = 25 model = Sequential (model.add) (Conv2D (32, (7), padding= (same, input_shape=input_shape)) (BatchNormalization () (model.add) (Activation 'tanh') (MaxPooling2D pool_size= (10)) (64) (model.add) (Activation' tanh') (MaxPooling2D pool_size= (10)) (64 Conv2D) (5) 5), padding= "same") model.add (BatchNormalization ()) model.add (Activation ('tanh')) model.add (MaxPooling2D (pool_size= (10,10)) model.add (Flatten ()) model.add (Dense) model.add (Activation (' relu') model.add (Dropout (0.5) model.add (Dense (10, activation='softmax')) model.compile (loss='categorical_crossentropy', optimizer= "Nadam") Metrics= ['accuracy']) print (model.summary ()) datagen = ImageDataGenerator (rescale=1. / 255) train_generator = datagen.flow_from_directory (train_dir, target_size= (img_width, img_height), batch_size=batch_size, class_mode='categorical') val_generator = datagen.flow_from_directory (val_dir, target_size= (img_width, img_height), batch_size=batch_size Class_mode='categorical') test_generator = datagen.flow_from_directory (test_dir, target_size= (img_width, img_height), batch_size=batch_size, class_mode='categorical') model.fit_generator (train_generator, steps_per_epoch=nb_train_samples / / batch_size, epochs=epochs, validation_data=val_generator Validation_steps=nb_validation_samples / / batch_size) print ('model.save / / batch_size) model.save ("grib.h6") print ("thank you") The model is loaded with from tensorflow.python.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.python.keras.models import Sequentialfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, Densefrom keras.models import load_model print ("grib.h6") model = load_model ("grib.h6") model. Error
/ usr/bin/python3.5 / home/disk2/py/neroset/do.py
/ home/mama/.local/lib/python3.5/site-packages/h6py/__init__.py:36: 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`.
From. _ conv import register_converters as _ register_converters
Using TensorFlow backend.
I don't know. I don't know.
Traceback (most recent call last):
File "/ home/disk2/py/neroset/do.py", line 13, in
Model = load_model ("grib.h6")
File "/ usr/local/lib/python3.5/dist-packages/keras/models.py", line 243, in load_model
Model = model_from_config (model_config, custom_objects=custom_objects)
File "/ usr/local/lib/python3.5/dist-packages/keras/models.py", line 317, in model_from_config
Return layer_module.deserialize (config, custom_objects=custom_objects)
File "/ usr/local/lib/python3.5/dist-packages/keras/layers/__init__.py", line 55, in deserialize
Printable_module_name='layer')
File "/ usr/local/lib/python3.5/dist-packages/keras/utils/generic_utils.py", line 144, in deserialize_keras_object
List (custom_objects.items ()
File "/ usr/local/lib/python3.5/dist-packages/keras/models.py", line 1350, in from_config
Model.add (layer)
File "/ usr/local/lib/python3.5/dist-packages/keras/models.py", line 492, in add
Output_tensor = layer (self.outputs [0])
File "/ usr/local/lib/python3.5/dist-packages/keras/engine/topology.py", line 590, in _ _ call__
Self.build (input_shapes [0])
File "/ usr/local/lib/python3.5/dist-packages/keras/layers/normalization.py", line 92, in build
Dim = input_ shape [self.axis]
TypeError: tuple indices must be integers or slices, not list
Process finished with exit code 1
Explanation of fighting race
I'm sorry, BatchNormalization, I'm sorry, I'm sorry, I'm sorry. I'm sorry, I don't know, I don't know, I Don't tell me what the mistake is. I found that saving keras and normalizing tensorflow don't work together; you just need to change the import string.)
Emphasize the text
Keras.preprocessing.image import ImageDataGeneratorkeras.models import Sequentialkeras.layers import Conv2D, MaxPooling2D, BatchNormalizationkeras.layers import Activation, Dropout, Flatten, Dense
# # perfect solution
Add: be careful when reading keras and tensorflow models at the same time
In the project, we first read a keras model to get the model input size, and then load the pb model after keras to tensorflow for prediction.
Error report:
Attempting to use uninitialized value batch_normalization_14/moving_mean
Visit the forum, there are suggestions plus initialization:
Sess.run (tf.global_variables_initializer ())
However, this will cause all the model parameters to become initialization data. Cannot use prediction model parameters.
Finally, it is found that the loading of the keras model can be removed.
Guess reason: keras model and tensorflow model read pits at the same time
Import cv2import numpy as npfrom keras.models import load_modelfrom utils.datasets import get_labelsfrom utils.preprocessor import preprocess_inputimport timeimport osimport tensorflow as tffrom tensorflow.python.platform import gfile os.environ ["CUDA_VISIBLE_DEVICES"] = "- 1" emotion_labels = get_labels ('fer2013') emotion_target_size = (64 fer2013' 64) # emotion_model_path ='. / models/emotion_model.hdf5'#emotion_classifier = load_model (emotion_model_path) # emotion_target_size = emotion_classifier. Input_shape [1:3] path ='/ mnt/nas/cv_data/emotion/test'filelist = os.listdir (path) total_num = len (filelist) timeall = 0n = 0 sess = tf.Session () # sess.run (tf.global_variables_initializer ()) with gfile.FastGFile (". / trans_model/emotion_mode.pb" 'rb') as f: graph_def = tf.GraphDef () graph_def.ParseFromString (f.read ()) sess.graph.as_default () tf.import_graph_def (graph_def Name='') pred = sess.graph.get_tensor_by_name ("predictions/Softmax:0") # # img## for item in filelist: if (item = = '.DS_Store') | (item = =' Thumbs.db'): continue Src = os.path.join (os.path.abspath (path)) Item) bgr_image = cv2.imread (src) gray_image = cv2.cvtColor (bgr_image, cv2.COLOR_BGR2GRAY) gray_face = gray_image try: gray_face = cv2.resize (gray_face, (emotion_target_size)) except: continue gray_face = preprocess_input (gray_face, True) gray_face = np.expand_dims (gray_face 0) gray_face = np.expand_dims (gray_face,-1) input = sess.graph.get_tensor_by_name ('input_1:0') res = sess.run (pred, {input: gray_face}) print ("src:" Src) emotion_probability = np.max (res [0]) emotion_label_arg = np.argmax (res [0]) emotion_text = emotion_ labels [emotion _ label_arg] print ("predict:", res [0], ", prob:", emotion_probability, ", label:", emotion_label_arg, ", text:" Emotion_text) this is the end of the introduction to "how to solve the problem of reading errors from keras and tensorflow models at the same time" Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.