8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

将 tensorflow 模型转换为 tensorflow.js 模型时出现 input_shape 错误

Jeel Vankhede 2月前

22 0

我想在 Web 应用程序中使用我的深度学习 CNN 算法,并且我使用终端 tensorflowjs_conv 中的这条命令将我的 tensorflow 模型 emotion_model.h5 转换为 tensorflow.js 模型...

我想在 Web 应用程序中使用我的深度学习 CNN 算法,并且我使用终端中的此命令将我的 tensorflow 模型 emotion_model.h5 转换为 tensorflow.js 模型

tensorflowjs_converter --input_format keras models/emotion_model.h5 models/tfjs_model 然而,当我在 Web 应用程序中使用 tfjs_model 对情绪进行分类时,控制台上出现以下错误:

“未捕获(在承诺中)错误:应向 InputLayer 传递 batchInputShape 或 inputShape”

请注意,我在模型训练期间有一个明确定义的 input_shape 参数,并且我的 tensorflow 模型运行良好。以下是我的模型层的摘要。

emotion_model = tf.keras.Sequential()

emotion_model.add(tf.keras.layers.Input(shape=(48, 48, 1)))
emotion_model.add(tf.keras.layers.Conv2D(32, kernel_size=(3,3), activation = 'relu'))
emotion_model.add(tf.keras.layers.Conv2D(64, kernel_size=(3,3), activation = 'relu'))
emotion_model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2)))
emotion_model.add(tf.keras.layers.Dropout(0.25))

emotion_model.add(tf.keras.layers.Conv2D(128, kernel_size=(3,3), activation = 'relu'))
emotion_model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2)))
emotion_model.add(tf.keras.layers.Conv2D(128, kernel_size=(3,3), activation = 'relu'))
emotion_model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2)))
emotion_model.add(tf.keras.layers.Dropout(0.25))

emotion_model.add(tf.keras.layers.Flatten())
emotion_model.add(tf.keras.layers.Dense(1024, activation='relu'))
emotion_model.add(tf.keras.layers.Dropout(0.5))
emotion_model.add(tf.keras.layers.Dense(7, activation='relu'))

emotion_model.compile(loss='categorical_crossentropy', optimizer= keras.optimizers.Adam(learning_rate= 0.0001, weight_decay=1e-6), metrics=['accuracy'])

我目前正在使用 tensorflow==16.0.2。我在网上找到了类似的查询,在切换到旧版本的 tensorflow(tensorflow==15.0.1)后,它们的错误得到了解决。我尝试卸载 tensorflow 16.0.2 并安装 tensorflow 15.0.1,但我的查询仍然没有得到解决。我不想在 tensorflow.js 中训练我的整个模型。我该怎么做才能解决这个错误?

帖子版权声明 1、本帖标题:将 tensorflow 模型转换为 tensorflow.js 模型时出现 input_shape 错误
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由Jeel Vankhede在本站《tensorflow》版块原创发布, 转载请注明出处!
最新回复 (0)
  • 我正在开发一个 Web 应用程序,该应用程序使用 AWS Rekognition 根据上传的图像预测健身器材。图像上传和预测工作正常,但我无法显示预测结果...

    我正在开发一个 Web 应用程序,该应用程序使用 AWS Rekognition 根据上传的图像预测健身器材。图像上传和预测工作正常,但我无法在单独的 HTML 页面上显示预测结果。

    homepage.html:允许用户上传图像并将其发送到 AWS Lambda 函数进行预测。results.html:应显示预测结果。

    即使预测结果正确记录在浏览器的控制台中,results.html 页面也会显示“未找到设备”而不是实际预测。

    homepage.html 的代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Gym Equipment Exercise Finder</title>
        <style>
            /* Your existing CSS here */
        </style>
    </head>
    <body>
        <header>
            <h1 style="font-family: Times New Roman, serif">Workout Wizard</h1>
            <nav>
                <a href="homepage.html">Home</a>
                <a href="products.html">Products</a>
                <a href="contact.html">Contact</a>
            </nav>
        </header>
        <section class="hero">
            <div class="hero-content">
                <h1>Find Your Workout!</h1>
                <p>Upload a photo of gym equipment and get exercises you can do with it.</p>
            </div>
        </section>
        <section class="upload-section">
            <div class="upload-container">
                <input type="file" id="imageInput" accept="image/*">
                <label for="imageInput">
                    <img src="camera.png" alt="Upload Icon">
                    <p>Drop an image here</p>
                    <p>or</p>
                    <p>click to browse</p>
                </label>
            </div>
            <button onclick="uploadImage()">Submit</button>
        </section>
        <footer>
            &copy; 2024 Workout Wizard. All rights reserved.
        </footer>
        <script>
            function uploadImage() {
                const imageInput = document.getElementById('imageInput');
                if (!imageInput || !imageInput.files || imageInput.files.length === 0) {
                    alert("Please choose an image file.");
                    return;
                }
    
                const selectedFile = imageInput.files[0];
                const reader = new FileReader();
                reader.onload = function (event) {
                    const base64EncodedImage = event.target.result.split(',')[1];
                    fetch('https://t6mn1ryxc4.execute-api.us-east-1.amazonaws.com/Gym_Equipments/predict', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ image: base64EncodedImage }),
                    })
                    .then(response => response.json())
                    .then(data => {
                        console.log('Lambda Response:', data);
                        localStorage.setItem('predictedEquipment', data);
                        console.log('Stored in localStorage:', localStorage.getItem('predictedEquipment'));
                        window.location.href = "results.html";
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('Error uploading image.');
                    });
                };
                reader.readAsDataURL(selectedFile);
            }
        </script>
    </body>
    </html>
    

    results.html 的代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Results</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 0;
                padding: 0;
                background-color: #f3f4f6;
            }
            header {
                background-color: #6200a9; 
                padding: 20px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                color: white;
            }
            header img {
                height: 50px;
            }
            nav {
                display: flex;
                align-items: center;
            }
            nav a {
                color: white;
                text-decoration: none;
                margin: 0 10px;
                font-size: 18px;
            }
            nav a:hover {
                text-decoration: underline;
            }
            .result-section {
                padding: 20px;
                text-align: center;
                background-color: #fff;
                border-radius: 10px;
                margin: 20px;
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            }
            footer {
                background-color: #6200a9;
                color: #ccc;
                padding: 20px;
                text-align: center;
            }
            footer a {
                color: #ff7f50;
                text-decoration: none;
            }
            footer a:hover {
                text-decoration: underline;
            }
        </style>
    </head>
    <body>
        <header>
            <h1>Workout Wizard</h1>
            <nav>
                <a href="homepage.html">Home</a>
                <a href="products.html">Products</a>
                <a href="contact.html">Contact</a>
            </nav>
        </header>
        <section class="result-section">
            <h1>Prediction Result</h1>
            <p id="result">Loading...</p>
        </section>
        <footer>
            &copy; 2024 Workout Wizard. All rights reserved. | <a href="privacy.html">Privacy Policy</a> | <a href="termsandconditions.html">Terms of Service</a>
        </footer>
        <script>
            window.onload = function() {
                // Retrieve the prediction result from localStorage
                const prediction = localStorage.getItem('predictedEquipment');
                if (prediction) {
                    document.getElementById('result').innerText = prediction;
                } else {
                    document.getElementById('result').innerText = 'No equipment predicted';
                }
            };
        </script>
    </body>
    </html>
    

    lambda 函数:

    import json
    import boto3
     
    bucket_name = "gymhtml"
     
    from botocore.exceptions import ClientError
    import base64
    from io import BytesIO
    from datetime import datetime
     
    s3 = boto3.client('s3')
     
    def saveToS3(image_binary):
        # Get the current timestamp
        timestamp = datetime.utcnow().strftime("%Y%m%d%H%M%S%f")
        # Generate a filename with the timestamp
        filename = f'uploads/{timestamp}.jpg'
        print("filename: ", filename)
        try:
            # need to save the image as image/jpeg content type
            s3.put_object(Bucket=bucket_name, Key=filename, Body=image_binary, ContentType='image/jpeg')
            # Log success message
            print(f"Image saved to S3: s3://{bucket_name}/{filename}")
            return filename
        except ClientError as e:
            # Log the error
            print("Error:", str(e))
            return None
     
    def predictImage(photo):
        rekognition = boto3.client('rekognition')
        model = "arn:aws:rekognition:us-east-1:414942631188:project/gymequipment/version/gymequipment.2024-07-31T18.03.52/1722420232922"
        min_confidence = 60
     
        #Call DetectCustomLabels
        response = rekognition.detect_custom_labels(Image={'S3Object': {'Bucket': bucket_name, 'Name': photo}},
            MinConfidence=min_confidence,
            ProjectVersionArn=model)
        print(response['CustomLabels'])
        result = json.dumps(response['CustomLabels'][0])
        #print to the log for debugging purposes
        print(response['CustomLabels'][0]["Name"])
        return response['CustomLabels'][0]["Name"]
     
    def lambda_handler(event, context):
        # TODO implement
        msg = "INVALID REQUEST"
        print( event );
        #if event['httpMethod'] == 'POST':
            # Extract the base64-encoded image and filename from the request body
            #request_body = json.loads(event['body'])
        request_body = json.loads(event['body'])
        image_base64 = request_body['image'];
        # Decode the base64-encoded image
        image_binary = base64.b64decode(image_base64)
        #save image to S3
        imagefilename = saveToS3(image_binary)
        #msg = 'Hello from Lambda!'
        #msg = predictImage(imagefilename)
        msg = predictImage(imagefilename)
        return {
            'statusCode': 200,
            'headers': {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*'
            },
            'body': json.dumps(msg)
        }
    
  • 您向我们展示了很多代码。您能把事情简化成其他人可以尝试并自己重现的东西吗?另外,您提到它显示“未找到设备”,但似乎没有任何代码会生成此消息。有关提出好问题的提示,请参阅:

返回
作者最近主题: