no metrics are built error while training a model using cnn python

the error which is being thrown WARNING:absl:Compiled the loaded model, but the compiled metrics have yet to be built. model.compile_metrics will be empty until you train or evaluate the model.
i tried chatgpt and google but didn’t find a solution
i saw a solution saying try dummy prediction so it’ll force the model to build metrics but i couldn’t figure it out
the code is as follows

import streamlit as st
import os
import numpy as np
from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Input
from tensorflow.keras import Model
from PIL import Image

# Define paths to training and testing data
train_data_path = 'C:\Users\kiree\OneDrive\Desktop\engineering\underwater-image-enhancement-main\underwater-image-enhancement-main\abc'
test_data_path = 'C:\Users\kiree\OneDrive\Desktop\engineering\underwater-image-enhancement-main\underwater-image-enhancement-main\abd'

# Function to build and train the CNN model
def train_model():
    st.write("Training the model...")
    # Set parameters
    image_height, image_width = 200, 200
    num_channels = 3
    input_size = (image_height, image_width, num_channels)
    batch_size = 32
    num_epochs = 50

    # Create data generators for training and validation data
    train_datagen = ImageDataGenerator(rescale=1./255, validation_split=0.3)

    train_generator = train_datagen.flow_from_directory(
        train_data_path,
        target_size=(image_height, image_width),
        batch_size=batch_size,
        class_mode='categorical',
        subset='training')

    validation_generator = train_datagen.flow_from_directory(
        train_data_path,
        target_size=(image_height, image_width),
        batch_size=batch_size,
        class_mode='categorical',
        subset='validation')

    # Build the CNN model
    inputs = Input(shape=input_size)
    x = Conv2D(8, (3, 3), padding='same', activation='relu')(inputs)
    x = MaxPooling2D(pool_size=(2, 2))(x)
    x = Conv2D(16, (3, 3), padding='same', activation='relu')(x)
    x = MaxPooling2D(pool_size=(2, 2))(x)
    x = Conv2D(32, (2, 2), padding='same', activation='relu')(x)
    x = MaxPooling2D(pool_size=(2, 2))(x)
    x = Conv2D(64, (3, 3), padding='same', activation='relu')(x)
    x = MaxPooling2D(pool_size=(2, 2))(x)
    x = Conv2D(128, (3, 3), padding='same', activation='relu')(x)
    x = MaxPooling2D(pool_size=(2, 2))(x)
    x = Flatten()(x)
    outputs = Dense(4, activation='softmax')(x)

    model = Model(inputs=inputs, outputs=outputs)

    # Compile the model
    model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])

    # Train the model
    model.fit(
        train_generator,
        steps_per_epoch=train_generator.samples // batch_size,
        epochs=num_epochs,
        validation_data=validation_generator,
        validation_steps=validation_generator.samples // batch_size)

    # Save the trained model
    model.save('trained_model.h5')
    st.write("Model trained and saved successfully!")

# Function to load and test the model on a single image
@st.cache_resource
def load_trained_model():
    model_path = 'trained_model.h5'
    if os.path.exists(model_path):
        model = load_model(model_path)
        model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])
        
        # Perform a dummy prediction to build metrics
        dummy_data = np.random.random((1, 200, 200, 3)).astype(np.float32)
        model.predict(dummy_data)
        
        return model
    return None

def test_model(model):
    st.write("Testing the model...")

    # Allow user to select an image for testing
    st.write("Select an image for testing:")
    uploaded_file = st.file_uploader("Upload an image...", type=["jpg", "jpeg", "png"])
    if uploaded_file is not None:
        image = Image.open(uploaded_file)
        st.image(image, caption='Uploaded Image', use_column_width=True)

        # Load and preprocess the test image
        image = image.resize((200, 200))  # Resize using PIL
        image = img_to_array(image) / 255.0
        image = np.expand_dims(image, axis=0)

        # Predict the class probabilities
        class_names = ['class_1', 'class_2', 'class_3', 'class_4']
        probabilities = model.predict(image)[0]

        # Display the predicted class and probability
        for i in range(len(class_names)):
            st.write(f"{class_names[i]}: {probabilities[i]*100:.2f}%")

# Streamlit GUI
st.title("CNN Model Training and Testing")

# Buttons for training and testing
train_button = st.button("Train Model")
test_button = st.button("Test Model")

# Perform actions based on button clicks
if train_button:
    train_model()

if test_button:
    model = load_trained_model()
    if model:
        test_model(model)
    else:
        st.write("Model file does not exist.")

New contributor

Helium is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật