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.