gusdelact commited on
Commit
4af85e0
·
verified ·
1 Parent(s): 9e1d3de

Upload notebooks/02_inferencia.ipynb with huggingface_hub

Browse files
Files changed (1) hide show
  1. notebooks/02_inferencia.ipynb +146 -0
notebooks/02_inferencia.ipynb ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "cell30",
6
+ "metadata": {},
7
+ "source": [
8
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/#fileId=https%3A%2F%2Fhuggingface.co%2Fgusdelact%2Fbond-trade-price-histgb%2Fresolve%2Fmain%2Fnotebooks%2F02_inferencia.ipynb)\n",
9
+ "\n",
10
+ "# 02 \u2014 Inferencia (Bond Trade Price)\n",
11
+ "\n",
12
+ "Descarga el modelo entrenado desde HF Hub y predice `trade_price`. No reentrena nada.\n"
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "id": "cell31",
18
+ "metadata": {},
19
+ "execution_count": null,
20
+ "outputs": [],
21
+ "source": [
22
+ "import importlib, subprocess\n",
23
+ "def _ensure(pkg, import_name=None):\n",
24
+ " name = import_name or pkg.split('[')[0].split('==')[0].split('>=')[0]\n",
25
+ " try:\n",
26
+ " importlib.import_module(name)\n",
27
+ " except ImportError:\n",
28
+ " subprocess.check_call(['uv','pip','install','--system','--quiet',pkg])\n",
29
+ "_ensure('huggingface-hub>=0.28.1', 'huggingface_hub')\n"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "id": "cell32",
35
+ "metadata": {},
36
+ "execution_count": null,
37
+ "outputs": [],
38
+ "source": [
39
+ "import json, joblib, sklearn\n",
40
+ "from pathlib import Path\n",
41
+ "import numpy as np, pandas as pd\n",
42
+ "from huggingface_hub import hf_hub_download\n",
43
+ "\n",
44
+ "REPO_ID = 'gusdelact/bond-trade-price-histgb'\n",
45
+ "model = joblib.load(hf_hub_download(REPO_ID, 'model.joblib'))\n",
46
+ "info = json.loads(Path(hf_hub_download(REPO_ID, 'model_info.json')).read_text())\n",
47
+ "exp = info['library_versions'].get('scikit-learn')\n",
48
+ "if exp and exp != sklearn.__version__:\n",
49
+ " print(f'[warn] sklearn instalado={sklearn.__version__}, modelo={exp}. Si falla, reentrena.')\n",
50
+ "FEATURE_ORDER = info['feature_order']; DEFAULTS = info['defaults']\n",
51
+ "print('modelo:', info['model_name'], '| MAE test:', info['test_metrics']['mae'] if 'test_metrics' in info else info.get('metrics'))\n"
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "markdown",
56
+ "id": "cell33",
57
+ "metadata": {},
58
+ "source": [
59
+ "## Funcion de prediccion\n",
60
+ "\n",
61
+ "Envuelve el input en un DataFrame con las columnas en el orden de `feature_order` (evita warnings y cruces silenciosos). Las features no provistas usan `defaults`."
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "id": "cell34",
67
+ "metadata": {},
68
+ "execution_count": null,
69
+ "outputs": [],
70
+ "source": [
71
+ "def predict(input_dict: dict) -> float:\n",
72
+ " row = dict(DEFAULTS)\n",
73
+ " row.update({k: v for k, v in input_dict.items() if k in FEATURE_ORDER})\n",
74
+ " X = pd.DataFrame([{c: row[c] for c in FEATURE_ORDER}])\n",
75
+ " return float(np.clip(model.predict(X), 0, None)[0])\n"
76
+ ]
77
+ },
78
+ {
79
+ "cell_type": "markdown",
80
+ "id": "cell35",
81
+ "metadata": {},
82
+ "source": [
83
+ "## Ejemplo feliz"
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "id": "cell36",
89
+ "metadata": {},
90
+ "execution_count": null,
91
+ "outputs": [],
92
+ "source": [
93
+ "ejemplo = {'curve_based_price': 101.5, 'trade_price_last1': 101.2,\n",
94
+ " 'current_coupon': 5.0, 'time_to_maturity': 8.0, 'trade_size': 100000,\n",
95
+ " 'trade_type': 2}\n",
96
+ "print('precio estimado:', round(predict(ejemplo), 3))\n"
97
+ ]
98
+ },
99
+ {
100
+ "cell_type": "markdown",
101
+ "id": "cell37",
102
+ "metadata": {},
103
+ "source": [
104
+ "## Ejemplo de error (feature desconocida se ignora; faltantes usan default)"
105
+ ]
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "id": "cell38",
110
+ "metadata": {},
111
+ "execution_count": null,
112
+ "outputs": [],
113
+ "source": [
114
+ "try:\n",
115
+ " print('con feature inexistente:', round(predict({'foo_bar': 1.0}), 3),\n",
116
+ " '(usa todos los defaults)')\n",
117
+ "except Exception as e:\n",
118
+ " print('error:', e)\n"
119
+ ]
120
+ },
121
+ {
122
+ "cell_type": "markdown",
123
+ "id": "cell39",
124
+ "metadata": {},
125
+ "source": [
126
+ "## Bonus \u2014 comparacion con el HF Space desplegado (opcional)\n",
127
+ "\n",
128
+ "El modelo esta desplegado en https://huggingface.co/spaces/gusdelact/bond-trade-price-predictor\n",
129
+ "La logica de `predict` aqui coincide con la de `app_inference/app_inference.py`."
130
+ ]
131
+ }
132
+ ],
133
+ "metadata": {
134
+ "kernelspec": {
135
+ "display_name": "Python 3",
136
+ "language": "python",
137
+ "name": "python3"
138
+ },
139
+ "language_info": {
140
+ "name": "python",
141
+ "version": "3.12"
142
+ }
143
+ },
144
+ "nbformat": 4,
145
+ "nbformat_minor": 5
146
+ }