Skip to content

Commit 15294d7

Browse files
authored
Update data_loader.py
1 parent 3682ebd commit 15294d7

1 file changed

Lines changed: 16 additions & 12 deletions

File tree

src/data_loader.py

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@
22
from pathlib import Path
33

44

5-
IMG_SIZE = (224, 224)
5+
IMG_SIZE = (224, 224)
66
BATCH_SIZE = 32
7-
AUTOTUNE = tf.data.AUTOTUNE
7+
AUTOTUNE = tf.data.AUTOTUNE
88

99

1010
def get_augmentation_layer() -> tf.keras.Sequential:
1111
"""
12-
Data augmentation applied ONLY to training set.
13-
Helps the model generalise — your old code had zero augmentation.
12+
Data augmentation applied ONLY during training.
13+
Applied AFTER cache so each epoch sees different augmentations.
1414
"""
1515
return tf.keras.Sequential([
1616
tf.keras.layers.RandomFlip("horizontal"),
@@ -23,11 +23,13 @@ def get_augmentation_layer() -> tf.keras.Sequential:
2323

2424
def load_datasets(data_dir: str, batch_size: int = BATCH_SIZE):
2525
"""
26-
Load train and validation datasets from a directory.
27-
Replaces the hardcoded path in your old main5.py.
26+
Load train and validation datasets from a directory structured as:
27+
data_dir/
28+
ClassName1/ image1.jpg ...
29+
ClassName2/ image1.jpg ...
2830
2931
Args:
30-
data_dir: path to dataset root (set via DATA_DIR env var in train.py)
32+
data_dir: path to dataset root (set via DATA_DIR env var in train.py)
3133
batch_size: images per batch
3234
3335
Returns:
@@ -38,7 +40,7 @@ def load_datasets(data_dir: str, batch_size: int = BATCH_SIZE):
3840
raise FileNotFoundError(
3941
f"Dataset not found at: {data_path}\n"
4042
f"Download PlantVillage from: https://www.kaggle.com/datasets/emmarex/plantdisease\n"
41-
f"Then set DATA_DIR environment variable to its path."
43+
f"Then set the DATA_DIR environment variable to its path."
4244
)
4345

4446
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
@@ -65,12 +67,14 @@ def load_datasets(data_dir: str, batch_size: int = BATCH_SIZE):
6567

6668
augment = get_augmentation_layer()
6769

68-
# Apply augmentation to training only, then cache + prefetch both
70+
# FIX: cache RAW images first, THEN augment so each epoch gets fresh augmentations.
71+
# Old order was: augment → cache → shuffle (froze augmentations, defeating the purpose).
6972
train_ds = (
7073
train_ds
71-
.map(lambda x, y: (augment(x, training=True), y), num_parallel_calls=AUTOTUNE)
72-
.cache()
73-
.shuffle(1000)
74+
.cache() # cache raw pixels
75+
.shuffle(1000, seed=42)
76+
.map(lambda x, y: (augment(x, training=True), y), # augment after cache
77+
num_parallel_calls=AUTOTUNE)
7478
.prefetch(buffer_size=AUTOTUNE)
7579
)
7680

0 commit comments

Comments
 (0)