-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
78 lines (62 loc) · 2.49 KB
/
utils.py
File metadata and controls
78 lines (62 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import torch
import torchvision.transforms as transforms
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import os
import streamlit as st
import pandas as pd
# Load and preprocess the image
def preprocess_image(image_path, transform):
image = Image.open(image_path).convert("RGB")
return image, transform(image).unsqueeze(0)
def extract_label_from_path(image_path):
# Extract the parent folder name as the label
label_name = os.path.basename(os.path.dirname(image_path))
return label_name
# Predict using the model
def predict(model, image_tensor, device):
model.eval()
with torch.no_grad():
image_tensor = image_tensor.to(device)
outputs = model(image_tensor)
# converts the raw data from our model(logits) into a probability distribution across classes
# uses sotftmax function
probabilities = torch.nn.functional.softmax(outputs, dim=1)
# converts probabilities tensor into a numpy array
return probabilities.cpu().numpy().flatten()
# display results
def visualize_predictions(original_image, probabilities, class_names, true_label = None):
fig, axarr = plt.subplots(1, 2, figsize=(14, 7))
# Display image
axarr[0].imshow(original_image)
axarr[0].axis("off")
# Add the true label to the image title
if true_label is not None:
axarr[0].set_title(f"True Label: {true_label}", fontsize=14)
# Display predictions
axarr[1].barh(class_names, probabilities)
axarr[1].set_xlabel("Probability")
axarr[1].set_title("Class Predictions")
axarr[1].set_xlim(0, 1)
plt.tight_layout()
plt.show()
# defining prediction functions for streamlit frontend visual which are slightly different
def preprocess_image_st(image, transform):
image = image.convert("RGB") # Ensure it's in RGB format
image_tensor = transform(image).unsqueeze(0) # Apply transformations and add batch dimension
return image_tensor
def visualize_predictions_st(probabilities, class_names, true_label=None):
# Display true label if available
if true_label is not None:
st.write(f"True Label: {true_label}")
# Display predictions as a bar chart
prediction_data = {
"Class Names": list(class_names.values()),
"Probabilities": probabilities
}
df = pd.DataFrame(prediction_data)
st.bar_chart(df.set_index("Class Names")["Probabilities"])
# Display a detailed table of predictions
st.write("Class Probabilities:")
st.dataframe(df)