Download inference.py from DaviNeg/Alzheimer_Clinical_Predictor: direct link, hf CLI and curl.
- Browser
- Download file 2.55 kB
-
https://huggingface.co/DaviNeg/Alzheimer_Clinical_Predictor/resolve/main/inference.py
- Command line
-
hf download hf://DaviNeg/Alzheimer_Clinical_Predictor/inference.py
-
curl -L -o inference.py https://huggingface.co/DaviNeg/Alzheimer_Clinical_Predictor/resolve/main/inference.py
2.55 kB
| """Inferência local para o artefato tabular publicado neste repositório.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import cloudpickle | |
| import numpy as np | |
| import pandas as pd | |
| ROOT = Path(__file__).resolve().parent | |
| def load_model(root: Path = ROOT): | |
| """Carrega somente o artefato deste repositório, que usa cloudpickle.""" | |
| with (root / "model" / "model.pkl").open("rb") as handle: | |
| return cloudpickle.load(handle) | |
| def prepare_features(data: pd.DataFrame, root: Path = ROOT) -> pd.DataFrame: | |
| schema = json.loads((root / "model" / "feature_schema.json").read_text(encoding="utf-8")) | |
| expected = schema["features"] | |
| missing = [name for name in expected if name not in data.columns] | |
| extra = [name for name in data.columns if name not in expected] | |
| if missing or extra: | |
| raise ValueError(f"Colunas incompatíveis. Ausentes: {missing}; extras: {extra}") | |
| features = data.loc[:, expected].apply(pd.to_numeric, errors="raise") | |
| if features.isna().any().any() or not np.isfinite(features.to_numpy(dtype=float)).all(): | |
| raise ValueError("Todas as 59 variáveis devem ser numéricas e finitas, sem valores ausentes.") | |
| return features | |
| def predict(data: pd.DataFrame, *, threshold: float = 0.5, root: Path = ROOT) -> pd.DataFrame: | |
| if not 0 <= threshold <= 1: | |
| raise ValueError("O limiar deve estar entre 0 e 1.") | |
| features = prepare_features(data, root) | |
| model = load_model(root) | |
| if hasattr(model, "feature_names_in_") and list(model.feature_names_in_) != list(features.columns): | |
| raise ValueError("A ordem das variáveis difere daquela armazenada no modelo.") | |
| probability = model.predict_proba(features)[:, list(model.classes_).index(1)] | |
| return pd.DataFrame({"probability_class_1": probability, | |
| "predicted_class": (probability >= threshold).astype(int)}, index=data.index) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description="Predição acadêmica sobre dados já preparados.") | |
| parser.add_argument("input_csv", type=Path, help="CSV com as 59 colunas de model/feature_schema.json") | |
| parser.add_argument("--output", type=Path, help="Caminho do CSV de saída") | |
| args = parser.parse_args() | |
| result = predict(pd.read_csv(args.input_csv)) | |
| if args.output: | |
| result.to_csv(args.output, index=False) | |
| print(f"Resultado salvo em {args.output}") | |
| else: | |
| print(result.to_csv(index=False), end="") | |
| if __name__ == "__main__": | |
| main() | |