bg_color = '#303030' # Lighter than black, as per the previous specification
text_color = 'white'
for i in range(num_images):
plt.figure(figsize=(10, 5))
plt.subplot(2, 3, 1)
plt.imshow(selected_images[i])
plt.title(f"Input Image\nGround Truth Label: {labels[np.argmax(selected_labels[i])]}\nPredicted Label: {labels[predicted_classes[i]]}", color=text_color)
plt.axis("off")
plt.gcf().set_facecolor(bg_color)
plt.subplot(2, 3, 2)
plt.imshow(selected_masks[i].squeeze(), cmap="gray")
plt.title("Ground Truth Segmentation Mask", color=text_color)
plt.axis("off")
plt.subplot(2, 3, 3)
plt.imshow(predicted_masks[i].squeeze(), cmap="gray")
plt.title("Predicted Segmentation Mask", color=text_color)
plt.axis("off")
plt.tight_layout()
plt.show()
preprocess and predict on the selected image
out = Output()
'''
def predict_image(image_path):
# Load and preprocess the image
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert BGR to RGB
img_resized = cv2.resize(img, (image_size, image_size))
img_expanded = np.expand_dims(img_resized, axis=0)
# Predict using the model
class_output, seg_output = model.predict(img_expanded)
# Get the predicted class
predicted_class_index = np.argmax(class_output)
predicted_class = labels[predicted_class_index]
# Clear the previous output
with out:
clear_output(wait=True)
# Visualize the input and segmentation output
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
axs[0].imshow(img)
axs[0].set_title("Input Image")
axs[0].axis("off")
axs[1].imshow(seg_output[0, :, :, 0], cmap='gray')
axs[1].set_title("Segmentation Output")
axs[1].axis("off")
class_probabilities = class_output[0]
x_pos = np.arange(len(labels))
axs[2].bar(x_pos, class_probabilities, align='center', alpha=0.7, color='blue')
axs[2].set_xticks(x_pos)
axs[2].set_xticklabels(labels, rotation=45, ha="right")
axs[2].set_ylabel('Probability')
axs[2].set_ylim([0, 1])
axs[2].set_title(f'Classification Output\nPredicted Class: {predicted_class}') # Increased title font size
for i, v in enumerate(class_probabilities):
axs[2].text(i, v + 0.02, f"{v:.2f}", color='black', ha='center')
plt.tight_layout()
plt.show()
'''
def predict_image(image_path):
# Load and preprocess the image
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert BGR to RGB
img_resized = cv2.resize(img, (image_size, image_size))
img_expanded = np.expand_dims(img_resized, axis=0)
# Predict using the model
class_output, seg_output = model.predict(img_expanded)
# Get the predicted class
predicted_class_index = np.argmax(class_output)
predicted_class = labels[predicted_class_index]
# Clear the previous output
with out:
clear_output(wait=True)
# Configure specific style options for lighter background
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
# Lighten background
bg_color = '#303030' # Lighter than black for contrast
fig.patch.set_facecolor(bg_color)
for ax in axs:
ax.set_facecolor(bg_color)
# Set spines color to lighter tone
ax.spines['bottom'].set_color('grey')
ax.spines['top'].set_color('grey')
ax.spines['right'].set_color('grey')
ax.spines['left'].set_color('grey')
ax.tick_params(axis='x', colors='white')
ax.tick_params(axis='y', colors='white')
axs[0].imshow(img)
axs[0].set_title("Input Image", color='white', fontweight='bold')
axs[0].axis("off")
axs[1].imshow(seg_output[0, :, :, 0], cmap='gray')
axs[1].set_title("Segmentation Output", color='white', fontweight='bold')
axs[1].axis("off")
# Adjusted plot for classification
class_probabilities = class_output[0]
x_pos = np.arange(len(labels))
bars = axs[2].bar(x_pos, class_probabilities, align='center', alpha=0.7, color='cyan')
axs[2].set_xticks(x_pos)
axs[2].set_xticklabels(labels, rotation=45, ha="right", color='white')
axs[2].set_ylabel('Probability', color='white')
axs[2].set_ylim([0, 1])
axs[2].set_title(f'Classification Output\nPredicted Class: {predicted_class}', color='white', fontweight='bold')
for i, v in enumerate(class_probabilities):
axs[2].text(i, v + 0.02, f"{v:.2f}", color='white', ha='center')
plt.tight_layout()
plt.show()
Define a callback function to handle the uploaded file
def on_upload(change):
# Get the uploaded file
uploaded_filename = next(iter(uploader.value))
uploaded_file = uploader.value[uploaded_filename]
# Save the uploaded file
with open(uploaded_filename, 'wb') as f:
f.write(uploaded_file['content'])
# Predict and visualize the image
predict_image(uploaded_filename)
Define a function to handle the button click event and clear the output
print("Number of train images:", len(X_train))
print("Number of train binary masks:", len(y_train_seg))
print("Number of validation images:", len(X_val))
print("Number of validation binary masks:", len(y_val_seg))
print("Number of test images:", len(X_test))
print("Number of test binary masks:", len(y_test_seg))
input_shape = (image_size, image_size, 3)
num_classes = len(labels)
saved_model_path = "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/model/pcbmtl_bdip.h5"
custom_objects = {"segmentation_loss": segmentation_loss}
Load model
model = load_model(saved_model_path, custom_objects=custom_objects)
Test model
test_model(model, X_test, y_test_class, y_test_seg, labels, num_images=5)
uploader = widgets.FileUpload(accept='image/*', multiple=False)
uploader.observe(on_upload, names='value')
buttons_layout = HBox([uploader, clear_button])
display(buttons_layout)
display(out)
"
The above is the Python code with Keras to do inference using the multi-task learning model, this model will take the image as input and provide one classification output and one segmentation output, this code let user to select one image and performance inference, however the predicted output always produce the wrong classification output. Check and correct these functions:"def predict_image(image_path):
# Load and preprocess the image
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert BGR to RGB
img_resized = cv2.resize(img, (image_size, image_size))
img_expanded = np.expand_dims(img_resized, axis=0)
# Predict using the model
class_output, seg_output = model.predict(img_expanded)
# Get the predicted class
predicted_class_index = np.argmax(class_output)
predicted_class = labels[predicted_class_index]
# Clear the previous output
with out:
clear_output(wait=True)
# Configure specific style options for lighter background
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
# Lighten background
bg_color = '#303030' # Lighter than black for contrast
fig.patch.set_facecolor(bg_color)
for ax in axs:
ax.set_facecolor(bg_color)
# Set spines color to lighter tone
ax.spines['bottom'].set_color('grey')
ax.spines['top'].set_color('grey')
ax.spines['right'].set_color('grey')
ax.spines['left'].set_color('grey')
ax.tick_params(axis='x', colors='white')
ax.tick_params(axis='y', colors='white')
axs[0].imshow(img)
axs[0].set_title("Input Image", color='white', fontweight='bold')
axs[0].axis("off")
axs[1].imshow(seg_output[0, :, :, 0], cmap='gray')
axs[1].set_title("Segmentation Output", color='white', fontweight='bold')
axs[1].axis("off")
# Adjusted plot for classification
class_probabilities = class_output[0]
x_pos = np.arange(len(labels))
bars = axs[2].bar(x_pos, class_probabilities, align='center', alpha=0.7, color='cyan')
axs[2].set_xticks(x_pos)
axs[2].set_xticklabels(labels, rotation=45, ha="right", color='white')
axs[2].set_ylabel('Probability', color='white')
axs[2].set_ylim([0, 1])
axs[2].set_title(f'Classification Output\nPredicted Class: {predicted_class}', color='white', fontweight='bold')
for i, v in enumerate(class_probabilities):
axs[2].text(i, v + 0.02, f"{v:.2f}", color='white', ha='center')
plt.tight_layout()
plt.show()
Define a callback function to handle the uploaded file
def on_upload(change):
# Get the uploaded file
uploaded_filename = next(iter(uploader.value))
uploaded_file = uploader.value[uploaded_filename]
# Save the uploaded file
with open(uploaded_filename, 'wb') as f:
f.write(uploaded_file['content'])
# Predict and visualize the image
predict_image(uploaded_filename)
Define a function to handle the button click event and clear the output
Your code defines a system for simultaneously performing image classification and segmentation using a shared neural network architecture, which is a form of multi-task learning. Based on the issue you're facing with incorrect classification outputs, you might be dealing with a few potential problems:
Data Preprocessing Mismatch: Ensure your training data and inference data undergo the same preprocessing steps. Any significant deviation might cause the model to perform poorly on new data. Specifically, verify that your images are correctly resized, normalized, and possibly augmented in the same way during both the training and prediction phases.
Model Training Issues: If your model is not generalizing well beyond the training set, consider revising your model architecture, regularization techniques (e.g., dropout, data augmentation), or training procedure (e.g., learning rate, batch size). Overfitting can be a concern if your model performs exceptionally well on the training data but poorly on validation/test data or new real-world examples.
Label Mismatch or Encoding Issues: Ensure that the labels used during training perfectly match those used during prediction. Label encoding (and decoding) should be consistent across the entire project. A common mistake is a discrepancy between the training labels array and the labels array used for prediction.
Evaluation on Diverse Data: Perhaps your test data or the data you use for inference significantly differ from the training data, or the model has not seen enough variation of the data. This situation can lead to poor performance. Evaluate if your model has been trained on a sufficiently diverse dataset.
Given the extensive code base you've provided, it's also essential to debug systematically:
Sanity Check on Predictions: For debugging, feed a known image from the training or validation set (where you know the expected outputs) and see if the prediction matches the expectation. This step can help you understand whether the problem lies in the model's generalization capability or if there's a mistake in how you're handling new images during inference.
Check Model Outputs Before argmax(): Inspect the raw outputs of the model (class_output before applying np.argmax()) to see the distribution of probabilities across classes. This inspection can provide insight into whether the model is entirely off or if there are close second predictions that might make sense.
Inspect Preprocessed Images: Visualize the preprocessed images (right before they are fed into the model for prediction) to ensure that they still retain meaningful visual content. A common pitfall is overly aggressive preprocessing that distorts the image beyond recognition.
Model Re-Evaluation: It may be worth re-evaluating the model using a different metric or on a different set of test data to gain additional insights into its performance. Sometimes, accuracy might not fully capture the model's predictive power, especially when the dataset is imbalanced.
Code Refinement Suggestions:
Your code is well-structured but consider modularizing preprocessing, prediction, and visualization functionalities further to make debugging and enhancements easier. Creating separate functions for preprocessing and visualization can help isolate issues and streamline the testing of new models or preprocessing strategies.
Given the complexity of debugging in a Multi-Task Learning scenario, it's also recommended to test each task separately if possible. This approach might involve temporarily isolating the classification and segmentation tasks to debug them individually, ensuring each performs as expected before integrating them again.
Lastly, ensure you're using an appropriate version of TensorFlow that's compatible with all features and functionalities you're utilizing, as TensorFlow evolves rapidly and API changes might affect model performance subtly.