Skip to content

Commit 801512c

Browse files
authored
Merge pull request #13 from DerikVo/streamlit
created a streamlit app to predict classes and created a page to show…
2 parents ba65e3a + 8df1223 commit 801512c

File tree

1 file changed

+137
-0
lines changed

1 file changed

+137
-0
lines changed

Streamlit/app.py

+137
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
import streamlit as st
2+
import numpy as np
3+
import os
4+
import pandas as pd
5+
6+
from tensorflow import keras
7+
from tensorflow.keras.models import load_model
8+
from PIL import Image, ImageOps
9+
from tensorflow.keras.preprocessing.image import ImageDataGenerator
10+
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, accuracy_score
11+
12+
import time
13+
import sys
14+
sys.path.append('../modules/')
15+
import model as m
16+
17+
_ = """
18+
All comments will be assigned to the underscore variable so they dont get rendered in streamlit
19+
as mention in this discussion form:
20+
https://discuss.streamlit.io/t/any-way-to-prevent-commented-out-code-via-triple-quotes-to-be-displayed-in-streamlit/8821/6
21+
22+
This code takes heavy influece from a previous project.
23+
https://github.com/DerikVo/NN_hackathon
24+
25+
There were many changes to the code to get it to work with this data set,
26+
but the general structure remains the same
27+
"""
28+
29+
30+
# function to load and cache pretrained model
31+
@st.cache_resource
32+
def load_model_stream():
33+
path = "../Models/CNN_base.h5"
34+
model = load_model(path)
35+
return model
36+
37+
# function to preprocess an image and get a prediction from the model
38+
def get_prediction(model, image):
39+
open_image = Image.open(image)
40+
resized_image = open_image.resize((256, 256))
41+
grayscale_image = resized_image.convert('L')
42+
img = np.expand_dims(grayscale_image, axis=0)
43+
predicted_prob = model.predict(img)[0]
44+
classes = ['glioma', 'meningioma', 'notumor', 'pituitary']
45+
probabilities = dict(zip(classes, predicted_prob))
46+
sorted_probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True)
47+
return sorted_probabilities
48+
def upload_mode():
49+
50+
st.header("Classification Mode")
51+
st.subheader("Upload an Image to Make a Prediction")
52+
53+
# upload an image
54+
uploaded_image = st.file_uploader("Upload your own image to test the model:", type=['jpg', 'jpeg', 'png'])
55+
56+
# when an image is uploaded, display image and run inference
57+
if uploaded_image is not None:
58+
st.image(uploaded_image)
59+
st.text(get_prediction(classifier, uploaded_image))
60+
61+
st.set_page_config(layout="wide")
62+
63+
# load model
64+
classifier = load_model_stream()
65+
66+
st.title("Brain Tumor Classifier")
67+
68+
st.write('Use the sidebar to select a page to view.')
69+
70+
page = st.sidebar.selectbox('Select Mode',['Upload Image','Model Evaluation'])
71+
72+
_ ='''
73+
This portion of the code was taken from the moduels function py file
74+
this code also brows ideas from previous projects and intergrates it into a function.
75+
Espically the model evaluation notebook.
76+
'''
77+
def model_Evaluation(path):
78+
'''
79+
Calculate accuracy, precision, recall, and F1 score.
80+
'''
81+
model = keras.models.load_model(path)
82+
testing_folder_path = '../Images/Testing'
83+
datagen = ImageDataGenerator()
84+
test_ds = datagen.flow_from_directory(
85+
testing_folder_path,
86+
target_size=(256, 256),
87+
color_mode='grayscale',
88+
class_mode='categorical',
89+
seed=42,
90+
shuffle=False
91+
)
92+
true_classes = test_ds.classes
93+
y_pred = model.predict(test_ds)
94+
predicted_classes = np.argmax(y_pred, axis=1)
95+
accuracy = accuracy_score(true_classes, predicted_classes)
96+
precision = precision_score(true_classes, predicted_classes, average='weighted')
97+
recall = recall_score(true_classes, predicted_classes, average='weighted')
98+
f1 = f1_score(true_classes, predicted_classes, average='weighted')
99+
data = {'Accuracy': round(accuracy,4), 'Precision': round(precision,4), 'Recall': round(recall,4), 'F1 Score': round(f1,4)}
100+
return data
101+
_ ='''
102+
This code utilized the streamlit documentation to implement columns
103+
and displaying images. In the future I want users to be able to upload their model and have it
104+
automatically be evaluated by the app.
105+
106+
The links are as folows:
107+
https://docs.streamlit.io/library/api-reference/layout/st.columns
108+
https://docs.streamlit.io/library/api-reference/media/st.image
109+
'''
110+
111+
if page == 'Model Evaluation':
112+
path = ('../Models/CNN_base.h5')
113+
data = model_Evaluation(path)
114+
115+
reg_path = ('../Models/CNN_regularization.h5')
116+
reg_data = model_Evaluation(path)
117+
st.write("CNN base Metrics:\n")
118+
119+
col1, col2 = st.columns(2)
120+
with col1:
121+
for metric_name, metric_value in data.items():
122+
st.write(f"{metric_name}: {metric_value}")
123+
with col2:
124+
st.image("../Created_images/Neural Network confusion matrix.png", caption = "No regularization")
125+
#add white space
126+
st.write("")
127+
st.write("")
128+
st.write("\n CNN regularization Metrics:")
129+
col3, col4 = st.columns(2)
130+
with col3:
131+
for metric_name, metric_value in reg_data.items():
132+
st.write(f"{metric_name}: {metric_value}")
133+
with col4:
134+
st.image("../Created_images/Neural Network with regularization confusion matrix.png", caption = "With regularization")
135+
136+
else:
137+
upload_mode()

0 commit comments

Comments
 (0)