При попытке повторного использования сохраненной модели нейронной сети получаю ошибку :
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_deviceoption intf.saved_model.LoadOptionsto 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. Путь к файлам прописан верный.
-
"You may be trying to load on a different device from the computational device" - ну оно пишет, что GPU другое (или настройки у него другие) при загрузке, а должно быть всё в точности такое же, как при сохранении модели.CrazyElf– CrazyElf2022年02月03日 06:58:30 +00:00Commented 3 февр. 2022 в 6:58
-
@CrazyElf , это я понимаю. Но как исправить? Запускаю на одном устройстве. Как может, что-либо измениться ?Artur Haiduk– Artur Haiduk2022年02月03日 07:02:59 +00:00Commented 3 февр. 2022 в 7:02
-
Почему вы не используете методы tensorflow / Keras для сохранения и загрузки модели?MaxU - stand with Ukraine– MaxU - stand with Ukraine2022年02月03日 07:22:20 +00:00Commented 3 февр. 2022 в 7:22
-
@MaxU , не могу найти пример с повторным использованием модели. Знаю только как сохранить и загрузить модель.Artur Haiduk– Artur Haiduk2022年02月03日 07:36:17 +00:00Commented 3 февр. 2022 в 7:36
-
Также заметил, что при использовании функции predict_disease, получаю ошибку: print((image_labels.classes_[result][0])) IndexError: arrays used as indices must be of integer (or boolean) typeArtur Haiduk– Artur Haiduk2022年02月03日 07:38:54 +00:00Commented 3 февр. 2022 в 7:38
Знаете кого-то, кто может ответить? Поделитесь ссылкой на этот вопрос по почте, через Твиттер или Facebook.
Начните задавать вопросы и получать на них ответы
Найдите ответ на свой вопрос, задав его.
Задать вопросИзучите связанные вопросы
Посмотрите похожие вопросы с этими метками.