0

При попытке повторного использования сохраненной модели нейронной сети получаю ошибку :

Traceback (most recent call last): File "D:\VillCNN1円\run.py", line 23, in model = pickle.load(open(filename, 'rb')) File "C:\Users\Professional\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\saving\pickle_utils.py", line 48, in deserialize_model_from_bytecode model = save_module.load_model(temp_dir) File "C:\Users\Professional\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler raise e.with_traceback(filtered_tb) from None File "C:\Users\Professional\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\saved_model\load.py", line 977, in load_internal raise FileNotFoundError( FileNotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for ram://16197d23-ea7a-44df-b95a-83b5ec02c2a9/variables/variables You may be trying to load on a different device from the computational device. Consider setting the experimental_io_device option in tf.saved_model.LoadOptions to the io_device such as '/job:localhost'.

Сохранение модели:

pickle.dump(label_binarizer,open('plant_disease_label_transform.pkl', 'wb'))
n_classes = len(label_binarizer.classes_)
#save the model to disk
# Dump pickle file of the model
print("[INFO] Сохранение модели...")
filename = 'plant_disease_classification_model.pkl'
pickle.dump(model, open(filename, 'wb'))
print("[INFO] Модель сохранена")
# Dump pickle file of the labels
print("[INFO] Сохранение меток...")
filename2 = 'plant_disease_label_transform.pkl'
image_labels = pickle.load(open(filename2, 'rb'))
print("[INFO] Модель сохранена")

Повторное использование:

# Load model
filename = r'D:\VillCNN1円\plant_disease_classification_model.pkl'
model = pickle.load(open(filename, 'rb'))
# Load labels
filename = r'D:\VillCNN1円\plant_disease_label_transform.pkl'
image_labels = pickle.load(open(filename, 'rb'))
# Dimension of resized image
DEFAULT_IMAGE_SIZE = tuple((256, 256))
def convert_image_to_array(image_dir):
 try:
 image = cv2.imread(image_dir)
 if image is not None:
 image = cv2.resize(image, DEFAULT_IMAGE_SIZE) 
 return img_to_array(image)
 else:
 return np.array([])
 except Exception as e:
 print(f"Error : {e}")
 return None
def predict_disease(image_path):
 image_array = convert_image_to_array(image_path)
 np_image = np.array(image_array, dtype=np.float16) / 225.0
 np_image = np.expand_dims(np_image,0)
 plt.imshow(plt.imread(image_path))
 result = model.predict(np_image)
 print((image_labels.classes_[result][0]))
 
predict_disease(r'D:\PlantVillage\val\Corn_(maize)___Northern_Leaf_Blight028159円fc-995e-455a-8d60-6d377580a898___RS_NLB 4023.JPG')

Библиотеки:

import numpy as np
import pickle
import cv2
import os
import matplotlib.pyplot as plt
from os import listdir
from sklearn.preprocessing import LabelBinarizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Activation, Flatten, Dropout, Dense
from tensorflow.keras import backend as K
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import img_to_array
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.model_selection import train_test_split

Версия python 3.10, tenserflow 2.7, OC Windows. Путь к файлам прописан верный.

задан 3 февр. 2022 в 6:52
5
  • "You may be trying to load on a different device from the computational device" - ну оно пишет, что GPU другое (или настройки у него другие) при загрузке, а должно быть всё в точности такое же, как при сохранении модели. Commented 3 февр. 2022 в 6:58
  • @CrazyElf , это я понимаю. Но как исправить? Запускаю на одном устройстве. Как может, что-либо измениться ? Commented 3 февр. 2022 в 7:02
  • Почему вы не используете методы tensorflow / Keras для сохранения и загрузки модели? Commented 3 февр. 2022 в 7:22
  • @MaxU , не могу найти пример с повторным использованием модели. Знаю только как сохранить и загрузить модель. Commented 3 февр. 2022 в 7:36
  • Также заметил, что при использовании функции predict_disease, получаю ошибку: print((image_labels.classes_[result][0])) IndexError: arrays used as indices must be of integer (or boolean) type Commented 3 февр. 2022 в 7:38

0

Знаете кого-то, кто может ответить? Поделитесь ссылкой на этот вопрос по почте, через Твиттер или Facebook.

Ваш ответ

Черновик сохранён
Черновик удалён

Зарегистрируйтесь или войдите

Регистрация через Google
Регистрация через почту

Отправить без регистрации

Необходима, но никому не показывается

Отправить без регистрации

Необходима, но никому не показывается

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Начните задавать вопросы и получать на них ответы

Найдите ответ на свой вопрос, задав его.

Задать вопрос

Изучите связанные вопросы

Посмотрите похожие вопросы с этими метками.