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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -79
app.py CHANGED
@@ -8,6 +8,7 @@ import tensorflow as tf
8
  from tensorflow import keras
9
  from tensorflow.keras import layers
10
  from tensorflow.keras.models import Sequential
 
11
 
12
  from PIL import Image
13
  import gdown
@@ -53,102 +54,75 @@ for root, dirs, files in os.walk(extracted_path):
53
  for f in files:
54
  print(f"{subindent}{f}")
55
 
56
- import pathlib
57
  # Path to the dataset directory
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,
78
- validation_split=0.2,
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):
91
- ax = plt.subplot(3, 3, i + 1)
92
- plt.imshow(images[i].numpy().astype("uint8"))
93
- plt.title(class_names[labels[i]])
94
- plt.axis("off")
95
-
96
  data_augmentation = keras.Sequential(
97
- [
98
- layers.RandomFlip("horizontal",
99
- input_shape=(img_height,
100
- img_width,
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):
112
- augmented_images = data_augmentation(images)
113
- ax = plt.subplot(3, 3, i + 1)
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
@@ -170,7 +144,7 @@ category_descriptions = {
170
  # Define the prediction function
171
  def predict_image(img):
172
  img = np.array(img)
173
- img_resized = tf.image.resize(img, (180, 180))
174
  img_4d = tf.expand_dims(img_resized, axis=0)
175
  prediction = model.predict(img_4d)[0]
176
  predicted_class = np.argmax(prediction)
@@ -182,22 +156,10 @@ def predict_image(img):
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,
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)
 
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
 
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
 
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
  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)