部分初始化的模块“keras.src”没有属性“utils”(很可能是由于循环导入)

问题描述 投票:0回答:1

AttributeError:部分初始化的模块“keras.src”没有属性“utils”(很可能是由于循环导入)

这是我的导入文件

  • 从flask导入Flask,render_template,request,jsonify
  • 从 keras.models 导入 load_model
  • 从 PIL 导入 Image、ImageOps
  • 将 numpy 导入为 np
from flask import Flask, render_template, request, jsonify
from keras.models import load_model
from PIL import Image, ImageOps
import numpy as np

app = Flask(__name__)

# Load the model and labels
model = load_model('/Users/Pratik/PycharmProjects/SIG_Project/keras_model.h55', compile=False)
class_names = open("/Users/Pratik/PycharmProjects/SIG_Project/labels.txt", "r").readlines()

# Set the confidence threshold
confidence_threshold = 0.2


@app.route('/')
def index():
    return '''
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Image Classifier</title>
    </head>
    <body>
        <h1>Image Classifier</h1>
        <form id="upload-form" enctype="multipart/form-data">
            <input type="file" name="file" accept="image/*">
            <button type="button" onclick="predict()">Predict</button>
        </form>
        <div id="result"></div>

        <script>
            function predict() {
                var form = document.getElementById('upload-form');
                var formData = new FormData(form);

                fetch('/predict', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    var resultDiv = document.getElementById('result');
                    resultDiv.innerHTML = '';

                    data.forEach(prediction => {
                        var classDiv = document.createElement('div');
                        classDiv.innerHTML = `<p>Class: ${prediction.class}</p><p>Confidence Score: ${prediction.confidence.toFixed(8)}</p>`;
                        resultDiv.appendChild(classDiv);
                    });
                })
                .catch(error => console.error('Error:', error));
            }
        </script>
    </body>
    </html>
    '''


@app.route('/predict', methods=['POST'])
def predict():
    # Get image from frontend
    file = request.files['file']

    # Preprocess the image
    image = Image.open(file).convert("RGB")
    size = (224, 224)
    image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)
    image_array = np.asarray(image)
    normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
    data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
    data[0] = normalized_image_array

    # Predict
    prediction = model.predict(data)

    # Prepare response
    response = []
    for i in range(len(class_names)):
        class_name = class_names[i].strip()
        confidence_score = prediction[0][i]

        if confidence_score > confidence_threshold:
            response.append({
                'class': class_name[2:],
                'confidence': float(confidence_score)
            })

    return jsonify(response)


if __name__ == '__main__':
    app.run(debug=True)

#我正在 jupyter 中运行此代码

python python-3.x python-2.7 tensorflow keras
1个回答
0
投票

您可以发布错误回溯吗?本来会添加评论而不是答案,但我没有足够的学分。新帐户。

© www.soinside.com 2019 - 2024. All rights reserved.