amariayudha commited on
Commit
1f80ded
·
verified ·
1 Parent(s): f3525fb

Upload 3 files

Browse files
Files changed (2) hide show
  1. eda.py +0 -12
  2. prediction.py +134 -134
eda.py CHANGED
@@ -9,10 +9,6 @@ import numpy as np
9
 
10
  @st.cache_data
11
  def load_data():
12
- # Load your dataset here
13
- # For example:
14
- # data = pd.read_csv('your_dataset.csv')
15
- # Return dummy data for now
16
  return pd.DataFrame({
17
  'Class': ['Plastic', 'Metal', 'Paper', 'Miscellaneous Trash', 'Cardboard', 'Vegetation', 'Glass', 'Food Organics', 'Textile Trash'],
18
  'Number of Images': [921, 790, 500, 495, 461, 436, 420, 411, 318]
@@ -38,21 +34,13 @@ def run():
38
  st.write("This chart shows the distribution of images across different waste categories. "
39
  "Plastic and Metal categories have significantly more images, which could lead to bias in the model.")
40
 
41
- # Add more EDA visualizations and insights here
42
- # For example:
43
- # - Sample images from each category
44
- # - Image size distribution
45
- # - Color histograms
46
- # - etc.
47
 
48
  st.subheader("Sample Images")
49
  st.write("Here are sample images from each waste category:")
50
- # Add code to display sample images here
51
 
52
  st.subheader("Image Size Distribution")
53
  st.write("All images in the dataset have a resolution of 524x524 pixels.")
54
 
55
- # Add more EDA components as needed
56
 
57
  if __name__ == "__main__":
58
  run()
 
9
 
10
  @st.cache_data
11
  def load_data():
 
 
 
 
12
  return pd.DataFrame({
13
  'Class': ['Plastic', 'Metal', 'Paper', 'Miscellaneous Trash', 'Cardboard', 'Vegetation', 'Glass', 'Food Organics', 'Textile Trash'],
14
  'Number of Images': [921, 790, 500, 495, 461, 436, 420, 411, 318]
 
34
  st.write("This chart shows the distribution of images across different waste categories. "
35
  "Plastic and Metal categories have significantly more images, which could lead to bias in the model.")
36
 
 
 
 
 
 
 
37
 
38
  st.subheader("Sample Images")
39
  st.write("Here are sample images from each waste category:")
 
40
 
41
  st.subheader("Image Size Distribution")
42
  st.write("All images in the dataset have a resolution of 524x524 pixels.")
43
 
 
44
 
45
  if __name__ == "__main__":
46
  run()
prediction.py CHANGED
@@ -1,134 +1,134 @@
1
- import streamlit as st
2
- import numpy as np
3
- from PIL import Image
4
- import plotly.graph_objects as go
5
- import tensorflow as tf
6
- import time
7
- import os
8
-
9
- # Load your trained model
10
- @st.cache_resource
11
- def load_model():
12
- return tf.keras.models.load_model('transfer_learning_model.h5')
13
-
14
- def preprocess_image(image):
15
- img = image.resize((299, 299))
16
- img_array = np.array(img) / 255.0
17
- img_array = np.expand_dims(img_array, axis=0)
18
- return img, img_array
19
-
20
- def predict(image):
21
- model = load_model()
22
- _, processed_image = preprocess_image(image)
23
- prediction = model.predict(processed_image)
24
- class_names = ['Cardboard', 'Food Organics', 'Glass', 'Metal', 'Miscellaneous Trash', 'Paper', 'Plastic', 'Textile Trash', 'Vegetation']
25
- return {class_names[i]: float(prediction[0][i]) for i in range(len(class_names))}
26
-
27
- def run():
28
- st.title('🔍 Waste Classification Prediction')
29
-
30
- # Example images
31
- example_images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg']
32
- example_path = '.' # Set the path to the current directory
33
-
34
- st.subheader("Choose an example image or upload your own:")
35
-
36
- # Initialize session state for the selected image
37
- if 'selected_image' not in st.session_state:
38
- st.session_state.selected_image = None
39
-
40
- # Create columns for example images
41
- cols = st.columns(4)
42
- for i, img_name in enumerate(example_images):
43
- with cols[i % 4]:
44
- img_path = os.path.join(example_path, img_name)
45
-
46
- # Display the preview image under the button
47
- st.image(img_path, width=100, caption=f'Example {i+1}')
48
-
49
- # Create the button for each example
50
- if st.button(f"Example {i+1}", key=f"example_{i}"):
51
- st.session_state.selected_image = img_path
52
-
53
- uploaded_file = st.file_uploader("Or upload your own image", type=["jpg", "jpeg", "png"])
54
-
55
- # Use session state to store the selected or uploaded image
56
- if uploaded_file is not None:
57
- st.session_state.selected_image = uploaded_file
58
-
59
- image = None
60
- if st.session_state.selected_image is not None:
61
- if isinstance(st.session_state.selected_image, str): # Example image case
62
- image = Image.open(st.session_state.selected_image).convert('RGB')
63
- else: # Uploaded image case
64
- image = Image.open(st.session_state.selected_image).convert('RGB')
65
-
66
- if image:
67
- # Create two columns for images
68
- col1, col2 = st.columns(2)
69
-
70
- # Display original image in the left column
71
- with col1:
72
- st.subheader("Selected Image")
73
- st.image(image, caption='Selected Image', use_column_width=True)
74
-
75
- # Add a button to start prediction
76
- if st.button("Start Prediction"):
77
- # Progress and status indicators
78
- progress_bar = st.progress(0)
79
- status_text = st.empty()
80
-
81
- # Preprocess the image
82
- status_text.text('Preprocessing image...')
83
- resized_image, _ = preprocess_image(image)
84
- progress_bar.progress(33)
85
- time.sleep(0.5) # Simulate processing time
86
-
87
- # Display resized image in the right column
88
- with col2:
89
- st.subheader("Resized Image (299x299 for Model)")
90
- st.image(resized_image, caption='Resized Image for Prediction (299x299)', use_column_width=True)
91
-
92
- # Make prediction
93
- status_text.text('Making prediction...')
94
- prediction = predict(image)
95
- progress_bar.progress(66)
96
- time.sleep(0.5) # Simulate processing time
97
-
98
- # Analyze results
99
- status_text.text('Analyzing results...')
100
- predicted_class = max(prediction, key=prediction.get)
101
- confidence = prediction[predicted_class]
102
- progress_bar.progress(100)
103
- time.sleep(0.5) # Simulate processing time
104
-
105
- # Clear the status text and progress bar
106
- status_text.empty()
107
- progress_bar.empty()
108
-
109
- # Display prediction results under the images
110
- st.subheader("Prediction Results")
111
- st.write(f"Predicted waste type: **{predicted_class}**")
112
- st.write(f"Confidence: {confidence:.2%}")
113
-
114
- # Display vertical bar chart of probabilities using Plotly
115
- fig = go.Figure(data=[go.Bar(
116
- x=list(prediction.keys()),
117
- y=list(prediction.values()),
118
- marker=dict(
119
- color=list(prediction.values()),
120
- colorscale='Viridis',
121
- colorbar=dict(title='Probability')
122
- )
123
- )])
124
- fig.update_layout(
125
- title='Prediction Probabilities',
126
- xaxis_title='Waste Type',
127
- yaxis_title='Probability',
128
- height=500,
129
- width=700
130
- )
131
- st.plotly_chart(fig)
132
-
133
- if __name__ == "__main__":
134
- run()
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ from PIL import Image
4
+ import plotly.graph_objects as go
5
+ import tensorflow as tf
6
+ import time
7
+ import os
8
+
9
+ # Load your trained model
10
+ @st.cache_resource
11
+ def load_model():
12
+ return tf.keras.models.load_model('transfer_learning_model.h5')
13
+
14
+ def preprocess_image(image):
15
+ img = image.resize((299, 299))
16
+ img_array = np.array(img) / 255.0
17
+ img_array = np.expand_dims(img_array, axis=0)
18
+ return img, img_array
19
+
20
+ def predict(image):
21
+ model = load_model()
22
+ _, processed_image = preprocess_image(image)
23
+ prediction = model.predict(processed_image)
24
+ class_names = ['Cardboard', 'Food Organics', 'Glass', 'Metal', 'Miscellaneous Trash', 'Paper', 'Plastic', 'Textile Trash', 'Vegetation']
25
+ return {class_names[i]: float(prediction[0][i]) for i in range(len(class_names))}
26
+
27
+ def run():
28
+ st.title('🔍 Waste Classification Prediction')
29
+
30
+ # Example images
31
+ example_images = ['cig_package.jpg', 'stella.jpg', 'water_bottle.jpg', 'textile_shoes.jpg', 'organic_eggs.jpg', 'men_metalic_pose.jpg', 'normal_men.jpg','uno.jpg']
32
+ example_path = '.\\visualization' # Set the path
33
+
34
+ st.subheader("Choose an example image or upload your own:")
35
+
36
+ # Initialize session state for the selected image
37
+ if 'selected_image' not in st.session_state:
38
+ st.session_state.selected_image = None
39
+
40
+ # Create columns for example images
41
+ cols = st.columns(4)
42
+ for i, img_name in enumerate(example_images):
43
+ with cols[i % 4]:
44
+ img_path = os.path.join(example_path, img_name)
45
+
46
+ # Display the preview image under the button
47
+ st.image(img_path, width=100, caption=f'Example {i+1}')
48
+
49
+ # Create the button for each example
50
+ if st.button(f"Example {i+1}", key=f"example_{i}"):
51
+ st.session_state.selected_image = img_path
52
+
53
+ uploaded_file = st.file_uploader("Or upload your own image", type=["jpg", "jpeg", "png"])
54
+
55
+ # Use session state to store the selected or uploaded image
56
+ if uploaded_file is not None:
57
+ st.session_state.selected_image = uploaded_file
58
+
59
+ image = None
60
+ if st.session_state.selected_image is not None:
61
+ if isinstance(st.session_state.selected_image, str): # Example image case
62
+ image = Image.open(st.session_state.selected_image).convert('RGB')
63
+ else: # Uploaded image case
64
+ image = Image.open(st.session_state.selected_image).convert('RGB')
65
+
66
+ if image:
67
+ # Create two columns for images
68
+ col1, col2 = st.columns(2)
69
+
70
+ # Display original image in the left column
71
+ with col1:
72
+ st.subheader("Selected Image")
73
+ st.image(image, caption='Selected Image', use_column_width=True)
74
+
75
+ # Add a button to start prediction
76
+ if st.button("Start Prediction"):
77
+ # Progress and status indicators
78
+ progress_bar = st.progress(0)
79
+ status_text = st.empty()
80
+
81
+ # Preprocess the image
82
+ status_text.text('Preprocessing image...')
83
+ resized_image, _ = preprocess_image(image)
84
+ progress_bar.progress(33)
85
+ time.sleep(0.5) # Simulate processing time
86
+
87
+ # Display resized image in the right column
88
+ with col2:
89
+ st.subheader("Resized Image (299x299 for Model)")
90
+ st.image(resized_image, caption='Resized Image for Prediction (299x299)', use_column_width=True)
91
+
92
+ # Make prediction
93
+ status_text.text('Making prediction...')
94
+ prediction = predict(image)
95
+ progress_bar.progress(66)
96
+ time.sleep(0.5) # Simulate processing time
97
+
98
+ # Analyze results
99
+ status_text.text('Analyzing results...')
100
+ predicted_class = max(prediction, key=prediction.get)
101
+ confidence = prediction[predicted_class]
102
+ progress_bar.progress(100)
103
+ time.sleep(0.5) # Simulate processing time
104
+
105
+ # Clear the status text and progress bar
106
+ status_text.empty()
107
+ progress_bar.empty()
108
+
109
+ # Display prediction results under the images
110
+ st.subheader("Prediction Results")
111
+ st.write(f"Predicted waste type: **{predicted_class}**")
112
+ st.write(f"Confidence: {confidence:.2%}")
113
+
114
+ # Display vertical bar chart of probabilities using Plotly
115
+ fig = go.Figure(data=[go.Bar(
116
+ x=list(prediction.keys()),
117
+ y=list(prediction.values()),
118
+ marker=dict(
119
+ color=list(prediction.values()),
120
+ colorscale='Viridis',
121
+ colorbar=dict(title='Probability')
122
+ )
123
+ )])
124
+ fig.update_layout(
125
+ title='Prediction Probabilities',
126
+ xaxis_title='Waste Type',
127
+ yaxis_title='Probability',
128
+ height=500,
129
+ width=700
130
+ )
131
+ st.plotly_chart(fig)
132
+
133
+ if __name__ == "__main__":
134
+ run()