NORLIE JHON MALAGDAO commited on
Commit
a2718c9
·
verified ·
1 Parent(s): 6e9d8d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -46
app.py CHANGED
@@ -8,13 +8,18 @@ import tensorflow as tf
8
  from tensorflow import keras
9
  from tensorflow.keras import layers
10
  from tensorflow.keras.models import Sequential
11
- from tensorflow.keras.applications import EfficientNetB0
12
 
13
  from PIL import Image
14
  import gdown
15
  import zipfile
 
16
  import pathlib
17
 
 
 
 
 
18
  # Define the Google Drive shareable link
19
  gdrive_url = 'https://drive.google.com/file/d/1HjHYlQyRz5oWt8kehkt1TiOGRRlKFsv8/view?usp=drive_link'
20
 
@@ -54,77 +59,110 @@ for root, dirs, files in os.walk(extracted_path):
54
  for f in files:
55
  print(f"{subindent}{f}")
56
 
 
57
  # Path to the dataset directory
58
  data_dir = pathlib.Path('extracted_files/Pest_Dataset')
59
  data_dir = pathlib.Path(data_dir)
60
 
61
- img_height, img_width = 180, 180
62
- batch_size = 32
 
 
 
 
 
 
 
 
 
 
 
63
  train_ds = tf.keras.preprocessing.image_dataset_from_directory(
64
- data_dir,
65
- validation_split=0.2,
66
- subset="training",
67
- seed=123,
68
- image_size=(img_height, img_width),
69
- batch_size=batch_size
70
- )
71
 
72
  val_ds = tf.keras.preprocessing.image_dataset_from_directory(
73
- data_dir,
74
- validation_split=0.2,
75
- subset="validation",
76
- seed=123,
77
- image_size=(img_height, img_width),
78
- batch_size=batch_size
79
- )
80
 
81
  class_names = train_ds.class_names
82
  print(class_names)
83
 
84
- # Enhanced Data Augmentation
 
 
 
 
 
 
 
 
 
 
 
85
  data_augmentation = keras.Sequential(
86
- [
87
- layers.RandomFlip("horizontal", input_shape=(img_height, img_width, 3)),
88
- layers.RandomRotation(0.2),
89
- layers.RandomZoom(0.2),
90
- layers.RandomContrast(0.2),
91
- layers.RandomBrightness(0.2)
92
- ]
 
93
  )
94
 
95
- # Use a Pretrained Model
96
- base_model = EfficientNetB0(input_shape=(img_height, img_width, 3), include_top=False, weights='imagenet')
97
- base_model.trainable = False # Freeze the base model
98
 
99
- # Define the model
 
 
 
 
 
 
 
 
100
  num_classes = len(class_names)
101
  model = Sequential([
102
- data_augmentation,
103
- layers.Rescaling(1./255),
104
- base_model,
105
- layers.GlobalAveragePooling2D(),
106
- layers.Dropout(0.5),
107
- layers.Dense(num_classes, activation='softmax', name="outputs") # Use softmax here
 
 
 
 
 
 
108
  ])
109
 
110
- model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.001),
111
  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), # Change from_logits to False
112
  metrics=['accuracy'])
113
 
114
  model.summary()
115
 
116
- # Callbacks
117
- early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
118
- lr_scheduler = keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=1e-5)
119
 
120
- epochs = 20
121
  history = model.fit(
122
- train_ds,
123
- validation_data=val_ds,
124
- epochs=epochs,
125
- callbacks=[early_stopping, lr_scheduler]
126
  )
127
 
 
 
128
  # Define category descriptions
129
  category_descriptions = {
130
  "Ants": "Ants are small insects known for their complex social structures and teamwork.",
@@ -144,7 +182,7 @@ category_descriptions = {
144
  # Define the prediction function
145
  def predict_image(img):
146
  img = np.array(img)
147
- img_resized = tf.image.resize(img, (img_height, img_width))
148
  img_4d = tf.expand_dims(img_resized, axis=0)
149
  prediction = model.predict(img_4d)[0]
150
  predicted_class = np.argmax(prediction)
@@ -156,10 +194,13 @@ def predict_image(img):
156
  image = gr.Image()
157
  label = gr.Label(num_top_classes=1)
158
 
 
159
  gr.Interface(
160
  fn=predict_image,
161
  inputs=image,
162
  outputs=label,
163
  title="Welcome to Agricultural Pest Image Classification",
164
- 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"
 
165
  ).launch(debug=True)
 
 
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'
25
 
 
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
+
78
+ img_height,img_width=180,180
79
+ batch_size=32
80
  train_ds = tf.keras.preprocessing.image_dataset_from_directory(
81
+ data_dir,
82
+ validation_split=0.2,
83
+ subset="training",
84
+ seed=123,
85
+ image_size=(img_height, img_width),
86
+ batch_size=batch_size)
87
+
88
 
89
  val_ds = tf.keras.preprocessing.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
 
98
  class_names = train_ds.class_names
99
  print(class_names)
100
 
101
+
102
+ import matplotlib.pyplot as plt
103
+
104
+ plt.figure(figsize=(10, 10))
105
+ for images, labels in train_ds.take(1):
106
+ for i in range(9):
107
+ ax = plt.subplot(3, 3, i + 1)
108
+ plt.imshow(images[i].numpy().astype("uint8"))
109
+ plt.title(class_names[labels[i]])
110
+ plt.axis("off")
111
+
112
+
113
  data_augmentation = keras.Sequential(
114
+ [
115
+ layers.RandomFlip("horizontal",
116
+ input_shape=(img_height,
117
+ img_width,
118
+ 3)),
119
+ layers.RandomRotation(0.1),
120
+ layers.RandomZoom(0.1),
121
+ ]
122
  )
123
 
 
 
 
124
 
125
+ plt.figure(figsize=(10, 10))
126
+ for images, _ in train_ds.take(1):
127
+ for i in range(9):
128
+ augmented_images = data_augmentation(images)
129
+ ax = plt.subplot(3, 3, i + 1)
130
+ plt.imshow(augmented_images[0].numpy().astype("uint8"))
131
+ plt.axis("off")
132
+
133
+
134
  num_classes = len(class_names)
135
  model = Sequential([
136
+ data_augmentation,
137
+ layers.Rescaling(1./255),
138
+ layers.Conv2D(16, 3, padding='same', activation='relu'),
139
+ layers.MaxPooling2D(),
140
+ layers.Conv2D(32, 3, padding='same', activation='relu'),
141
+ layers.MaxPooling2D(),
142
+ layers.Conv2D(64, 3, padding='same', activation='relu'),
143
+ layers.MaxPooling2D(),
144
+ layers.Dropout(0.2),
145
+ layers.Flatten(),
146
+ layers.Dense(128, activation='relu'),
147
+ layers.Dense(num_classes, activation='softmax', name="outputs") # Use softmax here
148
  ])
149
 
150
+ model.compile(optimizer='adam',
151
  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), # Change from_logits to False
152
  metrics=['accuracy'])
153
 
154
  model.summary()
155
 
 
 
 
156
 
157
+ epochs = 15
158
  history = model.fit(
159
+ train_ds,
160
+ validation_data=val_ds,
161
+ epochs=epochs
 
162
  )
163
 
164
+
165
+
166
  # Define category descriptions
167
  category_descriptions = {
168
  "Ants": "Ants are small insects known for their complex social structures and teamwork.",
 
182
  # Define the prediction function
183
  def predict_image(img):
184
  img = np.array(img)
185
+ img_resized = tf.image.resize(img, (180, 180))
186
  img_4d = tf.expand_dims(img_resized, axis=0)
187
  prediction = model.predict(img_4d)[0]
188
  predicted_class = np.argmax(prediction)
 
194
  image = gr.Image()
195
  label = gr.Label(num_top_classes=1)
196
 
197
+
198
  gr.Interface(
199
  fn=predict_image,
200
  inputs=image,
201
  outputs=label,
202
  title="Welcome to Agricultural Pest Image Classification",
203
+ 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",
204
+ css=custom_css
205
  ).launch(debug=True)
206
+