NORLIE JHON MALAGDAO commited on
Commit
79cd26d
·
verified ·
1 Parent(s): 6d21ad0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -118
app.py CHANGED
@@ -1,24 +1,14 @@
1
- import gradio as gr
2
- import matplotlib.pyplot as plt
3
- import numpy as np
4
  import os
5
- import PIL
 
 
6
  import tensorflow as tf
7
-
8
  from tensorflow import keras
9
  from tensorflow.keras import layers
10
  from tensorflow.keras.models import Sequential
11
-
12
-
13
- from PIL import Image
14
- import gdown
15
- import zipfile
16
-
17
- import pathlib
18
-
19
-
20
-
21
-
22
 
23
  # Define the Google Drive shareable link
24
  gdrive_url = 'https://drive.google.com/file/d/1HjHYlQyRz5oWt8kehkt1TiOGRRlKFsv8/view?usp=drive_link'
@@ -48,9 +38,9 @@ except zipfile.BadZipFile:
48
  os.remove(local_zip_file)
49
 
50
  # Convert the extracted directory path to a pathlib.Path object
51
- data_dir = pathlib.Path(extracted_path)
52
 
53
- # Print the directory structure to debug
54
  for root, dirs, files in os.walk(extracted_path):
55
  level = root.replace(extracted_path, '').count(os.sep)
56
  indent = ' ' * 4 * (level)
@@ -59,143 +49,143 @@ for root, dirs, files in os.walk(extracted_path):
59
  for f in files:
60
  print(f"{subindent}{f}")
61
 
62
- import pathlib
63
- # Path to the dataset directory
64
- data_dir = pathlib.Path('extracted_files/Pest_Dataset')
65
- data_dir = pathlib.Path(data_dir)
66
-
67
-
68
- bees = list(data_dir.glob('bees/*'))
69
- print(bees[0])
70
- PIL.Image.open(str(bees[0]))
71
-
72
 
73
- bees = list(data_dir.glob('bees/*'))
74
- print(bees[0])
75
- PIL.Image.open(str(bees[0]))
 
 
 
 
 
 
76
 
77
- batch_size = 32
78
- img_height = 180
79
- img_width = 180
80
-
81
- train_ds = tf.keras.utils.image_dataset_from_directory(
82
- data_dir,
83
- validation_split=0.2,
84
- subset="training",
85
- seed=123,
86
- image_size=(img_height, img_width),
87
- batch_size=batch_size)
88
-
89
- val_ds = tf.keras.utils.image_dataset_from_directory(
90
- data_dir,
91
- validation_split=0.2,
92
- subset="validation",
93
- seed=123,
94
- image_size=(img_height, img_width),
95
- batch_size=batch_size)
96
 
97
  class_names = train_ds.class_names
98
  print(class_names)
99
 
100
- import matplotlib.pyplot as plt
101
-
102
  plt.figure(figsize=(10, 10))
103
  for images, labels in train_ds.take(1):
104
- for i in range(9):
105
- ax = plt.subplot(3, 3, i + 1)
106
- plt.imshow(images[i].numpy().astype("uint8"))
107
- plt.title(class_names[labels[i]])
108
- plt.axis("off")
109
 
 
 
 
 
 
 
 
 
 
 
110
 
111
- for image_batch, labels_batch in train_ds:
112
- print(image_batch.shape)
113
- print(labels_batch.shape)
114
- break
 
 
 
 
115
 
 
 
 
116
 
117
- AUTOTUNE = tf.data.AUTOTUNE
 
118
 
119
- train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
120
- val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
 
121
 
122
- normalization_layer = layers.Rescaling(1./255)
 
 
123
 
124
- normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
125
- image_batch, labels_batch = next(iter(normalized_ds))
126
- first_image = image_batch[0]
127
- # Notice the pixel values are now in `[0,1]`.
128
- print(np.min(first_image), np.max(first_image))
129
 
130
- data_augmentation = keras.Sequential(
131
- [
132
- layers.RandomFlip("horizontal",
133
- input_shape=(img_height,
134
- img_width,
135
- 3)),
136
- layers.RandomRotation(0.1),
137
- layers.RandomZoom(0.1),
138
- ]
139
- )
140
 
 
 
 
141
 
142
- plt.figure(figsize=(10, 10))
143
- for images, _ in train_ds.take(1):
144
- for i in range(9):
145
- augmented_images = data_augmentation(images)
146
- ax = plt.subplot(3, 3, i + 1)
147
- plt.imshow(augmented_images[0].numpy().astype("uint8"))
148
- plt.axis("off")
149
 
150
- num_classes = len(class_names)
 
 
 
151
 
152
- model = Sequential([
153
- data_augmentation,
154
- layers.Rescaling(1./255),
155
- layers.Conv2D(16, 3, padding='same', activation='relu'),
156
- layers.MaxPooling2D(),
157
- layers.Conv2D(32, 3, padding='same', activation='relu'),
158
- layers.MaxPooling2D(),
159
- layers.Conv2D(64, 3, padding='same', activation='relu'),
160
- layers.MaxPooling2D(),
161
- layers.Dropout(0.2),
162
- layers.Flatten(),
163
- layers.Dense(128, activation='relu'),
164
- layers.Dense(num_classes, name="outputs")
165
- ])
166
-
167
- model.compile(optimizer='adam',
168
- loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
169
  metrics=['accuracy'])
170
 
171
  model.summary()
172
 
173
- epochs = 15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  history = model.fit(
175
- train_ds,
176
- validation_data=val_ds,
177
- epochs=epochs
 
178
  )
179
 
180
- import gradio as gr
181
- import numpy as np
182
- import tensorflow as tf
183
-
184
  def predict_image(img):
185
  img = np.array(img)
186
  img_resized = tf.image.resize(img, (180, 180))
187
  img_4d = tf.expand_dims(img_resized, axis=0)
188
  prediction = model.predict(img_4d)[0]
189
- return {class_names[i]: float(prediction[i]) for i in range(len(class_names))}
190
-
 
191
 
 
192
  image = gr.Image()
193
  label = gr.Label(num_top_classes=1)
194
 
195
  # Define custom CSS for background image
196
  custom_css = """
197
  body {
198
- background-image: url('\extracted_files\Pest_Dataset\bees\bees (444).jpg');
199
  background-size: cover;
200
  background-repeat: no-repeat;
201
  background-attachment: fixed;
@@ -208,6 +198,6 @@ gr.Interface(
208
  inputs=image,
209
  outputs=label,
210
  title="Welcome to Agricultural Pest Image Classification",
211
- description="The image data set used was obtaied from Kaggle and has a collection of 12 different types of agricultral pests: Ants, Bees, Beetles, Caterpillars, Earthworms, Earwigs, Grasshoppers, Moths, Slugs, Snails, Wasps, and Weevils",
212
  css=custom_css
213
- ).launch(debug=True)
 
 
 
 
1
  import os
2
+ import zipfile
3
+ import gdown
4
+ import pathlib
5
  import tensorflow as tf
 
6
  from tensorflow import keras
7
  from tensorflow.keras import layers
8
  from tensorflow.keras.models import Sequential
9
+ import matplotlib.pyplot as plt
10
+ import gradio as gr
11
+ import numpy as np
 
 
 
 
 
 
 
 
12
 
13
  # Define the Google Drive shareable link
14
  gdrive_url = 'https://drive.google.com/file/d/1HjHYlQyRz5oWt8kehkt1TiOGRRlKFsv8/view?usp=drive_link'
 
38
  os.remove(local_zip_file)
39
 
40
  # Convert the extracted directory path to a pathlib.Path object
41
+ data_dir = pathlib.Path('extracted_files/Pest_Dataset')
42
 
43
+ # Verify the directory structure
44
  for root, dirs, files in os.walk(extracted_path):
45
  level = root.replace(extracted_path, '').count(os.sep)
46
  indent = ' ' * 4 * (level)
 
49
  for f in files:
50
  print(f"{subindent}{f}")
51
 
52
+ # Set image dimensions and batch size
53
+ img_height, img_width = 180, 180
54
+ batch_size = 32
 
 
 
 
 
 
 
55
 
56
+ # Create training and validation datasets
57
+ train_ds = tf.keras.preprocessing.image_dataset_from_directory(
58
+ data_dir,
59
+ validation_split=0.2,
60
+ subset="training",
61
+ seed=123,
62
+ image_size=(img_height, img_width),
63
+ batch_size=batch_size
64
+ )
65
 
66
+ val_ds = tf.keras.preprocessing.image_dataset_from_directory(
67
+ data_dir,
68
+ validation_split=0.2,
69
+ subset="validation",
70
+ seed=123,
71
+ image_size=(img_height, img_width),
72
+ batch_size=batch_size
73
+ )
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  class_names = train_ds.class_names
76
  print(class_names)
77
 
78
+ # Display some sample images
 
79
  plt.figure(figsize=(10, 10))
80
  for images, labels in train_ds.take(1):
81
+ for i in range(9):
82
+ ax = plt.subplot(3, 3, i + 1)
83
+ plt.imshow(images[i].numpy().astype("uint8"))
84
+ plt.title(class_names[labels[i]])
85
+ plt.axis("off")
86
 
87
+ # Enhanced data augmentation
88
+ data_augmentation = keras.Sequential(
89
+ [
90
+ layers.RandomFlip("horizontal", input_shape=(img_height, img_width, 3)),
91
+ layers.RandomRotation(0.2),
92
+ layers.RandomZoom(0.2),
93
+ layers.RandomContrast(0.2),
94
+ layers.RandomBrightness(0.2),
95
+ ]
96
+ )
97
 
98
+ # Display augmented images
99
+ plt.figure(figsize=(10, 10))
100
+ for images, _ in train_ds.take(1):
101
+ for i in range(9):
102
+ augmented_images = data_augmentation(images)
103
+ ax = plt.subplot(3, 3, i + 1)
104
+ plt.imshow(augmented_images[0].numpy().astype("uint8"))
105
+ plt.axis("off")
106
 
107
+ # Define a deeper CNN model with more regularization techniques
108
+ num_classes = len(class_names)
109
+ model = Sequential()
110
 
111
+ model.add(data_augmentation)
112
+ model.add(layers.Rescaling(1./255))
113
 
114
+ model.add(layers.Conv2D(32, 3, padding='same', activation='relu'))
115
+ model.add(layers.BatchNormalization())
116
+ model.add(layers.MaxPooling2D())
117
 
118
+ model.add(layers.Conv2D(64, 3, padding='same', activation='relu'))
119
+ model.add(layers.BatchNormalization())
120
+ model.add(layers.MaxPooling2D())
121
 
122
+ model.add(layers.Conv2D(128, 3, padding='same', activation='relu'))
123
+ model.add(layers.BatchNormalization())
124
+ model.add(layers.MaxPooling2D())
 
 
125
 
126
+ model.add(layers.Conv2D(256, 3, padding='same', activation='relu'))
127
+ model.add(layers.BatchNormalization())
128
+ model.add(layers.MaxPooling2D())
 
 
 
 
 
 
 
129
 
130
+ model.add(layers.Conv2D(512, 3, padding='same', activation='relu'))
131
+ model.add(layers.BatchNormalization())
132
+ model.add(layers.MaxPooling2D())
133
 
134
+ model.add(layers.Dropout(0.5))
135
+ model.add(layers.Flatten())
 
 
 
 
 
136
 
137
+ model.add(layers.Dense(256, activation='relu'))
138
+ model.add(layers.Dropout(0.5))
139
+
140
+ model.add(layers.Dense(num_classes, activation='softmax', name="outputs"))
141
 
142
+ model.compile(optimizer=keras.optimizers.Adam(learning_rate=1e-4),
143
+ loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  metrics=['accuracy'])
145
 
146
  model.summary()
147
 
148
+ # Implement early stopping
149
+ from tensorflow.keras.callbacks import EarlyStopping
150
+
151
+ early_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
152
+
153
+ # Learning rate scheduler
154
+ def scheduler(epoch, lr):
155
+ if epoch < 10:
156
+ return lr
157
+ else:
158
+ return lr * tf.math.exp(-0.1)
159
+
160
+ lr_scheduler = keras.callbacks.LearningRateScheduler(scheduler)
161
+
162
+ # Train the model
163
+ epochs = 30
164
  history = model.fit(
165
+ train_ds,
166
+ validation_data=val_ds,
167
+ epochs=epochs,
168
+ callbacks=[early_stopping, lr_scheduler]
169
  )
170
 
171
+ # Define the prediction function
 
 
 
172
  def predict_image(img):
173
  img = np.array(img)
174
  img_resized = tf.image.resize(img, (180, 180))
175
  img_4d = tf.expand_dims(img_resized, axis=0)
176
  prediction = model.predict(img_4d)[0]
177
+ predicted_class = np.argmax(prediction)
178
+ predicted_label = class_names[predicted_class]
179
+ return {predicted_label: f"{float(prediction[predicted_class]):.2f}"}
180
 
181
+ # Set up Gradio interface
182
  image = gr.Image()
183
  label = gr.Label(num_top_classes=1)
184
 
185
  # Define custom CSS for background image
186
  custom_css = """
187
  body {
188
+ background-image: url('extracted_files/Pest_Dataset/bees/bees (444).jpg');
189
  background-size: cover;
190
  background-repeat: no-repeat;
191
  background-attachment: fixed;
 
198
  inputs=image,
199
  outputs=label,
200
  title="Welcome to Agricultural Pest Image Classification",
201
+ description="The image data set used was obtained from Kaggle and has a collection of 12 different types of agricultural pests: Ants, Bees, Beetles, Caterpillars, Earthworms, Earwigs, Grasshoppers, Moths, Slugs, Snails, Wasps, and Weevils",
202
  css=custom_css
203
+ ).launch(debug=True)