hansaka01 commited on
Commit
40ef76b
·
verified ·
1 Parent(s): 16dca43

add keras_example.py

Browse files
Files changed (1) hide show
  1. keras_example.py +102 -0
keras_example.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal Keras/TF training pipeline for the CropHelth dataset.
2
+
3
+ Setup:
4
+ huggingface-cli download hansaka01/crophelth --repo-type dataset --local-dir .
5
+ pip install tensorflow pandas
6
+
7
+ Run:
8
+ python keras_example.py
9
+
10
+ Uses dataset_index.csv (file, label, class_index, split) for a stratified
11
+ train/val tf.data pipeline. Output classes are your codes (potato_lb etc.),
12
+ so the model's argmax maps straight to the treatment lookup in
13
+ knowledge/treatments.json.
14
+ """
15
+ import os
16
+
17
+ import numpy as np
18
+ import pandas as pd
19
+ import tensorflow as tf
20
+
21
+ DATA_DIR = os.path.dirname(os.path.abspath(__file__)) # repo root (where dataset_index.csv is)
22
+ IMG_SIZE = (256, 256)
23
+ BATCH = 32
24
+ EPOCHS = 10
25
+ IMG_MEAN, IMG_STD = 127.5, 127.5 # ImageNet-style normalization
26
+
27
+ df = pd.read_csv(os.path.join(DATA_DIR, "dataset_index.csv"))
28
+ CLASSES = sorted(df["label"].unique())
29
+ CLASS_TO_INT = {c: i for i, c in enumerate(CLASSES)}
30
+ NUM_CLASSES = len(CLASSES)
31
+ df["label_int"] = df["label"].map(CLASS_TO_INT)
32
+ print(f"classes: {NUM_CLASSES} rows: {len(df)}")
33
+
34
+
35
+ def make_dataset(frame: pd.DataFrame, shuffle: bool) -> tf.data.Dataset:
36
+ files = tf.constant(frame["file"].to_numpy())
37
+ labels = tf.constant(frame["label_int"].to_numpy(), tf.int32)
38
+
39
+ def parse(file, label):
40
+ path = tf.strings.join([tf.constant(DATA_DIR), file], separator="/")
41
+ img = tf.io.read_file(path)
42
+ img = tf.io.decode_image(img, channels=3) # jpg + png
43
+ img = tf.image.resize(img, IMG_SIZE)
44
+ img = (tf.cast(img, tf.float32) - IMG_MEAN) / IMG_STD
45
+ return img, label
46
+
47
+ ds = tf.data.Dataset.from_tensor_slices((files, labels))
48
+ if shuffle:
49
+ ds = ds.shuffle(len(frame))
50
+ ds = ds.map(parse, num_parallel_calls=tf.data.AUTOTUNE)
51
+ ds = ds.batch(BATCH)
52
+ ds = ds.prefetch(tf.data.AUTOTUNE)
53
+ return ds
54
+
55
+
56
+ train_ds = make_dataset(df[df["split"] == "train"], shuffle=True)
57
+ val_ds = make_dataset(df[df["split"] == "val"], shuffle=False)
58
+
59
+ # --- model: EfficientNetB0 transfer learning ---
60
+ backbone = tf.keras.applications.EfficientNetB0(
61
+ include_top=False, weights="imagenet", input_shape=(256, 256, 3))
62
+ backbone.trainable = False
63
+
64
+ model = tf.keras.Sequential([
65
+ backbone,
66
+ tf.keras.layers.GlobalAveragePooling2D(),
67
+ tf.keras.layers.Dropout(0.3),
68
+ tf.keras.layers.Dense(NUM_CLASSES, activation="softmax"),
69
+ ], name="crophelth")
70
+
71
+ model.compile(
72
+ optimizer=tf.keras.optimizers.Adam(1e-3),
73
+ loss="sparse_categorical_crossentropy",
74
+ metrics=["accuracy"],
75
+ )
76
+ model.summary()
77
+
78
+ # --- stage 1: train the head ---
79
+ model.fit(train_ds, validation_data=val_ds, epochs=4)
80
+
81
+ # --- stage 2: unfreeze top of backbone, fine-tune ---
82
+ backbone.trainable = True
83
+ for layer in backbone.layers[:-30]:
84
+ layer.trainable = False
85
+ model.compile(
86
+ optimizer=tf.keras.optimizers.Adam(1e-5),
87
+ loss="sparse_categorical_crossentropy",
88
+ metrics=["accuracy"],
89
+ )
90
+ model.fit(train_ds, validation_data=val_ds, epochs=EPOCHS - 4)
91
+
92
+ model.save(os.path.join(DATA_DIR, "crophelth_model.keras"))
93
+ np.savez(os.path.join(DATA_DIR, "class_names.npz"), classes=np.array(CLASSES))
94
+ print("saved crophelth_model.keras + class_names.npz")
95
+
96
+ # --- inference: code-based output, ready for the treatment lookup ---
97
+ import json
98
+ x, y = next(iter(val_ds.batch(1)))
99
+ pred = int(np.argmax(model.predict(x, verbose=0)[0]))
100
+ print("predicted code:", CLASSES[pred])
101
+ treatments = json.load(open(os.path.join(DATA_DIR, "knowledge", "treatments.json")))
102
+ print("treatment:", treatments.get(CLASSES[pred]))