crophelth / keras_example.py
hansaka01's picture
add keras_example.py
40ef76b verified
Raw
History Blame Contribute Delete
3.48 kB
"""Minimal Keras/TF training pipeline for the CropHelth dataset.
Setup:
huggingface-cli download hansaka01/crophelth --repo-type dataset --local-dir .
pip install tensorflow pandas
Run:
python keras_example.py
Uses dataset_index.csv (file, label, class_index, split) for a stratified
train/val tf.data pipeline. Output classes are your codes (potato_lb etc.),
so the model's argmax maps straight to the treatment lookup in
knowledge/treatments.json.
"""
import os
import numpy as np
import pandas as pd
import tensorflow as tf
DATA_DIR = os.path.dirname(os.path.abspath(__file__)) # repo root (where dataset_index.csv is)
IMG_SIZE = (256, 256)
BATCH = 32
EPOCHS = 10
IMG_MEAN, IMG_STD = 127.5, 127.5 # ImageNet-style normalization
df = pd.read_csv(os.path.join(DATA_DIR, "dataset_index.csv"))
CLASSES = sorted(df["label"].unique())
CLASS_TO_INT = {c: i for i, c in enumerate(CLASSES)}
NUM_CLASSES = len(CLASSES)
df["label_int"] = df["label"].map(CLASS_TO_INT)
print(f"classes: {NUM_CLASSES} rows: {len(df)}")
def make_dataset(frame: pd.DataFrame, shuffle: bool) -> tf.data.Dataset:
files = tf.constant(frame["file"].to_numpy())
labels = tf.constant(frame["label_int"].to_numpy(), tf.int32)
def parse(file, label):
path = tf.strings.join([tf.constant(DATA_DIR), file], separator="/")
img = tf.io.read_file(path)
img = tf.io.decode_image(img, channels=3) # jpg + png
img = tf.image.resize(img, IMG_SIZE)
img = (tf.cast(img, tf.float32) - IMG_MEAN) / IMG_STD
return img, label
ds = tf.data.Dataset.from_tensor_slices((files, labels))
if shuffle:
ds = ds.shuffle(len(frame))
ds = ds.map(parse, num_parallel_calls=tf.data.AUTOTUNE)
ds = ds.batch(BATCH)
ds = ds.prefetch(tf.data.AUTOTUNE)
return ds
train_ds = make_dataset(df[df["split"] == "train"], shuffle=True)
val_ds = make_dataset(df[df["split"] == "val"], shuffle=False)
# --- model: EfficientNetB0 transfer learning ---
backbone = tf.keras.applications.EfficientNetB0(
include_top=False, weights="imagenet", input_shape=(256, 256, 3))
backbone.trainable = False
model = tf.keras.Sequential([
backbone,
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(NUM_CLASSES, activation="softmax"),
], name="crophelth")
model.compile(
optimizer=tf.keras.optimizers.Adam(1e-3),
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
model.summary()
# --- stage 1: train the head ---
model.fit(train_ds, validation_data=val_ds, epochs=4)
# --- stage 2: unfreeze top of backbone, fine-tune ---
backbone.trainable = True
for layer in backbone.layers[:-30]:
layer.trainable = False
model.compile(
optimizer=tf.keras.optimizers.Adam(1e-5),
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
model.fit(train_ds, validation_data=val_ds, epochs=EPOCHS - 4)
model.save(os.path.join(DATA_DIR, "crophelth_model.keras"))
np.savez(os.path.join(DATA_DIR, "class_names.npz"), classes=np.array(CLASSES))
print("saved crophelth_model.keras + class_names.npz")
# --- inference: code-based output, ready for the treatment lookup ---
import json
x, y = next(iter(val_ds.batch(1)))
pred = int(np.argmax(model.predict(x, verbose=0)[0]))
print("predicted code:", CLASSES[pred])
treatments = json.load(open(os.path.join(DATA_DIR, "knowledge", "treatments.json")))
print("treatment:", treatments.get(CLASSES[pred]))