У меня проблемы с загрузкой модели машинного обучения на моем Django-сайте

Я построил модель классификации изображений, которая относит их к одному из трех классов: огурец, цуккини или ни то, ни другое.

Теперь я хочу развернуть эту модель на сайте Django, но у меня возникли некоторые проблемы. Когда я выполняю команду python manage.py runserver, в терминале появляется следующее сообщение:

Watching for file changes with StatReloader
Performing system checks...

2024-07-10 01:26:11.875397: I tensorflow/core/util/port.cc:113] oneDNN custom operations are 
on. You may see slightly different numerical results due to floating-point round-off errors 
from different computation orders. To turn them off, set the environment variable 
`TF_ENABLE_ONEDNN_OPTS=0`.
2024-07-10 01:26:12.947630: I tensorflow/core/util/port.cc:113] oneDNN custom operations are 
on. You may see slightly different numerical results due to floating-point round-off errors 
from different computation orders. To turn them off, set the environment variable 
`TF_ENABLE_ONEDNN_OPTS=0`.
C:\path\to\virtual\environment\virtual_environment_name\Lib\site-
packages\keras\src\layers\preprocessing\tf_data_layer.py:19: UserWarning: Do not pass an 
`input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an 
`Input(shape)` object as the first layer in the model instead.
super().__init__(**kwargs)
2024-07-10 01:26:14.748468: I tensorflow/core/platform/cpu_feature_guard.cc:210] This 
TensorFlow binary is optimized to use available CPU instructions in performance-critical 
operations.
To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with 
the appropriate compiler flags.

Для меня это не похоже на сообщения об ошибках, но локальный хостинг сайта не работает, так что, похоже, что-то не так.

Файл views.py, в котором я пытаюсь загрузить модель, выглядит следующим образом:

from django.shortcuts import render
from django.conf import settings
from .forms import ImageUploadForm
import tensorflow as tf
from tensorflow.keras.preprocessing import image as keras_image
import numpy as np
import os

# Create your views here.

# cucumber_zucchini_classifier/views.py

# Load the trained model
model_path = 'C:\path\to\model_directory\image_classifier_model.h5'

# Load the trained model
model = tf.keras.models.load_model(model_path)

# Define the labels
LABELS = ['cucumber', 'zucchini', 'neither']

def preprocess_image(img):
    img = keras_image.img_to_array(img)
    img = np.expand_dims(img, axis=0)
    img = img / 255.0  # Normalize the image
    return img

def classify_image(img):
    img = preprocess_image(img)
    predictions = model.predict(img)
    predicted_class = LABELS[np.argmax(predictions)]
    return predicted_class

def image_upload_view(request):
    classification = None
    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            img = form.cleaned_data['image']
            img = keras_image.load_img(img, target_size=(180, 180))  # Resize to the input size of model
            classification = classify_image(img)
    else:
        form = ImageUploadForm()
    return render(request, 'cucumber_zucchini_classifier/upload.html', {'form': form, 'classification': classification})

Есть (по крайней мере) две вещи, которые я не понимаю и не знаю, могут ли они быть связаны с этим. Это:

  1. если я указываю точный путь к файлу модели в переменной model_path, то получается ситуация, описанная выше, но если я указываю только имя модели, т.е.:

    model_path = 'image_classifier_model.h5'

Я получаю ошибку, говорящую мне, что нет такого файла или каталога:

FileNotFoundError: [Errno 2] Unable to synchronously open file (unable
to open file: name = 'image_classifier_model.h5', errno = 2, error
message = 'No such file or directory', flags = 0, o_flags = 0)

И это при том, что файл модели находится в том же каталоге, что и файл views.py.

  1. Похоже, что существует проблема с импортом из tensorflow.keras.preprocessing (строка 5 в файле views.py), однако нет проблемы с импортом tensorflow (строка 4 в файле views.py): highlighting import issue with tensorflow.keras.preprocessing

Для контекста, когда я загружаю модель в jupyter notebook, она работает нормально, и я могу использовать ее для классификации изображений, как и ожидалось:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing import image

# Load the saved model
loaded_model = tf.keras.models.load_model('image_classifier_model.h5')


# Function to preprocess the image
def preprocess_image(img_path, img_height, img_width):
    img = image.load_img(img_path, target_size=(img_height, img_width))
    img_array = image.img_to_array(img)
    img_array = np.expand_dims(img_array, axis=0)  # Create batch axis
    #img_array = img_array / 255.0  # Normalize the image to [0, 1] range
    return img_array

def preprocess_image(img_path, img_height, img_width):
    # Load the image from the file path
    img = image.load_img(img_path, target_size=(img_height, img_width))

    # Convert the image to a NumPy array
    img_array = image.img_to_array(img)

    # Expand the dimensions to match the input shape for the model (batch_size, height, width, channels)
    img_array = np.expand_dims(img_array, axis=0)

    return img_array

def predict_and_display(images_paths, model, img_height, img_width, class_names):
    fig, axes = plt.subplots(3, 3, figsize=(12, 12))

    for i, img_path in enumerate(images_paths):
        img_array = preprocess_image(img_path, img_height, img_width)
        predictions = model.predict(img_array)
        predicted_class = np.argmax(predictions, axis=1)[0]
        predicted_class_name = class_names[predicted_class]
    
        img = image.load_img(img_path, target_size=(img_height, img_width))
    
        ax = axes[i//3, i%3]
        ax.imshow(img)
        ax.set_title(f'Predicted: {predicted_class_name}')
        ax.axis('off')

    plt.tight_layout()
    plt.show()

# Examples
img_paths = [
    r'path\to\image1.jpg',
    r'path\to\image2.jpg',
    r'path\to\image3.PNG',
    r'path\to\image4.png',
    r'path\to\image5.jpg',
    r'path\to\image6.png',
    r'path\to\image7.jpg',
    r'path\to\image8.jpg',
    r'path\to\image9.jpg'
]

img_height = 180
img_width = 180
class_names = ['cucumber', 'zucchini', 'neither']

predict_and_display(img_paths, final_model, img_height, img_width, class_names)

Запустив это, я получил следующее (с тестовыми образами, которые я использовал, конечно), так что в этой среде, похоже, нет никаких проблем:

outpu of running the shown code in a jupyter notebook

Кто-нибудь знает, почему я застреваю после этой серии сообщений и сайт никогда не запускается (локально), когда я выполняю команду python manage.py runserver?

Любая помощь будет оценена по достоинству. Спасибо :)

Вернуться на верх