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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -36
app.py CHANGED
@@ -9,17 +9,11 @@ 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
 
@@ -64,27 +58,20 @@ import pathlib
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,
@@ -92,15 +79,12 @@ val_ds = tf.keras.preprocessing.image_dataset_from_directory(
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):
@@ -109,7 +93,6 @@ for images, labels in train_ds.take(1):
109
  plt.title(class_names[labels[i]])
110
  plt.axis("off")
111
 
112
-
113
  data_augmentation = keras.Sequential(
114
  [
115
  layers.RandomFlip("horizontal",
@@ -118,10 +101,11 @@ data_augmentation = keras.Sequential(
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):
@@ -130,39 +114,43 @@ for images, _ in train_ds.take(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.",
@@ -194,6 +182,16 @@ def predict_image(img):
194
  image = gr.Image()
195
  label = gr.Label(num_top_classes=1)
196
 
 
 
 
 
 
 
 
 
 
 
197
 
198
  gr.Interface(
199
  fn=predict_image,
@@ -203,4 +201,3 @@ gr.Interface(
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
-
 
9
  from tensorflow.keras import layers
10
  from tensorflow.keras.models import Sequential
11
 
 
12
  from PIL import Image
13
  import gdown
14
  import zipfile
 
15
  import pathlib
16
 
 
 
 
 
17
  # Define the Google Drive shareable link
18
  gdrive_url = 'https://drive.google.com/file/d/1HjHYlQyRz5oWt8kehkt1TiOGRRlKFsv8/view?usp=drive_link'
19
 
 
58
  data_dir = pathlib.Path('extracted_files/Pest_Dataset')
59
  data_dir = pathlib.Path(data_dir)
60
 
 
61
  bees = list(data_dir.glob('bees/*'))
62
  print(bees[0])
63
  PIL.Image.open(str(bees[0]))
64
 
65
+ img_height, img_width = 180, 180
66
+ batch_size = 32
 
 
 
 
 
 
67
  train_ds = tf.keras.preprocessing.image_dataset_from_directory(
68
  data_dir,
69
  validation_split=0.2,
70
  subset="training",
71
  seed=123,
72
  image_size=(img_height, img_width),
73
+ batch_size=batch_size
74
+ )
75
 
76
  val_ds = tf.keras.preprocessing.image_dataset_from_directory(
77
  data_dir,
 
79
  subset="validation",
80
  seed=123,
81
  image_size=(img_height, img_width),
82
+ batch_size=batch_size
83
+ )
84
 
85
  class_names = train_ds.class_names
86
  print(class_names)
87
 
 
 
 
88
  plt.figure(figsize=(10, 10))
89
  for images, labels in train_ds.take(1):
90
  for i in range(9):
 
93
  plt.title(class_names[labels[i]])
94
  plt.axis("off")
95
 
 
96
  data_augmentation = keras.Sequential(
97
  [
98
  layers.RandomFlip("horizontal",
 
101
  3)),
102
  layers.RandomRotation(0.1),
103
  layers.RandomZoom(0.1),
104
+ layers.RandomContrast(0.1),
105
+ layers.RandomBrightness(0.1)
106
  ]
107
  )
108
 
 
109
  plt.figure(figsize=(10, 10))
110
  for images, _ in train_ds.take(1):
111
  for i in range(9):
 
114
  plt.imshow(augmented_images[0].numpy().astype("uint8"))
115
  plt.axis("off")
116
 
 
117
  num_classes = len(class_names)
118
  model = Sequential([
119
  data_augmentation,
120
  layers.Rescaling(1./255),
 
 
121
  layers.Conv2D(32, 3, padding='same', activation='relu'),
122
  layers.MaxPooling2D(),
123
  layers.Conv2D(64, 3, padding='same', activation='relu'),
124
  layers.MaxPooling2D(),
125
+ layers.Conv2D(128, 3, padding='same', activation='relu'),
126
+ layers.MaxPooling2D(),
127
+ layers.Dropout(0.5),
128
  layers.Flatten(),
129
+ layers.Dense(256, activation='relu'),
130
+ layers.Dropout(0.5),
131
+ layers.Dense(num_classes, activation='softmax', name="outputs")
132
  ])
133
 
134
  model.compile(optimizer='adam',
135
+ loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
136
  metrics=['accuracy'])
137
 
138
  model.summary()
139
 
140
+ # Learning rate scheduler
141
+ lr_scheduler = keras.callbacks.LearningRateScheduler(lambda epoch: 1e-3 * 10**(epoch / 20))
142
 
143
+ # Early stopping
144
+ early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
145
+
146
+ epochs = 20
147
  history = model.fit(
148
  train_ds,
149
  validation_data=val_ds,
150
+ epochs=epochs,
151
+ callbacks=[lr_scheduler, early_stopping]
152
  )
153
 
 
 
154
  # Define category descriptions
155
  category_descriptions = {
156
  "Ants": "Ants are small insects known for their complex social structures and teamwork.",
 
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;
192
+ color: white;
193
+ }
194
+ """
195
 
196
  gr.Interface(
197
  fn=predict_image,
 
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)