tensorflow와keras 혼용 구덩이 해결

9331 단어 tensorflowkeras
tensorflow와keras를 혼용하는 것이 모델입니다.save는 정상이지만load_모델 때 잘못 보고했어요. 여기서 마크해 주세요.
오류: TypeError: tuple indices must be integers, not list
다시 한 번 바이두는 결과가 없었고 구글에 올라가 비슷한 문제를 찾았다.그런데 한 쌍의 새문인데 뭘 몰라요.나중에 구글이 번역해서 해결 방법을 찾았어요.그러므로 원시적인 문제 문장을 붙여 경고하다

원훈련 코드


from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalization
from tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense
 
#Каталог с данными для обучения
train_dir = 'train'
# Каталог с данными для проверки
val_dir = 'val'
# Каталог с данными для тестирования
test_dir = 'val'
 
# Размеры изображения
img_width, img_height = 800, 800
# Размерность тензора на основе изображения для входных данных в нейронную сеть
# backend Tensorflow, channels_last
input_shape = (img_width, img_height, 3)
# Количество эпох
epochs = 1
# Размер мини-выборки
batch_size = 4
# Количество изображений для обучения
nb_train_samples = 300
# Количество изображений для проверки
nb_validation_samples = 25
# Количество изображений для тестирования
nb_test_samples = 25
 
model = Sequential()
 
model.add(Conv2D(32, (7, 7), padding="same", input_shape=input_shape))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(MaxPooling2D(pool_size=(10, 10)))
 
model.add(Conv2D(64, (5, 5), padding="same"))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(MaxPooling2D(pool_size=(10, 10)))
 
model.add(Flatten())
model.add(Dense(512))
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("grib.h5")
print("Сохранение завершено!")


모델 로드


from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Conv2D, MaxPooling2D, BatchNormalization
from tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense
from keras.models import load_model
 
print("Загрузка сети")
model = load_model("grib.h5")
print("Загрузка завершена!")

잘못 보고하다


/usr/bin/python3.5/home/disk2/py/neroset/do.py
/home/mama/.local/lib/python3.5/site-packages/h5py/__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.
Загрузка сети
Traceback (most recent call last):
File "/home/disk2/py/neroset/do.py", line 13, in
model = load_model("grib.h5")
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

전투 종족 해석


убераю BatchNormalization всё работает хорошо. Не подскажите в чём ошибка?Выяснил что сохранение keras и нормализация tensorflow не работают вместе нужно просто изменить строку импорта.(번역문: BatchNormalization을 정리하는 것은 정상입니다. 오류가 무엇인지 알려주지 마십시오. keras를 저장하고 규범화된 tensorflow와 함께 작업할 수 없습니다. 가져오는 문자열만 변경하면 됩니다.)
강조 텍스트 강조 텍스트

keras.preprocessing.image import ImageDataGenerator
keras.models import Sequential
keras.layers import Conv2D, MaxPooling2D, BatchNormalization
keras.layers import Activation, Dropout, Flatten, Dense
## 완벽한 해결
## 원문 링크 첨부
https://qa-help.ru/questions/keras-batchnormalization
추가:keras와tensorflow모델을 동시에 읽는 것은 신중해야 한다
프로젝트에서 먼저keras모델을 읽고 모델 입력size를 가져온 다음에keras가tensorflow로 전환된 pb모델을 불러와서 예측합니다.

오류 보고:


Attempting to use uninitialized value batch_normalization_14/moving_mean
포럼을 둘러보고 초기화를 권장합니다.

sess.run(tf.global_variables_initializer())
그러나 이렇게 되면 모델 매개 변수가 모두 초기화 데이터로 바뀔 수 있다.예측 모델 매개변수를 사용할 수 없습니다.
마지막으로keras모델의 마운트를 제거하면 됩니다.

추측 원인:keras모델과tensorflow모델이 동시에 갱도를 읽는다


import cv2
import numpy as np
from keras.models import load_model
from utils.datasets import get_labels
from utils.preprocessor import preprocess_input
import time
import os
import tensorflow as tf
from tensorflow.python.platform import gfile
 
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
 
emotion_labels = get_labels('fer2013')
emotion_target_size = (64,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 = 0
n = 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)
이상의 개인적인 경험으로 여러분께 참고가 되었으면 좋겠습니다. 또한 많은 응원 부탁드립니다.

좋은 웹페이지 즐겨찾기