Spaces:
Sleeping
Sleeping
Download train.py from budijuarto/kriyatrack: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/spaces/budijuarto/kriyatrack/resolve/main/train.py
- Command line
-
hf download hf://spaces/budijuarto/kriyatrack/train.py
-
curl -L -o train.py https://huggingface.co/spaces/budijuarto/kriyatrack/resolve/main/train.py
12 kB
| """Train TensorFlow forecasts and build a chronological benchmark.""" | |
| import hashlib | |
| from keras_archive import make_portable | |
| import json | |
| import math | |
| import os | |
| import subprocess | |
| from pathlib import Path | |
| os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2") | |
| os.environ.setdefault("TF_ENABLE_ONEDNN_OPTS", "0") | |
| os.environ.setdefault("CUDA_VISIBLE_DEVICES", "-1") | |
| os.environ.setdefault("TF_NUM_INTEROP_THREADS", "1") | |
| os.environ.setdefault("TF_NUM_INTRAOP_THREADS", "2") | |
| import keras | |
| import numpy as np | |
| import tensorflow as tf | |
| from forecast_features import FEATURE_NAMES, feature_row, forecast_features, next_month | |
| ROOT = Path(__file__).resolve().parent | |
| DATA = ROOT / "data" / "ledger.json" | |
| MODELS = ROOT / "models" | |
| BENCHMARK = ROOT / "benchmark" | |
| SEED = 2882026 | |
| TRAIN_END = 42 | |
| VALIDATION_END = 54 | |
| GRIDS = ( | |
| {"hidden": [8, 4], "epochs": 80, "learningRate": 0.009, "l2": 0.05}, | |
| {"hidden": [12, 6], "epochs": 120, "learningRate": 0.008, "l2": 0.025}, | |
| ) | |
| class TrainingTrace(keras.callbacks.Callback): | |
| """Record actual training objective at repeatable checkpoints.""" | |
| def __init__(self, epochs): | |
| super().__init__() | |
| self.epochs = epochs | |
| self.points = [] | |
| def on_epoch_end(self, epoch, logs=None): | |
| loss = float(logs["loss"]) | |
| if not math.isfinite(loss): | |
| raise FloatingPointError("Loss model berubah menjadi tak hingga.") | |
| index = epoch + 1 | |
| if index in {1, self.epochs} or index % 20 == 0: | |
| self.points.append({"epoch": index, "loss": loss}) | |
| def run_node(args=(), payload=None): | |
| cmd = ["node", str(BENCHMARK / "causal.mjs"), *args] | |
| success = subprocess.run(cmd, input=payload, capture_output=True, check=False, encoding="utf-8", cwd=ROOT) | |
| if success.returncode: | |
| raise RuntimeError(success.stderr or success.stdout) | |
| return json.loads(success.stdout) | |
| def train_neural(history, settings): | |
| keras.backend.clear_session() | |
| keras.utils.set_random_seed(SEED) | |
| values = [row["value"] for row in history] | |
| features = np.asarray([feature_row(values[:index], row["month"]) | |
| for index, row in enumerate(history) if index >= 12], dtype=np.float32) | |
| residual = np.asarray(values[12:], dtype=np.float32) - features[:, 4] | |
| input_mean = features.mean(axis=0) | |
| input_variance = np.where(features.var(axis=0) > 0, features.var(axis=0), 1).astype(np.float32) | |
| output_mean = float(residual.mean()) | |
| output_scale = float(residual.std()) or 1.0 | |
| normalized_x = (features - input_mean) / np.sqrt(input_variance) | |
| normalized_y = ((residual - output_mean) / output_scale)[:, None] | |
| signal = keras.Input(shape=(len(FEATURE_NAMES),), dtype="float32", name="lag_terstandar") | |
| value = signal | |
| layers = [] | |
| for width in settings["hidden"]: | |
| layer = keras.layers.Dense(width, activation="tanh", kernel_regularizer=keras.regularizers.L2(settings["l2"])) | |
| layers.append(layer) | |
| value = layer(value) | |
| output = keras.layers.Dense(1, activation="linear", name="penyesuaian") | |
| layers.append(output) | |
| correction_model = keras.Model(signal, output(value), name="koreksi_neural_musiman") | |
| correction_model.compile(optimizer=keras.optimizers.Adam(settings["learningRate"]), loss="mse") | |
| training = tf.data.Dataset.from_tensor_slices((normalized_x, normalized_y)).batch(len(normalized_x)) | |
| options = tf.data.Options() | |
| options.threading.private_threadpool_size = 1 | |
| training = training.with_options(options) | |
| trace = TrainingTrace(settings["epochs"]) | |
| correction_model.fit(training, epochs=settings["epochs"], callbacks=[trace], verbose=0) | |
| raw = keras.Input(shape=(len(FEATURE_NAMES),), dtype="float32", name="fitur_kausal_bulanan") | |
| normalized = keras.layers.Normalization(axis=-1, mean=input_mean, variance=input_variance, name="normalisasi_latih")(raw) | |
| normalized_residual = correction_model(normalized) | |
| predicted_residual = keras.layers.Rescaling(output_scale, offset=output_mean, name="koreksi_rupiah")(normalized_residual) | |
| seasonal_selector = np.zeros((len(FEATURE_NAMES), 1), dtype=np.float32) | |
| seasonal_selector[4, 0] = 1.0 | |
| seasonal = keras.layers.Dense(1, use_bias=False, trainable=False, name="omzet_tahun_lalu", | |
| kernel_initializer=keras.initializers.Constant(seasonal_selector))(raw) | |
| prediction = keras.layers.Add(name="prakiraan_rupiah")([seasonal, predicted_residual]) | |
| model = keras.Model(raw, prediction, name="kriyatrack_prakiraan_bulanan") | |
| artifact = { | |
| "schema": "kriyatrack-neural/v1", "featureNames": list(FEATURE_NAMES), "trainedThrough": history[-1]["month"], | |
| "settings": settings, "normalization": {"mean": input_mean.tolist(), "variance": input_variance.tolist()}, | |
| "correction": {"scale": output_scale, "offset": output_mean}, | |
| "layers": [{"activation": layer.activation.__name__, "weights": layer.get_weights()[0].tolist(), | |
| "bias": layer.get_weights()[1].tolist()} for layer in layers], | |
| } | |
| return model, artifact, trace.points | |
| def model_value(model, features): | |
| return float(model(np.asarray([features], dtype=np.float32), training=False).numpy()[0, 0]) | |
| def rounded_value(raw): | |
| if not math.isfinite(raw) or raw > 10**12: | |
| raise ValueError("Prakiraan di luar batas rupiah yang didukung.") | |
| return math.floor(max(0, raw) + 0.5) | |
| def walk_neural(history, settings, start, end, parity=None): | |
| forecasts = [] | |
| for i in range(start, end): | |
| past = history[:i] | |
| target = history[i] | |
| assert next_month(past[-1]["month"]) == target["month"] | |
| model, artifact, _ = train_neural(past, settings) | |
| row = forecast_features(past) | |
| raw = model_value(model, row) | |
| predicted = rounded_value(raw) | |
| forecasts.append({"month": target["month"], "actual": target["value"], "predicted": predicted, | |
| "error": predicted - target["value"]}) | |
| if parity is not None: | |
| parity.append({"history": past, "features": row, "expected": raw, "artifact": artifact}) | |
| return forecasts | |
| def accuracy(rows): | |
| targets = [row["actual"] for row in rows] | |
| errors = [row["error"] for row in rows] | |
| absolute = sum(abs(error) for error in errors) | |
| percentages = [abs(error) / target for error, target in zip(errors, targets) if target > 0] | |
| return { | |
| "n": len(rows), "mae": absolute / len(rows), "rmse": math.sqrt(sum(error ** 2 for error in errors) / len(rows)), | |
| "wape": absolute / sum(targets) if sum(targets) else None, | |
| "mape": sum(percentages) / len(percentages) if percentages else None, "mapeCount": len(percentages), | |
| "bias": sum(errors) / len(rows), | |
| } | |
| def write_json(path, data): | |
| path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", newline="\n") | |
| def period(rows): | |
| return {"from": rows[0]["month"], "to": rows[-1]["month"]} | |
| def main(): | |
| tf.config.experimental.enable_op_determinism() | |
| ledger_bytes = DATA.read_bytes() | |
| ledger = json.loads(ledger_bytes) | |
| history = ledger["history"] | |
| assert len(history) == 72 | |
| assert len(ledger["orders"]) >= 1000 | |
| candidates = [] | |
| for settings in GRIDS: | |
| parity = [] | |
| validation = accuracy(walk_neural(history, settings, TRAIN_END, VALIDATION_END, parity)) | |
| candidates.append((settings, validation, parity)) | |
| print("Neural validation", settings, round(100 * validation["wape"], 2), flush=True) | |
| settings, validation, parity = min(candidates, key=lambda entry: (entry[1]["wape"], entry[1]["mae"])) | |
| print("Validation locked; predicting neural holdout.", settings, flush=True) | |
| test_points = walk_neural(history, settings, VALIDATION_END, len(history), parity) | |
| test = accuracy(test_points) | |
| MODELS.mkdir(exist_ok=True) | |
| final, artifact, trace = train_neural(history, settings) | |
| final_file = MODELS / "forecast-neural.keras" | |
| final.save(final_file) | |
| make_portable(final_file) | |
| reopened = keras.models.load_model(final_file, compile=False) | |
| assert tuple(reopened.input_shape) == (None, len(FEATURE_NAMES)) | |
| assert tuple(reopened.output_shape) == (None, 1) | |
| observed = [] | |
| for multiplier in (1.0, 0.78, 1.22): | |
| different = [{**row, "value": round(row["value"] * multiplier)} for row in history] | |
| features = forecast_features(different) | |
| expected = model_value(final, features) | |
| reloaded = model_value(reopened, features) | |
| observed.append(abs(expected - reloaded)) | |
| parity.append({"history": different, "features": features, "expected": reloaded, "artifact": artifact}) | |
| assert max(observed) <= 0.5 | |
| js_parity = run_node(("--parity",), json.dumps(parity, ensure_ascii=False)) | |
| write_json(MODELS / "forecast-neural.json", artifact) | |
| neural = { | |
| "id": "neural", "label": "Neural Network", "minHistory": 24, | |
| "description": "TensorFlow Functional, dua lapisan tersembunyi yang mempelajari koreksi dari omzet musiman.", | |
| "params": settings, "validation": validation, "test": test, "predictions": test_points, | |
| "nextForecast": rounded_value(model_value(reopened, forecast_features(history))), | |
| } | |
| models = [*run_node(), neural] | |
| ranked = sorted(models, key=lambda row: (row["validation"]["wape"], row["validation"]["mae"])) | |
| moving = next(row for row in models if row["id"] == "moving") | |
| report = { | |
| "schema": "kriyatrack-forecast-benchmark/v1", "synthetic": True, "currency": "IDR", | |
| "ledgerSha256": hashlib.sha256(ledger_bytes).hexdigest(), | |
| "salesRows": len(ledger["orders"]), "paidRows": sum(row["status"] == "paid" for row in ledger["orders"]), | |
| "sizes": {"initialTrain": TRAIN_END, "validation": VALIDATION_END - TRAIN_END, "test": len(history) - VALIDATION_END}, | |
| "periods": {"initialTrain": period(history[:TRAIN_END]), "validation": period(history[TRAIN_END:VALIDATION_END]), | |
| "test": period(history[VALIDATION_END:])}, | |
| "horizonMonths": 1, | |
| "defaultProfile": ranked[0]["id"], "deploymentProfile": "neural", | |
| "forecastMonth": next_month(history[-1]["month"]), | |
| "targets": { | |
| "mapeMax": 0.20, "mapeMet": test["mape"] <= 0.20, | |
| "movingAverageMape": moving["test"]["mape"], "beatsMovingAverage": test["mape"] < moving["test"]["mape"], | |
| }, | |
| "parity": {"js": js_parity, "kerasReload": {"rows": len(observed), "maxRawDiff": max(observed)}}, | |
| "training": { | |
| "tensorflow": tf.__version__, "keras": keras.__version__, "seed": SEED, | |
| "architecture": [len(FEATURE_NAMES), *settings["hidden"], 1], | |
| "customCallback": "TrainingTrace", | |
| "candidateValidation": [{"params": params, "validation": row} for params, row, _ in candidates], | |
| "finalTrainingTrace": trace, | |
| }, | |
| "method": { | |
| "history": "Omzet per bulan tanggal order, dari transaksi lunas pada bulan tertutup. Total transaksi adalah jumlah × harga satuan.", | |
| "evaluation": "Prediksi satu bulan ke depan secara walk-forward. Setiap model hanya menerima omzet sebelum bulan target.", | |
| "selection": "Parameter dan pembanding bawaan dipilih menurut WAPE validasi. Bulan uji tidak dipakai memilih parameter.", | |
| "metrics": "MAE/RMSE dalam rupiah. WAPE dan MAPE sebagai pecahan; MAPE melewati bulan nol. Bias = prediksi dikurangi aktual.", | |
| "deployment": "TensorFlow neural dilatih kembali pada semua 72 bulan setelah pengujian. Prediksi bulan sesudahnya belum memiliki aktual.", | |
| }, | |
| "models": models, | |
| } | |
| write_json(BENCHMARK / "results.json", report) | |
| print(json.dumps({ | |
| "tf": tf.__version__, "targets": report["targets"], "parity": report["parity"], | |
| "models": [{key: row[key] for key in ("id", "test", "nextForecast")} for row in models], | |
| }, ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |