diff --git a/.env b/.env index deecc7d..44680b5 100644 --- a/.env +++ b/.env @@ -1,11 +1,8 @@ WATCHPACK_POLLING=true FAST_REFRESH=true -NODE_ENV="development" PUBLIC_URL="http://localhost:5173/n4l" VITE_PUBLIC_URL="https://localhost:5173/n4l" VITE_PATH="/n4l" VITE_ENVIRONMENT="development" VITE_GA_MEASUREMENT_ID="G-3644EFBXMG" -VITE_SHOW_NEW_FEATURE="true" -VITE_NEW_FEATURE="linear-regression" GENERATE_SOURCEMAP=true \ No newline at end of file diff --git a/.env.netlify b/.env.netlify index ea465f3..d67607b 100644 --- a/.env.netlify +++ b/.env.netlify @@ -1,11 +1,8 @@ WATCHPACK_POLLING=true FAST_REFRESH=true -NODE_ENV="production" PUBLIC_URL="http://nets4learning.netlify.app" VITE_PUBLIC_URL="https://nets4learning.netlify.app" VITE_PATH="" VITE_ENVIRONMENT="production" VITE_GA_MEASUREMENT_ID="G-3644EFBXMG" -VITE_SHOW_NEW_FEATURE="true" -VITE_NEW_FEATURE="linear-regression" GENERATE_SOURCEMAP=true \ No newline at end of file diff --git a/.env.simidat b/.env.simidat index 430c2e8..14d1e45 100644 --- a/.env.simidat +++ b/.env.simidat @@ -1,11 +1,8 @@ WATCHPACK_POLLING=true FAST_REFRESH=true -NODE_ENV="production" PUBLIC_URL="http://simidat.ujaen.es/n4l" VITE_PUBLIC_URL="https://simidat.ujaen.es/n4l" VITE_PATH="/n4l" VITE_ENVIRONMENT="production" VITE_GA_MEASUREMENT_ID="G-3644EFBXMG" -VITE_SHOW_NEW_FEATURE="true" -VITE_NEW_FEATURE="linear-regression" GENERATE_SOURCEMAP=true \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/accessibility.md b/.github/ISSUE_TEMPLATE/accessibility.md new file mode 100644 index 0000000..c35e809 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/accessibility.md @@ -0,0 +1,21 @@ +--- +name: Barrera de accesibilidad / Accessibility barrier +about: Algo que no se puede usar con lector de pantalla, teclado, zoom… / Something you cannot use with a screen reader, keyboard, zoom… +title: '[Accesibilidad] ' +labels: 'accesibilidad' +assignees: '' + +--- + + + +**¿En qué página estabas y qué querías hacer? / Which page were you on and what did you want to do?** + + +**¿Qué ha pasado? / What happened?** + + +**Navegador y ayudas técnicas / Browser and assistive technology** + + + diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..d52b368 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,14 @@ +## Qué cambia + + + +## Accesibilidad + + + +- [ ] Se puede usar solo con el teclado: se llega a todo, el orden es lógico, el foco se ve y no se pierde. +- [ ] Cada control tiene un nombre que empieza por lo que se ve; las imágenes y las gráficas, su texto alternativo o su tabla («Ver los datos»). +- [ ] Lo que cambia sin mover el foco se anuncia con `announce()`; los errores se dicen junto al campo. +- [ ] Contraste suficiente en los temas claro y oscuro (texto 4,5:1; bordes, iconos y gráficas 3:1) y nada depende solo del color. +- [ ] Se ve bien a 320 px de ancho, con el texto al 200 % y con los ajustes de accesibilidad de /settings. +- [ ] Las páginas o estados nuevos están en las pruebas de axe (`e2e/accesibilidad*.spec.ts`) y, si tienen un flujo nuevo, en `e2e/teclado.spec.ts`. diff --git a/.github/workflows/checks.yaml b/.github/workflows/checks.yaml new file mode 100644 index 0000000..6b800ff --- /dev/null +++ b/.github/workflows/checks.yaml @@ -0,0 +1,64 @@ +name: 'Checks' + +# Lint, tipos, tests unitarios (vitest) y pruebas en el navegador (Playwright). Se lanzan en cada pull request y, +# antes de publicar, desde deploy.yaml: si algo falla, no se despliega. +on: + pull_request: + workflow_call: + +jobs: + static: + name: 'Lint, tipos y tests unitarios' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + + # La versión de pnpm se toma de "packageManager" en package.json (pnpm 12, que necesita la 6.1.0 o posterior: + # la etiqueta v6 se quedó en la anterior). + - name: Install pnpm + uses: pnpm/action-setup@v6.1.0 + + - name: Install Node.js + uses: actions/setup-node@v7 + with: + node-version: 24 + cache: 'pnpm' + + - run: pnpm install --frozen-lockfile + - run: pnpm lint + - run: pnpm exec tsc -b + - run: pnpm exec vitest run + + e2e: + name: 'Pruebas en el navegador (Playwright)' + runs-on: ubuntu-24.04 + # Entrenar las tres tareas con WebGL por software lleva unos minutos + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + + - name: Install pnpm + uses: pnpm/action-setup@v6.1.0 + + - name: Install Node.js + uses: actions/setup-node@v7 + with: + node-version: 24 + cache: 'pnpm' + + - run: pnpm install --frozen-lockfile + - run: pnpm exec playwright install --with-deps chromium + + # playwright.config.ts construye la versión de Netlify y la sirve con `vite preview` + - run: pnpm test:e2e + env: + NODE_OPTIONS: "--max_old_space_size=6144" + + # Informe con capturas y trazas de las pruebas que fallen + - uses: actions/upload-artifact@v7 + if: ${{ !cancelled() }} + with: + name: playwright-report + path: playwright-report + retention-days: 14 diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml index ff99963..5f310b2 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -4,43 +4,84 @@ on: push: tags: - 'v*' + # Rama de mejoras de la interfaz: se publica en Netlify antes de pasar a main + branches: + - 'mejoras-ui' + # Despliegue manual desde la pestaña Actions + workflow_dispatch: + +# Si llegan dos pushes seguidos, solo se publica el último +concurrency: + group: deploy-netlify-stable + cancel-in-progress: true jobs: + # Lint, tipos, tests unitarios y pruebas en el navegador (checks.yaml): si fallan, no se publica + checks: + name: 'Checks' + uses: ./.github/workflows/checks.yaml + deploy-stable: name: 'Deploy to netlify stable' + needs: checks runs-on: ubuntu-24.04 + timeout-minutes: 20 steps: - - name: 'Create env file' + # Antes de instalar y construir: que el token valga y pueda publicar en el sitio, con un error que diga cuál de + # los dos falla (netlify-cli 17, el de la acción que se usaba antes, decía "Site not found" en ambos casos). + - name: 'Check the Netlify token and site' + env: + NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} + NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID_STABLE }} run: | - echo "${{ vars.NETLIFY_ENV_FILE_STABLE }}" > .env.netlify - - uses: actions/checkout@v4 + if [ -z "$NETLIFY_AUTH_TOKEN" ] || [ -z "$NETLIFY_SITE_ID" ]; then + echo "::error::Faltan los secretos NETLIFY_AUTH_TOKEN o NETLIFY_SITE_ID_STABLE (Settings › Secrets and variables › Actions)" + exit 1 + fi + status() { + curl -sS --retry 2 -o /dev/null -w '%{http_code}' -H "Authorization: Bearer $NETLIFY_AUTH_TOKEN" "https://api.netlify.com/api/v1/$1" + } + user=$(status user) + if [ "$user" != "200" ]; then + echo "::error::Netlify no acepta NETLIFY_AUTH_TOKEN (HTTP $user): ha caducado o se ha revocado. Crea otro en https://app.netlify.com/user/applications#personal-access-tokens y actualiza el secreto" + exit 1 + fi + site=$(status "sites/$NETLIFY_SITE_ID") + if [ "$site" != "200" ]; then + echo "::error::El token es válido pero no llega al sitio de NETLIFY_SITE_ID_STABLE (HTTP $site): comprueba el Project ID (Project configuration › General) y que el dueño del token esté en el equipo del sitio" + exit 1 + fi + echo "Token y sitio de Netlify correctos" + + - uses: actions/checkout@v7 with: submodules: recursive - # La versión de pnpm se toma de "packageManager" en package.json (pnpm 12). + # Se usa el .env.netlify del repositorio salvo que la variable NETLIFY_ENV_FILE_STABLE traiga otro. Va después + # del checkout: antes, el checkout lo sobrescribía. + - name: 'Create env file' + if: ${{ vars.NETLIFY_ENV_FILE_STABLE != '' }} + env: + ENV_FILE: ${{ vars.NETLIFY_ENV_FILE_STABLE }} + run: printf '%s\n' "$ENV_FILE" > .env.netlify + + # La versión de pnpm se toma de "packageManager" en package.json (pnpm 12, que necesita la 6.1.0 o posterior: + # la etiqueta v6 se quedó en la anterior). - name: Install pnpm - uses: pnpm/action-setup@v4 + uses: pnpm/action-setup@v6.1.0 - name: Install Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@v7 with: - node-version: 22 + node-version: 24 cache: 'pnpm' - - uses: jsmrcaga/action-netlify-deploy@v2.4.0 - with: - NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} - NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID_STABLE }} - NETLIFY_DEPLOY_MESSAGE: "Deploy v${{ github.ref }}" - NETLIFY_DEPLOY_TO_PROD: true - # NODE_ENV=production (abajo) haría que pnpm omitiera las devDependencies (vite, typescript…) - # que necesita el build: --production=false las instala igualmente. - INSTALL_COMMAND: pnpm install --frozen-lockfile --production=false - BUILD_COMMAND: pnpm run build:netlify - # Vite genera el build en dist/ (no en build/, que era la carpeta de Create React App). - BUILD_DIRECTORY: 'dist' + - run: pnpm install --frozen-lockfile + + # Vite genera el build en dist/ + - name: Build + run: pnpm run build:netlify env: - CI: false NODE_OPTIONS: "--max_old_space_size=6144" NODE_ENV: "production" PUBLIC_URL: "https://nets4learning.netlify.app" @@ -48,4 +89,12 @@ jobs: VITE_PATH: "" VITE_PUBLIC_URL: "https://nets4learning.netlify.app" VITE_GA_MEASUREMENT_ID: "G-3644EFBXMG" - VITE_SHOW_NEW_FEATURE: "false" + + # netlify-cli al día (jsmrcaga/action-netlify-deploy, la acción de antes, fijaba la 17, de 2024). Ahora `deploy` + # construye por defecto: --no-build publica el dist/ de arriba. + - name: 'Deploy to Netlify' + env: + NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} + NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID_STABLE }} + DEPLOY_MESSAGE: "Deploy ${{ github.ref_name }} (${{ github.sha }})" + run: npx --yes netlify-cli@27 deploy --no-build --prod --dir dist --message "$DEPLOY_MESSAGE" diff --git a/.gitignore b/.gitignore index a547bf3..8a8f40c 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,10 @@ dist-ssr *.njsproj *.sln *.sw? + +# Playwright (pnpm test:e2e) +playwright-report +test-results +blob-report + +_tmp/ \ No newline at end of file diff --git a/README.md b/README.md index 2ac9408..0e9ad96 100644 --- a/README.md +++ b/README.md @@ -9,10 +9,10 @@

- Open the app · - Manual · - Paper · - Changelog · + Open the app | + Manual | + Paper | + Changelog | MIT License

@@ -34,7 +34,9 @@ Models*](https://doi.org/10.3390/electronics13224378) (Electronics, 2024). If yo - **Four tasks:** tabular classification, regression, object detection and image classification. - **Training in the browser:** layer editor, optimizers, loss functions, metrics and live training charts (tfjs-vis). You can train several models and compare them. -- **Your own data:** upload a CSV, then clean, encode and scale its columns before training. +- **Your own data:** upload a CSV (comma or semicolon separated, with decimal commas too), ARFF, JSON, JSONL or + Parquet file, then clean, encode and scale its columns before training. Every format is converted to CSV in the + browser and read the same way. - **Pre-trained models** for each task, ready to try with examples, your own images, a drawing canvas or the webcam. - **Explainability:** SHAP for tabular data, regression and images, and LRP (layer-wise relevance propagation) for the handwriting models. @@ -61,7 +63,7 @@ React 19, TypeScript 5.9 and Vite 7, with: - React-Bootstrap for the interface; - Chart.js and Plotly for charts; - i18next for translations; -- Vitest and Testing Library for tests. +- Vitest and Testing Library for unit tests, Playwright for browser tests. ## Getting started @@ -85,12 +87,15 @@ The app is served at . | `pnpm preview` | Serve the last build locally | | `pnpm test` | Run the tests in watch mode (`pnpm test run` runs them once) | | `pnpm test:ui` / `pnpm test:coverage` | Tests in the Vitest UI / with coverage | +| `pnpm test:e2e` | Browser tests (Playwright, `e2e/`) against the Netlify build | | `pnpm lint` | ESLint | | `pnpm version` | Update `CHANGELOG.md` from the commit history | The build is memory-hungry. If it runs out of memory, run it with `NODE_OPTIONS="--max-old-space-size=8192"`, as the Docker image does. +The first time you run `pnpm test:e2e`, install its browser with `pnpm exec playwright install chromium`. + ### Environment variables Vite reads `.env` and then `.env.`. The three files are versioned: @@ -106,10 +111,15 @@ The app uses these variables: | `VITE_PATH` | Path the app is served under: `"/n4l"` or `""` for the domain root. It also sets Vite's `base`. | | `VITE_ENVIRONMENT` | `development` enables i18next debug logs, shorter default training and development panels. Any value other than `production` also enables the development-only pages, `/debug` and the test pages. | | `VITE_GA_MEASUREMENT_ID` | Google Analytics 4 measurement ID. | -| `VITE_SHOW_NEW_FEATURE` | `"true"` shows sections that are still in progress (glossary, datasets page). | ## Deployment +### Netlify + +[`deploy.yaml`](.github/workflows/deploy.yaml) publishes to Netlify on every `v*` tag (and on pushes to the +`mejoras-ui` branch). It first runs [`checks.yaml`](.github/workflows/checks.yaml) (lint, types, unit tests and +browser tests), the same checks every pull request gets: if any of them fails, nothing is published. + ### Docker The [Dockerfile](Dockerfile) builds the app with pnpm and serves it with an unprivileged nginx under `/n4l/`. It uses @@ -136,6 +146,7 @@ src/ MODEL_KEYS.ts Dataset and model identifiers Scripts/ Dataset and model generation tests/ Vitest tests +e2e/ Playwright tests ``` To add a dataset or a pre-trained model: @@ -148,7 +159,7 @@ To add a dataset or a pre-trained model: - Commits follow [Conventional Commits](https://www.conventionalcommits.org/); commitlint checks them. - Before opening a pull request, run `pnpm lint`, `pnpm test run` and `pnpm build:simidat`. The build also - type-checks the project. + type-checks the project. CI also runs `pnpm test:e2e`. - New interface texts go into the three translation files. Manual pages go into `public/docs/{en,es,ja}`. ## Team diff --git a/Scripts/__pycache__/build_kmnist_examples.cpython-313.pyc b/Scripts/__pycache__/build_kmnist_examples.cpython-313.pyc new file mode 100644 index 0000000..fee4289 Binary files /dev/null and b/Scripts/__pycache__/build_kmnist_examples.cpython-313.pyc differ diff --git a/Scripts/build_cifar10_package.py b/Scripts/build_cifar10_package.py new file mode 100644 index 0000000..21794a9 --- /dev/null +++ b/Scripts/build_cifar10_package.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +""" +Prepara el paquete .n4l de CIFAR-10 (public/n4l/cifar10.n4l/) con sus datos, sus imágenes de ejemplo y su manifiesto +(sus textos, en locales/, se escriben a mano; el modelo lo entrena Scripts/train_cifar10_model.py): + + - data/cifar10_images.png : sprite en color, una imagen de 32×32 por fila (1024 px de ancho, RGB). Primero las de + entrenamiento y después las de prueba. + - data/cifar10_labels_uint8: sus clases en one-hot, 10 bytes por imagen, en el mismo orden. + - examples/.png : una foto de prueba de cada clase, ampliada ×4 sin suavizar (128×128). + +Se toma un subconjunto equilibrado, como en KMNIST: las primeras --train-per-class imágenes de cada clase de las de +entrenamiento oficiales y las primeras --test-per-class de las de prueba (con los valores por defecto, unos 16 MB). El +modelo ya entrenado no vio ninguna de las de prueba. + +Las fotos de ejemplo son de prueba, pero no del sprite: de cada clase, la primera que sigue a las del sprite y que el +modelo del paquete acierta (los ejemplos enseñan lo que reconoce; sus fallos se ven con las imágenes de prueba). Por eso +este script va después de entrenar el modelo, y después de él, el que mide el modelo con las imágenes de prueba del +sprite y guarda sus métricas en el manifiesto: + + python3 Scripts/train_cifar10_model.py + python3 Scripts/build_cifar10_package.py + python3 Scripts/measure_image_models.py --package cifar10 --write + +Uso: python3 Scripts/build_cifar10_package.py [--train-per-class 500] [--test-per-class 200] [--data-dir …] +Requiere numpy y Pillow. +""" +import argparse +import json +from pathlib import Path + +import numpy as np +from PIL import Image + +from cifar10_data import CLASS_LABELS, DEFAULT_DATA_DIR, TEST_FILES, TRAIN_FILES, cifar_dir, load_split +import measure_image_models + +PACKAGE = Path(__file__).resolve().parent.parent / 'public' / 'n4l' / 'cifar10.n4l' +MODEL = 'models/cnn/model.json' +EXAMPLE_SCALE = 4 +IMAGE = {'width': 32, 'height': 32, 'channels': 3} +# La red con la que se empieza a entrenar en la aplicación: la del tutorial de CIFAR-10 de TensorFlow, pequeña para que +# entrene en el navegador. La primera capa recibe las fotos: no se puede quitar +TRAINING_LAYERS = [ + {'class': 'conv2d', 'filters': 32, 'kernelSize': 3, 'activation': 'relu', 'locked': True}, + {'class': 'maxPooling2d', 'poolSize': 2, 'strides': 2}, + {'class': 'conv2d', 'filters': 64, 'kernelSize': 3, 'activation': 'relu'}, + {'class': 'maxPooling2d', 'poolSize': 2, 'strides': 2}, + {'class': 'conv2d', 'filters': 64, 'kernelSize': 3, 'activation': 'relu'}, + {'class': 'flatten'}, + {'class': 'dense', 'units': 64, 'activation': 'relu'}, + {'class': 'dense', 'units': len(CLASS_LABELS), 'activation': 'softmax'}, +] +CITATION = '''@techreport{krizhevsky2009learning, + title = {Learning Multiple Layers of Features from Tiny Images}, + author = {Krizhevsky, Alex}, + institution = {University of Toronto}, + year = {2009} +}''' + + +def balanced(labels: np.ndarray, per_class: int) -> np.ndarray: + """Las primeras `per_class` de cada clase, en el orden original""" + return np.sort(np.concatenate([np.flatnonzero(labels == c)[:per_class] for c in range(len(CLASS_LABELS))])) + + +def hwc(images: np.ndarray) -> np.ndarray: + """(n, 3, 32, 32) → (n, 32, 32, 3): alto, ancho y canal, como el sprite y la red""" + return images.transpose(0, 2, 3, 1) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--train-per-class', type=int, default=500) + parser.add_argument('--test-per-class', type=int, default=200) + parser.add_argument('--data-dir', type=Path, default=DEFAULT_DATA_DIR) + args = parser.parse_args() + + batches = cifar_dir(args.data_dir) + train_images, train_labels = load_split(batches, TRAIN_FILES) + test_images, test_labels = load_split(batches, TEST_FILES) + train_rows = balanced(train_labels, args.train_per_class) + test_rows = balanced(test_labels, args.test_per_class) + + # El sprite y sus clases + images = np.concatenate([hwc(train_images[train_rows]), hwc(test_images[test_rows])]) + labels = np.concatenate([train_labels[train_rows], test_labels[test_rows]]) + (PACKAGE / 'data').mkdir(parents=True, exist_ok=True) + Image.fromarray(images.reshape(len(images), 32 * 32, 3), 'RGB').save(PACKAGE / 'data' / 'cifar10_images.png', optimize=True) + np.eye(len(CLASS_LABELS), dtype=np.uint8)[labels].tofile(PACKAGE / 'data' / 'cifar10_labels_uint8') + print(f'Sprite: {len(train_rows)} imágenes de entrenamiento y {len(test_rows)} de prueba, ' + f'{(PACKAGE / "data" / "cifar10_images.png").stat().st_size / 1e6:.1f} MB') + + # Las fotos de ejemplo: de las de prueba que no están en el sprite, la primera de cada clase que el modelo acierta + layers, weights = measure_image_models.load_layers_model(PACKAGE / MODEL) + outside = np.setdiff1d(np.arange(len(test_labels)), test_rows) + candidates = outside[:2000] + predictions = measure_image_models.predict(layers, weights, hwc(test_images[candidates]).astype(np.float32) / 255).argmax(axis=1) + (PACKAGE / 'examples').mkdir(exist_ok=True) + examples = [] + for label, name in enumerate(CLASS_LABELS): + row = next(int(row) for row, prediction in zip(candidates, predictions) if test_labels[row] == label and prediction == label) + big = Image.fromarray(hwc(test_images[[row]])[0]).resize((32 * EXAMPLE_SCALE, 32 * EXAMPLE_SCALE), Image.Resampling.NEAREST) + big.save(PACKAGE / 'examples' / f'{name}.png', optimize=True) + examples.append({'file': f'examples/{name}.png', 'expected': name}) + + manifest = { + '$schema' : '../n4l.schema.json', + 'format' : 'n4l', + 'formatVersion': 1, + 'id' : 'cifar10', + 'version' : '1.0.0', + 'locales' : ['es', 'en', 'ja'], + 'source' : {'url': 'https://www.cs.toronto.edu/~kriz/cifar.html', 'citation': CITATION}, + 'datasets' : [{ + 'id' : 'cifar10', + 'kind' : 'image-sprite', + 'file' : 'data/cifar10_images.png', + 'labels': 'data/cifar10_labels_uint8', + 'rows' : len(images), + 'train' : len(train_rows), + 'image' : IMAGE, + }], + 'tasks' : [{ + 'task' : 'image-classification', + 'key' : 'IMAGE-CIFAR10', + 'runtime' : 'image-classification', + 'datasets' : ['cifar10'], + 'order' : 3, + 'preprocessing': [], + 'classes' : [{'id': name} for name in CLASS_LABELS], + 'models' : [{'id': 'cnn', 'format': 'tfjs-layers', 'path': MODEL, 'dataset': 'cifar10'}], + 'prediction' : {'images': examples}, + # Con 5.000 fotos, 0,001 y 20 épocas llegan a un 43 % de aciertos; con los valores de la aplicación (0,01 y 5), + # a un 16 % + 'training' : {'layers': TRAINING_LAYERS, 'learningRate': 0.001, 'epochs': 20}, + }], + } + (PACKAGE / 'manifest.json').write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + '\n') + print(f'Manifiesto en {PACKAGE / "manifest.json"}') + + +if __name__ == '__main__': + main() diff --git a/Scripts/build_kmnist_examples.py b/Scripts/build_kmnist_examples.py index 3a5e7d1..70fe61f 100644 --- a/Scripts/build_kmnist_examples.py +++ b/Scripts/build_kmnist_examples.py @@ -1,25 +1,36 @@ #!/usr/bin/env python3 """ -Genera las imágenes de ejemplo del modelo KMNIST (public/assets/kmnist/0.png … 9.png): cada uno de los -10 caracteres hiragana escrito con una fuente, en negro sobre fondo blanco. +Genera las imágenes de ejemplo del paquete de KMNIST (public/n4l/kmnist.n4l/examples/; su manifest.json las nombra en +prediction.images), en negro sobre fondo blanco: -El carácter se encaja en un cuadrado de 200x200 centrado en la imagen de 280x280, la misma proporción -(20/28) con la que están centrados los caracteres en KMNIST y los dígitos en MNIST. + - 0.png … 9.png: cada uno de los 10 caracteres hiragana como se escribe hoy, con una fuente. + - forms/.png: sus formas antiguas, las hentaigana de Unicode (de U+1B000 + en adelante, p. ej. 1B09E.png es HENTAIGANA LETTER HA-1), con una fuente que las tenga. Hasta 1900 + una misma sílaba se escribía de varias formas; en KMNIST aparecen escritas a mano bajo el carácter + de hoy. Son de 112x112 (4 veces 28): se enseñan pequeñas y pesan poco. -Uso: python3 Scripts/build_kmnist_examples.py [--font /ruta/a/la/fuente.ttc] -Requiere Pillow y una fuente con hiragana (por defecto Noto Sans CJK JP Bold, del paquete fonts-noto-cjk). +El carácter se encaja en un cuadrado centrado que ocupa 20/28 de la imagen, la misma proporción con la +que están centrados los caracteres en KMNIST y los dígitos en MNIST. + +Uso: python3 Scripts/build_kmnist_examples.py [--font fuente.ttc] [--hentaigana-font fuente.ttf] +Requiere Pillow (y Python 3.11 o posterior, por los nombres Unicode de las hentaigana). Por defecto, +Noto Sans CJK JP Bold (paquete fonts-noto-cjk) para los de hoy y Noto Serif Hentaigana para los +antiguos, en negrita: https://github.com/google/fonts/tree/main/ofl/notoserifhentaigana (licencia OFL). """ import argparse +import unicodedata from pathlib import Path from PIL import Image, ImageDraw, ImageFont -OUT_DIR = Path(__file__).resolve().parent.parent / 'public' / 'assets' / 'kmnist' +OUT_DIR = Path(__file__).resolve().parent.parent / 'public' / 'n4l' / 'kmnist.n4l' / 'examples' DEFAULT_FONT = '/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc' -# Los 10 caracteres de KMNIST (kmnist_classmap.csv), en el orden de las etiquetas +DEFAULT_HENTAIGANA_FONT = '/usr/share/fonts/truetype/noto/NotoSerifHentaigana[wght].ttf' +# Los 10 caracteres de KMNIST (kmnist_classmap.csv), en el orden de las etiquetas, con su sílaba en los nombres Unicode CHARS = ['お', 'き', 'す', 'つ', 'な', 'は', 'ま', 'や', 'れ', 'を'] +SYLLABLES = ['O', 'KI', 'SU', 'TU', 'NA', 'HA', 'MA', 'YA', 'RE', 'WO'] SIZE = 280 -BOX = 200 +FORMS_SIZE = 112 def load_font(path: str) -> ImageFont.FreeTypeFont: @@ -34,24 +45,47 @@ def load_font(path: str) -> ImageFont.FreeTypeFont: return ImageFont.truetype(path, 400) -def render(char: str, font: ImageFont.FreeTypeFont) -> Image.Image: - # Se dibuja grande, se recorta al contorno del carácter y se encaja en BOX×BOX - canvas = Image.new('L', (600, 600), 255) +def load_hentaigana_font(path: str) -> ImageFont.FreeTypeFont: + """En negrita, como los de hoy: si la fuente es variable, con el eje de grosor a 700.""" + font = ImageFont.truetype(path, 400) + try: + font.set_variation_by_axes([700]) + except OSError: + pass + return font + + +def hentaigana(syllable: str) -> list[str]: + """Las hentaigana de una sílaba, en el orden de Unicode (HENTAIGANA LETTER HA-1, HA-2…).""" + prefix = f'HENTAIGANA LETTER {syllable}-' + return [chr(code) for code in range(0x1B000, 0x1B130) if unicodedata.name(chr(code), '').startswith(prefix)] + + +def render(char: str, font: ImageFont.FreeTypeFont, size: int = SIZE) -> Image.Image: + # Se dibuja grande, se recorta al contorno del carácter y se encaja en un cuadrado de 20/28 de la imagen + canvas = Image.new('L', (700, 700), 255) ImageDraw.Draw(canvas).text((100, 50), char, font=font, fill=0) - glyph = canvas.crop(Image.eval(canvas, lambda v: 255 - v).getbbox()) - scale = BOX / max(glyph.size) + box = Image.eval(canvas, lambda v: 255 - v).getbbox() + if box is None: + raise SystemExit(f'La fuente no tiene U+{ord(char):04X}') + glyph = canvas.crop(box) + scale = size * 20 / 28 / max(glyph.size) glyph = glyph.resize((round(glyph.width * scale), round(glyph.height * scale)), Image.LANCZOS) - image = Image.new('L', (SIZE, SIZE), 255) - image.paste(glyph, ((SIZE - glyph.width) // 2, (SIZE - glyph.height) // 2)) + image = Image.new('L', (size, size), 255) + image.paste(glyph, ((size - glyph.width) // 2, (size - glyph.height) // 2)) return image def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--font', default=DEFAULT_FONT) + parser.add_argument('--hentaigana-font', default=DEFAULT_HENTAIGANA_FONT) args = parser.parse_args() if not Path(args.font).exists(): raise SystemExit(f'No existe la fuente {args.font}: instala fonts-noto-cjk o indica otra con --font') + if not Path(args.hentaigana_font).exists(): + raise SystemExit(f'No existe la fuente {args.hentaigana_font}: descarga Noto Serif Hentaigana ' + 'o indica otra con --hentaigana-font') font = load_font(args.font) OUT_DIR.mkdir(parents=True, exist_ok=True) @@ -59,6 +93,19 @@ def main(): render(char, font).save(OUT_DIR / f'{label}.png', optimize=True) print(f'{len(CHARS)} imágenes en {OUT_DIR} con la fuente {" ".join(font.getname())}') + hentaigana_font = load_hentaigana_font(args.hentaigana_font) + forms_dir = OUT_DIR / 'forms' + forms_dir.mkdir(exist_ok=True) + total = 0 + for char, syllable in zip(CHARS, SYLLABLES): + forms = hentaigana(syllable) + for form in forms: + image = render(form, hentaigana_font, FORMS_SIZE) + image.save(forms_dir / f'{ord(form):X}.png', optimize=True) + total += len(forms) + print(f'{char}: {len(forms)} formas antiguas') + print(f'{total} imágenes en {forms_dir} con la fuente {hentaigana_font.getname()[0]}') + if __name__ == '__main__': main() diff --git a/Scripts/build_kmnist_sprite.py b/Scripts/build_kmnist_sprite.py index a44fb83..eac4f10 100644 --- a/Scripts/build_kmnist_sprite.py +++ b/Scripts/build_kmnist_sprite.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 """ -Convierte KMNIST (ficheros .npy de NumPy) al formato que usa la app para MNIST: +Convierte KMNIST (los .npy de NumPy de public/datasets/03-image-classification/kmnist/) en el conjunto de su paquete +.n4l (public/n4l/kmnist.n4l/data/, kind image-sprite en su manifest.json), con el mismo formato que el de MNIST: - kmnist_images.png : sprite en escala de grises, una imagen de 28x28 por fila (784 px de ancho). Primero las filas de entrenamiento y después las de test. @@ -10,6 +11,9 @@ en el navegador usa 11.000 imágenes de entrenamiento y 2.000 de test, así que no hace falta descargar las 70.000 (unos 21 MB). Con los valores por defecto el sprite pesa ~7 MB. +Si cambia el número de imágenes, hay que cambiar también rows y train en el manifiesto (y medir de nuevo el modelo con +Scripts/measure_image_models.py --package kmnist --write). + Uso: python3 Scripts/build_kmnist_sprite.py [--train-per-class 2000] [--test-per-class 500] Requiere numpy y Pillow. """ @@ -20,6 +24,7 @@ from PIL import Image KMNIST_DIR = Path(__file__).resolve().parent.parent / 'public' / 'datasets' / '03-image-classification' / 'kmnist' +OUT_DIR = Path(__file__).resolve().parent.parent / 'public' / 'n4l' / 'kmnist.n4l' / 'data' NUM_CLASSES = 10 @@ -46,10 +51,10 @@ def main(): images = np.concatenate([p[0] for p in parts]).reshape(-1, 28 * 28).astype(np.uint8) labels = np.concatenate([p[1] for p in parts]) - sprite_path = KMNIST_DIR / 'kmnist_images.png' + sprite_path = OUT_DIR / 'kmnist_images.png' Image.fromarray(images, mode='L').save(sprite_path, format='PNG', optimize=True) - labels_path = KMNIST_DIR / 'kmnist_labels_uint8' + labels_path = OUT_DIR / 'kmnist_labels_uint8' np.eye(NUM_CLASSES, dtype=np.uint8)[labels].tofile(labels_path) print(f'{sprite_path.name}: {images.shape[1]}x{images.shape[0]}, {sprite_path.stat().st_size / 1e6:.1f} MB') diff --git a/Scripts/build_mnist_examples.py b/Scripts/build_mnist_examples.py new file mode 100644 index 0000000..15e9496 --- /dev/null +++ b/Scripts/build_mnist_examples.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +""" +Genera las imágenes de ejemplo del paquete de MNIST (public/n4l/mnist.n4l/examples/0.png … 9.png): cada dígito escrito con una +fuente, en negro sobre fondo blanco, encajado como los de KMNIST (Scripts/build_kmnist_examples.py) y como MNIST +centra sus dígitos: en un cuadrado de 20/28 de la imagen. + +Por defecto, Lato Bold (paquete fonts-lato, licencia OFL): de las fuentes probadas, la red de MNIST reconoce sus diez +dígitos (con otras, el 6 o el 7 se confunden). + +Uso: python3 Scripts/build_mnist_examples.py [--font /ruta/a/la/fuente.ttf] +Requiere Pillow. +""" +import argparse +from pathlib import Path + +from PIL import ImageFont + +from build_kmnist_examples import render + +OUT_DIR = Path(__file__).resolve().parent.parent / 'public' / 'n4l' / 'mnist.n4l' / 'examples' +DEFAULT_FONT = '/usr/share/fonts/truetype/lato/Lato-Bold.ttf' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--font', default=DEFAULT_FONT) + args = parser.parse_args() + if not Path(args.font).exists(): + raise SystemExit(f'No existe la fuente {args.font}: instala fonts-lato o indica otra con --font') + + font = ImageFont.truetype(args.font, 400) + OUT_DIR.mkdir(parents=True, exist_ok=True) + for digit in range(10): + render(str(digit), font).save(OUT_DIR / f'{digit}.png', optimize=True) + print(f'10 imágenes en {OUT_DIR} con la fuente {" ".join(font.getname())}') + + +if __name__ == '__main__': + main() diff --git a/Scripts/capture_manual_screenshots.mjs b/Scripts/capture_manual_screenshots.mjs new file mode 100644 index 0000000..3b9a8d6 --- /dev/null +++ b/Scripts/capture_manual_screenshots.mjs @@ -0,0 +1,138 @@ +// Rehace las capturas del manual de clasificación tabular (inglés, tema claro) siguiendo el tutorial con el +// dataset Car, en Chrome sin ventana (google-chrome) controlado por su protocolo de depuración. +// Uso, con `pnpm dev` en marcha: +// node Scripts/capture_manual_screenshots.mjs http://localhost:5173/n4l public/docs/images/00-tabular-classification +// Las capturas de subir y procesar un CSV (00-*) y la del visor de tfjs-vis (05-visor-training) no se generan aquí. +import { spawn } from 'node:child_process' +import { mkdtempSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +const [base, outDir] = process.argv.slice(2) +const port = 9337 +const chrome = spawn('google-chrome', [ + '--headless=new', '--no-sandbox', '--disable-gpu', `--remote-debugging-port=${port}`, '--hide-scrollbars', + `--user-data-dir=${mkdtempSync(join(tmpdir(), 'n4l-manual-'))}`, '--window-size=1240,2600', 'about:blank', +], { stdio: 'ignore' }) +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +let target +for (let i = 0; i < 50 && !target; i++) { + try { target = (await (await fetch(`http://127.0.0.1:${port}/json`)).json()).find((t) => t.type === 'page') } catch { await sleep(200) } +} +const ws = new WebSocket(target.webSocketDebuggerUrl) +await new Promise((r) => ws.addEventListener('open', r)) +let id = 0 +const pending = new Map() +const errors = [] +ws.addEventListener('message', (e) => { + const msg = JSON.parse(e.data) + if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id) } + if (msg.method === 'Runtime.exceptionThrown') errors.push(msg.params.exceptionDetails.exception?.description ?? msg.params.exceptionDetails.text) +}) +const send = (method, params = {}) => new Promise((r) => { const i = ++id; pending.set(i, r); ws.send(JSON.stringify({ id: i, method, params })) }) +const evaluate = async (expression) => (await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true })).result?.result?.value +const waitFor = async (expression, timeout = 60000) => { + const start = Date.now() + while (Date.now() - start < timeout) { if (await evaluate(expression)) return true; await sleep(300) } + throw new Error('Timeout: ' + expression) +} +// Cambia un campo como lo haría el usuario (React escucha input en los y change en los como lo haría el usuario (React escucha el evento change) +const select = (selector, value) => evaluate(`(() => { + const el = document.querySelector(${JSON.stringify(selector)}) + Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value').set.call(el, ${JSON.stringify(value)}) + el.dispatchEvent(new Event('change', { bubbles: true })) +})()`) +const setFile = async (selector, file) => { + const { result: { root } } = await send('DOM.getDocument') + const { result: { nodeId } } = await send('DOM.querySelector', { nodeId: root.nodeId, selector }) + await send('DOM.setFileInputFiles', { nodeId, files: [join(PUBLIC, file)] }) +} +const closeAlerts = () => evaluate(`document.querySelector('.swal2-confirm')?.click()`) + +await send('Page.enable') +await send('Runtime.enable') +await send('DOM.enable') +// Registro de tareas largas desde que empieza cada página +await send('Page.addScriptToEvaluateOnNewDocument', { + source: `window.__longtasks = []; new PerformanceObserver((list) => { for (const e of list.getEntries()) window.__longtasks.push({ start: e.startTime, duration: e.duration }) }).observe({ type: 'longtask', buffered: true })`, +}) +const goto = async (path, readySelector) => { + await send('Page.navigate', { url: base + path }) + await waitFor(`!!document.querySelector(${JSON.stringify(readySelector)})`) +} + +const results = [] +const record = (label, tasks, wall) => { + const total = tasks.reduce((sum, t) => sum + t.duration, 0) + const max = tasks.reduce((m, t) => Math.max(m, t.duration), 0) + const row = { label, count: tasks.length, total: Math.round(total), max: Math.round(max), wall } + results.push(row) + console.log(`${label}: ${row.count} tareas largas · bloqueo ${row.total} ms · la mayor ${row.max} ms · ${(row.wall / 1000).toFixed(1)} s`) +} +const measure = async (label, action, settleMs = 1500) => { + await evaluate('window.__mark = performance.now()') + const start = Date.now() + await action() + await sleep(settleMs) + record(label, await evaluate('window.__longtasks.filter((t) => t.start >= window.__mark)'), Date.now() - start - settleMs) +} + +// Sin el aviso de cookies (se acepta el rechazo como haría el usuario) +await send('Page.navigate', { url: base + '/' }) +await sleep(1500) +await evaluate(`[...document.querySelectorAll('button')].find((b) => /Rechazar|Reject/.test(b.textContent))?.click()`) + +if (scenarios.includes('analyze')) { + for (const file of ['datasets/01-regression/housing-prices/california-housing.csv', 'datasets/01-regression/housing-price/housing-price.csv']) { + const name = file.split('/').pop() + await goto('/analyze', '#analyze-project-dataset') + await sleep(1500) + await measure(`/analyze ${name}: cargar y analizar`, async () => { + await setFile('input[type=file][accept*="csv"]', file) + await waitFor(`!!document.querySelector('[data-testid=Test-AnalyzeInfo]')`) + }, 3000) + await measure(`/analyze ${name}: cambiar el escalado`, () => select('#analyze-preprocess-scaler', 'standard'), 2000) + const other = await evaluate(`[...document.querySelectorAll('#analyze-target option')].map((o) => o.value).filter(Boolean)[1]`) + await measure(`/analyze ${name}: cambiar la variable objetivo`, () => select('#analyze-target', other), 2500) + } +} + +if (scenarios.includes('mnist')) { + const start = Date.now() + await goto('/playground/image-classification/model/IMAGE-MNIST', '#ModelReviewImageClassification') + await waitFor(`!!document.querySelector('.swal2-confirm')`) + // Desde que empieza la página: descargar y preparar el modelo (y compilar sus shaders, también los de LRP) + await sleep(1500) + record('MNIST: abrir la página y cargar el modelo', await evaluate('window.__longtasks'), Date.now() - start - 1500) + await closeAlerts() + await sleep(1500) + await measure('MNIST: cargar las imágenes de test', async () => { + await click('[data-testid=Test-LoadTestDataset]') + await waitFor(`!document.querySelector('[data-testid=Test-LoadTestDataset]')`) + }) + // Dos veces: la primera incluye compilar los shaders de WebGL (síncrono y solo una vez) + for (const [round, example] of [['primera vez', 0], ['otra vez', 1]]) { + await measure(`MNIST: clasificar un ejemplo (${round})`, async () => { + await evaluate(`document.querySelectorAll('.n4l-example-image')[${example}].click()`) + await waitFor(`!!document.querySelector('[data-testid=Test-ClassificationChart-class]')`) + }, 800) + await measure(`MNIST: explicar con LRP (${round})`, async () => { + await click('[data-testid=Test-ExplainButton]') + await waitFor(`document.querySelector('[data-testid=Test-ExplainButton]')?.dataset.calculating === 'true'`, 10000).catch(() => undefined) + await waitFor(`document.querySelector('[data-testid=Test-ExplainButton]')?.dataset.calculating === 'false'`, 600000) + }) + } +} + +if (scenarios.includes('car')) { + await goto('/playground/tabular-classification/dataset/CAR', '#TabularClassificationCustomDataset') + await sleep(2500) + // Dos veces: la primera incluye compilar los shaders de WebGL (síncrono y solo una vez) + for (const round of ['primera vez', 'otra vez']) { + await measure(`Car: entrenar (${round})`, async () => { + await click('#TabularClassificationCustomDataset button[type=submit]') + await waitFor(`!!document.querySelector('.swal2-confirm')`, 300000) + }, 500) + await closeAlerts() + await sleep(500) + } + await measure('Car: SHAP global', async () => { + await click('[data-testid=Test-ShapGlobal]') + await waitFor(`document.querySelector('[data-testid=Test-ShapGlobal]')?.dataset.calculating === 'true'`, 10000) + await waitFor(`document.querySelector('[data-testid=Test-ShapGlobal]')?.dataset.calculating === 'false'`, 600000) + }, 1000) +} + +if (scenarios.includes('mnist-train')) { + await goto('/playground/image-classification/dataset/IMAGE-MNIST', '#ImageClassification') + await sleep(2500) + await measure('MNIST: cargar el conjunto y entrenar', async () => { + await click('#ImageClassification button[type=submit]') + await waitFor(`!!document.querySelector('.swal2-confirm')`, 900000) + }, 500) +} + +console.log('\n| Escenario | Tareas largas | Bloqueo total | La mayor | Duración |\n|---|---|---|---|---|') +for (const r of results) console.log(`| ${r.label} | ${r.count} | ${r.total} ms | ${r.max} ms | ${(r.wall / 1000).toFixed(1)} s |`) +if (errors.length) console.log('\nErrores en la página:', errors) +ws.close() +chrome.kill() +process.exit(0) diff --git a/Scripts/train_cifar10_model.py b/Scripts/train_cifar10_model.py new file mode 100644 index 0000000..7b6d070 --- /dev/null +++ b/Scripts/train_cifar10_model.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +""" +Entrena el modelo ya entrenado del paquete de CIFAR-10 (/playground/image-classification/model/IMAGE-CIFAR10) y lo +guarda en formato TensorFlow.js (model.json + weights.bin) en public/n4l/cifar10.n4l/models/cnn/. + +- Datos: las 50.000 imágenes de entrenamiento oficiales de CIFAR-10 (se descargan la primera vez en --data-dir). Las + 10.000 de prueba solo se usan al final, para medirlo: no deciden nada del entrenamiento. +- Red: como la de KMNIST (tres bloques de dos Conv2D y MaxPooling2D, y dos Dense), porque la explicación con LRP de la + aplicación solo sabe propagar Conv2D, MaxPooling2D, Dropout, Flatten y Dense. Se entrena con BatchNormalization detrás + de cada Conv2D (aprende más y antes) y, al guardarla, cada una se funde en los pesos de su Conv2D: la red que se guarda + da lo mismo sin ellas. +- Aumento de datos: recortes desplazados (con 4 píxeles de margen) y volteos horizontales. +- Entrada: cada píxel entre 0 y 1, en RGB, como se la da la aplicación. + +Después, para que el manifiesto del paquete tenga sus métricas con las imágenes de prueba del paquete: + + python3 Scripts/measure_image_models.py --package cifar10 --write + +Uso: python3 Scripts/train_cifar10_model.py [--epochs 50] [--data-dir …] [--out-dir …] [--threads 24] +Requiere numpy y PyTorch (en la CPU, unos 30 s por época con 24 hilos). +""" +import argparse +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch import nn + +from cifar10_data import CLASS_LABELS, DEFAULT_DATA_DIR, TEST_FILES, TRAIN_FILES, cifar_dir, load_split + +ROOT = Path(__file__).resolve().parent.parent +# Filtros de las Conv2D de cada bloque y lo que se apaga (Dropout) al final de cada uno +BLOCKS = [(32, 0.2), (64, 0.3), (128, 0.4)] +DENSE_UNITS = 256 +DENSE_DROPOUT = 0.5 + + +class Net(nn.Module): + def __init__(self): + super().__init__() + layers, channels = [], 3 + for filters, dropout in BLOCKS: + for _ in range(2): + layers += [nn.Conv2d(channels, filters, 3, padding=1, bias=False), nn.BatchNorm2d(filters), nn.ReLU()] + channels = filters + layers += [nn.MaxPool2d(2), nn.Dropout(dropout)] + self.features = nn.Sequential(*layers) + self.dense = nn.Linear(channels * 4 * 4, DENSE_UNITS) + self.dropout = nn.Dropout(DENSE_DROPOUT) + self.output = nn.Linear(DENSE_UNITS, len(CLASS_LABELS)) + + def forward(self, x): + x = self.features(x) + # Aplanado como en TF.js (channels_last): alto, ancho y canal + x = x.permute(0, 2, 3, 1).reshape(x.shape[0], -1) + return self.output(self.dropout(torch.relu(self.dense(x)))) + + +def augment(x: torch.Tensor) -> torch.Tensor: + """Recortes de 32×32 desplazados hasta 4 píxeles (con ceros en el margen) y la mitad, volteadas""" + padded = nn.functional.pad(x, (4, 4, 4, 4)) + offsets = torch.randint(0, 9, (x.shape[0], 2)) + out = torch.stack([padded[i, :, dy:dy + 32, dx:dx + 32] for i, (dy, dx) in enumerate(offsets.tolist())]) + flip = torch.rand(x.shape[0]) < 0.5 + out[flip] = out[flip].flip(3) + return out + + +def accuracy(model: nn.Module, images: np.ndarray, labels: np.ndarray) -> float: + model.eval() + hits = 0 + with torch.no_grad(): + for i in range(0, len(images), 1000): + x = torch.from_numpy(images[i:i + 1000]).float() / 255 + hits += int((model(x).argmax(1).numpy() == labels[i:i + 1000]).sum()) + return hits / len(images) + + +def fused_weights(model: Net) -> list[np.ndarray]: + """Los pesos como los espera TF.js (kernel, bias de cada capa), con cada BatchNormalization fundida en su Conv2D""" + weights = [] + modules = list(model.features) + for i, module in enumerate(modules): + if not isinstance(module, nn.Conv2d): + continue + bn = modules[i + 1] + scale = bn.weight.detach() / torch.sqrt(bn.running_var + bn.eps) + kernel = module.weight.detach() * scale[:, None, None, None] + bias = bn.bias.detach() - bn.running_mean * scale + # (salida, entrada, alto, ancho) → (alto, ancho, entrada, salida) + weights += [kernel.permute(2, 3, 1, 0).numpy(), bias.numpy()] + for dense in (model.dense, model.output): + weights += [dense.weight.detach().T.numpy(), dense.bias.detach().numpy()] + return [np.ascontiguousarray(weight, dtype=np.float32) for weight in weights] + + +def fused_accuracy(weights: list[np.ndarray], images: np.ndarray, labels: np.ndarray) -> float: + """La precisión de la red sin BatchNormalization (con los pesos fundidos): tiene que ser la misma""" + tensors = [torch.from_numpy(weight) for weight in weights] + convs = [(tensors[i], tensors[i + 1]) for i in range(0, 4 * len(BLOCKS), 2)] + dense, dense_bias, output, output_bias = tensors[4 * len(BLOCKS):] + hits = 0 + with torch.no_grad(): + for i in range(0, len(images), 1000): + x = torch.from_numpy(images[i:i + 1000]).float() / 255 + for block in range(len(BLOCKS)): + for kernel, bias in convs[2 * block:2 * block + 2]: + x = torch.relu(nn.functional.conv2d(x, kernel.permute(3, 2, 0, 1), bias, padding=1)) + x = nn.functional.max_pool2d(x, 2) + x = x.permute(0, 2, 3, 1).reshape(x.shape[0], -1) + x = torch.relu(x @ dense + dense_bias) @ output + output_bias + hits += int((x.argmax(1).numpy() == labels[i:i + 1000]).sum()) + return hits / len(images) + + +def tfjs_layer(class_name: str, name: str, **config): + return {'class_name': class_name, 'config': {**config, 'name': name, 'trainable': True}} + + +INITIALIZERS = { + 'kernel_initializer' : {'class_name': 'VarianceScaling', 'config': {'scale': 1, 'mode': 'fan_avg', 'distribution': 'normal', 'seed': None}}, + 'bias_initializer' : {'class_name': 'Zeros', 'config': {}}, + 'kernel_regularizer' : None, 'kernel_constraint': None, 'bias_regularizer': None, 'activity_regularizer': None, 'bias_constraint': None, +} + + +def tfjs_model(weights: list[np.ndarray], metadata: dict): + """El model.json de TF.js (una red Sequential, como la que guarda tfjs-layers) y la lista de sus pesos""" + layers, names = [], [] + conv = pool = dropout = 0 + for filters, rate in BLOCKS: + for _ in range(2): + conv += 1 + name = f'conv2d_Conv2D{conv}' + layers.append(tfjs_layer('Conv2D', name, filters=filters, kernel_size=[3, 3], strides=[1, 1], padding='same', + data_format='channels_last', dilation_rate=[1, 1], activation='relu', use_bias=True, + **INITIALIZERS, **({'batch_input_shape': [None, 32, 32, 3], 'dtype': 'float32'} if conv == 1 else {}))) + names += [f'{name}/kernel', f'{name}/bias'] + pool += 1 + dropout += 1 + layers.append(tfjs_layer('MaxPooling2D', f'max_pooling2d_MaxPooling2D{pool}', pool_size=[2, 2], padding='valid', strides=[2, 2], data_format='channels_last')) + layers.append(tfjs_layer('Dropout', f'dropout_Dropout{dropout}', rate=rate, noise_shape=None, seed=None)) + layers.append(tfjs_layer('Flatten', 'flatten_Flatten1', data_format='channels_last')) + layers.append(tfjs_layer('Dense', 'dense_Dense1', units=DENSE_UNITS, activation='relu', use_bias=True, **INITIALIZERS)) + layers.append(tfjs_layer('Dropout', f'dropout_Dropout{dropout + 1}', rate=DENSE_DROPOUT, noise_shape=None, seed=None)) + layers.append(tfjs_layer('Dense', 'dense_Dense2', units=len(CLASS_LABELS), activation='softmax', use_bias=True, **INITIALIZERS)) + names += ['dense_Dense1/kernel', 'dense_Dense1/bias', 'dense_Dense2/kernel', 'dense_Dense2/bias'] + return { + 'modelTopology' : {'class_name': 'Sequential', 'config': {'name': 'sequential_1', 'layers': layers}, 'keras_version': 'tfjs-layers 4.22.0', 'backend': 'tensor_flow.js'}, + 'weightsManifest' : [{'paths': ['weights.bin'], 'weights': [{'name': name, 'shape': list(weight.shape), 'dtype': 'float32'} for name, weight in zip(names, weights)]}], + 'format' : 'layers-model', + 'generatedBy' : 'Scripts/train_cifar10_model.py (PyTorch)', + 'convertedBy' : None, + 'userDefinedMetadata': metadata, + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--epochs', type=int, default=50) + parser.add_argument('--batch-size', type=int, default=128) + parser.add_argument('--data-dir', type=Path, default=DEFAULT_DATA_DIR) + parser.add_argument('--out-dir', type=Path, default=ROOT / 'public' / 'n4l' / 'cifar10.n4l' / 'models' / 'cnn') + parser.add_argument('--threads', type=int, default=24) + parser.add_argument('--seed', type=int, default=1) + args = parser.parse_args() + + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + batches = cifar_dir(args.data_dir) + train_images, train_labels = load_split(batches, TRAIN_FILES) + test_images, test_labels = load_split(batches, TEST_FILES) + + model = Net() + steps = args.epochs * ((len(train_images) + args.batch_size - 1) // args.batch_size) + optimizer = torch.optim.SGD(model.parameters(), lr=0.05, momentum=0.9, nesterov=True, weight_decay=5e-4) + schedule = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=0.1, total_steps=steps) + loss_fn = nn.CrossEntropyLoss() + x_all = torch.from_numpy(train_images) + y_all = torch.from_numpy(train_labels) + for epoch in range(1, args.epochs + 1): + start = time.time() + model.train() + order = torch.randperm(len(x_all)) + total = 0.0 + for i in range(0, len(order), args.batch_size): + index = order[i:i + args.batch_size] + x = augment(x_all[index].float() / 255) + loss = loss_fn(model(x), y_all[index]) + optimizer.zero_grad() + loss.backward() + optimizer.step() + schedule.step() + total += loss.item() * len(index) + print(f'Época {epoch}/{args.epochs}: pérdida {total / len(order):.4f} ({time.time() - start:.0f} s)', flush=True) + + test_accuracy = accuracy(model, test_images, test_labels) + weights = fused_weights(model) + fused = fused_accuracy(weights, test_images, test_labels) + print(f'Precisión con las {len(test_images)} de prueba: {test_accuracy:.4f} (sin BatchNormalization: {fused:.4f})') + if abs(fused - test_accuracy) > 0.002: + raise SystemExit('Al fundir las BatchNormalization la red cambia: no se guarda') + + args.out_dir.mkdir(parents=True, exist_ok=True) + (args.out_dir / 'weights.bin').write_bytes(b''.join(weight.tobytes() for weight in weights)) + metadata = {'dataset': 'CIFAR-10', 'classLabels': CLASS_LABELS, 'trainImages': len(train_images), 'testImages': len(test_images), + 'testAccuracy': round(fused, 4), 'epochs': args.epochs} + (args.out_dir / 'model.json').write_text(json.dumps(tfjs_model(weights, metadata))) + print(f'Modelo guardado en {args.out_dir}') + + +if __name__ == '__main__': + main() diff --git a/Scripts/train_kmnist_model.cjs b/Scripts/train_kmnist_model.cjs index 2c5e4d0..67595d9 100644 --- a/Scripts/train_kmnist_model.cjs +++ b/Scripts/train_kmnist_model.cjs @@ -1,8 +1,11 @@ #!/usr/bin/env node /** * Entrena el modelo preentrenado de KMNIST (/playground/image-classification/model/IMAGE-KMNIST) y lo guarda - * en formato TensorFlow.js (model.json + weights.bin). Las imágenes de ejemplo de esa página las genera - * Scripts/build_kmnist_examples.py. + * en formato TensorFlow.js (model.json + weights.bin) en su paquete, public/n4l/kmnist.n4l/models/cnn/. Las + * imágenes de ejemplo de esa página las genera Scripts/build_kmnist_examples.py. Después, para que el manifiesto + * del paquete tenga sus métricas con las imágenes de prueba del paquete: + * + * python3 Scripts/measure_image_models.py --package kmnist --write * * - Datos: los .npy originales de KMNIST (60.000 imágenes de entrenamiento y 10.000 de test). Se apartan * 5.000 de entrenamiento para validar; el test solo se usa al final para medir la precisión. @@ -37,7 +40,7 @@ const { values: args } = util.parseArgs({ 'epochs' : { type: 'string', default: '30' }, 'batch-size' : { type: 'string', default: '128' }, 'data-dir' : { type: 'string', default: path.join(ROOT, 'public/datasets/03-image-classification/kmnist') }, - 'out-dir' : { type: 'string', default: path.join(ROOT, 'public/models/03-image-classification/kmnist') }, + 'out-dir' : { type: 'string', default: path.join(ROOT, 'public/n4l/kmnist.n4l/models/cnn') }, }, }) diff --git a/Scripts/train_regression_models.mjs b/Scripts/train_regression_models.mjs new file mode 100644 index 0000000..fd07690 --- /dev/null +++ b/Scripts/train_regression_models.mjs @@ -0,0 +1,206 @@ +#!/usr/bin/env node +/** + * Reentrena modelos de regresión de los paquetes .n4l (public/n4l/.n4l) y, si mejoran en datos que no han + * visto, los guarda en su paquete. + * + * - Datos: el CSV del conjunto del modelo, preparado como lo prepara la aplicación al cargar el paquete + * (src/core/n4l/regression.ts): las columnas de «label-encoder» numeradas en el orden en que aparecen (como el + * LabelEncoder de danfo), sin las de «drop» ni las que no son de entrada, y escaladas con min-max sobre todo el + * conjunto. El objetivo, tal cual. + * - Se aparta un 20 % para prueba (con semilla). Con el resto se entrenan varias redes (con un 15 % para validar y + * parar a tiempo) y se elige la de menor error de validación. + * - El modelo actual se mide en la misma prueba. Solo si el nuevo tiene mejor R² se guarda (con --write): su + * model.json y sus pesos, sus métricas de prueba en el manifiesto y la versión del paquete subida (1.0.0 → 1.1.0). + * - --force lo guarda aunque no mejore: cuando el actual pudo entrenarse con esas mismas filas de prueba, su nota + * sale inflada y solo la del nuevo dice cómo predice con datos que no ha visto. + * + * Uso: node Scripts/train_regression_models.mjs --package wine-quality --model white [--write [--force]] [--seed 1] + * Con TensorFlow.js de JavaScript (sin binarios nativos): son conjuntos pequeños. + */ +import fs from 'node:fs' +import path from 'node:path' +import util from 'node:util' +import * as tf from '@tensorflow/tfjs' + +const ROOT = path.resolve(import.meta.dirname, '..') +const { values: args } = util.parseArgs({ + options: { + 'package': { type: 'string' }, + 'model' : { type: 'string' }, + 'seed' : { type: 'string', default: '1' }, + 'write' : { type: 'boolean', default: false }, + 'force' : { type: 'boolean', default: false }, + }, +}) +if (args.package === undefined || args.model === undefined) { + console.error('Uso: node Scripts/train_regression_models.mjs --package --model [--write]') + process.exit(1) +} + +const TEST_SIZE = 0.2 +const VALIDATION_SIZE = 0.15 +const MAX_EPOCHS = 400 +const PATIENCE = 30 +// Las redes que se prueban (la salida, una neurona lineal, se añade siempre) +const CANDIDATES = [ + { layers: [[64, 'relu'], [32, 'relu']], learningRate: 0.001 }, + { layers: [[64, 'relu'], [64, 'relu']], learningRate: 0.001 }, + { layers: [[128, 'relu'], [64, 'relu'], [32, 'relu']], learningRate: 0.0005 }, + { layers: [[32, 'sigmoid'], [16, 'relu']], learningRate: 0.003 }, +] + +/** Números pseudoaleatorios con semilla (mulberry32): la misma partición siempre */ +function seededRandom(seed) { + let state = seed >>> 0 + return () => { + state = (state + 0x6D2B79F5) >>> 0 + let value = Math.imul(state ^ (state >>> 15), 1 | state) + value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value + return ((value ^ (value >>> 14)) >>> 0) / 4294967296 + } +} + +/** Un CSV sencillo (comas, comillas dobles): cabecera y filas */ +function readCSV(file) { + const lines = fs.readFileSync(file, 'utf-8').split(/\r?\n/).filter((line) => line.trim() !== '') + const parse = (line) => { + const cells = [] + let cell = '' + let quoted = false + for (const char of line) { + if (char === '"') quoted = !quoted + else if (char === ',' && !quoted) { + cells.push(cell) + cell = '' + } else cell += char + } + cells.push(cell) + return cells.map((value) => value.trim()) + } + const [header, ...rows] = lines.map(parse) + return { header, rows } +} + +const packageDir = path.join(ROOT, 'public/n4l', `${args.package}.n4l`) +const manifestFile = path.join(packageDir, 'manifest.json') +const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf-8')) +const section = manifest.tasks.find(({ task }) => task === 'regression') +const entry = section?.models.find(({ id }) => id === args.model) +if (entry === undefined) throw new Error(`${args.package} no tiene el modelo de regresión ${args.model}`) +const dataset = manifest.datasets.find(({ id }) => id === entry.dataset) + +// El preprocesado del paquete, como lo aplica la aplicación +const isCategorical = ({ type }) => type === 'Categorical' || type === 'Binary' +const stepColumns = (selector) => (selector === 'categorical' + ? dataset.columns.filter(isCategorical) + : selector === 'features' ? dataset.columns.filter(({ role }) => role === 'Feature') : dataset.columns.filter(({ name }) => selector.includes(name))) +const encoded = new Set(section.preprocessing.filter(({ op }) => op === 'label-encoder').flatMap(({ columns }) => stepColumns(columns).map(({ name }) => name))) +const dropped = new Set(section.preprocessing.filter(({ op }) => op === 'drop').flatMap(({ columns }) => stepColumns(columns).map(({ name }) => name))) +const features = dataset.columns.filter(({ role, name }) => role === 'Feature' && !dropped.has(name)).map(({ name }) => name) +const target = dataset.columns.find(({ role }) => role === 'Target').name + +const { header, rows } = readCSV(path.join(packageDir, dataset.file)) +const index = (name) => header.indexOf(name) +// LabelEncoder de danfo: cada valor, su posición en el orden en que aparece +const codes = Object.fromEntries([...encoded].map((name) => [name, [...new Set(rows.map((row) => row[index(name)]))]])) +const raw = rows.map((row) => features.map((name) => (encoded.has(name) ? codes[name].indexOf(row[index(name)]) : Number(row[index(name)])))) +const y = rows.map((row) => Number(row[index(target)])) +const minimum = features.map((_, column) => Math.min(...raw.map((row) => row[column]))) +const maximum = features.map((_, column) => Math.max(...raw.map((row) => row[column]))) +const X = raw.map((row) => row.map((value, column) => (maximum[column] === minimum[column] ? 0 : (value - minimum[column]) / (maximum[column] - minimum[column])))) + +// Partición de prueba, con semilla +const random = seededRandom(Number(args.seed)) +const order = rows.map((_, row) => row) +for (let i = order.length - 1; i > 0; i--) { + const j = Math.floor(random() * (i + 1)); + [order[i], order[j]] = [order[j], order[i]] +} +const testCount = Math.round(order.length * TEST_SIZE) +const testRows = order.slice(0, testCount) +const trainRows = order.slice(testCount) + +function metrics(model, rowsToUse) { + const predictions = model.predict(tf.tensor2d(rowsToUse.map((row) => X[row]))).dataSync() + const actual = rowsToUse.map((row) => y[row]) + const mean = actual.reduce((sum, value) => sum + value, 0) / actual.length + const mae = actual.reduce((sum, value, i) => sum + Math.abs(value - predictions[i]), 0) / actual.length + const baseline = actual.reduce((sum, value) => sum + Math.abs(value - mean), 0) / actual.length + const residual = actual.reduce((sum, value, i) => sum + (value - predictions[i]) ** 2, 0) + const total = actual.reduce((sum, value) => sum + (value - mean) ** 2, 0) + return { r2: 1 - residual / total, mae, baseline } +} + +/** Un model.json y sus pesos (de este paquete), en memoria */ +async function loadModel(modelPath) { + const file = path.join(packageDir, modelPath) + const json = JSON.parse(fs.readFileSync(file, 'utf-8')) + const buffers = json.weightsManifest.flatMap(({ paths }) => paths.map((weights) => fs.readFileSync(path.join(path.dirname(file), weights)))) + const weightData = Buffer.concat(buffers) + return tf.loadLayersModel(tf.io.fromMemory({ + modelTopology: json.modelTopology, + weightSpecs : json.weightsManifest.flatMap(({ weights }) => weights), + weightData : weightData.buffer.slice(weightData.byteOffset, weightData.byteOffset + weightData.byteLength), + })) +} + +async function train({ layers, learningRate }, seed) { + const model = tf.sequential() + layers.forEach(([units, activation], i) => model.add(tf.layers.dense({ + units, activation, ...(i === 0 && { inputShape: [features.length] }), + kernelInitializer: tf.initializers.glorotUniform({ seed: seed + i }), + }))) + model.add(tf.layers.dense({ units: 1, activation: 'linear', kernelInitializer: tf.initializers.glorotUniform({ seed: seed + 99 }) })) + model.compile({ optimizer: tf.train.adam(learningRate), loss: 'meanSquaredError' }) + const validationCount = Math.round(trainRows.length * VALIDATION_SIZE) + const fitRows = trainRows.slice(validationCount) + const validationRows = trainRows.slice(0, validationCount) + const history = await model.fit(tf.tensor2d(fitRows.map((row) => X[row])), tf.tensor2d(fitRows.map((row) => [y[row]])), { + epochs : MAX_EPOCHS, + batchSize : 32, + shuffle : false, + validationData: [tf.tensor2d(validationRows.map((row) => X[row])), tf.tensor2d(validationRows.map((row) => [y[row]]))], + callbacks : tf.callbacks.earlyStopping({ monitor: 'val_loss', patience: PATIENCE }), + verbose : 0, + }) + const validationLoss = Math.min(...history.history.val_loss) + return { model, validationLoss, epochs: history.epoch.length } +} + +const current = metrics(await loadModel(entry.path), testRows) +console.log(`${args.package}/${args.model} (${dataset.file}): ${rows.length} filas, ${features.length} columnas de entrada; prueba: ${testRows.length}`) +console.log(` actual: R² ${current.r2.toFixed(3)}, error medio ${current.mae.toFixed(3)} (prediciendo la media, ${current.baseline.toFixed(3)})`) + +let best = null +for (const [i, candidate] of CANDIDATES.entries()) { + const result = await train(candidate, Number(args.seed) * 1000 + i * 10) + const test = metrics(result.model, testRows) + console.log(` ${candidate.layers.map(([units, activation]) => `${units} ${activation}`).join(' → ')} (lr ${candidate.learningRate}, ${result.epochs} épocas): validación ${result.validationLoss.toFixed(4)}, prueba R² ${test.r2.toFixed(3)}, error ${test.mae.toFixed(3)}`) + if (best === null || result.validationLoss < best.validationLoss) best = { ...result, candidate, test } +} +console.log(` elegida por validación: R² ${best.test.r2.toFixed(3)} en prueba (antes, ${current.r2.toFixed(3)})`) + +if (best.test.r2 <= current.r2 && !args.force) { + console.log(' no mejora: se queda el actual (con --write --force se guarda igualmente)') +} else if (!args.write) { + console.log(' mejora: con --write se guarda en el paquete') +} else { + // El modelo, como lo guarda TF.js: model.json y un fichero de pesos + await best.model.save(tf.io.withSaveHandler(async (artifacts) => { + const dir = path.join(packageDir, path.dirname(entry.path)) + fs.writeFileSync(path.join(packageDir, entry.path), JSON.stringify({ + modelTopology : artifacts.modelTopology, + format : 'layers-model', + generatedBy : `TensorFlow.js tfjs-layers v${tf.version.tfjs}`, + convertedBy : null, + weightsManifest: [{ paths: ['model.weights.bin'], weights: artifacts.weightSpecs }], + })) + fs.writeFileSync(path.join(dir, 'model.weights.bin'), Buffer.from(artifacts.weightData)) + return { modelArtifactsInfo: { dateSaved: new Date(), modelTopologyType: 'JSON' } } + })) + entry.metrics = { test_r2: Number(best.test.r2.toFixed(4)), test_mae: Number(best.test.mae.toFixed(4)), test_baseline_mae: Number(best.test.baseline.toFixed(4)) } + const [major, minor] = manifest.version.split('.').map(Number) + manifest.version = `${major}.${minor + 1}.0` + fs.writeFileSync(manifestFile, JSON.stringify(manifest, null, 2) + '\n') + console.log(` guardado en ${path.relative(ROOT, packageDir)} (versión ${manifest.version})`) +} diff --git a/Scripts/train_time_series_models.mjs b/Scripts/train_time_series_models.mjs new file mode 100644 index 0000000..e5372f0 --- /dev/null +++ b/Scripts/train_time_series_models.mjs @@ -0,0 +1,165 @@ +#!/usr/bin/env node +/** + * Entrena el modelo ya entrenado de una serie temporal de un paquete .n4l (public/n4l/.n4l) y, con --write, lo + * guarda en el paquete con sus métricas de prueba. + * + * - La serie se prepara como en la aplicación, con el mismo código (src/core/timeSeries/series.ts): la ventana, la + * parte de prueba (lo último de la serie, sin barajar), si se diferencia y el escalado min-max con el entrenamiento, + * según `forecast` del manifiesto. + * - Las últimas ventanas del entrenamiento (un 15 %) se apartan para validar: con ellas se para a tiempo y se elige, + * de varias veces que se entrena la red de `training`, la que menos se equivoca. La prueba no se mira hasta el final. + * - Con la prueba se mide a un paso y seguida (en las unidades de la serie) y se guardan en el manifiesto: test_mae, + * test_rmse, test_recursive_mae y, para compararse, test_naive_mae y (con estación) test_seasonal_mae. La versión del + * paquete sube (1.0.0 → 1.1.0). + * + * Uso: node Scripts/train_time_series_models.mjs --package airline-passengers [--write] [--runs 5] + * Con TensorFlow.js de JavaScript (sin binarios nativos): son series pequeñas. + */ +import fs from 'node:fs' +import path from 'node:path' +import util from 'node:util' +import { pathToFileURL } from 'node:url' +import * as tf from '@tensorflow/tfjs' + +const ROOT = path.resolve(import.meta.dirname, '..') +const series = await import(pathToFileURL(path.join(ROOT, 'src/core/timeSeries/series.ts')).href) + +const { values: args } = util.parseArgs({ + options: { + 'package': { type: 'string' }, + 'runs' : { type: 'string', default: '5' }, + 'write' : { type: 'boolean', default: false }, + }, +}) +if (args.package === undefined) { + console.error('Uso: node Scripts/train_time_series_models.mjs --package [--write] [--runs 5]') + process.exit(1) +} + +const VALIDATION_SIZE = 0.15 +const MAX_EPOCHS = 400 +const PATIENCE = 40 +const BATCH_SIZE = 32 +const MODEL_ID = 'forecast' + +const packageDir = path.join(ROOT, 'public/n4l', `${args.package}.n4l`) +const manifestFile = path.join(packageDir, 'manifest.json') +const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf-8')) +const section = manifest.tasks.find(({ task }) => task === 'time-series') +if (section === undefined) throw new Error(`${args.package} no tiene la tarea time-series`) +const dataset = manifest.datasets.find(({ id }) => id === section.datasets[0]) +const dateColumn = dataset.columns.find(({ type }) => type === 'Date').name +const valueColumn = dataset.columns.find(({ role }) => role === 'Target').name + +// La serie, como la lee la aplicación (los CSV de los paquetes no llevan comillas) +const [header, ...lines] = fs.readFileSync(path.join(packageDir, dataset.file), 'utf-8').trim().split(/\r?\n/).map((line) => line.split(',')) +const { values } = series.readSeries(header, lines, valueColumn, dateColumn) +const prep = { window: section.forecast.window, testSize: section.forecast.testSize ?? 20, difference: section.forecast.difference ?? false } +const season = section.forecast.season +const prepared = series.prepareSeries(values, prep) + +// Validación: las últimas ventanas del entrenamiento (en orden, como la prueba) +const validationCount = Math.round(prepared.train.X.length * VALIDATION_SIZE) +const fitCount = prepared.train.X.length - validationCount +const tensor = (rows) => tf.tensor2d(rows) +const column = (values) => tf.tensor2d(values, [values.length, 1]) +const XFit = tensor(prepared.train.X.slice(0, fitCount)) +const yFit = column(prepared.train.y.slice(0, fitCount)) +const XValidation = tensor(prepared.train.X.slice(fitCount)) +const yValidation = column(prepared.train.y.slice(fitCount)) + +/** La red de `training` del manifiesto (las recurrentes reciben la ventana como secuencia) */ +function buildModel() { + const layers = section.training.layers + const lastRecurrent = layers.reduce((last, layer, index) => (layer.class !== 'dense' ? index : last), -1) + const model = tf.sequential() + if (lastRecurrent !== -1) model.add(tf.layers.reshape({ targetShape: [prep.window, 1], inputShape: [prep.window] })) + layers.forEach((layer, index) => { + const config = { units: layer.units, activation: layer.activation ?? 'tanh' } + if (layer.class === 'dense') model.add(tf.layers.dense({ ...config, ...(index === 0 && lastRecurrent === -1 && { inputShape: [prep.window] }) })) + else model.add(tf.layers[layer.class]({ ...config, returnSequences: index < lastRecurrent })) + }) + model.compile({ optimizer: tf.train.adam(section.training.learningRate ?? 0.001), loss: 'meanSquaredError' }) + return model +} + +/** Entrena hasta que la validación deja de mejorar y se queda con los pesos de su mejor época */ +async function train() { + const model = buildModel() + let best = { loss: Infinity, epoch: 0, weights: null } + await model.fit(XFit, yFit, { + epochs : MAX_EPOCHS, + batchSize : BATCH_SIZE, + shuffle : true, + validationData: [XValidation, yValidation], + verbose : 0, + callbacks : { + onEpochEnd: async (epoch, logs) => { + if (logs.val_loss < best.loss) { + best.weights?.forEach((weight) => weight.dispose()) + best = { loss: logs.val_loss, epoch, weights: model.getWeights().map((weight) => weight.clone()) } + } else if (epoch - best.epoch >= PATIENCE) { + model.stopTraining = true + } + }, + }, + }) + model.setWeights(best.weights) + best.weights.forEach((weight) => weight.dispose()) + return { model, loss: best.loss, epochs: best.epoch + 1 } +} + +const predict = (model, rows) => tf.tidy(() => Array.from(model.predict(tf.tensor2d(rows, [rows.length, prep.window])).dataSync())) + +console.log(`${args.package}: ${values.length} valores · ventana ${prep.window} · prueba ${prep.testSize} % · ${prepared.train.X.length} ventanas de entrenamiento (${validationCount} para validar)`) +let chosen = null +for (let run = 1; run <= Number(args.runs); run++) { + const result = await train() + console.log(` vez ${run}: validación ${result.loss.toFixed(5)} (época ${result.epochs})`) + if (chosen === null || result.loss < chosen.loss) { + chosen?.model.dispose() + chosen = result + } else { + result.model.dispose() + } +} + +// La prueba, solo con el elegido +const actual = prepared.test.targets.map((t) => values[t]) +const oneStep = series.forecastErrors(actual, series.oneStepValues(values, prepared.test.targets, predict(chosen.model, prepared.test.X), prep, prepared.scale)) +const recursive = series.forecastErrors(actual, await series.recursiveForecast(values, prepared.test.targets[0], actual.length, prep, prepared.scale, (window) => predict(chosen.model, [window])[0])) +const baselines = series.baselineErrors(values, prepared, season) +const round = (value) => Number(value.toFixed(4)) +const metrics = { + test_mae : round(oneStep.mae), + test_rmse : round(oneStep.rmse), + test_recursive_mae: round(recursive.mae), + test_naive_mae : round(baselines.oneStep.naive.mae), + ...(baselines.oneStep.seasonal !== undefined && { test_seasonal_mae: round(baselines.oneStep.seasonal.mae) }), +} +console.log(' prueba:', metrics) + +if (!args.write) { + console.log(' con --write se guarda en el paquete') +} else { + const entry = { id: MODEL_ID, format: 'tfjs-layers', path: `models/${MODEL_ID}/model.json`, dataset: dataset.id, input: 'scaled', metrics } + const dir = path.join(packageDir, path.dirname(entry.path)) + fs.mkdirSync(dir, { recursive: true }) + // El modelo, como lo guarda TF.js: model.json y un fichero de pesos + await chosen.model.save(tf.io.withSaveHandler(async (artifacts) => { + fs.writeFileSync(path.join(packageDir, entry.path), JSON.stringify({ + modelTopology : artifacts.modelTopology, + format : 'layers-model', + generatedBy : `TensorFlow.js tfjs-layers v${tf.version.tfjs}`, + convertedBy : null, + weightsManifest: [{ paths: ['model.weights.bin'], weights: artifacts.weightSpecs }], + })) + fs.writeFileSync(path.join(dir, 'model.weights.bin'), Buffer.from(artifacts.weightData)) + return { modelArtifactsInfo: { dateSaved: new Date(), modelTopologyType: 'JSON' } } + })) + section.models = [entry] + const [major, minor] = manifest.version.split('.').map(Number) + manifest.version = `${major}.${minor + 1}.0` + fs.writeFileSync(manifestFile, JSON.stringify(manifest, null, 2) + '\n') + console.log(` guardado en ${path.relative(ROOT, packageDir)} (versión ${manifest.version})`) +} diff --git a/TODO-A11y.md b/TODO-A11y.md new file mode 100644 index 0000000..b6658a4 --- /dev/null +++ b/TODO-A11y.md @@ -0,0 +1,357 @@ +# TODO — Accesibilidad de Nets4Learning + +Objetivo: que cualquier persona pueda usar toda la aplicación (aprender, analizar datos, entrenar y probar redes) sea +cual sea su discapacidad. Eso incluye a quien usa lector de pantalla o magnificador, a quien navega solo con el +teclado, un conmutador o la voz, a quien tiene baja visión o no distingue colores, y a quien necesita menos movimiento, +más tiempo o textos más claros. Plan sacado de revisar el código y de pasar axe con WCAG 2.2 AA y buenas prácticas por +las páginas principales (11/10/2026). Cada fase agrupa tareas independientes; se marcan a medida que se terminan. + +**Nivel que se busca:** WCAG 2.2 AA. Incluye el WCAG 2.1 AA que exige la UNE-EN 301 549. Si la aplicación se publica +como web de la Universidad de Jaén, le aplica el RD 1112/2018 (accesibilidad de las webs del sector público), que +además pide una declaración de accesibilidad y una forma de comunicar barreras (fase 7). + +Leyenda: `[x]` hecho, `[ ]` pendiente, `[~]` en curso o hecho a medias (ver nota), `[-]` descartado. + +--- + +## Diagnóstico (11/10/2026) + +### Lo que ya está + +- [x] Pruebas de axe (WCAG 2.1 A y AA) en unas 25 páginas, en los temas claro y oscuro (`e2e/accesibilidad.spec.ts`), + y en los resultados del agrupamiento y de las series temporales tras entrenar. Todas pasan. +- [x] Al cambiar de página, el foco va al título de la nueva (`N4LScrollManager`), también si tarda en cargar. +- [x] `lang` del documento según el idioma elegido (`src/i18n.ts`) y `lang="ja"` en los caracteres japoneses de KMNIST. +- [x] Movimiento reducido (`prefers-reduced-motion`) en la guía, el paso a paso, el índice de secciones, la animación + del glosario, el fondo de la 404 y las imágenes de ejemplo. +- [x] Regiones `aria-live` en el progreso del entrenamiento, en el aviso de carga de las páginas y en los avisos de + «Empieza aquí». +- [x] Descripción (`aria-label`) en casi todas las gráficas de Chart.js y Plotly. +- [x] Ayuda de los hiperparámetros también con el teclado (el popover se abre con el foco, no solo al pasar el ratón). +- [x] Guía de cada página con voz, que se puede silenciar, repetir o hacer avanzar sola. +- [x] Ninguna página se sale en horizontal en el móvil (`e2e/movil.spec.ts`). + +### Lo que falla (encontrado) + +| Problema | Dónde | WCAG | +|---|---|---| +| El `` es «Nets4Learning» en todas las páginas | toda la aplicación | 2.4.2 (A) | +| No hay enlace para saltar al contenido: con el teclado, antes se pasa por los 12 enlaces y menús de la barra de navegación | toda la aplicación | 2.4.1 (A) | +| `index.html` empieza con `lang="en"` aunque la aplicación esté en español hasta que carga i18n | `index.html` | 3.1.1 (A) | +| Las descripciones de las fichas de variables (UCI) están en inglés dentro de páginas en español, sin `lang="en"` | `/datasets`, AED | 3.1.2 (AA) | +| Orden de encabezados con saltos: 10 en el glosario y otros en `/select-model`, `/manual` y el AED | varias | 1.3.1 (A) | +| Texto sin contraste suficiente: 2 casos en el AED y 1 en `/learn` | AED, `/learn` | 1.4.3 (AA) | +| Objetivos táctiles de menos de 24 × 24 px | páginas de modelos y entrenadores | 2.5.8 (AA, 2.2) | +| Tres gráficas sin descripción: comparación de modelos, explicación del modelo y SHAP (enjambre) | `N4LModelComparison`, `ModelExplanationChart`, `ShapBeeswarmChart` | 1.1.1 (A) | +| Las gráficas complejas solo tienen una frase; sus datos no se pueden leer (sin tabla alternativa) | toda la aplicación | 1.1.1, 1.3.1 | +| Información que solo da el color: los grupos del agrupamiento, las líneas de las series y los mapas de calor | agrupamiento, series, AED | 1.4.1 (A) | +| «Modelo entrenado» (SweetAlert2) se cierra solo a los 1,5 s y se lleva el foco | `alertHelper.alertSuccess` | 2.2.1 (A), 4.1.3 (AA) | +| La detección de objetos (con cámara o con una foto) solo dibuja los resultados en un `canvas`: no hay texto | detección de objetos | 1.1.1 (A) | +| Dibujar un dígito exige arrastrar (hay alternativas, pero no en todas partes) | clasificación de imágenes | 2.5.7 (AA, 2.2) | +| El visor de tfjs-vis no es accesible: regiones sin foco y gráficas sin texto | entrenadores, resumen del modelo | 2.1.1, 1.1.1 | +| Sin estilos para los colores forzados (alto contraste de Windows) | toda la aplicación | 1.4.11 | +| La barra de navegación fija y la de secciones pueden tapar el elemento con el foco | páginas largas | 2.4.11 (AA, 2.2) | +| Los campos numéricos (épocas, ventana, k…) recortan los valores en silencio, sin mensaje de error | entrenadores | 3.3.1 (A) | +| Sin `eslint-plugin-jsx-a11y` y sin pruebas de teclado; las de axe no usan WCAG 2.2 | pruebas | — | +| No hay declaración de accesibilidad ni forma de comunicar barreras | — | RD 1112/2018 | + +Las herramientas automáticas solo encuentran una parte de los problemas: el resto sale de las pruebas con teclado, con +lectores de pantalla y, sobre todo, con personas con discapacidad (fases 0 y 8). + +--- + +## Fase 0 — Base: objetivo, herramientas y medición + +Para medir cada fase igual antes y después, y para que lo arreglado no se vuelva a romper. + +- [x] **Nivel de conformidad.** WCAG 2.2 AA para toda la aplicación, apuntado en `docs/accessibility.md` junto con + las excepciones justificadas (p. ej. el visor de tfjs-vis, que es de una librería). +- [x] **axe con WCAG 2.2.** Añadir `wcag22aa` y `best-practice` a `e2e/accesibilidad.spec.ts` y a las demás + pruebas de axe, con una sola función compartida (hoy cada spec repite `withTags`). → `e2e/axe.ts` +- [x] **axe en todos los estados, no solo al cargar:** modales abiertos (información de un conjunto, descripción de + un modelo, compartir sesión), guía abierta, menú móvil abierto, tras entrenar, tras predecir, AED con un + conjunto cargado, errores de subida y páginas de los paquetes `.n4l`. + *En `e2e/accesibilidad-estados.spec.ts`, `movil.spec.ts` y `series.spec.ts`; además, los desplegables de la + barra, el aviso de cookies, la red mal montada con su error y el glosario sin resultados.* +- [x] **Todas las rutas en las pruebas de axe**, también las nuevas, con un test que avise si una ruta de `App.tsx` + no está en la lista. +- [x] **`eslint-plugin-jsx-a11y`** en `eslint.config.ts`, con las reglas recomendadas en error. +- [x] **Pruebas de teclado (e2e)** de los flujos principales sin ratón: elegir tarea → elegir conjunto → montar la red + → entrenar → predecir; subir un fichero; abrir un modelo ya entrenado y predecir; analizar un conjunto en el AED. + → `e2e/teclado.spec.ts` (también saltar al contenido y el título de las páginas). +- [~] **Lista de comprobación manual** (`docs/accessibility.md`) para cada versión. *Escrita; falta pasarla:* + - [ ] NVDA con Firefox y Chrome (Windows). + - [ ] VoiceOver con Safari (macOS e iOS). + - [ ] TalkBack con Chrome (Android). + - [ ] Solo teclado. + - [ ] Zoom al 200 % y al 400 %. + - [ ] Alto contraste de Windows. + - [ ] Control por voz (Voice Access o Control por voz de Apple). +- [x] **Inventario de componentes interactivos** (selector virtual, editor de capas, lienzo, cámara, gráficas, + tablas paginadas, guía, visor, alertas…) con su estado en teclado, lector y contraste, para repartir el + trabajo de las fases 2 y 3. → `docs/accessibility.md` + +## Fase 1 — Lo básico que falla hoy (arreglos rápidos) + +Problemas de nivel A y AA con un arreglo acotado y mucho efecto en todas las páginas. + +- [x] **Título de cada página (2.4.2).** `document.title` según la ruta y lo abierto, en el idioma elegido: + «Pasajeros de avión - Series temporales - Nets4Learning». Un hook `usePageTitle` que usen todas las páginas, y + un test que compruebe que ninguna ruta se queda con el título genérico. + *En vez de un hook en cada página, uno solo para todas (`N4LPageTitle` con `src/core/pageTitle.ts`), que saca el + título de la ruta; pruebas en `tests/core/pageTitle.test.ts` y `e2e/teclado.spec.ts`.* +- [x] **Saltar al contenido (2.4.1).** Enlace «Saltar al contenido» al principio, visible al recibir el foco, que + lleve al `<main>`. +- [x] **Regiones (1.3.1).** Un solo `<main>`, `<header>` y `<footer>` por página. `aria-label` en cada `<nav>` + (principal, migas de pan, índice de secciones, paginación) y en las regiones con nombre. + *Quitados los `<main>` de dentro de los componentes; los modales y la guía, con nombre.* +- [x] **Idioma inicial (3.1.1).** Poner en `index.html` el idioma guardado o el del navegador antes de que cargue + i18n (un script pequeño en el `<head>`), para que el lector no empiece a leer en inglés. +- [x] **Partes en otro idioma (3.1.2).** `lang="en"` en las descripciones originales (en inglés) de las fichas de + variables, en los nombres de las clases y columnas de los conjuntos y en las citas BibTeX. + *Hecho en las fichas de variables, en las citas y en los nombres de las capas del resumen del modelo. Los + nombres de clases y columnas no: son los identificadores del fichero, en cualquier idioma (el CSV del aire está + en español; «vhigh» o «unacc» no son de ninguno), y 3.1.2 exceptúa las palabras de idioma indeterminado.* +- [x] **Orden de encabezados (1.3.1).** Sin saltos de nivel en el glosario, `/select-model`, `/manual` y el AED. + Repasar la jerarquía de cada página: un `h1` y después `h2`, `h3`… en orden. +- [x] **Contraste de texto (1.4.3).** Arreglar los 2 casos del AED y el de `/learn`. Revisar `text-body-secondary` + sobre los fondos grises y en el tema oscuro. +- [x] **Contraste de lo que no es texto (1.4.11).** Bordes de los campos, iconos, el anillo del foco, las líneas y + puntos de las gráficas y las insignias, con al menos 3:1 en los dos temas. + *Bordes de los campos y de la zona para soltar ficheros, anillo del foco y una paleta común para las gráficas + (`src/core/chartColors.ts`, con un tono por tema y una prueba que comprueba el 3:1 de cada color). Los iconos + toman el color del texto. Los textos de error en rojo, con el tono «emphasis» (en el tema oscuro, el rojo de + Bootstrap se quedaba en 3,4:1).* +- [x] **Tamaño de los objetivos (2.5.8).** Al menos 24 × 24 px (o con separación suficiente) en los botones + pequeños (`btn-sm`), los botones de cerrar, la paginación y los selectores de las cabeceras. +- [x] **Foco visible y sin tapar (2.4.7, 2.4.11).** Un anillo de foco claro y común a toda la aplicación (sin + `outline: none` sin sustituto), y `scroll-padding-top` con el alto de la barra fija y del índice de secciones. +- [x] **Gráficas sin descripción (1.1.1).** `aria-label` en `N4LModelComparison`, `ModelExplanationChart` y + `ShapBeeswarmChart`, como en las demás. +- [x] **Imágenes (1.1.1).** Texto alternativo en las imágenes de ejemplo de la clasificación de imágenes (su clase: + «un 7 escrito a mano»). Revisar las capturas del manual y las imágenes del glosario. Mantener `alt=""` solo + en las decorativas. + *Las capturas del manual tenían de texto alternativo el nombre del fichero: ahora dicen lo que enseñan, en los + tres idiomas.* +- [x] **«Modelo entrenado» (2.2.1, 4.1.3).** Cambiar la alerta que se cierra sola a los 1,5 s por un mensaje de + estado (`role="status"`) que no robe el foco y se quede hasta el siguiente entrenamiento. Repasar los demás + avisos de `alertHelper`: los de error, con foco y botón para cerrarlos. + *Todos los avisos de éxito son ahora una notificación en una esquina que no se lleva el foco, dura 6 s, se para + con el ratón encima y tiene botón para cerrarla (el resultado se queda en la página). Los de error ya eran un + diálogo con el foco en su botón.* + +## Fase 2 — Teclado, foco y lectores de pantalla + +Que todo lo que se hace con el ratón se pueda hacer con el teclado, en un orden lógico, y que el lector diga qué pasa. + +- [~] **Recorrido con teclado de cada página (2.1.1, 2.4.3, 2.1.2):** orden lógico, sin trampas y sin elementos a + los que no se llega. *Probado en `e2e/teclado.spec.ts` lo de abajo; falta el repaso a mano de cada página + (fase 0).* + - [x] Editor de capas: acordeones, añadir y quitar capas, y el aviso de capas con su botón de arreglar. + - [x] `N4LVirtualSelect` (selector de ejemplos y de valores de una serie), siguiendo el patrón *combobox* de ARIA: + flechas, Inicio/Fin, escribir para buscar, Escape, y anuncio del número de resultados. + *Ya lo seguía (con AvPág/RePág y Ctrl+Inicio/Fin, y sus pruebas). Faltaba decir para qué es el botón: solo + enseñaba la opción elegida («Fila 12»); ahora el lector oye antes qué se elige.* + - [x] Pestañas, desplegables de la barra de navegación, migas de pan con desplegable, conmutadores (*toggle + buttons*) y tablas paginadas. + - [x] Modales (información de un conjunto, descripción de un modelo, compartir sesión, guía): foco inicial + dentro, el Tab no se sale, Escape cierra y el foco vuelve al botón que lo abrió. + *El Tab se salía del modal al pasar de su último elemento: `N4LDialogFocusWrap` le hace dar la vuelta.* +- [x] **Mensajes de estado (4.1.3).** Anunciar con `aria-live`, sin mover el foco: + *Con `announce()` (`src/core/a11y/announce.ts`) y una sola región que está en la página desde el principio + (`N4LAnnouncer`): una región que aparece a la vez que su texto no siempre se lee.* + - [x] Entrenamiento: empieza, va por la época N (no cada época: cada 10 % o cada 10 s), termina o se para, y + con qué error. *Cada 10 s como mucho; al terminar bien lo dice el aviso de «modelo entrenado».* + - [x] Predicción y clasificación: el resultado. + - [x] Carga de datos: «144 valores cargados», «fichero rechazado: formato no admitido». + *Las series y el AED al cargar; lo aceptado y lo rechazado en la zona de ficheros, traducido.* + - [x] Avisos del editor de capas al cambiar algo, y cambios de idioma, de tema y de backend. +- [~] **Foco tras las acciones (2.4.3).** Al terminar de entrenar, opción de ir al resultado. Al subir un fichero, al + paso siguiente. Al borrar una capa, a la capa de al lado (no al principio de la página). + *Hecho: el foco ya no se pierde al empezar a entrenar (pasa a «Detener» y vuelve a «Entrenar»); al terminar, + un enlace «Ir al resultado» en la clasificación tabular y de imágenes (en regresión y series el resultado está + justo debajo del botón); al borrar una capa, a la de al lado; el selector del AED, la guía y el aviso de cookies + devuelven el foco al cerrarse o al terminar de cargar. Falta: al subir un fichero, al paso siguiente.* +- [x] **Errores en los formularios (3.3.1, 3.3.3).** En vez de recortar los valores en silencio, mensaje junto al + campo (`aria-invalid`, `aria-describedby`) con el rango admitido: épocas, tasa, tamaño del lote, ventana, + porcentaje de prueba, k, columnas del formulario de predicción. + *`N4LNumberField`: dice qué se puede escribir y qué valor se sigue usando. Además, antes no se podía borrar el + número para escribir otro (volvía al mínimo al instante). La tasa es un desplegable y el formulario de + predicción no recortaba nada.* +- [x] **Subir ficheros.** El área de arrastrar y soltar con un botón visible «Elegir fichero», que se anuncie qué + formatos admite y qué fichero se ha aceptado o rechazado. +- [x] **Visor de tfjs-vis.** No es accesible y es de una librería: + - [x] Que no se abra solo al entrenar (ajuste en la fase 4); las curvas propias (`N4LTrainingCurves`) ya lo + cubren. + *«Abrir el visor de TensorFlow.js al entrenar», en `/settings` → Accesibilidad: lo respetan los entrenamientos + densos, de series temporales y de imágenes (`shouldOpenVisor`).* + - [x] El resumen del modelo como tabla propia y accesible (capas, forma de salida, pesos), en vez de abrir el visor. +- [x] **Guía.** Que se maneje entera con el teclado (Escape, flechas), que se anuncie el paso y que no hable a la vez + que el lector de pantalla: avisar en `/settings` de que conviene desactivar la voz si se usa un lector. + *Al abrirse, el foco va al título del paso; al cerrarse, vuelve al botón «Guía».* +- [x] **Aviso de cookies.** Que el foco y el orden del teclado lleguen a él sin tapar el contenido. + *Va justo después de «Saltar al contenido» y la página deja libre su alto al final. Abierto desde el pie, el foco + entra en él y vuelve al cerrarlo.* +- [x] **Etiqueta en el nombre (2.5.3).** El nombre accesible de cada control empieza por el texto que se ve (para el + control por voz): revisar los botones con icono y `aria-label` distinto del texto. + *La regla experimental de axe (`label-content-name-mismatch`) se pasa en todas las pruebas; los desplegables de + hiperparámetros tenían de nombre su ayuda en vez de su etiqueta.* + +## Fase 3 — Gráficas, imágenes, lienzo y cámara + +Lo más propio de esta aplicación: casi todo lo que enseña se ve en gráficas y dibujos. + +- [x] **Cada gráfica con sus datos en texto (1.1.1, 1.3.1).** Un botón «Ver los datos» que enseñe una tabla + accesible con lo dibujado, además de la frase que la describe: + *`N4LChartData`: botón con `aria-expanded`, tabla con encabezados de fila y columna, paginada si es larga y en + una región que se alcanza con el tabulador. `N4LPlot` la admite (`table`) para los gráficos de Plotly.* + - [x] Curvas de entrenamiento y comparación de modelos. + - [x] Series temporales: valor real, predicho y error de cada fecha. *Real y predicho; el error, en la tabla de + errores que ya había.* + - [x] Dispersión del agrupamiento: grupos con sus filas y sus centroides. Codo: k e inercia. + - [x] SHAP y explicaciones: contribución de cada variable. + - [x] Gráficas de Plotly del AED: enlazar a la tabla y a las estadísticas que ya existen. *Cada una con su tabla: + clases del objetivo, histogramas, frecuencias, cajas, correlaciones y correlación con el objetivo.* + - [x] Matriz de confusión: comprobar que es una tabla con encabezados de fila y columna. *Lo era; tenía una esquina + `<th>` vacía y el porcentaje gris sin contraste sobre el verde y el rojo.* +- [x] **Resumen de la tendencia.** En las gráficas que lo permiten, una frase que diga lo importante: «la pérdida baja + de 0,9 a 0,1 en 50 épocas», «la red sigue la serie salvo en los picos de 1960». + *Debajo de cada curva, a la vista. En las series lo dice el veredicto (cuánto mejora a las predicciones + sencillas) que ya había.* +- [x] **No solo el color (1.4.1).** Distinguir también por la forma o el texto: + - [x] Grupos del agrupamiento: forma del marcador distinta y número de grupo. *También en la leyenda.* + - [x] Líneas de las series: estilo de línea y leyenda con texto, no solo color. *Continua, de puntos y de rayas.* + - [x] Mapas de calor de correlaciones: el valor en cada celda. *En su tabla (con muchas variables la gráfica no + cabe con los valores).* + - [x] Marca del mejor modelo, avisos y errores: siempre con texto o icono con nombre. + *Ya lo llevaban («Mejor», «Error», «Aviso»). La clase real de una predicción dice si acierta o falla (✓/✗ y, + para el lector, con palabras); los modelos comparados, con una forma de punto cada uno.* +- [x] **Diagrama de la red y Paso a paso.** Descripción estructurada (lista de capas con sus neuronas y activaciones). + Las neuronas del paso a paso se recorren con el teclado (ya tienen foco visible), con nombre y valor + accesibles. *Las neuronas ya eran botones con nombre y valor; su borde, ahora con contraste.* +- [~] **Dibujar un dígito (2.5.7).** Alternativa a arrastrar en todas las páginas con lienzo: elegir una imagen de + ejemplo o subir una. Opcionalmente, dibujar con el teclado sobre una cuadrícula. El resultado, anunciado. + *Los ejemplos y las imágenes de prueba ya estaban; el lienzo tiene nombre y dice cuál es la alternativa, y el + resultado se anuncia. Falta (opcional) dibujar con el teclado.* +- [x] **Detección de objetos.** + - [x] Lo detectado también en texto: una lista con cada objeto y su confianza (con una foto, al terminar; con la + cámara, resumida y sin saturar el lector: como mucho cada pocos segundos, o al pulsar un botón). + *Igual en todos los modelos: usa lo mismo que su explicabilidad.* + - [x] Que la foto subida (la alternativa a la cámara, que ya existe) funcione igual en todos los modelos y se + anuncie su resultado. + - [x] Que la cámara se pueda encender y parar con el teclado. *Es un interruptor.* +- [~] **Fórmulas (KaTeX).** Comprobar que se generan con MathML para los lectores de pantalla y que se leen bien con + NVDA y VoiceOver. *Se generan con MathML y el dibujo oculto (prueba e2e); falta escucharlas con NVDA y + VoiceOver.* + +## Fase 4 — Visión baja, movimiento y ajustes de accesibilidad + +Que cada persona adapte la aplicación a lo que necesita, y que respete lo que ya ha elegido en su sistema. + +- [x] **Sección «Accesibilidad» en `/settings`**, guardada como los demás ajustes: + *`src/core/a11y/displaySettings.ts`: se aplica en `<html>` antes de pintar (`index.html`) y al cambiarla, se + borra con «Restablecer todo» y no va a las analíticas (diría qué necesidades tiene quien la usa).* + - [x] Tamaño del texto (100 %, 125 %, 150 %, 200 %). *Con el texto grande, la barra de navegación es la del móvil + (la del escritorio no cabe).* + - [x] Más espacio entre líneas, letras y palabras. + - [x] Tema de alto contraste, además del claro y el oscuro. *En los dos temas; también si el sistema lo pide + (`prefers-contrast: more`).* + - [x] Reducir el movimiento aunque el sistema no lo pida. + - [x] Subrayar siempre los enlaces. + - [x] Foco más grueso y visible. + - [x] No abrir el visor de tfjs-vis al entrenar. + - [x] Guía sin voz y sin avance automático por defecto. *Ya estaba en «Voz de las guías»; la sección enlaza a ella.* +- [x] **Reflow (1.4.10).** Usable a 320 px de ancho y con zoom al 400 % sin desplazarse en dos direcciones (salvo + las tablas de datos, con su propio desplazamiento y enfocables). Probar el editor de capas, el AED, los + formularios de predicción y la barra de navegación. *`e2e/vision.spec.ts`, en 13 páginas; los botones del + editor de capas no bajaban de línea.* +- [x] **Espaciado del texto (1.4.12).** Nada se corta ni se solapa con el espaciado máximo de WCAG. *Probado con el + espaciado y el texto al 200 %; la tabla de datos que se desplazaba no se podía enfocar.* +- [x] **Colores forzados.** `@media (forced-colors: active)` para insignias, bordes, foco, barras de progreso y + gráficas, con colores del sistema en Chart.js cuando estén activos. Y `prefers-contrast: more`. + *Bordes en lo que solo se distinguía por el fondo y el foco con el color de resaltado del sistema. En las + gráficas, las series se distinguen ya por la forma y el trazo (fase 3), que los colores forzados no quitan.* +- [x] **Movimiento (2.3.3).** Todas las animaciones respetan el movimiento reducido: las de Chart.js, los acordeones, + la animación del agrupamiento, los avisos y el desplazamiento suave. *La del agrupamiento solo empieza con su + botón y se puede parar.* +- [x] **Contenido al pasar el ratón o con el foco (1.4.13).** Los popovers de ayuda se cierran con Escape, no se + cierran al mover el puntero sobre ellos y no tapan lo que se está escribiendo. *También se abren al pulsarlos + (en pantallas táctiles).* +- [x] **Orientación (1.3.4).** Ninguna página obliga a girar el móvil. *Probado en horizontal.* + +## Fase 5 — Comprensión (accesibilidad cognitiva) + +Que se entienda qué hacer en cada página y qué ha pasado, sin conocimientos previos. + +- [~] **Lenguaje claro.** Revisar los textos más antiguos (descripciones de conjuntos traducidas de forma literal, + como «Dicho conjunto de datos…»), con frases cortas y términos técnicos explicados la primera vez. + *Reescritos los «Dicho conjunto…» (vino, cáncer de mama, en español e inglés) y el manual de regresión. Falta + repasar con calma el resto de descripciones y del manual.* +- [x] **Términos técnicos enlazados al glosario.** Época, pérdida, ventana o activación, con su definición accesible + con teclado y lector. *Con `N4LHelpTerm` en los hiperparámetros y ahora también en las neuronas y la activación + de cada capa; la ventana, la estación y la prueba de las series tienen su ayuda escrita debajo, y cada editor + enlaza a su apartado del glosario.* +- [x] **Qué se hace en cada página, al principio.** Una o dos frases y los pasos, en las páginas de entrenar y de los + modelos, como en las series temporales. *`N4LPageHeader` con `intro`: entrenar, probar un modelo o detectar.* +- [x] **Ayuda siempre en el mismo sitio (3.2.6).** La guía, el manual y el glosario, en la misma posición en todas + las páginas. *Ya lo estaban: la guía junto al título, arriba a la derecha; el manual y el glosario en la barra.* +- [x] **Evitar errores (3.3.4).** Confirmar antes de borrar los modelos guardados o una capa con cambios, y poder + deshacer. *Borrar una capa se puede deshacer; borrar los modelos desde /settings y quitar un paquete `.n4l` + preguntan antes (`N4LConfirmButton`, con el foco en «Cancelar»). Restablecer todo y borrar los modelos desde el + aviso del entrenador ya preguntaban. El número de neuronas ya no se rompe al borrarlo para escribir otro.* +- [x] **Tiempo.** Avisar de cuánto tardará un entrenamiento largo antes de empezarlo. Ninguna acción con límite de + tiempo. *Mientras se entrena, lo que queda (también para el lector, cada 10 s); al terminar, cuánto tardó y + cuánto por época, para saber qué esperar del siguiente. No hay nada con límite de tiempo.* +- [x] **Resultados explicados con palabras.** Seguir el ejemplo del diagnóstico del entrenamiento y del veredicto de + las series: decir qué significa un número, no solo darlo. *Ya lo hacían el diagnóstico, el veredicto, la silueta + del agrupamiento y la matriz de confusión; la tabla de modelos ahora dice cuál es el valor de validación (antes + iba entre paréntesis).* + +## Fase 6 — Móvil y otras tecnologías de apoyo + +- [x] **Gestos (2.5.1, 2.5.2).** Todo lo que se hace con varios dedos o con un trazo (zoom de Plotly, dibujar) tiene + alternativa con un solo toque, y las acciones se hacen al soltar, no al tocar. + *El zoom de Plotly tiene sus botones (y los datos, su tabla); dibujar, los ejemplos y las imágenes de prueba. Los + botones actúan al soltar (clic); el lienzo empieza a dibujar al tocar porque dibujar es eso.* +- [~] **Control por voz y por conmutador.** Todos los controles tienen un nombre que se puede decir y se llega a ellos + en secuencia. *Lo comprueban las pruebas: nombre con el texto que se ve (regla de axe) y recorridos con el + teclado. Falta probarlo con Voice Access o Control por voz.* +- [ ] **Lectores de pantalla móviles.** Pasar la lista de la fase 0 con VoiceOver (iOS) y TalkBack (Android) en los + flujos principales. +- [x] **Menú móvil.** Foco dentro al abrirlo, Escape para cerrarlo y anuncio de abierto o cerrado. + *El botón dice si está abierto (aria-expanded) y lo de dentro va justo después con el tabulador (patrón de + «disclosure»); Escape lo cierra con el foco en el botón, salvo si hay un desplegable abierto dentro.* + +## Fase 7 — Declaración, documentación y mantenimiento + +- [x] **Página «Accesibilidad» (`/accessibility`)**, enlazada desde el pie: + - [x] Declaración de accesibilidad según el modelo de la Decisión de Ejecución (UE) 2018/1523: situación de + cumplimiento, contenido no accesible y por qué, fecha y forma de revisión. + - [x] Forma de comunicar barreras: correo o formulario, y plazo de respuesta. + *Una incidencia de GitHub con su plantilla y la web de SIMIDAT. Falta decidir un plazo de respuesta concreto (el + RD 1112/2018 lo pide si la web es del sector público) y, si se quiere, un correo.* + - [x] Cómo usar la aplicación con lector de pantalla y con el teclado (atajos), y los ajustes de la fase 4. +- [x] **`docs/accessibility.md` para quien desarrolla.** Patrones del proyecto (gráfica con tabla, mensaje de estado, + foco tras una acción, formulario con errores), la lista de comprobación manual y qué revisar en cada cambio. +- [x] **En las revisiones de código.** Un apartado de accesibilidad en la plantilla de los pull requests. +- [x] **CI.** axe (WCAG 2.2 AA), `jsx-a11y` y las pruebas de teclado bloquean la integración si fallan. + *Ya se lanzaban todas en cada pull request y antes de publicar (`checks.yaml`). Que bloqueen la fusión depende de + marcarlas como obligatorias en la protección de la rama en GitHub.* +- [x] **Revisión anual** de la declaración y repaso manual completo (fase 0) en cada versión mayor. *Escrito en la + declaración y en `docs/accessibility.md` (mantenimiento).* +- [x] **Analíticas.** No registrar el uso de tecnologías de apoyo ni de los ajustes de accesibilidad: es información + sensible. *Los ajustes no van a las analíticas, ni sus clics (`data-analytics-private`), y está en + `docs/analytics.md`.* + +## Fase 8 — Pruebas con personas + +Las pruebas automáticas y las de quien desarrolla no sustituyen a las de quien usa la aplicación cada día con una +tecnología de apoyo. + +- [ ] **Sesiones con personas con distintas discapacidades:** ceguera (lector de pantalla), baja visión + (magnificador, alto contraste), motora (teclado, conmutador, voz), sordera y discapacidad cognitiva. Buscarlas + a través del servicio de atención a la diversidad de la universidad, de la ONCE y de asociaciones. +- [ ] **Tareas de la sesión:** entrenar una red con un conjunto de ejemplo, probar un modelo ya entrenado, subir un + conjunto propio y entender un resultado. +- [ ] **Lo encontrado, a este plan.** Cada barrera como tarea en la fase que corresponda, y repetir las sesiones tras + los cambios grandes. diff --git a/TODO-mejoras-ui.md b/TODO-mejoras-ui.md new file mode 100644 index 0000000..e73d053 --- /dev/null +++ b/TODO-mejoras-ui.md @@ -0,0 +1,418 @@ +# TODO — Mejoras de la UI de Nets4Learning + +Plan de mejoras de la interfaz, sacado de la revisión del código y de capturas de la app en escritorio y móvil +(30/09/2026). Cada hito agrupa tareas independientes; se marcan a medida que se terminan. + +Leyenda: `[x]` hecho · `[ ]` pendiente · `[~]` en curso o hecho a medias (ver nota) · `[-]` descartado. + +--- + +## Hito 1 — Errores visibles (arreglos rápidos) + +- [x] **Título de la página de datasets.** Muestra "Contribuye" porque usa la clave `pages.contribute.title` + (`src/pages/datasets/Datasets.tsx`). Ahora usa `datasets.title` y se quita la cabecera de la tarjeta, que + repetía el mismo texto. +- [x] **Funciones de pérdida que no funcionan.** `model.compile()` de tfjs-layers solo acepta estos nombres: + `meanSquaredError`, `meanAbsoluteError`, `meanAbsolutePercentageError`, `meanSquaredLogarithmicError`, + `squaredHinge`, `hinge`, `categoricalHinge`, `logcosh`, `categoricalCrossentropy`, + `sparseCategoricalCrossentropy`, `binaryCrossentropy`, `kullbackLeiblerDivergence`, `poisson` y + `cosineProximity`. + - Las opciones `losses-*` del selector (salvo `meanSquaredError`) lanzan "Unknown loss" al entrenar. + - Las opciones `metrics-*` usadas como pérdida no existen en `createLoss()` y entrenan en silencio con + `categoricalCrossentropy`. + - Ofrecer solo pérdidas válidas y quitar las métricas del selector de pérdida. + - Hecho: `LossName_t` y `TYPE_LOSSES` solo tienen pérdidas de tfjs-layers; el selector las agrupa en + "Clasificación" y "Regresión" (en regresión va primero su grupo). Test nuevo `tests/core/createLoss.test.ts` + que compila un modelo con cada opción. +- [x] **Pérdida por defecto en clasificación tabular.** Es `meanSquaredError`; debe ser `categoricalCrossentropy`. +- [x] **Pérdida por defecto en clasificación de imágenes.** `'categoricalCrossentropy'` no coincide con ningún + `value` del selector, así que el selector enseña otra opción distinta de la que se usa. Ahora es + `'losses-categoricalCrossentropy'`. +- [x] **Métrica por defecto en clasificación tabular.** Era `metrics-binaryAccuracy`, que no está entre las + opciones del selector (desactivado): enseñaba `CategoricalAccuracy` y entrenaba con `BinaryAccuracy`, que + con salida one-hot da valores inflados. Ahora es `categoricalAccuracy`. +- [x] **Tasa de aprendizaje como porcentaje entero (1–100).** El campo dice "1" y la tabla "1%" cuando el valor + real es 0.01, y no se puede poner 0.001. Usar el valor real con un selector de valores típicos en las tres + tareas que entrenan (tabular, regresión e imágenes). Hecho con `HyperparameterLearningRate` + (0.0001 … 1, por defecto 0.01), sin divisiones entre 100 ni "%" en las tablas; texto de ayuda y manual + actualizados. +- [x] **Los enlaces "Más información" borran lo entrenado.** Llevan a `/glossary` o `/manual` en la misma pestaña + y, como el contexto vive dentro de la ruta del playground, se pierden los modelos. Abrirlos en otra pestaña + pasando la sección por la URL (el `state` del router no llega a una pestaña nueva). Hecho con + `N4LHelpLink` (17 enlaces en 10 ficheros); el manual lee `?action=`. +- [x] **El glosario ignora la sección del enlace.** Recibe `?action=task-00-…` pero no tiene secciones que + correspondan a esas acciones; decidir a qué parte lleva cada enlace y abrirla. Hecho: + `glossaryTarget.ts` lleva los pasos de datos al apartado de su tarea, los editores al glosario del editor de + capas o de hiperparámetros y la tabla de modelos a las métricas; el glosario abre ese apartado y se desplaza + hasta él. Regresión tiene ahora sus propias acciones (`task-01-…`). +- [x] **Textos sin traducir.** + - Alertas escritas a mano en inglés o en español dentro del código. + - "Return to Home" y "Error 404" en la página 404. + - "Light" y "Dark" en el menú de tema. + - "Manual" escrito a mano en `ImageClassification.tsx`. + - Hecho: claves nuevas en `error.*`, `warning.*`, `pages.not-found.*` y `header.theme-*` (es, en, ja). De + paso, `t('error')` devolvía un objeto en `TabularClassification.tsx` y las guías del playground seguían + diciendo que la tasa de aprendizaje era "un valor entre 0 y 100". +- [x] **URL de modelo inválida en clasificación de imágenes.** Enseña "Error, option not valid" sobre la página + vacía; debe redirigir a `/404` como hace la clasificación tabular. `createReviewModelInstance` ya no + muestra la alerta antes de ir a `/404` (afecta a todas las páginas de modelos preentrenados). +- [x] **Tema.** No se guarda ni sigue el tema del sistema (`prefers-color-scheme`); cada recarga vuelve a claro. + La página 404 tiene el fondo oscuro fijo. Hecho con `src/core/theme.ts` (mismo patrón que el idioma), el + tema se aplica en `main.tsx` antes de pintar y el menú marca el activo; test en `tests/core/theme.test.ts`. + La 404 usa los colores del tema. +- [x] **Tarea elegida en la home.** Se guarda en `localStorage` pero nunca se lee. Ahora se lee al entrar (con + try/catch por si no hay almacenamiento); test en `tests/pages/PageHome.test.tsx`. +- [x] **Nombre del modelo descargado.** Usa el índice dentro de la página de la tabla, así que en la página 2 se + repiten nombres (tabular, y revisar regresión e imágenes). Ahora usa el mismo ID que la columna de la tabla + en las tres tareas (desde 1). + +## Hito 2 — Flujo y navegación + +- [-] **Home con tarjetas de tarea.** Descartado: se probó una tarjeta por tarea con icono y dos botones, pero se + prefiere el menú original (cuatro botones de colores y la tarjeta de la tarea elegida debajo), que se + mantiene. Sí se conserva que recuerde la última tarea elegida (hito 1). +- [x] **Cabecera en la home.** Qué es Nets4Learning, a quién va dirigido y enlace al artículo. La home tiene un + párrafo de presentación; la cita del artículo va en el pie, entre la descripción y los logos. +- [x] **Selección de modelo o dataset como galería.** Tarjetas con la descripción visible (filas, columnas, + clases, fuente) y un clic para entrar; sobran el desplegable, el botón "Descripción" y el modal. Hecho a + medias a propósito: cada tarjeta abre el playground con un clic ("Abrir"), pero la descripción completa + sigue en un modal ("Descripción") porque sale de la clase de cada modelo y cargarlas todas arrastraría + librerías pesadas. Las listas de opciones pasan a `src/TASK_OPTIONS.ts` (sin registros de modelos) y + `DATA_MODEL` las reexporta. Una tarea o lista inexistente lleva a `/404`. En la selección de datasets, + "Subir conjunto de datos - CSV" va aparte ("Tu propio conjunto de datos"), encima de los "Conjuntos de datos + de ejemplo". +- [x] **Datos de cada dataset en su tarjeta.** Filas, columnas, clases y fuente sin cargar la clase del modelo + (metadatos en `TASK_OPTIONS.ts` o en las traducciones). Quitar de paso el prefijo "Modelo - " / "Conjunto + de datos - " de las etiquetas, que en la galería sobra. Hecho: + "150 filas · 4 características · 3 clases" (o el objetivo en regresión, o "65.000 imágenes de 28×28") en + las galerías de datasets y de modelos; los números viven en `TASK_OPTIONS.ts` y + `tests/core/datasetInfo.test.ts` los compara con los CSV. Etiquetas sin el prefijo en los tres idiomas. +- [-] **Colores de tarea.** Descartado: la home conserva sus colores (primary, danger, info y warning). La + variable `--n4l-task-color` (bordes de la galería de selección) usa esos mismos colores para que cada tarea + tenga el mismo en todas partes. +- [x] **Aviso de cookies no bloqueante.** Banner inferior con "Aceptar / Rechazar" en lugar del modal estático. + Hecho con `N4LCookiesBanner` (a nivel de `App`, no solo en la home) y un enlace "Preferencias de cookies" en + el pie para cambiar la decisión. Borrado `CookiesModal`. +- [x] **Consentimiento de analítica.** Google Analytics se inicia antes del consentimiento (`App.tsx`); iniciarlo + solo tras aceptar. "Si continúa navegando acepta" no vale como consentimiento según el RGPD. Hecho con + `src/core/analytics.ts`: se mantiene la cookie `n4l-accept-cookies` (quien ya aceptó no vuelve a ver el + aviso), las 7 llamadas a `ReactGA.send` pasan por `trackPageView`, que no hace nada sin consentimiento, y + el texto de términos ya no dice "al navegar aceptas". Tests en `tests/core/analytics.test.ts`. +- [x] **Migas de pan en el playground.** Inicio › Clasificación tabular › Iris, con un selector para cambiar de + dataset o modelo sin volver a la home. Hecho con `N4LBreadcrumb` en la selección y en el playground; la + última miga es un desplegable con los demás modelos o datasets de la tarea. Tests en + `tests/pages/MenuSelect.test.tsx`. De paso, el botón "Activar el tutorial" (ahora siempre visible) ya no + se estira a la altura del título. +- [x] **Navbar.** Selector de tema como un único botón con icono; idiomas sin banderas (nombre o EN / ES / JA); + `aria-label` en el enlace de GitHub. Hecho: idiomas con su nombre y `lang` (sin banderas; borrados + `es.svg` y `gb.svg`), GitHub en otra pestaña con `aria-label` y el logo con `alt=""`. El selector de tema + se queda como desplegable "Tema" (Claro / Oscuro), por preferencia. + +## Hito 3 — Pantalla de entrenamiento + +- [x] **Pasos numerados.** 1 Datos → 2 Arquitectura → 3 Entrenar → 4 Modelos → 5 Predecir → 6 Explicar, con estado + (hecho / bloqueado) y un índice fijo al lado. Los `N4LDivider` ya marcan esas secciones. + Hecho a medias por elección: los separadores de las tres páginas de entrenamiento van numerados + ("3 · Modelo"; con un CSV propio aparece el paso de procesamiento y se renumera). Sin índice lateral. +- [x] **Entrenamiento visible en la página.** Gráfica de pérdida y precisión en directo, "Época x/N" y botón de + detener, en lugar de mandar las curvas al visor de tfjs-vis. + Hecho: mientras entrena, el botón pasa a ser una barra "Entrenando… época 3 de 10" con "Detener" (el + modelo se guarda con las épocas completadas y la tabla enseña "2/5"); tras entrenar, curvas de cada métrica + (entrenamiento y validación) dentro de la tarjeta de modelos, con selector de modelo. El visor de tfjs-vis + se mantiene. Probado en Chrome con Iris, Auto MPG y MNIST. +- [x] **Tabla de modelos útil.** Precisión y pérdida finales en vez del historial en texto, marcar el mejor + modelo, botón "Usar para predecir" en cada fila y curvas superpuestas para comparar modelos. + Hecho: valores finales por métrica con la validación entre paréntesis y marca "Mejor" (menor pérdida de + validación final). No se añade "Usar para predecir": la tarjeta de predicción ya tiene su selector de + modelo (ahora numerado desde 1, como la tabla). +- [x] **Editor de capas.** Cabecera de cada capa con su resumen ("Capa 1 · Dense · 10 · relu"); diagrama de red + sin mezclar idiomas ni abreviaturas ("Layer", "U:", "F.A."). Hecho: "Capa 1 · 10 neuronas · ReLU" en la + cabecera (tabular y regresión) y el diagrama traducido, con las capas numeradas desde 1 como en el editor. + El editor de imágenes también (numerado desde 1, antes desde 0), con un resumen común a diagrama y editores + (`layerSummary.ts`). +- [x] **Hiperparámetros.** Quitar el selector de métrica desactivado y marcar los valores recomendados. Hecho: el + selector de métrica de clasificación tabular ya se puede usar; de paso, varias métricas no compilaban en + tfjs-layers ("Unknown metric": mae, mse, mape y cosine con su nombre largo) y ahora se traducen en + `createMetrics`, con test. No se marcan "recomendados": el texto de ayuda de cada campo ya orienta. +- [x] **Capturas del manual.** `04-editor-hyperparameters.png` (y las demás del editor) ya no coinciden con el + selector de tasa de aprendizaje ni con los grupos de pérdidas; rehacerlas. Hecho: 10 capturas + rehechas en inglés y tema claro con `Scripts/capture_manual_screenshots.mjs` (Chrome sin ventana con el + dataset Car y la arquitectura del tutorial); el manual (es, en, ja) explica ya el modo extendido, la métrica + por defecto y las curvas y la matriz de confusión. No cambian las de subir y procesar el CSV ni la del visor. + De paso, en modo extendido cada neurona lleva solo el nombre de su capa (con el texto completo se pisaban). +- [x] **Glosario de pérdidas.** La tabla describe las de `tf.losses.*` (AbsoluteDifference, HuberLoss, + SoftmaxCrossEntropy…), que ya no están en el selector; alinearla con las pérdidas de tfjs-layers. Hecho: la + tabla se genera con las mismas listas que el selector (agrupada en clasificación y regresión), con una + descripción nueva de cada pérdida en los tres idiomas; test en `tests/core/lossGlossary.test.ts`. +- [x] **Estados vacíos.** Icono, mensaje y botón ("Entrena un modelo para ver aquí la predicción") en lugar de + "Esperando" con una barra gris, gráficas con ejes vacíos o el cuadro negro de "Resultado". Hecho sin icono: + `N4LEmptyState` (recuadro discontinuo con un texto que dice qué hacer) en los 19 sitios que esperaban una + acción del usuario; `WaitingPlaceholder` queda para las cargas reales. Las gráficas de predicción y el + "Resultado" de imágenes enseñan el aviso hasta la primera predicción (el lienzo y la gráfica siguen + montados, ocultos, porque la predicción dibuja en ellos). +- [x] **Explicabilidad bloqueada sin modelo.** El panel enseña los controles activos antes de que exista un + modelo o una predicción. Hecho: `TabularShapPanel` recibe `modelReady` y `hasPrediction`; sin modelo solo + avisa, sin predicción la explicación local avisa y la importancia global sigue disponible. En imágenes el + botón ya se desactivaba y ahora dice por qué. +- [x] **Detalles de texto.** Paginación que empieza en "0" y repite flechas ("« ‹ ‹ ‹"); en imágenes el botón de + predecir se llama "Validar" y "Limpiar" está en amarillo. Hecho: la paginación cuenta desde 1, solo enseña + páginas que existen (los "-" eran los huecos) y se oculta con una sola página; "Clasificar" y "Borrar" (gris + con borde) en imágenes. + +- [x] **Botón "Resumen del modelo" en todos los modelos preentrenados.** Solo estaba en la revisión tabular, en la + cabecera de la tarjeta y con el texto "Summary" sin traducir. Ahora es `N4LModelSummaryButton`, arriba del + `Card.Body` de la tarjeta del modelo en tabular, regresión (modelo seleccionado) e imágenes, y cierra el + visor al salir de la página. Cada modelo tiene su pestaña en el visor con su nombre (en regresión, con el + CSV: "Calidad del vino (wine-quality-red.csv)") y el resumen se titula "Resumen del modelo: <modelo>". + De paso: el primer clic no hacía nada, porque `tfvis.visor()` crea el visor ya abierto y el botón lo + cerraba al momento. Solo aparece con un `LayersModel`: MobileNet (`GraphModel`) y los detectores + de detección de objetos no admiten `tfvis.show.modelSummary`. +- [x] **Quitar las flags `VITE_SHOW_NEW_FEATURE` y `VITE_NEW_FEATURE`.** Ocultaban la regresión, que ya está + terminada, y de paso otras partes. Ahora se ven siempre: pestaña de regresión en datasets, regresión en + el glosario y en el manual, ecuaciones del glosario (optimizadores, activaciones, pérdidas y métricas), + enlace "AED" del navbar, botón "Activar el tutorial" de clasificación tabular y botón de resumen del + modelo. Quitadas también de `.env`, `.env.netlify`, `.env.simidat`, del workflow de despliegue (que la + ponía a `"false"` en Netlify) y del README. + +## Hito 4 — Consistencia visual + +- [x] **Una sola librería de gráficos.** Hoy conviven Chart.js, Recharts, Plotly, tfjs-vis y vis-network; unificar + (Chart.js ya es la de por defecto) con una paleta común que funcione en modo oscuro. Hecho hasta donde tiene + sentido: las gráficas de SHAP (barras y beeswarm) pasan a Chart.js y se quita Recharts (25 paquetes menos); + el cálculo del beeswarm está en `beeswarmLayout.ts`, con test. Se quedan Plotly (gráficas de danfo), + tfjs-vis (visor del entrenamiento) y vis-network (diagrama de la red), que cubren cosas que Chart.js no. +- [~] **Tokens de color.** Llevar a `stylesheet.scss` (variables de Bootstrap) y a variables CSS los colores fijos: + `#E8EaEd`, `#914091`, el borde negro del canvas, los hexadecimales de los TSX y el azul de las alertas + (`#0081D5`, que no es el primario de Bootstrap). SweetAlert2 debe seguir el tema. + Hecho: las alertas siguen el tema de la app (`theme` de SweetAlert2) y usan todas el azul primario; las + aristas del diagrama y las líneas de los separadores ya se ven en tema oscuro (`useTheme` para lo que se + pinta en canvas). Quedan los colores fijos con variante oscura ya definida y el resto de hexadecimales. +- [-] **Color por tarea.** Reutilizarlo en la home, la selección y la cabecera del playground. Los bordes de la + galería de selección usan los colores de los botones de la home; falta la cabecera del playground. Sin + iconos de tarea (se probaron y se quitaron). Se deja así: en la cabecera del + playground no se añade color, para no cambiar su diseño. +- [x] **Logos del pie en tema oscuro.** SIMIDAT y DaSCI apenas se distinguen sobre el fondo oscuro. Hecho: fondo claro + redondeado solo en tema oscuro (`.n4l-footer-logo`). +- [~] **Tipografía y CSS.** Barlow como una familia con dos pesos; quitar la fuente Bangers (se descarga y no se + usa); acotar `#root { white-space: pre-line }`; borrar `N4LFooter.css` (no se importa). + +## Hito 5 — Móvil y accesibilidad + Hecho: fuera Bangers y `N4LFooter.css`. Se dejan a propósito las dos familias de Barlow (el canvas de + detección de objetos las usa por nombre) y `white-space: pre-line`, que necesitan los `\n` de las + traducciones. +- [x] **Tablas en móvil.** Indicar que se pueden desplazar en horizontal (la de Iris corta la columna de clase). + Hecho en `N4LTablePagination`: "Desliza en horizontal para ver todas las columnas →" solo cuando la tabla no + cabe, y la barra de desplazamiento ya no sale si cabe. +- [x] **Diagrama de red en móvil.** Corta "Salida". Hecho: flecha más pequeña en pantallas estrechas y estilos en + `NeuralNetwork.css` en lugar de en línea. +- [x] **Botones de las cabeceras de tarjeta en móvil.** "Activar el tutorial" y "Abrir/Cerrar visor" parten el + texto en varias líneas. Hecho: las cabeceras pasan a + varias filas (`flex-wrap`) y los botones no parten su texto (tutorial, visor, añadir capas). +- [x] **Encabezados anidados.** No meter `<h2>` dentro de `Accordion.Header`, que ya genera un `h2`. Hecho en 33 + acordeones: el nivel lo da `as` de `Accordion.Header` y las clases `n4l-accordion-h2/h3` mantienen el + tamaño de letra. +- [-] **Texto alternativo.** 8 `<img>` sin `alt`. No hacía falta: todas lo tienen (el recuento salía de una + búsqueda por líneas que no veía el `alt` en la línea siguiente). Sí faltaba en el botón de la cámara de + detección de objetos, que solo tenía un icono: ahora tiene `aria-label`. +- [x] **Contraste.** Botones `outline-info` ("Descripción") y botones amarillos. Los cinco `outline-info` pasan a + `outline-primary`; los amarillos de la home llevan texto negro y tienen buen contraste. +- [x] **Índice de secciones en móvil.** Los entrenadores miden 5000–7000 px en un móvil y el índice lateral solo + está en escritorio. Hecho: por debajo de xl, barra fija arriba (`N4LSectionBar`) que aparece al bajar de la + cabecera, con una pestaña por sección que se desliza en horizontal y la actual siempre a la vista. Un solo + cálculo de la sección actual (`useActiveSection`) para la barra y el índice lateral. +- [x] **Selectores que se salen de la tarjeta.** El selector de instancias (`minWidth: 16rem`) estrujaba el título + o se salía por la derecha (formulario de Iris, predicción de regresión, webcam de detección, dispersión). + Hecho: todas las cabeceras `.card-header.d-flex` pasan a varias filas si no caben, y en el móvil los controles + (`n4l-card-header-controls`, `n4l-instance-select`) bajan bajo el título y ocupan todo el ancho. +- [x] **Dibujar con el dedo.** El lienzo de MNIST pintaba cuadrados de 20 px desplazados arriba a la izquierda del + dedo, sin trazo continuo, y no limpiaba el mapa de calor. Hecho con eventos de puntero (ratón, dedo y lápiz), + `touch-action: none` (la página no se mueve al dibujar) y lienzo de hasta 260 px que se adapta al ancho. +- [x] **Migas de pan en móvil.** En el móvil se quita la tarea (ya es el título de la página) y el desplegable del + modelo o dataset tiene más alto en pantallas táctiles. +- [x] **Barra de navegación (escritorio, tablet y móvil).** En el móvil el menú se quedaba abierto al cambiar de página + y tapaba la nueva; ahora se cierra (también al pulsar la página en la que ya se está). La página actual se marca + (subrayada en escritorio, resaltada en el menú desplegado; `aria-current`). Idioma, Tema y Backend siguen siendo + desplegables con su nombre; en el menú del móvil y la tablet enseñan además su valor actual (en escritorio + no, a petición). + Los desplegables de la derecha se alinean a la derecha (el de Backend se salía de la pantalla). Menú del móvil: + filas más altas, ajustes aparte con el valor a la derecha, "GitHub" con su nombre, el botón pasa a ser una X al + abrirlo, sin borde negro tras pulsarlo y con nombre accesible ("Menú"). Tablet: el menú en dos columnas. Fuera + la sombra roja sin usar de `N4LNavbar.css`. +- [x] **Migas de pan mejoradas.** Separador ›, enlaces en gris sin subrayar (se subrayan al pasar por encima) y el + modelo o dataset abierto como un selector con borde (del color de la tarea al pasar por encima). Siempre en una + línea: si no cabe, se recorta antes "Modelos pre-entrenados"/"Entrenar un modelo" que el nombre abierto. La + tarea enlaza a su tarjeta en la home (`/?task=…`, que la home lee y recuerda). En el desplegable: enlaces de + verdad (se pueden abrir en otra pestaña), "Subir conjunto de datos" aparte de los de ejemplo, menú tan ancho + como el nombre más largo y un enlace al otro lado: del modelo preentrenado a entrenar con su dataset y al revés. +- [x] **Tabla de `/datasets` en móvil.** Cada fila es un bloque (nombre arriba; referencia, información y descarga + debajo) en vez de una tabla con la descarga fuera de la pantalla (`n4l-stack-table`). +- [x] **Home en móvil.** Los cuatro botones de disciplina con el mismo alto y las listas de dos columnas de las + tarjetas en una sola. +- [x] **Visor de entrenamiento en móvil.** El visor de tfjs-vis (550 px fijo a la derecha) se abría al entrenar y + tapaba la página entera. Hecho (`showTrainingVisor`): en pantallas estrechas (< 768 px) o bajas (< 500 px, + móvil en horizontal) se dibuja cerrado en las tres tareas; las gráficas siguen ahí y se ven con "Abrir visor". + +## Hito 6 — Funciones nuevas + +- [x] **Tutorial guiado para quien entra por primera vez.** Joyride ya está integrado y su botón se ve en + clasificación tabular; falta lanzarlo solo la primera vez y cubrir el resto de tareas. + Hecho: en la primera visita a cada página de entrenamiento el tour arranca solo (con el punto que late de + react-joyride) y se marca como visto al empezar, para que no vuelva a salir solo. +- [x] **Glosario dentro de la pantalla.** Recuadro emergente al pulsar "tasa de aprendizaje", "optimizador", etc. + Hecho sin iconos: las etiquetas de tasa de aprendizaje, épocas, tamaño de prueba, optimizador, pérdida y + métrica van subrayadas con puntos y enseñan una definición breve al pasar el ratón o con el teclado. +- [x] **Evaluación de cada modelo.** Matriz de confusión y precisión sobre el conjunto de prueba. + Hecho en clasificación tabular: matriz de confusión del conjunto de validación con el porcentaje de aciertos, + debajo de las curvas del modelo elegido. En imágenes ya la enseña el visor de tfjs-vis. +- [x] **Matriz de confusión validada y rediseñada.** Fallo corregido: las clases se sacaban con + `Object.keys(labelEncoder.classes)`, que ordena primero las claves numéricas, mientras que el one-hot de `y` + sigue el orden de aparición. En Lymphography (clases 3, 2, 4, 1) la matriz y la predicción tras entrenar + nombraban cada clase con la de otra. Ahora usan `DataFrameUtils.LabelEncoderClasses`. La matriz es más grande y + centrada: ejes "Clase real" / "Clase predicha", recuento y porcentaje de la fila en cada celda, color según + esa parte (verde aciertos, rojo errores), total y sensibilidad por fila, precisión por columna y exactitud, + con ayuda emergente. Los tensores de datos se liberan al acabar el entrenamiento. Comprobado en Chrome: la + exactitud de la matriz coincide con la `val_categoricalAccuracy` final (Iris 100 %, Car 95,6 %). +- [x] **Guardar y compartir el trabajo.** Exportar e importar la sesión (arquitectura e hiperparámetros), o + compartirla por URL. Hecho: + "Exportar configuración" e "Importar configuración" en la cabecera de las tres páginas de entrenamiento + (fichero JSON con capas e hiperparámetros, validado en `src/core/session/trainingSession.ts`, con tests). + No se comparte por URL: basta con pasar el fichero. +- [x] **Página de datasets generada desde los modelos.** Hoy es una lista escrita a mano: falta Lymphography y + las pestañas de imágenes están por hacer. Hecho: + la tabla principal de cada tarea (clasificación tabular, regresión e imágenes) sale de `TASK_OPTIONS`, con + los datos de cada dataset, su fuente original y la descarga de los mismos CSV que usa el modelo (ya está + Lymphography). Los conjuntos que no usa ningún modelo siguen aparte (`extraDatasets.ts`) para practicar + subiendo un CSV. Test: todos los ficheros existen y cada dataset tiene fuente. +- [x] **Información del dataset en un modal.** En `/datasets` la columna "Número de muestras" pasa a + "Información", entre Referencia y Descargar, con un botón "Ver información" que abre un modal: resumen + (filas, características, clases), descripción completa del modelo (se descarga al abrir el modal), enlace a + la fuente y descargas. Los conjuntos extra muestran el mismo modal sin descripción propia. Tests en + `tests/pages/Pages.test.tsx` (Iris y hepatitis C). +- [x] **Tabla de variables en el modal del dataset.** El modal pasa a `xl` con dos pestañas: "Información" y + "Variables". La tabla sigue la de UCI (variable, rol, tipo, descripción, unidades, valores ausentes). Rol, tipo, + descripción y unidades salen de la ficha de UCI (API `archive.ics.uci.edu/api/dataset?id=<id>`) o, si no está en + UCI, de la documentación original (Boston, new-thyroid, titanic, salary). Las columnas y los valores ausentes + son los de nuestros CSV (`src/pages/datasets/datasetVariables.ts`). Los conjuntos de imágenes lo explican en la + pestaña. Tests: cada CSV tabular tiene tabla y coincide con sus columnas y ausentes. + +--- +- [x] **Glosario renovado.** Antes: acordeones cerrados y, para cada término, la descripción en una tabla y la fórmula + en otro acordeón; las métricas no salían (sus textos estaban en las traducciones sin usar). Ahora: índice de + apartados (lateral en escritorio, barra arriba en el móvil), buscador (sin tildes ni mayúsculas, todas las + palabras), una tarjeta por término con descripción, características, fórmulas, gráfica y referencia, y enlace a + cada término (`/glossary#glossary-activation-relu`). Las ayudas del playground (`?action=`) llevan al término o + grupo. Datos en `glossaryTerms.ts`. Corregidas fórmulas: Adam (β₂ en la corrección de s), RMSProp (sin + corrección), Hard Sigmoid (`x ≥ +3`) y Linear (la identidad); nuevas las de SGD, hinge al cuadrado, hinge + categórica, MAPE, MSLE, logcosh y Poisson. Arreglado: las claves del editor de capas iban cruzadas en las + traducciones y la leyenda TP/TN/FP/FN estaba escrita en español en el código. +- [x] **Activaciones animadas en el glosario.** La gráfica de cada activación va en dos pestañas: "Imagen" (la de + PyTorch, primero) y "Animación": la curva se dibuja con Chart.js hasta la x que marca un deslizador de 0 a 1 (paso + 0,01; x de -6 a 6), con el punto (x, f(x)) y sus valores debajo. Al abrir la pestaña se dibuja sola en 3 s + ("Reproducir"/"Pausa"; sin animación si el sistema pide movimiento reducido). Funciones en + `activationFunctions.ts`, con los parámetros de PyTorch (α = 1, β = 1, negative_slope = 0,01). +- [x] **Barra de navegación fija.** Va arriba siempre (`sticky-top`) y deja su alto en `--n4l-navbar-height`: la barra + del índice del móvil aparece justo debajo, el índice lateral, las tarjetas fijas (`sticky-top`) y los saltos a + una sección o un término quedan por debajo de ella, y el visor de tfjs-vis va por encima. En el móvil, si el + menú no cabe en la pantalla, se desliza dentro. +- [x] **AED: distribución del objetivo y avisos en tarjetas**, como el resto de apartados (con el número de avisos). +- [x] **De /datasets al AED.** La columna "Referencia" pasa a ser "AED": cada CSV se abre en `/analyze?dataset=<clave>` + (la clave es el nombre del fichero sin extensión: `iris`, `wine-quality-red`…), que lo carga solo; al elegir otro + en el AED la dirección cambia. La referencia sigue en el modal de información, que también enlaza al AED. +- [x] **Tablas de /datasets.** El nombre (con filas, características y clases) a la izquierda y las acciones a la + derecha ajustadas a su contenido; cabeceras discretas; con varios ficheros, un enlace por fichero. En el móvil, + un bloque por conjunto y, si hay varios ficheros, cada grupo de enlaces dice de qué es. +- [x] **Datos y estadísticas en el modal de /datasets.** Además de "Información" y "Variables", los conjuntos con CSV + tienen "Datos" (el CSV entero como tabla, con el tipo de cada columna y la variable objetivo resaltada) y + "Estadísticas" (el describe() de las columnas numéricas, con qué significa cada fila). Con varios ficheros se elige + cuál. El CSV se lee al abrir la pestaña (danfo.js va aparte, `DatasetDataFrame`) y una sola vez para las dos. Las + de imágenes (MNIST, KMNIST) solo tienen "Información". En el móvil las pestañas van en una línea que se desliza. +- [x] **CSV con ";" al subir un fichero.** Fallaban los CSV de Excel en español (";" y coma decimal, como + AirQualityUCI.csv) y los "alineados" por un editor (", " como separador y "2,6" como número). Ahora el separador + (",", ";", tabulador o "|") sale de las primeras líneas (`csvFormat.ts`); con ";", o con comas y espacios, las + columnas de coma decimal pasan a ser numéricas, y se quitan los espacios de relleno y las columnas vacías sin + nombre (los ";;" del final). Solo lo que sube el usuario: los CSV del proyecto se leen como siempre. +- [x] **ARFF, JSON, JSONL y Parquet.** Al subir un fichero (AED y los dos entrenadores) se pasa a CSV y sigue el mismo + camino (`datasetFormats.ts`): ARFF de Weka (numéricos, nominales, texto, fechas, "?" y filas dispersas), JSON + (registros o las formas de `pandas.to_json`), JSON Lines y Parquet con cualquier compresión (hyparquet y + hyparquet-compressors, en un trozo aparte: 20 kB comprimidos que solo se descargan con un Parquet). + +## Registro + +- 30/09/2026 — Plan creado. Empiezo por el hito 1. +- 02/10/2026 — Ficheros propios con ";" (y coma decimal) o alineados, y en ARFF, JSON, JSONL y Parquet. Verificado: + `pnpm lint`, `tsc -b`, 56 ficheros de tests (337 tests: cada formato de Iris da el mismo CSV que iris.csv), Playwright + (los 8 ficheros de `e2e/files` en el AED) y AirQualityUCI.csv (9357 filas × 15 columnas, 13 numéricas) en sus tres + formas en el AED y en los entrenadores. +- 02/10/2026 — Pestañas "Datos" y "Estadísticas" en el modal de /datasets. Verificado: `pnpm lint`, `tsc -b`, 54 + ficheros de tests (311 tests), Playwright (Iris y los dos ficheros del vino) y Chrome a 390 y 1440 px, claro y oscuro. +- 02/10/2026 — Barra de navegación fija, AED con tarjetas para la distribución del objetivo y los avisos, enlaces de + /datasets al AED (`?dataset=`) y tablas de /datasets nuevas. Verificado: `pnpm lint`, `tsc -b`, 54 ficheros de tests + (310 tests), 15 pruebas de Playwright y Chrome a 390 y 1440 px, claro y oscuro. +- 02/10/2026 — Activaciones animadas en el glosario (pestañas Imagen / Animación, deslizador y Chart.js). Verificado: + `tsc -b`, `pnpm lint`, 54 ficheros de tests (308 tests) y Chrome a 390 y 1440 px, claro y oscuro. +- 02/10/2026 — Glosario renovado (índice, buscador, una tarjeta por término con su fórmula y su gráfica, enlaces a cada + término y las métricas que faltaban). Verificado: `tsc -b`, `pnpm lint`, 54 ficheros de tests (304 tests; uno + comprueba que todos los textos del glosario están en los tres idiomas) y Chrome a 390 y 1440 px, claro y oscuro. +- 02/10/2026 — Arreglos de base: `vite build` ya no empaqueta React de desarrollo (fuera `NODE_ENV` de los `.env`: + el bundle principal pasa de 818 a 578 kB), el despliegue de Netlify pasa antes lint, tipos, tests y pruebas en el + navegador (`checks.yaml`, también en cada pull request) y hay pruebas de Playwright (`e2e/`, `pnpm test:e2e`). Las + pruebas encontraron un fallo: al cambiar de modelo desde las migas de pan (Iris → Car) la página reutilizaba el + estado del anterior y danfo lanzaba "data must be a 1D array"; ahora el playground se monta de nuevo al cambiar de + ejemplo. +- 02/10/2026 — Móvil: índice de secciones como barra fija en pantallas estrechas, cabeceras de tarjeta que bajan + los controles bajo el título, dibujo con el dedo en el lienzo de MNIST, migas de pan más cortas, tabla de + `/datasets` por bloques y botones de la home del mismo alto. Verificado: `tsc`, `pnpm lint`, 51 ficheros de + tests (289 tests) y Chrome a 390 px (15 páginas sin desbordes ni controles fuera de su tarjeta; un 7 dibujado + con el dedo y con el ratón sale 7 al 99 %), 820 px y 1440 px. +- 02/10/2026 — En el móvil el visor ya no se abre al entrenar (tabular, regresión e imágenes). Verificado: `tsc`, + `pnpm lint`, 52 ficheros de tests (292 tests) y entrenamientos en Chrome a 390×844 y 844×390 (visor cerrado + durante y después; "Abrir visor" lo abre) y a 1440 px (se abre como antes). +- 02/10/2026 — Barra de navegación mejorada en escritorio, tablet y móvil. Verificado: `tsc`, `pnpm lint`, 53 + ficheros de tests (300 tests) y Chrome a 390, 820, 992, 1180, 1200, 1400 y 1440 px en español, inglés y japonés, + claro y oscuro (sin desbordes; en japonés entre 992 y 1199 px los enlaces se parten en dos líneas, como antes). +- 02/10/2026 — Migas de pan mejoradas (estilo, una sola línea, tarea enlazada a la home con `?task=`, enlaces en el + desplegable y paso entre modelo preentrenado y entrenamiento). Verificado: `tsc`, `pnpm lint`, 52 ficheros de + tests (296 tests) y Chrome a 390 y 1440 px en tema claro y oscuro (los enlaces de la tarea, del otro lado y del + desplegable llevan donde deben). +- 01/10/2026 — /analyze pasa a ser una interfaz de AED con índice lateral: elegir un CSV del proyecto (los 19, con su + ficha de variables) o uno propio y la variable objetivo; resumen (filas, columnas, ausentes, repetidas, distribución + del objetivo y avisos de calidad), ficha de cada variable (o tabla), distribuciones por clase con diagrama de caja, + matriz de correlación, correlación con el objetivo y dispersión, datos y consultas, y preprocesado en directo con + descarga del CSV. Cálculos en `eda.ts` y `preprocess.ts`, con tests. Verificado: `tsc -b`, `pnpm lint`, 47 ficheros + de tests y Chrome (Iris, Car, Lymphography, Auto MPG, vino, Titanic, breast cancer, CSV propio, oscuro y móvil). +- 01/10/2026 — Tablas de dataframes (Plotly) con un solo componente (`N4LDataFrameTable`, `DataFrameTable.ts`): + colores del tema, columna objetivo resaltada, índice, tipo de cada columna y altura justa; `describe()` con una + fila por columna. /analyze sin `<details>` y con Iris de ejemplo. Entrenador de regresión: el procesado ya aplica + lo elegido en el formulario (columnas descartadas, objetivo), la predicción usa el formulario de los modelos + preentrenados con valor real y error, y la revisión de regresión avisa de los conjuntos sin modelo (SALARY + `salary-extra.csv` fallaba; el modelo de wdbc no encajaba). Verificado: `tsc -b`, `pnpm lint`, 45 ficheros de + tests y pruebas en Chrome (Iris en /analyze, AUTO_MPG, todos los modelos de regresión y subida de CSV). +- 01/10/2026 — Avisos de Rollup de mathjs ("/* #__PURE__ */ … cannot interpret") en la build: mathjs 11 → 12.4.3 + (también el override de danfojs), que ya no trae esas anotaciones. Además, en la build el require("mathjs") de + danfojs recibe la versión ESM (alias en `vite.config.ts`): antes iban dos copias (CJS entera y ESM) y ahora una, + unos 965 KB menos de JS (240 KB con gzip). Verificado: `tsc -b`, `pnpm lint`, 164 tests, build de Netlify sin + esos avisos y, sobre la build servida, SHAP (local y beeswarm) y la página de AED (describe, gráficos y matriz de + correlación) sin errores. +- 01/10/2026 — Matriz de confusión: clases en el orden del one-hot (fallo en Lymphography) y nuevo diseño. + Verificado: `tsc -b`, `pnpm lint`, 36 ficheros de tests (164 tests) y entrenamientos en Chrome (Iris, Car, + Lymphography) en tema claro y oscuro. +- 01/10/2026 — Tabla de variables (pestaña "Variables") en el modal de cada dataset, con datos de UCI. + Verificado: `tsc -b`, `pnpm lint`, tests y capturas de HCV, Student Performance y MNIST. +- 01/10/2026 — Curvas de aprendizaje con borde y el modal de información en `/datasets`. Verificado: `tsc -b`, + `pnpm lint`, 35 ficheros de tests (154 tests) y capturas de la tabla y del modal de Iris. +- 01/10/2026 — Hechos el glosario por secciones, las métricas que no compilaban, los datos de los datasets, el + tutorial inicial, la ayuda emergente, la matriz de confusión, la página de datasets y las capturas del manual. + Después: exportar e importar la configuración y las gráficas de SHAP en Chart.js (sin Recharts). Verificado: + `tsc -b`, `pnpm lint`, 35 ficheros de tests (152 tests), build de Netlify y pruebas reales en Chrome. +- 01/10/2026 — Hito 3 casi completo (faltan hiperparámetros y capturas del manual) y buena parte de los hitos 4 y + 5. Verificado: `tsc -b`, `pnpm lint`, 30 ficheros de tests (124 tests), capturas en móvil y tema oscuro y + entrenamientos reales con progreso y "Detener". +- 30/09/2026 — Cambios de rumbo en el hito 2: vuelve el menú original de la home, fuera los iconos de tarea, el + selector de tema vuelve a ser un desplegable y la cita del artículo pasa al pie. +- 30/09/2026 — Hito 2 hecho salvo los datos de cada dataset en su tarjeta. Verificado: `tsc -b`, `pnpm lint`, + 28 ficheros de tests (114 tests) y capturas de la home (claro, oscuro y móvil), la galería y las migas en el + playground. +- 30/09/2026 — Hito 1 hecho salvo "El glosario ignora la sección del enlace" (necesita decidir el contenido). + Verificado: `tsc -b`, `pnpm lint`, 26 ficheros de tests (106 tests) en verde, capturas de datasets y 404 (tema + claro y oscuro del sistema) y entrenamiento real en Chrome sin ventana: Iris (pérdida por defecto y + `kullbackLeiblerDivergence`), Auto MPG y MNIST entrenan con tasa 0.01 y sin errores en consola. diff --git a/TODO-worker.md b/TODO-worker.md new file mode 100644 index 0000000..9960553 --- /dev/null +++ b/TODO-worker.md @@ -0,0 +1,300 @@ +# TODO — Cálculos pesados fuera del hilo principal (Web Workers) + +Objetivo: que la interfaz no se congele mientras se procesan datos. Hoy todo (lectura y análisis de CSV, preprocesado, +decodificación de imágenes, TF.js, explicabilidad) corre en el hilo principal, y no hay ningún Web Worker en el +proyecto. Plan sacado de medir la aplicación (01/10/2026); cada fase se mide antes y después con el mismo guion. + +Leyenda: `[x]` hecho · `[ ]` pendiente · `[~]` en curso o hecho a medias (ver nota) · `[-]` descartado. + +--- + +## Diagnóstico (01/10/2026) + +Medido en Chrome sin ventana contra el servidor de desarrollo, con un `PerformanceObserver` de tareas largas (más de +50 ms bloqueando el hilo principal). Los tiempos de TF.js son orientativos: sin ventana, WebGL va por SwiftShader +(software), más lento que con GPU. + +| Escenario | Bloqueo total | Tarea más larga | Duración | +|---|---|---|---| +| /analyze: cargar California housing (20 640 × 14) | 2233 ms | **1981 ms** | 2,3 s | +| /analyze: cargar housing-price (1460 × 81) | 774 ms | 704 ms | 0,9 s | +| /analyze: cambiar el escalado del preprocesado (California) | 334 ms | 334 ms | 0,3 s | +| /analyze: cambiar la variable objetivo (housing-price) | 445 ms | 445 ms | 0,5 s | +| MNIST: cargar las imágenes de test (sprite) | 322 ms | 322 ms | 1,9 s | +| MNIST: clasificar el primer ejemplo | 321 ms | 321 ms | 0,4 s | +| MNIST: explicar con LRP | 693 ms | **693 ms** | 0,8 s | +| MobileNet: explicar con SHAP | 171 ms | 171 ms | 14 s | +| Car: entrenar (épocas de desarrollo) | 972 ms | 524 ms | 17 s | +| Car: SHAP global | 306 ms | 132 ms | 1,3 s | +| MNIST: cargar el conjunto y entrenar | 1872 ms | **841 ms** | 94 s | + +Desglose de /analyze con California, cálculo a cálculo: + +| Cálculo | Tiempo | +|---|---| +| `profileDataFrame` (perfil de las columnas) | **1517 ms** | +| … de ello, ordenar valores con `localeCompare(…, { numeric: true })` | 1330 ms (200 ms con un `Intl.Collator` compartido) | +| `preprocessDataFrame` | 79 ms | +| `describe()` de danfo | 59 ms | +| Leer el CSV (danfo/papaparse) | 56 ms | +| Tabla de Plotly con 20 640 filas | 35–51 ms | +| Dispersión (`scattergl`) / histograma de 20 640 puntos | 35 / 25 ms | +| `correlationMatrix` | 12 ms | + +Conclusiones: + +1. **Lo que más bloquea es el AED con CSV grandes**, y la mayor parte es un problema de algoritmo (un comparador que + se crea en cada comparación), no de hilo: se arregla antes de mover nada (fase 0). +2. **Cálculo puro, sin DOM ni TF.js** (perfil, correlaciones, avisos, preprocesado, decodificar sprites): buenos + candidatos para un worker, baratos de mover (fases 1 a 3). +3. **TF.js ya cede el control** entre lotes e instancias (entrenar dura 17–94 s con picos de 0,5–0,8 s; SHAP de + MobileNet, 14 s con 171 ms de bloqueo). Los picos vienen de lecturas síncronas (`dataSync`/`arraySync`) y de + preparar los datos. Moverlo a un worker es posible (modelo serializado con `tf.io`, WebGL con `OffscreenCanvas`) + pero caro: se evalúa después (fases 4 y 5). +4. **Lo que no puede ir a un worker** (pintar con Plotly y React, el DOM, tfjs-vis, la cámara): cada gráfico cuesta + poco, pero /analyze repinta unos diez a la vez al cambiar el objetivo. Ahí la solución es pintar menos (fase 6). + +## Decisiones de arquitectura + +- Workers de módulo con Vite: `new Worker(new URL('./x.worker.ts', import.meta.url), { type: 'module' })` y + `worker: { format: 'es' }` en `vite.config.ts`. +- Los workers de datos no importan danfo ni TF.js (cada worker que los importa carga otra copia de TF.js): reciben y + devuelven columnas (`Float64Array` transferibles para las numéricas, arrays para el texto). +- Una función asíncrona por cálculo (p. ej. `profileInWorker(columns)`) con alternativa en el mismo hilo si no hay + `Worker` (jsdom en los tests, navegadores antiguos): las funciones puras siguen probándose como hasta ahora. +- Cada petición lleva un id: si llega una respuesta vieja (el usuario ya cambió el formulario), se descarta. +- Cada fase se mide con el mismo guion y se anota en el registro. + +--- + +## Fase 0 — Arreglos sin worker (rápidos y medidos) + +- [x] **Guion de medida en el repositorio.** `Scripts/perf/longtasks.mjs`: Chrome sin ventana con un + `PerformanceObserver` de tareas largas y los escenarios de la tabla del diagnóstico, para comparar antes y + después de cada fase. Uso: `node Scripts/perf/longtasks.mjs http://localhost:5173/n4l [analyze|mnist|car|mnist-train]`. + Clasificar, explicar y entrenar se miden dos veces (la primera compila los shaders de WebGL). +- [x] **`valueCounts` (`src/core/dataframe/eda.ts`).** Un `Intl.Collator` compartido (`naturalCompare`) en vez de + `localeCompare` con opciones, y `topValues`: los 10 más frecuentes sin ordenar todos los valores distintos. + `profileDataFrame` con California: 1517 → 75 ms; con housing-price: 98 → 14 ms. +- [x] **Estadísticos por clase en `AnalyzeDistributions`.** Memorizados con `useMemo` (antes, `profileColumn` de + cada clase en cada render). +- [x] **Lecturas síncronas de tensores → `await tensor.data()`.** + - [x] `src/core/controller/trainDenseModel.ts`: evaluación al acabar de entrenar (matriz de confusión). + - [x] `src/pages/playground/3_ImageClassification/models/_model_28x28.tsx`: predicción de imágenes de 28×28. + - [x] `src/pages/playground/3_ImageClassification/explainPrediction/runImageClassificationExplain.ts`: LRP. + - [-] `src/core/history/utils.tsx` y `src/core/history/trainingSummary.ts`: no hace falta; es una rama defensiva que + no se ejecuta, porque TF.js ya guarda el historial de `fit()` como números. + - [x] `src/core/explainability/webshap/explainer/lstsq.ts`: reescrito en JavaScript sin tensores. Antes construía W + como matriz diagonal m×m (250 000 elementos con 500 muestras), multiplicaba con TF.js, leía con `arraySync` y + no liberaba ninguno de sus 7 tensores; ahora X'WX en O(m·n²). Test nuevo en `tests/explainability/lstsq.test.ts`. +- [x] **Medir otra vez** todos los escenarios y anotar la mejora (en el registro). +- [~] **Compilar los shaders antes de usarlos.** Tras la fase 0, todo lo que bloquea TF.js es compilar los shaders de + WebGL la primera vez (entrenar Car la segunda vez: 0 ms; clasificar y LRP la segunda vez: 0 ms). El perfil de + CPU del entrenamiento de MNIST lo confirma: `getShaderParameter` (TF.js esperando a que WebGL compile) suma + 1456 ms. + - [x] `warmUpModel()` (`src/core/nn-utils/warmUpModel.ts`): una predicción con `ENGINE_COMPILE_ONLY`, + `checkCompileCompletionAsync()` y `getUniformLocations()` antes de dar el modelo por cargado (los programas no + están listos hasta entonces). En la página de los modelos de imágenes de 28×28: en la primera clasificación, + `getShaderParameter` pasa a 5 ms. Lo que queda (≈120 ms en Chrome sin ventana) es trabajo nativo de la GPU por + software (SwiftShader: "GPU stall due to ReadPixels"), no JavaScript. + - [ ] Comprobar en un equipo con GPU que, con `KHR_parallel_shader_compile`, el calentamiento no bloquea (Chrome + sin ventana no tiene la extensión: aquí compila igual, pero al cargar el modelo en vez de al pulsar). + - [x] LRP (≈300 ms la primera vez) usa otras operaciones que este calentamiento no compila. Hecho: `warmUpLrp()` + propaga la relevancia con activaciones a cero de la forma de cada capa en modo solo compilar + (`compileShaders()`, el mismo mecanismo que `warmUpModel`): gradientes, `argMax`, `oneHot`, conv y pooling + hacia atrás. Va en segundo plano tras cargar el modelo (ya se puede clasificar) y "Explicar" espera a que + acabe. También en el entrenador de imágenes, tras cada entrenamiento (con `warmUpModel`). Página del modelo: + primera explicación 345 → 0 ms (cargar el modelo pasa de 355 a ≈440 ms sin `KHR_parallel_shader_compile`); + entrenador: primera clasificación 226–232 → 0 ms y primera explicación 426–442 → 0 ms. Los mapas de calor son + idénticos con y sin calentamiento (comprobado con tres imágenes). + +## Fase 1 — Infraestructura de workers + +- [x] **Protocolo.** Mensajes propios tipados, sin dependencias (`{ id, type, payload }` → `{ id, result }` o + `{ id, error }`): `src/core/workers/workerProtocol.ts`. +- [x] **Cliente y worker (`src/core/workers/`).** `createWorkerClient` (worker que se crea en la primera petición, ids, + errores, `terminate`, alternativa en el mismo hilo si no hay `Worker`) y `exposeWorker` (el lado del worker, + que transfiere los `ArrayBuffer` del resultado en vez de copiarlos). +- [x] **Vite y despliegue.** `worker.format: 'es'`. Comprobado en desarrollo y en las builds con `base` `/n4l` + (`--mode simidat`) y en la raíz (`--mode netlify`): los dos workers se piden en `/assets/…` y responden 200. +- [x] **Datos por columnas.** `ColumnData_t` y `dataframeColumns()` en `eda.ts`. +- [-] **Hook `useWorkerTask`.** No ha hecho falta: el análisis se pide al cargar un conjunto (en el manejador, no en + un efecto) y una cuenta de cargas descarta los resultados viejos. +- [x] **Tests.** `tests/core/workers.test.ts`, con un worker de mentira que pasa por `exposeWorker`: respuestas en + otro orden, errores, transferencias, `terminate` y alternativa sin `Worker`. + +## Fase 2 — AED de /analyze en un worker + +- [x] **`eda.ts` sin danfo.** `analyzeColumns(columns)` (perfil, valores numéricos y correlaciones) y + `profileColumns`; `profileDataFrame` queda como envoltorio para danfo. +- [x] **Worker de análisis.** `src/pages/analyze/analysis.worker.ts` (3,35 kB en la build, sin danfo ni TF.js) y + `analysisClient.ts`; los avisos y los estadísticos por clase dependen de la variable objetivo y son baratos: + se quedan en el hilo principal. +- [-] **Preprocesado en el worker.** No compensa: 22 ms con California; enviar las columnas cuesta casi lo mismo. +- [x] **Interfaz.** "Analizando el conjunto de datos…" mientras llega el resultado; si se carga otro conjunto entre + tanto, el resultado viejo se descarta. +- [x] **(Opcional) Leer el CSV en el worker** (papaparse lo admite). Con 206 400 filas es lo que más bloquea (≈580 ms); + el `DataFrame` de danfo hace falta en el hilo principal (tabla, consultas, «Más gráficos»). Hecho: lo que sube + el usuario (en el AED y en los entrenadores) se lee en `datasetReader.worker.ts` (28 kB): pasar a CSV si es + ARFF, JSON, JSONL o Parquet, averiguar el separador, papaparse con las opciones de danfo y los arreglos de las + columnas; el worker calcula además el tipo de cada columna con las reglas de danfo pero mirando todas las filas + (no solo las 500 primeras), así que `DataFrameFixMixedColumns` ya no hace falta para estos ficheros (y se evita + su `asType`, que fallaba con valores ausentes). En el hilo principal solo queda `new dfd.DataFrame(rows, + { columns, dtypes })`. Medido sin danfo: `readCSV` eran ≈500 ms de papaparse y 22 ms de crear el DataFrame. + Producción, California × 10: 1844 / 646 → 1393 / 307 ms (bloqueo total / la tarea más larga); lo que queda es + pintar la tabla de datos de 206 400 filas en Plotly y los DataFrames del preprocesado, repartido en tareas. +- [x] **Medir.** California: 1981 ms de la tarea más larga al empezar → 134 ms. Con 206 400 filas (California × 10), + el worker baja la tarea más larga de 1478 a 646 ms. +- [x] **Arreglado de paso: CSV grandes.** Con 206 400 filas la página se caía («Maximum call stack size exceeded»): + `Math.min(...valores)` pasa cada valor como argumento. `extent()` con un bucle en `histogram` y en el escalado. + +## Fase 3 — Imágenes: decodificar los sprites en un worker + +- [x] **`SpriteImageDataset.loadImages`**: `sprite.worker.ts` (1,33 kB) con `fetch` + `createImageBitmap` + + `OffscreenCanvas`, solo las filas pedidas, y el `Float32Array` transferido. Comprobado píxel a píxel contra el + camino de siempre (MNIST y KMNIST: diferencia 0). +- [x] **Un solo camino** para el sprite de test y el completo: `loadSpriteDataset(config, { testOnly })`. La página del + modelo solo decodifica las imágenes de test (10 000 de 65 000 en MNIST) y reutiliza el conjunto entero si ya se + cargó al entrenar. +- [x] **Sin copias al repartir.** `subarray` en vez de `slice` para separar entrenamiento y test (MNIST entero son + 204 MB de `Float32Array`; antes se copiaban otra vez). +- [x] **Alternativa sin worker u `OffscreenCanvas`**: si el worker falla, el camino de siempre. +- [x] **Medir.** Cargar las imágenes de test de MNIST: 304 → 0 ms. El pico al entrenar MNIST no era el sprite: es + compilar los shaders (ver fase 0). + +## Fase 4 — Explicabilidad con TF.js en un worker (evaluar primero) + +> Tras la fase 0: SHAP global de Car bloquea 114 ms (una tarea) y LRP 286 ms solo la primera vez (0 ms después). Lo +> que queda es compilar shaders: mejor resolverlo calentándolos (fase 0) que copiando el modelo a un worker. + +- [-] **Prueba de concepto.** Modelo serializado con `tf.io.withSaveHandler` → `tf.loadLayersModel(tf.io.fromMemory())` + en el worker. Descartada (ver la decisión). +- [-] **KernelSHAP local y global en el worker.** Descartado: tras reescribir `lstsq`, el SHAP global de Car bloquea + 121 ms en una sola tarea y el resto ya cede el control. +- [-] **LRP de imágenes en el worker.** Descartado: 0 ms a partir de la segunda vez; la primera es compilar shaders. +- [x] **Decidir con las medidas de la fase 0.** No se mueve TF.js: lo que queda es compilar shaders, que un worker no + evita (también compilaría) y se resuelve mejor calentándolos (fase 0). + +## Fase 5 — Entrenamientos en un worker + +> Primero se descartó (tras la fase 0, entrenar solo bloqueaba al compilar shaders la primera vez). Se ha hecho porque +> el objetivo es que entrenar no toque nunca el hilo principal. + +- [x] **Worker de entrenamiento** (`src/core/training/training.worker.ts`): entrena las redes dense (clasificación + tabular y regresión) y la convolucional (clasificación de imágenes, que descarga y decodifica el sprite allí + mismo) con el backend elegido en el navbar. Comprobados webgl, webgpu, wasm y cpu. +- [x] **Construcción de las redes compartida** (`src/core/training/buildModels.ts`): la misma en el worker y en el + hilo principal (resumen del visor y entrenamiento sin worker). Los errores de la arquitectura (activación sin + elegir, pérdida o métrica que no compila) se distinguen de los del worker y se avisan como antes. +- [x] **Progreso y parada por mensajes.** El protocolo admite avisos de progreso y peticiones de parar + (`AbortSignal`): cada lote y cada época llegan al visor de tfjs-vis (`tfvis.show.fitCallbacks`, llamado desde el + hilo principal) y a "Entrenando… época x de N"; "Detener" para al acabar el lote (Car: 408 ms). +- [x] **El modelo vuelve como datos** (`model.save(tf.io.withSaveHandler())`, pesos transferidos) y se reconstruye con + `tf.loadLayersModel(tf.io.fromMemory())`; el historial vuelve como números. Predicción, explicabilidad, + matriz de confusión, tabla de modelos y descarga funcionan igual. +- [x] **Sin worker, como antes.** jsdom (los tests), sin `Worker` o con un backend que el worker no puede usar: + `trainDenseModel` y `trainImageClassifier` entrenan en el hilo principal. +- [x] **Medir.** Car: 763 / 439 ms de bloqueo la primera vez → 0 ms en desarrollo y una tarea de 51 ms al acabar + (reconstruir el modelo y pintar la tabla) en producción; además tarda 10 s en vez de 16 s. MNIST: 1554 / 860 ms → + 0 ms en los 92 s de entrenamiento, con el mismo resultado (pérdida 0,056, 8 de 8 imágenes de test bien). +- [x] **Tests.** `tests/core/trainingWorker.test.ts` (las funciones del worker con el backend cpu: avisos, historial, + evaluación, modelo serializado que se reconstruye y predice, regresión, parar y errores de la arquitectura) y + `tests/core/workers.test.ts` (progreso, parada y búferes anidados). +- [-] **Tamaño.** El worker lleva su copia de TF.js: 944 kB sin comprimir, que solo se descargan al entrenar por + primera vez. Si pesa, cargar los backends que no se usen (webgpu, wasm) solo cuando se elijan, como en la página. + No se puede recortar: 944 kB (249 kB comprimidos) son tfjs-core, layers y los backends webgl y cpu; el converter + y tfjs-data ya no entran (tree shaking) y webgpu y wasm ya son trozos aparte que solo se descargan al elegirlos. + Vite construye los workers por separado, así que no pueden compartir el trozo de TF.js de la página. + Probado y descartado: preparar el worker al abrir el entrenador (crearlo, cargar TF.js y activar el backend + mientras el navegador está libre). La primera época de Car llega a los 3,9 s con el worker nuevo y a 1,0 s con + él ya usado, pero prepararlo no cambia nada (3,87 frente a 3,83 s): lo que cuesta es compilar los shaders del + entrenamiento dentro del worker, que dependen de la red elegida. Solo ahorraría la descarga en conexiones + lentas, a cambio de descargar TF.js en cada visita aunque no se entrene. + +## Fase 6 — Pintar menos (lo que no puede ir a un worker) + +- [x] **Cola de tiempo libre** (`src/core/scheduler/idleQueue.ts`): un trabajo de pintado por hueco del navegador + (`requestIdleCallback`). `N4LPlot` (con `useIdleValue`) y `N4LDataFrameTable` se dibujan ahí, cada uno en su + propia tarea corta. +- [x] **/analyze: secciones diferidas** (`N4LDeferredMount`): se montan cuando les toca en la cola o, antes, al + acercarse a la vista. El resumen se pinta al momento. +- [x] **`useDeferredValue`** para la variable objetivo: el selector responde al momento y el análisis se pone al día + después. California en producción: cambiar el objetivo o el escalado, 0 ms de bloqueo (antes 338 / 312 ms). +- [x] **Gráficos ya calculados.** Histogramas como barras con `binCounts` y diagramas de caja con sus cuartiles y + bigotes (`boxStats`, como mucho 500 atípicos por grupo): Plotly ya no recorre cada punto (`D.box` tardaba + 1238 ms con 206 400 filas). «Más gráficos» usa una muestra aleatoria de 20 000 filas si hay más. +- [-] **Tablas de Plotly con muchas filas.** No hace falta: dibujar la tabla de California (20 640 filas) cuesta + 35–50 ms y ya va en su propia tarea. +- [-] **Fuera del plan.** + - Detección de objetos con cámara: face-api ya es asíncrona y depende del vídeo y del DOM. + - El visor de tfjs-vis. + - El banco de pruebas de /debug: mide el hilo principal a propósito. + +--- + +## Riesgos y notas + +- Cada worker que importe TF.js descarga otra copia: medir el tamaño en la build antes de decidir las fases 4 y 5. +- Clonar datos grandes en `postMessage` también cuesta: transferir `ArrayBuffer` siempre que se pueda. +- jsdom (los tests) no tiene `Worker`: la alternativa en el mismo hilo es obligatoria y es la que prueban los tests. +- Las medidas sin ventana usan WebGL por software: repetir las de TF.js en un equipo con GPU antes de decidir. +- **Medir sobre la build de producción.** En desarrollo, React 19.2 registra cada render y compara sus props para el + panel de rendimiento (`logComponentRender`, `addObjectDiffToProperties`), y con props de 20 000 valores eso cuesta + cientos de ms que en producción no existen. (Hasta el 02/10/2026, `.env` tenía `NODE_ENV="development"` y + `vite build` sin `--mode` empaquetaba React de desarrollo; ya no.) Para medir: + `npx vite build --mode simidat --outDir /tmp/n4l-perf && npx vite preview --outDir /tmp/n4l-perf --port 4795`. + +## Registro + +- 02/10/2026 — Lo que quedaba del plan: leer los ficheros subidos en un worker (fase 2) y calentar los shaders de + LRP (fase 0); el tamaño del worker de entrenamiento se queda como está (fase 5). Build de producción + (`--mode simidat`): + + | Escenario | Antes | Ahora | + |---|---|---| + | /analyze: subir 206 400 filas (California × 10) | 1844 / 646 ms | 1393 / 307 ms | + | MNIST, página del modelo: primera explicación con LRP | 345 ms | 0 ms | + | MNIST, página del modelo: abrirla y cargar el modelo | 355 ms | ≈440 ms | + | MNIST, entrenador: primera clasificación / primera explicación | 229 / 434 ms | 0 / 0 ms | + + Lo único pendiente: comprobar en un equipo con GPU que, con `KHR_parallel_shader_compile`, los calentamientos no + bloquean (aquí, sin la extensión, compilan igual pero al cargar). +- 02/10/2026 — Fase 5 hecha: los tres entrenamientos (clasificación tabular, regresión y clasificación de imágenes) van + en un worker. Bloqueo durante el entrenamiento: Car 0 ms (antes 763 ms), MNIST 0 ms (antes 1554 ms). Comprobado con + webgl, webgpu, wasm y cpu y en las builds de producción. +- 01/10/2026 — Fases 1, 2, 3 y 6 hechas (salvo lo marcado). Build de producción (`--mode simidat`), bloqueo total / + la tarea más larga, desde el diagnóstico: + + | Escenario | Diagnóstico | Ahora | + |---|---|---| + | /analyze: cargar California housing | 2240 / 1989 ms | 265 / 134 ms | + | /analyze: cargar housing-price | 769 / 701 ms | 310 / 93 ms | + | /analyze: cambiar el escalado (California) | 312 ms | 0 ms | + | /analyze: cambiar la variable objetivo (California) | 338 ms | 0 ms | + | /analyze: cargar 206 400 filas (California × 10) | la página se caía | 1844 / 646 ms | + | MNIST: cargar las imágenes de test | 304 ms | 0 ms | + | MNIST: clasificar un ejemplo (primera vez / otra vez) | 295 ms | 141 / 0 ms | + | MNIST: explicar con LRP (primera vez / otra vez) | 591 ms | 308 / 0 ms | + | Car: entrenar (primera vez / otra vez) | 1066 / 575 ms | 763 / 439 ms · 0 ms | + | Car: SHAP global | 367 / 140 ms | 121 / 121 ms | + + Lo que queda: compilar los shaders de WebGL la primera vez (fase 0, pendiente de un equipo con GPU) y leer CSV muy + grandes (fase 2, opcional). Las fases 4 y 5 (TF.js en un worker) no compensan: tras la fase 0, TF.js solo bloquea + al compilar shaders. +- 01/10/2026 — Fase 0 hecha. Con `Scripts/perf/longtasks.mjs` (antes → después, bloqueo total / la tarea más larga): + + | Escenario | Antes | Después | + |---|---|---| + | /analyze: cargar California housing | 2240 / 1989 ms | 694 / 451 ms | + | /analyze: cargar housing-price | 769 / 701 ms | 630 / 560 ms | + | /analyze: cambiar el escalado / la variable objetivo (California) | 312 / 338 ms | 311 / 328 ms | + | MNIST: clasificar un ejemplo (primera vez / otra vez) | 295 ms | 136 / 0 ms | + | MNIST: explicar con LRP (primera vez / otra vez) | 591 ms | 286 / 0 ms | + | Car: entrenar (primera vez / otra vez) | 1066 / 575 ms | 775 / 458 ms · 0 ms | + | Car: SHAP global | 367 / 140 ms | 114 / 114 ms | + + Conclusión: los cálculos del AED ya están todos por debajo de 100 ms (perfil de California 75 ms, preprocesado + 22 ms); lo que queda en /analyze es pintar (fase 6). En TF.js solo queda compilar shaders la primera vez. Siguen + mereciendo un worker los sprites de imágenes (fase 3, ~320 ms de cálculo puro) y el AED con CSV muy grandes (fase 2). +- 01/10/2026 — Diagnóstico y plan. Medidas de la tabla con Chrome sin ventana (servidor de desarrollo) y + `PerformanceObserver` de tareas largas. diff --git a/docs/accessibility.md b/docs/accessibility.md new file mode 100644 index 0000000..18d6c72 --- /dev/null +++ b/docs/accessibility.md @@ -0,0 +1,146 @@ +# Accesibilidad de Nets4Learning + +Qué nivel se busca, cómo se comprueba, qué patrones usa el código y qué queda por hacer. El plan por fases, con lo hecho +y lo pendiente, está en `TODO-A11y.md`. + +## Objetivo + +- **WCAG 2.2 AA en toda la aplicación.** Incluye WCAG 2.1 AA, que es lo que exige la UNE-EN 301 549. Si la aplicación se + publica como web de la Universidad de Jaén, también le aplica el RD 1112/2018, que pide además una declaración de + accesibilidad y una forma de comunicar barreras (fase 7 del plan). +- **Para cualquier persona.** Para quien usa lector de pantalla o magnificador, para quien navega solo con el teclado, + un conmutador o la voz, para quien tiene baja visión o no distingue colores y para quien necesita menos movimiento, + más tiempo o textos más claros. + +### Excepciones + +| Qué | Por qué | Alternativa en la aplicación | +|---|---|---| +| Visor de tfjs-vis (`#tfjs-visor-container`) | Es de una librería: sus regiones no reciben el foco y sus gráficas no tienen texto. Se excluye de axe (`e2e/axe.ts`) | Cada entrenador tiene sus propias gráficas con descripción y sus datos; el resumen del modelo es una tabla de la página; en /settings se puede elegir que no se abra al entrenar | +| Imagen de la cámara en la detección de objetos | Es vídeo en directo | Pendiente: los objetos detectados en texto (fase 3) | + +Una excepción nueva se apunta aquí, con su motivo y su alternativa. + +## Cómo se comprueba + +Las herramientas automáticas solo encuentran una parte de los problemas. El resto sale de la revisión manual y de las +pruebas con personas (fases 0 y 8 del plan). + +| Prueba | Dónde | Qué mira | +|---|---|---| +| axe por página | `e2e/accesibilidad.spec.ts` | Cada ruta de `App.tsx` al cargar, en los temas claro y oscuro. Un test falla si se añade una ruta sin incluirla en la lista | +| axe por estado | `e2e/accesibilidad-estados.spec.ts`, `e2e/movil.spec.ts`, `e2e/series.spec.ts`, `e2e/agrupamiento.spec.ts` | Lo que aparece al usar la aplicación: modales, desplegables, la guía, el aviso de cookies, el resultado de una predicción, los errores, el menú del móvil y los resultados de entrenar | +| Teclado | `e2e/teclado.spec.ts` | Saltar al contenido, el título de cada página y los flujos principales solo con el teclado: de la portada a entrenar, editar las capas y clasificar con un modelo ya entrenado | +| Visión baja | `e2e/vision.spec.ts` | Nada se sale en horizontal a 320 px (zoom al 400 %), con el móvil en horizontal ni con el espaciado de WCAG y el texto al 200 % | +| Títulos | `tests/core/pageTitle.test.ts` | El título de cada ruta, con las traducciones reales (falla si falta una clave en algún idioma) | +| Linter | `eslint.config.ts` (`eslint-plugin-jsx-a11y`, reglas recomendadas) | Textos alternativos, nombres de los controles, ARIA válido, elementos con clic sin teclado… | +| Unitarias | `tests/core/chartColors.test.ts`, `tests/components/N4LNumberField.test.tsx`, `useTrainingProgress.test.ts`… | El contraste de la paleta, los errores de los campos, lo que se anuncia | + +Todas las pruebas de axe usan `axeViolations(page)` de `e2e/axe.ts`: WCAG 2.0, 2.1 y 2.2 A y AA, las buenas prácticas +de axe y su regla experimental de etiqueta en el nombre (2.5.3). Antes de analizar sube al principio de la página: si no, la barra de navegación fija tapa lo que pasa por +debajo y axe lo cuenta como un objetivo demasiado pequeño. + +```bash +pnpm lint # incluye jsx-a11y +pnpm exec vitest run tests/core/pageTitle.test.ts +pnpm exec playwright test e2e/accesibilidad.spec.ts e2e/accesibilidad-estados.spec.ts e2e/teclado.spec.ts +``` + +### Revisión manual (en cada versión) + +- [ ] NVDA con Firefox y con Chrome (Windows). +- [ ] VoiceOver con Safari (macOS e iOS). +- [ ] TalkBack con Chrome (Android). +- [ ] Solo con el teclado: todo se alcanza, el orden es lógico, el foco se ve siempre y no queda atrapado. +- [ ] Zoom al 200 % y al 400 % (y a 320 px de ancho): nada se corta ni obliga a desplazarse en dos direcciones. +- [ ] Alto contraste de Windows (colores forzados). +- [ ] Control por voz (Voice Access o Control por voz de Apple): cada control se activa diciendo lo que se ve. +- [ ] Movimiento reducido activado en el sistema: no hay animaciones que no se puedan parar. + +Para cada flujo: entrenar una red con un conjunto de ejemplo, probar un modelo ya entrenado, subir un fichero propio, +analizar un conjunto en el AED y seguir la guía de una página. + +## En cada cambio + +La plantilla de los pull requests (`.github/pull_request_template.md`) tiene un apartado de accesibilidad con lo que hay +que revisar: teclado y foco, nombres y textos alternativos, anuncios y errores, contraste y color, 320 px, texto al +200 % y ajustes de /settings, y que lo nuevo esté en las pruebas. Las comprobaciones de `.github/workflows/checks.yaml` +(lint con jsx-a11y, tipos, unitarias y todas las e2e, con axe y teclado) se lanzan en cada pull request y antes de +publicar: si fallan, no se publica. + +## Mantenimiento + +- La declaración de accesibilidad está en `/accessibility` (`src/pages/accessibility/Accessibility.tsx`): se revisa + cada año y en cada versión mayor, junto con la revisión manual de arriba. Al revisarla, cambiar su fecha + (`pages.accessibility.updated`) y el contenido no accesible si ha cambiado. +- Las barreras que nos comuniquen llegan como incidencias con la plantilla `.github/ISSUE_TEMPLATE/accessibility.md` + (etiqueta `accesibilidad`). +- Lo pendiente y lo hecho, por fases, en `TODO-A11y.md`. + +## Patrones del código + +Lo que ya resuelve la aplicación y cómo usarlo en lo nuevo. + +| Necesidad | Cómo | Dónde | +|---|---|---| +| Título de la página (2.4.2) | Se pone solo según la ruta, en el idioma elegido: «Pasajeros de avión - Entrenar un modelo - Series temporales - Nets4Learning». Una página nueva añade su clave en `PAGE_TITLES` | `src/core/pageTitle.ts`, `N4LPageTitle` | +| Saltar al contenido (2.4.1) | Primer elemento al tabular; lleva el foco al `<main>` de la página | `N4LSkipLink` | +| Foco al cambiar de página (2.4.3) | Va al `h1` de la página nueva. Cada página tiene un solo `<main>` y un `h1` dentro | `N4LScrollManager` | +| Foco visible y sin tapar (2.4.7, 2.4.11) | Anillo de 3 px (`--n4l-focus-color`) en todo lo que se maneja con el teclado y margen (`scroll-margin`) para que la barra fija no tape lo que tiene el foco. No quitar el `outline` sin poner otro. Lo que va dentro de una barra fija o pegada al borde no lleva margen: si no, al pulsarlo el navegador mueve la página | `src/globals.css` | +| Encabezados (1.3.1) | Un `h1` por página y después `h2`, `h3`… sin saltos. El aspecto se cambia con clases (`className={'h5'}`), no con el nivel | — | +| Contraste (1.4.3, 1.4.11) | Los colores de Bootstrap que no llegan están corregidos en los dos temas: enlaces, botones de contorno, `.link-primary`, `.link-secondary`, el código y los bordes de los campos (`--n4l-input-border-color`) | `src/globals.css` | +| Algo que el lector tiene que oír sin mover el foco (4.1.3) | `announce(mensaje)`: el resultado de una predicción, los datos cargados, cómo va un entrenamiento (cada 10 s como mucho), los avisos de las capas, los cambios de ajustes. No poner `aria-live` en algo que aparece a la vez que su texto: no siempre se lee | `src/core/a11y/announce.ts`, `N4LAnnouncer` | +| Aviso de que algo ha ido bien (4.1.3, 2.2.1) | `alertHelper.alertSuccess`: en una esquina, sin llevarse el foco, se para con el ratón encima y se puede cerrar. No esperar (`await`) a que se cierre | `src/utils/alertHelper.tsx` | +| Error que hay que leer | `alertHelper.alertError`: diálogo con el foco en su botón | `src/utils/alertHelper.tsx` | +| Modales (4.1.2) | `aria-labelledby` con el id (`useId`) de su `Modal.Title` y `closeLabel={t('modal.close')}` en `Modal.Header` (el de Bootstrap dice «Close»). El tabulador da la vuelta dentro de cualquier diálogo modal (`aria-modal`) sin hacer nada más | `N4LModal` y los demás modales, `N4LDialogFocusWrap` | +| Campo numérico (3.3.1, 3.3.3) | `N4LNumberField`: deja borrar y escribir; si no vale, lo dice junto al campo (`aria-invalid`, `aria-describedby`) con el rango y el valor que se sigue usando. No recortar en silencio | `src/components/form/N4LNumberField.tsx` | +| Subir ficheros | `DragAndDrop`: botón «Elegir fichero» que dice los formatos y una región de estado con lo aceptado y lo rechazado (traducido) | `src/components/dragAndDrop/DragAndDrop.tsx` | +| Colores de las gráficas (1.4.11) | `chartColor(nombre, tema)` y `categoryColor(orden, i, tema)` con `useTheme()`: cada color tiene un tono por tema con al menos 3:1 (lo comprueba `tests/core/chartColors.test.ts`). No poner colores sueltos | `src/core/chartColors.ts` | +| Selector con miles de opciones | `N4LVirtualSelect` con `label` (qué se elige): el botón solo enseña la opción elegida | `src/components/select/N4LVirtualSelect.tsx` | +| Elementos de un desplegable | `as={N4LDropdownLink}` o `as={N4LDropdownButton}`: React-Bootstrap pone `aria-selected`, que no vale en enlaces ni botones. El elegido, con `aria-current` | `src/components/dropdown/N4LDropdownItems.tsx` | +| Botón que se sustituye o desaparece | Pasar el foco al que lo sustituye y devolverlo después; si no, se pierde en `<body>`. Al terminar de entrenar, «Ir al resultado» (`resultSection`); al borrar una capa, a la de al lado; al cerrar la guía o el aviso de cookies, a lo que los abrió | `N4LTrainButton`, `N4LEditorLayers`, `N4LGuide`, `N4LCookiesBanner` | +| Resumen del modelo | Tabla propia (capas, forma de salida, parámetros), no el visor de tfjs-vis | `N4LModelSummaryButton` | +| Gráficas (1.1.1, 1.3.1) | `aria-label` con lo que enseñan y sus valores principales (en Chart.js, con `role="img"`) o una frase visible debajo, y siempre «Ver los datos» con la tabla completa: `N4LChartData` (o `table` en `N4LPlot`). Si distinguen series por color, también por la forma del punto o el trazo de la línea | `src/components/chart/N4LChartData.tsx`, `plotTables.ts` | +| Lienzos y canvas | Con nombre (`role="img"` y `aria-label`) o fuera del lector si lo que enseñan ya está en texto. Lo que se detecta o se predice, en texto y anunciado. Lo que exige arrastrar, con una alternativa de un clic | `customCanvasDrawer`, `detectionSummary.ts`, `NeuralNetwork` | +| Imágenes (1.1.1) | `alt` con lo que enseña; `alt=""` solo si es decorativa o si su botón ya lo dice. En el manual, el texto entre corchetes de la imagen | `public/docs/*/` | +| Algo que se desplaza (2.1.1) | `tabIndex={0}`, `role={'region'}` y un `aria-label` distinto en cada uno, para recorrerlo con el teclado | `Contribute`, `GlossaryFormula` | +| Término con ayuda | `N4LHelpTerm`: un botón que enseña la ayuda con el foco o con el ratón encima | `src/components/helpLink/N4LHelpTerm.tsx` | +| Tablas largas | `N4LPagination`: en un `<nav>` con nombre, la página actual con `aria-current` y botones de al menos 32 px | `src/components/table/N4LPagination.tsx` | +| Texto en otro idioma (3.1.2) | `lang="en"` en las descripciones originales de los conjuntos (UCI) y en las citas; `lang="ja"` en los caracteres japoneses | `DatasetVariables`, `AnalyzeVariables`, `N4LPackageDescription` | +| Idioma de la página (3.1.1) | `index.html` pone `lang` antes de que cargue la aplicación; después lo cambia i18n | `index.html`, `src/i18n.ts` | +| Movimiento | En JavaScript, `prefersReducedMotion()` (el ajuste de /settings o el del sistema); en CSS ya se anulan las animaciones y transiciones con los dos | `src/core/a11y/displaySettings.ts`, `src/globals.css` | +| Ajustes de accesibilidad | Tamaño del texto, espaciado, alto contraste, menos movimiento, enlaces subrayados, foco grueso y visor de tfjs-vis, en `<html>` (atributo y clases). Lo nuevo tiene que verse bien con ellos: lo comprueban `e2e/vision.spec.ts` y `accesibilidad-estados.spec.ts` | `displaySettings.ts`, `/settings` | +| Ayuda al pasar el ratón (1.4.13) | `N4LHelpTerm`: se puede pasar el ratón por encima, se cierra con Escape y se abre al pulsarlo. No usar `OverlayTrigger` con `hover` | `src/components/helpLink/N4LHelpTerm.tsx` | +| Lo que no se puede deshacer (3.3.4) | `N4LConfirmButton`: pregunta en el sitio qué se pierde, con el foco en «Cancelar». Si se puede, mejor deshacer (como al borrar una capa: `onRestore` en `N4LEditorLayers`) | `src/components/form/N4LConfirmButton.tsx` | +| Qué se hace en la página | `N4LPageHeader` con `intro` («train», «review», «detect»): una frase y los pasos, antes de todo lo demás | `src/components/neural-network/N4LPageHeader.tsx` | +| Términos técnicos | `N4LHelpTerm` con su definición (`pages.playground.generator.help.*`) la primera vez que salen en un formulario | `N4LHyperparameterFields`, `N4LDenseLayerFields` | +| Tiempos | `formatDuration` para decir cuánto falta o cuánto tardó, en palabras | `src/core/format/duration.ts` | +| Responsive | Nada se sale en horizontal a 320 px ni con el texto al 200 %; lo que tenga que desplazarse (tablas), con su propio desplazamiento y enfocable | `e2e/vision.spec.ts` | + +## Inventario de componentes interactivos + +Estado de cada componente con el teclado, con lector de pantalla y en contraste, para repartir el trabajo de las fases +2 y 3. «Pendiente» quiere decir que falta revisarlo a mano o arreglarlo (la fase del plan va entre paréntesis). + +| Componente | Teclado | Lector de pantalla | Contraste | Pendiente | +|---|---|---|---|---| +| Barra de navegación y desplegables | Sí (`e2e/teclado.spec.ts`); en el móvil, Escape cierra el menú | Sí (navegación con nombre, página actual, menú abierto o cerrado) | Sí | — | +| Selector con búsqueda (`N4LVirtualSelect`) | Sí (flechas, Enter, `aria-activedescendant`) | Dice qué se elige; revisar con NVDA y VoiceOver | Sí | — | +| Editor de capas | Sí, también arreglar los avisos (`e2e/teclado.spec.ts`) | Los avisos se anuncian al aparecer | Sí | — | +| Hiperparámetros | Sí | Sí, con el error junto al campo | Sí | — | +| Botón de entrenar y progreso | Sí, el foco no se pierde; «Ir al resultado» | Empieza, cada 10 s y si se para | Sí | — | +| Visor de tfjs-vis | No | No | — | Excepción (arriba) | +| Gráficas (Chart.js, Plotly) | Sí, «Ver los datos» | Descripción y tabla con los datos | Sí (paleta común, 3:1; no solo color) | — | +| Lienzo para dibujar | Con puntero; con teclado, los ejemplos y las imágenes de prueba | Con nombre y la alternativa | Sí | Dibujar con el teclado (opcional) | +| Cámara y detección de objetos | Sí (interruptor, botones) | Lo detectado en texto; con la cámara, al pulsar un botón | — | — | +| Imágenes de ejemplo | Sí | Sí, con su clase | Sí | — | +| Tablas paginadas | Sí | Sí | Sí | — | +| Modales | Sí (foco dentro, da la vuelta, Escape, vuelve al botón) | Sí, con nombre | Sí | — | +| Guía de la página | Sí (flechas, Escape, el foco va y vuelve) | Diálogo con el nombre del paso; cada paso se anuncia | Sí | — | +| Avisos (SweetAlert2) | Sí | Éxito como estado; error como diálogo | Sí | — | +| Aviso de cookies | Sí, justo después de «Saltar al contenido» | Región con nombre | Sí | — | +| Subir ficheros | Sí, con el botón «Elegir fichero» | Formatos, aceptado y rechazado | Sí | Al subir, el foco al paso siguiente (2) | +| Resumen del modelo | Sí | Tabla con encabezados | Sí | — | +| Ayuda de los términos | Sí (con el foco o al pulsar; Escape la cierra) | Sí | Sí | — | +| Fórmulas (KaTeX) | Sí, si se desplazan | MathML (falta escucharlas con NVDA y VoiceOver) | Sí | — | +| Paso a paso y diagrama de la red | Neuronas con botón y teclado | Lista de capas; cada neurona con nombre y valor | Sí | — | diff --git a/docs/analytics.md b/docs/analytics.md new file mode 100644 index 0000000..0c925d1 --- /dev/null +++ b/docs/analytics.md @@ -0,0 +1,143 @@ +# Analíticas de Nets4Learning (Google Analytics 4) + +Qué se mide, dónde está en el código y cómo configurar la propiedad de GA4 para verlo en los informes. + +## Principios + +- **Solo con consentimiento.** Google Analytics no se carga hasta que el usuario lo acepta en el aviso de cookies o en + `/settings`. Antes no se envía nada ni se guarda para enviarlo después. La única excepción es la página en la que el + usuario está cuando acepta, que se registra en ese momento. Rechazar es tan fácil como aceptar: lo exigen el RGPD, la + LSSI y la guía de cookies de la AEPD, y sin eso el consentimiento no vale. +- **Sin datos personales ni contenido del usuario.** No se envían los ficheros, sus nombres ni sus valores, ni los + dibujos o las imágenes de la cámara. Tampoco el texto de los formularios ni los textos de la interfaz (dependen del + idioma). Solo se envían identificadores estables (`data-testid`, claves de modelos y conjuntos de datos), números + (épocas, tiempos, tamaños) y categorías. +- **Nada sobre accesibilidad.** No se registran los ajustes de accesibilidad de `/settings` (tamaño del texto, alto + contraste, menos movimiento…) ni nada que diga si se usa un lector de pantalla u otra ayuda técnica: diría qué + necesidades tiene quien usa la aplicación (`src/core/a11y/displaySettings.ts` no llama a `trackEvent`). +- **Sin publicidad.** `allow_google_signals` y `allow_ad_personalization_signals` están desactivados y el modo de + consentimiento deniega `ad_storage`, `ad_user_data` y `ad_personalization`. +- **Solo tráfico real.** Solo se envía en producción (`VITE_ENVIRONMENT=production`). En desarrollo, con las cookies + aceptadas, cada evento se escribe en la consola (`console.debug('[analytics]', …)`). Con `VITE_GA_DEBUG=true` se + envía de verdad con `debug_mode`, para verlo en DebugView. Los e2e rechazan las cookies (`e2e/fixtures.ts`). +- Las cookies `_ga` y `_ga_*` duran 13 meses (`cookie_expires`). Por defecto Google usa 2 años. + +## Código + +| Archivo | Qué hace | +|---|---| +| `src/core/analytics.ts` | Consentimiento, carga de GA, `trackEvent`, contexto de la página, propiedades del usuario | +| `src/core/analyticsPage.ts` | De la URL al contexto de la página (`page_type`, `task`, `mode`, `item`) y el identificador de un clic | +| `src/components/analytics/N4LAnalytics.tsx` | Lo automático: páginas vistas, tiempo en cada página, clics, cambios de idioma, tema y backend, errores y tiempos de carga | +| `src/hooks/useTrainingProgress.ts` | `train_start` / `train_end` de las tareas que entrenan | +| `src/core/downloadProgress.ts` | `model_load`: lo que tarda en cargar un modelo y cuánto descarga | +| `src/core/models/downloadConsent.ts` | `download_consent`: la pregunta antes de descargar un modelo grande | +| `src/components/dragAndDrop/DragAndDrop.tsx` | `file_upload` / `file_rejected` de todas las zonas de subida | +| `src/components/guide/N4LGuide.tsx` | `guide_start` / `guide_end` | + +Para medir un botón nuevo no hay que escribir código: basta con que tenga `data-testid` (o `data-analytics` si no debe +llevar uno de test). + +## Eventos + +Todos los eventos llevan el **contexto de la página** en la que ocurren: + +| Parámetro | Valores | +|---|---| +| `page_type` | `home`, `task`, `select_dataset`, `select_model`, `playground`, `regression_description`, `learn`, `report`, `manual`, `glossary`, `datasets`, `packages`, `analyze`, `contribute`, `terms`, `version`, `settings`, `not_found`, `dev` | +| `task` | `tabular-classification`, `regression`, `image-classification`, `object-detection`, `clustering`, `time-series` | +| `mode` | `train` (entrenar con un conjunto de datos) o `pretrained` (probar un modelo ya entrenado) | +| `item` | El conjunto de datos o el modelo: `CAR`, `IRIS`, `AUTO_MPG`, `UPLOAD`, `IMAGE-MNIST`… En `/analyze`, el de `?dataset=` | + +### Navegación y uso + +| Evento | Cuándo | Parámetros propios | +|---|---|---| +| `page_view` | Cada cambio de ruta (o de `?dataset=` en el AED) | `page_location`, `page_title` | +| `page_time` | Al salir de una página, cerrar la pestaña o pasar a otra app | `engaged_seconds`: solo el tiempo con la pestaña visible | +| `ui_click` | Clic en un botón, enlace, pestaña o elemento de menú con identificador | `element`: `data-analytics`, `data-testid`, `id` o la ruta del enlace interno | +| `settings_change` | Cambio de idioma, tema o backend de TF.js (desde la barra o desde `/settings`), activar Paso a paso o cambiar el aviso de descargas | `setting` (`language`, `theme`, `tf_backend`, `step_by_step`, `download_warning`), `value`, `outcome` (backend: `completed` o `error` si el navegador no puede usarlo) | +| `consent_granted` | Al aceptar las cookies | `source` (`banner`, `settings`, `terms`) | +| `not_found` | Al llegar a la 404 desde una ruta que no existe | `missing_path` | +| `search` | Búsqueda en el glosario: 1,5 s después de dejar de escribir, con 3 letras o más | `search_term`, `results` (0: lo que se busca y no está) | + +### Aprendizaje automático + +| Evento | Cuándo | Parámetros propios | +|---|---|---| +| `train_start` | Pulsar «Entrenar» | `epochs`, `learning_rate`, `optimizer`, `loss`, `layers` | +| `train_end` | Fin del entrenamiento | `outcome` (`completed`, `stopped`, `error`), `duration_sec`, `epochs`, `epochs_done` | +| `train_result` | Cómo terminó un entrenamiento que ha dado un modelo (lo usan también los retos de `/learn`) | `accuracy` (aciertos con los datos de prueba, 0–1; solo en clasificación), `hidden_units`, `layers`, `epochs` (entrenadas), `diagnosis` (`good`, `overfitting`, `still-improving`…) | +| `model_load` / `dataset_load` | Carga de un modelo preentrenado (detección, imágenes, CAR…, regresión) o de los datos de la página de un modelo de regresión | `load_ms`, `download_kb` (de la red o de la caché del navegador), `outcome` (`completed`, `error`) | +| `download_consent` | Antes de descargar un modelo grande con ahorro de datos, conexión lenta o «Preguntar siempre»: al preguntar y al aceptar | `reason` (`save-data`, `slow`, `always`), `download_mb`, `outcome` (`shown`, `accepted`) | +| `models_compare` | Activar «Comparar modelos» en las curvas de entrenamiento | `models` (cuántos modelos hay en la tabla) | +| `layer_fix` | Arreglar las capas con el botón de su aviso (antes de entrenar) | `kind` (`output-units`, `output-activation`, `dense-before-flatten`…) | +| `report_open` | Abrir el informe de un modelo entrenado (botón «Informe» de la tabla de modelos) | — | +| `session_share` | Compartir la configuración de una página de entrenamiento con un enlace | `action` (`open`: abrir la ventana; `copy`: copiar el enlace; `native`: compartir con otra aplicación) | +| `cluster_run` | Agrupar con k-means (`/playground/clustering/dataset/…`) | `k`, `features` (columnas usadas), `scaled`, `rows` | +| `n4l_import` | Abrir un fichero .n4l en «Paquetes .n4l» (/packages) | `outcome` (`ok`, `error`), `item` (su id) | +| `n4l_download` | Descargar el .n4l de un modelo | `item` (su id) | +| `predict` | Una predicción o clasificación | `input` (`form`, `drawing`, `image`, `sample`, `test_sample`; `forecast`: cambiar cuántos valores futuros predice una serie temporal) | +| `webcam_start` / `webcam_end` | Activar y desactivar la cámara en tiempo real | `duration_sec` (en `webcam_end`) | +| `model_code` | Abrir «Ver el código» de un entrenador o copiar el código | `action` (`open`, `copy`), `language` (`tfjs`, `keras`), `task` | +| `training_prediction` | Al terminar un entrenamiento, comparar lo que se predijo antes («Antes de entrenar, ¿qué crees que pasará?») con su diagnóstico | `prediction` (`good`, `overfitting`, `not-learning`…), `outcome` (`right`, `wrong`) | +| `lab_train` | Empezar a entrenar en el laboratorio 2D (`/lab`); completa su paso de `/learn` | `dataset` (`blobs`, `circles`, `xor`, `spiral`), `layers` (capas ocultas), `features` (cuántas entradas) | +| `lab_experiment` | Elegir un ejemplo de «Prueba esto» en el laboratorio | `id` (`xor-line`, `xor-hidden`, `circles-features`, `spiral`, `learning-rate`, `overfitting`) | +| `step_by_step` | Avanzar por primera vez en Paso a paso (en cada visita a la página); completa su paso de `/learn` | `action` (`step`) | +| `explain` | Pedir la explicación de una predicción | `method` (`shap`, `lrp`), `scope` (`local`, `global`; en SHAP tabular) | +| `file_upload` | Fichero aceptado en una zona de subida | `zone`, `format` (la extensión: `csv`, `parquet`, `png`…), `size_kb` | +| `file_rejected` | Fichero rechazado (formato no admitido) | `zone`, `format` | + +### Guías + +| Evento | Cuándo | Parámetros propios | +|---|---|---| +| `guide_start` | Empezar o retomar una guía | `guide_id`, `step`, `steps` | +| `guide_end` | Terminarla o cerrarla | `guide_id`, `step`, `steps`, `outcome` (`completed`, `closed`) | + +### Calidad + +| Evento | Cuándo | Parámetros propios | +|---|---|---| +| `exception` | Error de JavaScript sin capturar (como mucho 10 distintos por visita) | `description` (100 caracteres), `fatal` | +| `app_performance` | Una vez por visita | `load_ms` (carga completa), `dom_ms` (DOM listo) | + +### Propiedades del usuario + +`app_language`, `app_theme` y `tf_backend` cambian con el usuario: así se puede segmentar todo por idioma o por backend. + +### Automáticos de GA4 (medición mejorada) + +`session_start`, `first_visit`, `user_engagement` (tiempo de interacción), `scroll` (90 %), `click` (enlaces externos, +como GitHub o las fuentes de los datos) y `file_download` (descargas de CSV y modelos). + +## Configuración en GA4 (una vez) + +En **Administrar** de la propiedad `G-3644EFBXMG`: + +1. **Recogida y modificación de datos → Flujos de datos → el flujo web (`G-3644EFBXMG`) → Medición mejorada (el + engranaje, no el interruptor) → Vistas de página → Mostrar configuración avanzada: desmarca «Cambios de página + basados en eventos del historial del navegador» y guarda.** La aplicación ya envía sus `page_view` con el contexto; si no, cada página contaría dos + veces. Deja activados el desplazamiento, los clics salientes y las descargas de archivos. +2. **Definiciones personalizadas → Crear dimensiones personalizadas**. Sin esto, los parámetros llegan pero no se pueden + usar en los informes ni en las exploraciones: + - Ámbito *evento*: `page_type`, `task`, `mode`, `item`, `element`, `setting`, `value`, `source`, `outcome`, + `optimizer`, `loss`, `input`, `method`, `scope`, `zone`, `format`, `guide_id`, `missing_path`, `description`. + - Ámbito *usuario*: `app_language`, `app_theme`, `tf_backend`. +3. **Definiciones personalizadas → Métricas personalizadas** (ámbito evento): `engaged_seconds` (segundos), + `duration_sec` (segundos), `epochs`, `epochs_done`, `learning_rate`, `layers`, `load_ms` (milisegundos), + `download_kb`, `size_kb`, `results`, `step`, `steps`, `dom_ms` (milisegundos). +4. **Configuración de datos → Conservación de datos: 14 meses.** El valor por defecto son 2 meses, que limita las + exploraciones. +5. **Configuración de datos → Recogida de datos:** deja desactivadas las señales de Google. + +Los informes se pueden crear en **Explorar**: + +- **Modelos y conjuntos de datos más usados:** `page_view` desglosado por `task`, `mode` e `item`. +- **Tiempo por sección:** suma de `engaged_seconds` de `page_time` por `page_type` o `item`. +- **Embudo de entrenamiento:** `page_view` (`mode=train`) → `train_start` → `train_end` con `outcome=completed`. +- **Botones:** `ui_click` por `element`, filtrado por `page_type`. +- **Rendimiento real:** media de `load_ms` de `model_load` por `item` y `tf_backend`; `app_performance` por + dispositivo. +- **Guías:** `guide_end` por `guide_id` y `outcome`, y en qué `step` se cierran. +- **Errores:** `exception` por `description` y navegador. diff --git a/docs/n4l-format.md b/docs/n4l-format.md new file mode 100644 index 0000000..f3f21a1 --- /dev/null +++ b/docs/n4l-format.md @@ -0,0 +1,190 @@ +# Formato .n4l + +Un paquete `.n4l` reúne todo lo de **un conjunto de datos**: los datos y su ficha, sus textos en cada idioma y, por cada +tarea en la que se usa, cómo usarlo en ella (el preprocesado, los modelos ya entrenados, el formulario o las imágenes de +ejemplo para predecir, la red por defecto para entrenar…). El iris, por ejemplo, se clasifica y se agrupa con el mismo +CSV; MNIST trae sus imágenes, su red convolucional y sus dígitos de ejemplo. + +Es **solo declarativo**: describe qué hay y cómo usarlo, y la aplicación lo interpreta con el motor que nombra cada +tarea (`runtime`). No lleva código, así que abrir un `.n4l` de otra persona es seguro. + +## Dónde están + +- **Los de la aplicación:** carpetas en `public/n4l/<id>.n4l/`. El plugin `vite/n4lPackages.ts` las recorre al + arrancar y al construir, comprueba cada una y las reúne en el módulo `virtual:n4l-catalog`. Para añadir un modelo + basta con dejar su carpeta: no hay que tocar código. En desarrollo, al añadir o cambiar una, la página se recarga. +- **Un fichero `.n4l`:** la misma carpeta comprimida en ZIP (con o sin la carpeta raíz dentro). Sirve para compartir, + exportar e importar. Se abre con `N4LZipSource` (`src/core/n4l/source.ts`). + +Un paquete no válido para la build con un mensaje que dice qué falla y dónde. + +## Abrir y descargar + +- **Descargar:** en la página de un modelo que sale de un paquete, «Descargar .n4l» da el paquete entero en un fichero + (`iris-1.0.0.n4l`): el manifiesto, los textos, los datos y cada modelo con sus pesos (`src/core/n4l/export.ts`). +- **Abrir:** en «Paquetes .n4l», en la barra de navegación (`/packages`). El fichero se valida (y se sube a la versión + actual del formato), tiene que tener alguna tarea que la aplicación ya sepa usar y ocupar como mucho 100 MB. Se guarda + en el navegador (IndexedDB, base de datos `n4l-packages`) y sale en esa página hasta que se quita: en cada una de sus + tareas, para probar su modelo (si trae alguno) o entrenar con su conjunto. La barra dice cuántos hay guardados. +- En las direcciones, un paquete abierto va como `local-<id>` (`/playground/tabular-classification/model/local-iris`) + y sus textos, en el espacio de nombres `n4l-local-<id>`: no chocan con uno de la aplicación con el mismo id. Volver a + abrir uno con el mismo id lo sustituye. + +Las tareas que ya se pueden usar con un paquete están en `src/core/n4l/runtimes.ts`. + +## Estructura + +``` +<conjunto>.n4l/ + manifest.json qué hay y cómo usarlo + locales/<idioma>.json sus textos (uno por idioma de "locales") + data/… los conjuntos de datos (CSV o sprites de imágenes) y su descripción original + models/<id>/model.json cada modelo de TF.js, con sus pesos al lado + examples/… las imágenes de ejemplo (clasificación de imágenes) +``` + +## manifest.json + +| Campo | | +|---|---| +| `format`, `formatVersion` | `"n4l"` y la versión del formato (ahora, `1`) | +| `id` | el del conjunto, el nombre de la carpeta sin `.n4l` | +| `version` | versión del contenido (semver): se sube al cambiar los datos o un modelo | +| `locales` | los idiomas de sus textos | +| `source` | `url` de la fuente original (`<link1>` en los textos), otras direcciones con nombre en `links` (`<link2>`…) y `citation` en BibTeX | +| `datasets` | cada conjunto, de uno de tres tipos (`kind`, ver abajo) | +| `tasks` | una sección por tarea en la que se usa (ver abajo) | + +Los tipos de conjunto (`kind`): + +| `kind` | | +|---|---| +| `table` (por defecto) | una tabla: `file` (el CSV), `info` (descripción original), `rows` y su ficha (`columns`). Una serie temporal lleva además `frequency`, cada cuánto hay una fila (`hour`, `day`, `week`, `month`, `quarter` o `year`): sus filas van en orden, con su fecha en la única columna de tipo `Date`, y tiene un objetivo, el valor que se predice | +| `image-sprite` | imágenes: `file` es un PNG con una imagen aplanada por fila (alto × ancho píxeles; en gris o en RGB), primero las de entrenamiento; `labels`, sus clases en one-hot (un byte por clase); `rows`, cuántas hay; `train`, cuántas son de entrenamiento (las demás, de prueba); `image`, su `width`, `height` y `channels` (1, gris; 3, color) | +| `external` | uno que no va en el paquete por su tamaño o su licencia (ImageNet): su `url` y, si se sabe, `rows` | + +Cada sección de `tasks`: + +| Campo | | +|---|---| +| `task`, `key` | la tarea y su clave en las direcciones (`/playground/<tarea>/model/<key>`) | +| `runtime` | el motor que la interpreta (`tabular-classification`, `regression`, `clustering`, `image-classification`, `time-series`) | +| `datasets` | los conjuntos que usa (sus `id`); el primero, el que se abre al entrar. Los de `time-series` tienen que ser series temporales (con `frequency`) | +| `listed` | si sale en los menús (por defecto, sí): `false` deja la tarea preparada sin enseñarla | +| `order` | su posición en los menús de la tarea, de menor a mayor; sin ella, después, por el nombre de la carpeta | +| `preprocessing` | pasos por nombre: `label-encoder` (codificar), `drop` (columnas de entrada que no entran en la red, p. ej. con «?») y `min-max` (escalar la entrada). `columns`: `"categorical"`, `"features"` o una lista | +| `classes` | clasificación: las salidas del modelo en orden; cada una, su `id` en el conjunto y otros nombres (`aliases`). Si son caracteres (KMNIST), cómo se leen (`reading`) y el kanji del que vienen (`origin`) | +| `models` | cada modelo, de un formato (`format`, ver abajo), con el `dataset` con el que se entrenó y sus `metrics` con datos que no vio al entrenar (`test_…`) | +| `prediction` | con una tabla, `defaults` del formulario y `examples` (valores y la clase que tienen); con imágenes, `images`: cada una, su `file` y su clase (`expected`), si se sabe. Las formas antiguas de un carácter llevan `old: true` y el kanji del que vienen (`origin`) | +| `training` | `learningRate` y `epochs`, si se proponen, para empezar a entrenar; `layers`: la red por defecto al entrenar, con capas `dense` (`units`, `activation`), `conv2d` (`filters`, `kernelSize`, `activation`), `maxPooling2d` (`poolSize`, `strides`), `flatten` y, en las series temporales, las recurrentes `simpleRNN`, `lstm` y `gru` (`units` y, si no es tanh, `activation`), que van antes que las `dense`; `locked: true`, una capa que no se puede cambiar (la salida de la regresión o de una serie, la entrada de una red de imágenes…) | +| `forecast` | series temporales: cómo se prepara la serie al entrar. `window`, los valores anteriores con los que se predice el siguiente; `season`, cada cuántos valores se repite el patrón (12 meses…), para compararse con la predicción estacional; `difference`, si se predice el cambio respecto al valor anterior (por defecto, no); `testSize`, el porcentaje final que se aparta para probar (por defecto, 20) | + +Los formatos de modelo (`format`): + +| `format` | | +|---|---| +| `tfjs-layers` | un modelo de TF.js del paquete: `path` de su model.json (sus pesos, al lado). Con una tabla, `input` es lo que recibe: `encoded` (las columnas codificadas; por defecto) o `scaled` (además, escaladas con el min-max del conjunto, como los de regresión y los entrenados en la aplicación). Con imágenes, cada píxel entre 0 y 1, como en el sprite | +| `tfjs-mobilenet` | MobileNet (`@tensorflow-models/mobilenet`): no va en el paquete, lo descarga la librería en la `version` (1 o 2) y el ancho (`alpha`) dados | + +Cada columna de la ficha lleva `name`, `role` (`Feature`, `Target`, `ID`, `Other`), `type` (`Continuous`, `Integer`, +`Categorical`, `Binary` o `Date`, la fecha de cada fila de una serie temporal) y `missing` (valores ausentes). Opcionalmente, `units`, `description` (en inglés, como en la +ficha original) y `options` (los valores posibles, en el orden del formulario). + +Todas las rutas son relativas al paquete y no pueden salir de él. El esquema completo está en +`public/n4l/n4l.schema.json`: con `"$schema": "../n4l.schema.json"` en el manifiesto, el editor lo autocompleta y lo +valida. + +## Textos (locales/<idioma>.json) + +| Clave | | +|---|---| +| `columns`, `classes` | nombre de cada columna y clase de las tablas (comunes a todas las tareas). Las clases de las imágenes pueden tener nombre (`airplane` → «avión») o, si no lo tienen, se enseñan tal cual («7», «お») | +| `options` | texto de cada valor de una columna, si no es el propio valor | +| `tasks.<tarea>.name` | nombre en los menús | +| `tasks.<tarea>.summary` | su frase en /datasets | +| `tasks.<tarea>.title` | título en la página del modelo | +| `tasks.<tarea>.description` | `text` (párrafos) y `sections` (`title`, `text`, `items`): admiten `<b>`, `<i>`, `<link1>…</link1>`, que enlaza a `source.url` (y `<link2>`…, a `source.links`), y las métricas de su primer modelo (`{{test_accuracy, number(style: percent)}}`) | +| `tasks.<tarea>.example` | `text` e `items`: cómo rellenar el formulario | +| `tasks.image-classification.forms` | caracteres con formas antiguas (KMNIST): `title`, `modern`, `old`, `old-alt` y `note` de su tabla | + +Las claves de `columns`, `classes` y `options` son el nombre de la columna o la clase con los `.` y `:` cambiados por +`_` (i18next los usa como separadores): `bl. of lymph. c` → `bl_ of lymph_ c`. + +En la aplicación, los textos de cada paquete son el espacio de nombres `n4l-<id>` de i18next +(`n4l-iris:tasks.tabular-classification.name`). + +## Versiones + +- `formatVersion` es la versión del formato. Cada cambio del formato la sube y añade en `src/core/n4l/migrate.ts` la + migración desde la anterior. Un paquete viejo se sube de versión en versión al cargarlo. Uno de una versión más nueva + que la aplicación se rechaza: hay que actualizar Nets4Learning. +- `version` es la del contenido del paquete. + +## Ampliar el formato + +- **Un paso de preprocesado nuevo:** se añade al registro del motor (`STEPS` en `src/core/n4l/tabularData.ts`) sin + tocar los demás. +- **Una tarea o un tipo de modelo nuevo:** un motor nuevo (`runtime`) que lea su parte del manifiesto. +- **Un campo nuevo opcional:** no cambia la versión del formato. Uno obligatorio, o un cambio de significado, sí: + `formatVersion` + 1 y su migración. + +## Estado + +| Tarea | | +|---|---| +| Clasificación tabular | en paquetes: Iris, Coches y Linfografía | +| Regresión | en paquetes: Salarios, Auto MPG, Viviendas de Boston, Rendimiento de estudiantes, Calidad del vino y Cáncer de mama (este, con `listed: false`) | +| Agrupamiento | en paquetes: Iris (compartido con la clasificación tabular), Vino y Tiroides | +| Clasificación de imágenes | en paquetes: MNIST, KMNIST (con las formas antiguas de sus caracteres), CIFAR-10 (fotos en color) e ImageNet (MobileNet V2) | +| Series temporales | en paquetes: Pasajeros de avión (mensual), Temperaturas mínimas en Melbourne (diaria) y Manchas solares (mensual), cada uno con su preparación (`forecast`), su red por defecto y un modelo ya entrenado. Se entrena y se prueba en el navegador (`src/pages/playground/5_TimeSeries/`); los paquetes abiertos por el usuario, todavía no | +| Detección | todavía en clases de TypeScript | + +La clasificación de imágenes (`src/core/n4l/imageClassification.ts`) sabe usar un modelo de TF.js con un sprite de +imágenes de hasta 64×64, en gris (se puede dibujar) o en color (se sube una foto), que se entrena en el navegador y se +explica con LRP (y SHAP, las de color), o MobileNet con un conjunto externo. + +## Calidad de los modelos + +`tests/models/N4L_QUALITY.test.ts` pasa cada modelo ya entrenado de cada paquete por su conjunto, preparado según el +manifiesto como lo hace la página del modelo: en clasificación tabular exige más del 90 % de aciertos y en regresión y +en las series temporales, las métricas de prueba de su manifiesto. `tests/models/N4L_IMAGES.test.ts` clasifica imágenes de prueba de MNIST y +KMNIST como la página del modelo (desde el lienzo). + +## Medir un modelo de imágenes + +`Scripts/measure_image_models.py --package <id> [--write]` ejecuta cada modelo de TF.js del paquete con numpy, capa a +capa, con las imágenes de prueba de su sprite (las que siguen a las de entrenamiento) y, con `--write`, guarda en su +manifiesto `test_accuracy` y `test_images`. Las 10.000 de prueba de MNIST son las de prueba oficiales; las de KMNIST y +CIFAR-10, un subconjunto equilibrado de las suyas. + +## El paquete de CIFAR-10 + +Su modelo lo entrena `Scripts/train_cifar10_model.py` (PyTorch) con las 50.000 imágenes de entrenamiento oficiales, con +BatchNormalization, que al guardarlo se funde en sus Conv2D: la red que se guarda solo tiene las capas que sabe explicar +LRP. `Scripts/build_cifar10_package.py` prepara después el sprite (500 de entrenamiento y 200 de prueba por clase), una +foto de ejemplo de cada clase y el manifiesto; y `Scripts/measure_image_models.py --package cifar10 --write`, sus +métricas. CIFAR-10 se descarga la primera vez en `~/.cache/nets4learning/`. + +## Reentrenar un modelo de regresión + +Las métricas de prueba de cada modelo (`metrics`) se enseñan en la página del modelo; si no mejora a predecir siempre la +media, se avisa. `tests/models/N4L_QUALITY.test.ts` rehace la misma partición de prueba con el preprocesado de la +aplicación y comprueba que salen esas métricas. + +`Scripts/train_regression_models.mjs --package <id> --model <id> [--write [--force]]` prepara el conjunto como la aplicación +(con el preprocesado del paquete), aparta un 20 % para prueba, entrena varias redes y elige la de menor error de +validación. Solo si mejora el R² de prueba del modelo actual lo guarda en el paquete (con `--write`): su model.json y +sus pesos, sus métricas de prueba en `metrics` (`test_r2`, `test_mae`, `test_baseline_mae`) y la versión del paquete +subida. `--force` lo guarda aunque no mejore: cuando el modelo actual pudo entrenarse con esas filas de prueba, su +nota sale inflada. + +## Entrenar el modelo de una serie temporal + +`Scripts/train_time_series_models.mjs --package <id> [--write] [--runs 5]` prepara la serie con el mismo código que la +aplicación (`src/core/timeSeries/series.ts`) y la preparación del paquete (`forecast`): la ventana, la prueba (el final +de la serie, sin barajar) y el escalado con el entrenamiento. Aparta las últimas ventanas del entrenamiento (un 15 %) +para validar, entrena varias veces la red de `training` parando cuando la validación deja de mejorar y elige la que +menos se equivoca. Solo entonces mide la prueba: con `--write` guarda el modelo en `models/forecast/`, sus métricas en +el manifiesto (`test_mae`, `test_rmse` y `test_recursive_mae`, a un paso y seguida, y para compararse `test_naive_mae` +y, con estación, `test_seasonal_mae`) y sube la versión del paquete. Los textos del paquete las enseñan en su +descripción (`{{test_mae, number(maximumFractionDigits: 1)}}`). diff --git a/docs/offline.md b/docs/offline.md new file mode 100644 index 0000000..07bc067 --- /dev/null +++ b/docs/offline.md @@ -0,0 +1,60 @@ +# Sin conexión y modelos guardados (service worker) + +Qué guarda Nets4Learning en el navegador para seguir funcionando sin conexión y para no volver a descargar los +modelos preentrenados, dónde está en el código y cómo cambiarlo. + +## Principios + +- **Nada por adelantado.** El service worker guarda lo que se va usando: no descarga páginas ni modelos que no se hayan + abierto. +- **Los modelos, aparte.** Los modelos preentrenados (los de detección de objetos, MobileNet…) son lo que más ocupa y lo + que más tarda en descargarse. Van en su propia caché, `n4l-models-…`, con su propia versión: una versión nueva de la + aplicación no los vuelve a descargar. +- **También en desarrollo, solo los modelos.** Con `pnpm dev` el service worker se registra en modo «solo modelos» + (`sw.js?models`): guarda los modelos, pero deja pasar el código que sirve Vite (guardarlo serviría código viejo al + cambiarlo). +- **Se ve y se borra en `/settings`.** En «Datos guardados en este navegador» se ve lo que ocupa cada cosa, con la lista + de modelos descargados, y se puede borrar cada modelo, todos o lo guardado para usar sin conexión. «Restablecer todos + los ajustes» lo borra todo. +- **Nunca las analíticas.** Las peticiones a Google Analytics no se guardan. + +## Qué se guarda y cómo + +| Qué | Caché | Estrategia | +|---|---|---| +| Páginas (navegación) | `n4l-shell-v1` | Primero la red; sin conexión, la última versión guardada de la aplicación | +| Código con hash en el nombre (`assets/…-<hash>.js`) | `n4l-runtime-v1` | Guardado la primera vez (no cambia nunca) | +| Traducciones, conjuntos de datos, paquetes .n4l | `n4l-runtime-v1` | Lo guardado enseguida y, por detrás, se actualiza | +| Modelos de otras webs (Google Storage, TF Hub, Kaggle, jsDelivr, unpkg) | `n4l-models-v1` | Guardados la primera vez y sin volver a descargarlos: su dirección lleva la versión | +| Modelos de la aplicación (`public/models/`, p. ej. face-api) | `n4l-models-v1` | Lo guardado enseguida y, por detrás, se actualiza | + +En modo «solo modelos» (desarrollo) solo se usan las dos últimas filas. + +## Código + +| Archivo | Qué hace | +|---|---| +| `public/sw.js` | El service worker: qué va a cada caché, sus estrategias, y al activarse borra las cachés de versiones anteriores y pasa a `n4l-models-…` los modelos que una versión anterior guardaba con todo lo demás | +| `src/core/offline/offline.ts` | Registra el service worker (completo en producción, `?models` en desarrollo), dice si hay conexión, cuánto ocupa lo guardado (con los modelos uno a uno) y lo borra | +| `src/core/models/pretrainedModels.ts` | De qué modelo es cada fichero descargado, por su dirección: para la lista de `/settings` y para borrar un modelo | +| `src/pages/settings/Settings.tsx` | «Datos guardados en este navegador» | +| `src/core/downloadProgress.ts` | El progreso de las descargas mientras se carga un modelo (cuenta igual lo que llega de la red y de la caché) | + +## Cambiarlo + +- **Una versión nueva de la aplicación** no necesita tocar nada: el código lleva hash y lo demás se actualiza por + detrás. Para empezar de cero las cachés de la aplicación, sube `VERSION` en `public/sw.js`. +- **Un modelo que cambia sin cambiar de dirección** (uno de otra web que se sustituye en el mismo sitio): sube + `MODELS_VERSION` en `public/sw.js`. Se volverán a descargar todos. +- **Un modelo preentrenado nuevo**: si se descarga de otra web, que su servidor esté en `CDN_HOSTS` (`public/sw.js`); si + es de la aplicación, en `public/models/`. Para que aparezca con su nombre en `/settings`, añádelo a + `PRETRAINED_MODELS` (`src/core/models/pretrainedModels.ts`) con una expresión regular que reconozca sus ficheros. Va + antes que cualquier otro cuyo patrón también encaje (los ficheros de COCO-SSD y de face-api llevan «mobilenet» en el + nombre, así que van antes que MobileNet). + +## Pruebas + +- `tests/core/serviceWorker.test.ts` ejecuta `public/sw.js` con cachés y `fetch` de mentira: a qué caché va cada cosa, + que un modelo no se vuelve a descargar, el modo de desarrollo y el paso de los modelos de una versión anterior. +- `tests/core/offline.test.ts`: de qué modelo es cada fichero y cómo se agrupan. +- `tests/pages/Settings.test.tsx`: la lista de modelos guardados y borrarlos (todos o uno). diff --git a/e2e/accesibilidad-estados.spec.ts b/e2e/accesibilidad-estados.spec.ts new file mode 100644 index 0000000..9a40b5d --- /dev/null +++ b/e2e/accesibilidad-estados.spec.ts @@ -0,0 +1,231 @@ +import type { Locator, Page } from '@playwright/test' +import { test, expect } from './fixtures' +import { axeViolations, expandChartData } from './axe' + +// Accesibilidad (e2e/axe.ts) de lo que aparece al usar la aplicación y no está al cargar la página +// (accesibilidad.spec.ts): modales, desplegables, la guía, los avisos, los resultados y los errores. En los dos temas. + +const THEMES = ['light', 'dark'] as const + +/** Espera a que termine de aparecer (con un fundido): a medio camino, axe ve el texto sin contraste */ +const toBeOpaque = (locator: Locator) => expect.poll(() => locator.evaluate((element) => { + let opacity = 1 + for (let node: Element | null = element; node !== null; node = node.parentElement) opacity *= Number(getComputedStyle(node).opacity) + return opacity +})).toBe(1) + +/** Prepara el estado en cada tema (lo que hace `open` tras cargar la página) y lo revisa con axe */ +async function checkInBothThemes(page: Page, name: string, open: () => Promise<void>) { + for (const colorScheme of THEMES) { + await page.emulateMedia({ colorScheme }) + await open() + // El «Descargado» de un modelo recién cargado se desvanece: a medio camino axe lo ve sin contraste + await expect(page.getByTestId('Test-DownloadProgress')).toHaveCount(0) + expect(await axeViolations(page), `${name} (tema ${colorScheme === 'light' ? 'claro' : 'oscuro'})`).toEqual([]) + } +} + +test('el modal de un conjunto de datos, con sus datos y sus estadísticas', async ({ page }) => { + await checkInBothThemes(page, 'modal de Iris', async () => { + await page.goto('/datasets') + await page.getByTestId('Test-DatasetInfo-IRIS').click() + const modal = page.getByRole('dialog') + await modal.getByRole('tab', { name: 'Datos' }).click() + await expect(modal.getByText('150 filas × 5 columnas')).toBeVisible() + await expect(modal.locator('.js-plotly-plot')).toBeVisible() + }) +}) + +test('los desplegables de la barra de navegación', async ({ page }) => { + for (const [name, button] of [['Tareas', 'Tareas'], ['idioma', /Idioma/], ['tema', /Tema/]] as const) { + await checkInBothThemes(page, `desplegable ${name}`, async () => { + await page.goto('/') + await page.locator('.n4l-navbar').getByRole('button', { name: button }).click() + await expect(page.locator('.n4l-navbar .dropdown-menu.show')).toBeVisible() + }) + } +}) + +test('la guía de una página, abierta', async ({ page }) => { + await page.addInitScript(() => { + window.speechSynthesis.speak = () => {} + // La guía recuerda que estaba abierta: al cargar la página en el otro tema se abriría sola + Object.keys(localStorage).filter((key) => key.startsWith('n4l-guide-progress.')).forEach((key) => localStorage.removeItem(key)) + }) + await checkInBothThemes(page, 'guía de CAR', async () => { + await page.goto('/playground/tabular-classification/model/CAR') + await page.getByTestId('Test-GuideButton').click() + await expect(page.getByTestId('Test-GuideTooltip')).toContainText('Paso 1 de') + await toBeOpaque(page.getByTestId('Test-GuideTooltip')) + }) +}) + +test('el aviso de cookies', async ({ page }) => { + await checkInBothThemes(page, 'aviso de cookies', async () => { + await page.context().clearCookies() + await page.goto('/') + await expect(page.getByTestId('Test-CookiesBanner')).toBeVisible() + }) +}) + +test('un modelo ya entrenado tras clasificar un ejemplo (con el aviso de «modelo cargado»)', async ({ page }) => { + await checkInBothThemes(page, 'IRIS tras clasificar', async () => { + await page.goto('/playground/tabular-classification/model/IRIS') + await expect(page.locator('.swal2-popup')).toContainText('Modelo cargado con éxito', { timeout: 30_000 }) + await page.locator('[data-guide="classify"] button').click() + await expect(page.getByText(/Clase predicha/).first()).toBeVisible({ timeout: 30_000 }) + }) +}) + +test('el aviso de una red mal montada y el error al intentar entrenarla', async ({ page }) => { + await checkInBothThemes(page, 'red mal montada', async () => { + await page.goto('/playground/tabular-classification/dataset/IRIS') + const layers = page.locator('[data-guide="layers"]') + await expect(page.getByTestId('Test-TrainButton')).toBeVisible({ timeout: 60_000 }) + const last = await layers.locator('.accordion-button').count() - 1 + await layers.locator('.accordion-button').nth(last).click() + await page.locator('#formUnitsLayer' + last).fill('5') + await expect(page.getByTestId('Test-LayerCheck-output-units')).toBeVisible() + await page.getByTestId('Test-TrainButton').click() + await expect(page.locator('.swal2-popup')).toContainText('así no se puede entrenar') + }) +}) + +test('el error al abrir un fichero que no es un .n4l', async ({ page }) => { + await checkInBothThemes(page, 'error de .n4l', async () => { + await page.goto('/packages') + await page.locator('input#drop-zone-n4l').setInputFiles({ name: 'roto.n4l', mimeType: 'application/octet-stream', buffer: Buffer.from('hola') }) + await expect(page.getByTestId('Test-N4LImportError')).toContainText('no es un fichero .n4l') + }) +}) + +test('el glosario con una búsqueda sin resultados', async ({ page }) => { + await checkInBothThemes(page, 'glosario sin resultados', async () => { + await page.goto('/glossary') + await page.getByRole('searchbox').first().fill('zzzzzz') + await page.waitForTimeout(500) + }) +}) + +test('el modal con la descripción de un modelo', async ({ page }) => { + await checkInBothThemes(page, 'descripción de COCO SSD', async () => { + await page.goto('/select-model/object-detection') + await page.getByTestId('Test-MenuSelectModel-Option-COCO-SSD').getByRole('button', { name: /^Descripción/ }).click() + const modal = page.getByRole('dialog') + await expect(modal).toBeVisible() + await expect(modal.getByRole('link', { name: 'Abrir' })).toBeVisible() + await toBeOpaque(modal) + }) +}) + +test('el modal para compartir un ejercicio', async ({ page }) => { + await checkInBothThemes(page, 'compartir un ejercicio', async () => { + await page.goto('/playground/tabular-classification/dataset/IRIS') + await expect(page.getByTestId('Test-TrainButton')).toBeVisible({ timeout: 60_000 }) + await page.getByTestId('Test-SessionShare').click() + const modal = page.getByTestId('Test-SessionShare-Modal') + await expect(modal.getByTestId('Test-SessionShare-QR')).toBeVisible() + await toBeOpaque(modal) + }) +}) + +test('las fórmulas llevan MathML para los lectores de pantalla y su dibujo queda oculto para ellos', async ({ page }) => { + await page.goto('/glossary') + await expect(page.locator('main h1')).toBeVisible() + const formulas = page.locator('.katex') + await expect(formulas.first()).toBeVisible() + const count = await formulas.count() + expect(count).toBeGreaterThan(5) + await expect(page.locator('.katex .katex-mathml math')).toHaveCount(count) + await expect(page.locator('.katex .katex-html[aria-hidden="true"]')).toHaveCount(count) +}) + +test('los datos de las gráficas del AED, desplegados', async ({ page }) => { + await checkInBothThemes(page, 'AED con los datos de sus gráficas', async () => { + await page.goto('/analyze?dataset=iris') + await expect(page.getByTestId('Test-AnalyzeInfo')).toBeVisible({ timeout: 30_000 }) + await expect(page.getByTestId('Test-ChartData-Toggle').first()).toBeVisible() + await expandChartData(page) + await expect(page.getByTestId('Test-ChartData').getByRole('table').first()).toBeVisible() + }) +}) + +test('tras entrenar dos modelos: las curvas, la comparación y sus datos', async ({ page }) => { + test.setTimeout(300_000) + await page.goto('/playground/tabular-classification/dataset/IRIS') + await page.getByRole('spinbutton', { name: 'N. épocas' }).fill('2') + for (const model of [1, 2]) { + await page.getByTestId('Test-TrainButton').click() + await expect(page.getByText(new RegExp(`Lista (de )?modelos generados \\| ${model}`))).toBeVisible({ timeout: 240_000 }) + await expect(page.getByTestId('Test-TrainButton')).toBeVisible() + await page.locator('#tfjs-visor-container').getByRole('button', { name: 'Hide' }).click() + } + // La tendencia de cada curva, en texto + await expect(page.getByTestId('Test-TrainingCurves-Trend').first()).toContainText('en 2 épocas') + // El aviso de «modelo entrenado» se va solo: a medio fundido axe lo vería sin contraste + await expect(page.locator('.swal2-container')).toHaveCount(0, { timeout: 15_000 }) + for (const colorScheme of THEMES) { + await page.emulateMedia({ colorScheme }) + await expandChartData(page) + expect(await axeViolations(page), `curvas (tema ${colorScheme === 'light' ? 'claro' : 'oscuro'})`).toEqual([]) + } + await page.getByTestId('Test-TrainingCurves-Compare').check() + await expect(page.getByTestId('Test-ModelComparison').locator('canvas').first()).toBeVisible() + for (const colorScheme of THEMES) { + await page.emulateMedia({ colorScheme }) + await expandChartData(page) + expect(await axeViolations(page), `comparación (tema ${colorScheme === 'light' ? 'claro' : 'oscuro'})`).toEqual([]) + } +}) + +test('con todos los ajustes de accesibilidad activados (alto contraste, texto grande, espaciado…)', async ({ page }) => { + await page.addInitScript(() => { + try { + localStorage.setItem('n4l-display', JSON.stringify({ textSize: 150, spacing: true, highContrast: true, reduceMotion: true, underlineLinks: true, strongFocus: true })) + } catch { + // Sin almacenamiento no se aplicarían + } + }) + for (const path of ['/', '/playground/tabular-classification/dataset/IRIS', '/analyze?dataset=iris', '/settings']) { + await checkInBothThemes(page, `${path} con los ajustes`, async () => { + await page.goto(path) + await expect(page.locator('main').first()).toBeVisible() + await expect(page.locator('html')).toHaveClass(/n4l-high-contrast/) + await page.waitForTimeout(1500) + }) + } +}) + +test('los ajustes de /settings cambian la página al momento y se recuerdan', async ({ page }) => { + await page.goto('/settings#accessibility') + const section = page.getByTestId('Test-Settings-accessibility') + const html = page.locator('html') + await section.getByLabel('150 %').check() + await expect(html).toHaveAttribute('data-n4l-text-size', '150') + await section.getByLabel('Subrayar siempre los enlaces').check() + await expect(html).toHaveClass(/n4l-underline-links/) + await section.getByLabel('Reducir el movimiento').check() + await expect(html).toHaveClass(/n4l-reduce-motion/) + // Con el texto grande, la barra de navegación es la del móvil (la del escritorio no cabe) + await expect(page.locator('.navbar-toggler')).toBeVisible() + await page.reload() + await expect(html).toHaveAttribute('data-n4l-text-size', '150') + await expect(html).toHaveClass(/n4l-underline-links/) +}) + +test('cada apartado de /settings (sus pestañas)', async ({ page }) => { + for (const colorScheme of THEMES) { + await page.emulateMedia({ colorScheme }) + await page.goto('/settings') + const tabs = page.getByRole('tablist', { name: 'Apartados de la configuración' }).getByRole('tab') + await expect(tabs).toHaveCount(9) + for (let index = 0; index < 9; index++) { + await tabs.nth(index).click() + await expect(tabs.nth(index)).toHaveAttribute('aria-selected', 'true') + // La pestaña cambia de color con una transición de Bootstrap (0,15 s): a medio camino axe la vería sin contraste + await page.waitForTimeout(300) + const name = await tabs.nth(index).textContent() + expect(await axeViolations(page), `${name} (tema ${colorScheme === 'light' ? 'claro' : 'oscuro'})`).toEqual([]) + } + } +}) diff --git a/e2e/accesibilidad.spec.ts b/e2e/accesibilidad.spec.ts new file mode 100644 index 0000000..e11a45e --- /dev/null +++ b/e2e/accesibilidad.spec.ts @@ -0,0 +1,88 @@ +import fs from 'node:fs' +import { join } from 'node:path' + +import { test, expect } from './fixtures' +import { axeViolations } from './axe' + +// Accesibilidad (WCAG 2.2 A y AA y buenas prácticas, e2e/axe.ts) de las páginas principales con axe, en el tema claro y +// en el oscuro: contraste, nombres de los controles, ARIA, orden de los encabezados, tamaño de los objetivos… Las +// páginas de modelos preentrenados se miran con la pregunta antes de descargar (preguntar siempre): así no se descarga +// nada y se revisa también esa pregunta. +const PAGES = [ + '/', + '/learn', + '/lab', + '/glossary', + '/manual', + '/datasets', + '/packages', + '/datasets?task=clustering', + '/datasets?task=time-series', + '/settings', + '/contribute', + '/terms-and-conditions', + '/accessibility', + '/version', + '/report', + '/analyze', + '/analyze?dataset=auto-mpg', + '/task/regression', + '/select-dataset/tabular-classification', + '/select-model/tabular-classification', + '/playground/description-regression', + '/playground/tabular-classification/dataset/IRIS', + '/playground/tabular-classification/model/CAR', + '/playground/regression/dataset/AUTO_MPG', + '/playground/image-classification/dataset/IMAGE-MNIST', + '/playground/image-classification/model/IMAGE-MOBILENET', + '/playground/image-classification/model/IMAGE-KMNIST', + '/playground/image-classification/model/IMAGE-CIFAR10', + '/playground/object-detection/model/COCO-SSD', + '/select-dataset/clustering', + '/playground/clustering/dataset/IRIS', + '/select-dataset/time-series', + '/playground/time-series/dataset/AIRLINE-PASSENGERS', + '/playground/time-series/dataset/UPLOAD', + '/playground/time-series/model/MELBOURNE-TEMPERATURES', + '/404', +] + +// Rutas de App.tsx que son la misma página que otra de la lista +const SAME_PAGE: Record<string, string> = { '/home': '/' } + +test('se revisan todas las rutas de la aplicación', () => { + const app = fs.readFileSync(join(__dirname, '..', 'src', 'App.tsx'), 'utf-8') + // Sin las páginas de desarrollo (no se publican) ni la que lleva a la 404 + const published = app.replace(/\{SHOW_DEV_PAGES && <>[\s\S]*?<\/>\}/, '') + const routes = [...published.matchAll(/<Route[^>]*\spath=\{?['"]([^'"]+)['"]/g)].map(([, route]) => route).filter((route) => route !== '*') + expect(routes.length).toBeGreaterThan(10) + const pathnames = PAGES.map((page) => page.split('?')[0]) + const missing = routes.filter((route) => { + if (SAME_PAGE[route] !== undefined) return !pathnames.includes(SAME_PAGE[route]) + const pattern = new RegExp(`^${route.replace(/\/$/, '').replace(/:[^/]+/g, '[^/]+')}/?$`) + return !pathnames.some((pathname) => pattern.test(pathname)) + }) + expect(missing, 'rutas sin revisar con axe (añadirlas a PAGES)').toEqual([]) +}) + +for (const path of PAGES) { + test(`${path} no tiene problemas de accesibilidad (temas claro y oscuro)`, async ({ page }) => { + await page.addInitScript(() => { + try { + localStorage.setItem('n4l-download-warning', 'always') + } catch { + // Sin almacenamiento: se descargaría el modelo, y se revisaría igual + } + }) + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }) + await page.goto(path) + await expect(page.locator('main').first()).toBeVisible() + // Lo que se carga después (datos, gráficas, la pregunta antes de descargar) + await page.waitForTimeout(2500) + // El «Descargado» de un modelo recién cargado se desvanece: a medio camino axe lo ve sin contraste + await expect(page.getByTestId('Test-DownloadProgress')).toHaveCount(0) + expect(await axeViolations(page), `${path} (tema ${colorScheme === 'light' ? 'claro' : 'oscuro'})`).toEqual([]) + } + }) +} diff --git a/e2e/agrupamiento.spec.ts b/e2e/agrupamiento.spec.ts new file mode 100644 index 0000000..15f7025 --- /dev/null +++ b/e2e/agrupamiento.spec.ts @@ -0,0 +1,87 @@ +import path from 'node:path' +import { test, expect } from './fixtures' +import { axeViolations, expandChartData } from './axe' + +// Agrupamiento (k-means): sin red ni entrenamiento, todo en el navegador y al momento + +test('desde la portada se agrupan las flores iris y los grupos se parecen a las especies', async ({ page }) => { + await page.goto('/') + await page.getByTestId('Test-InitialMenu-Clustering').click() + await page.getByTestId('Test-GoTo-SelectDataset-Clustering').click() + await expect(page).toHaveURL(/\/select-dataset\/clustering$/) + // Sin modelos preentrenados no hay descripción que enseñar + await expect(page.getByTestId('Test-MenuSelectDataset-Option-IRIS').getByRole('button')).toHaveCount(0) + await page.getByTestId('Test-MenuSelectDataset-Open-IRIS').click() + + const controls = page.getByTestId('Test-Clustering-Controls') + await expect(controls).toContainText('150 filas') + // La especie no se usa para agrupar: es la columna con la que se compara al final + await expect(controls.getByLabel('Columna con las clases reales')).toHaveValue('class') + await expect(controls.getByLabel('Número de grupos (k)')).toHaveValue('3') + await page.getByTestId('Test-Clustering-Run').click() + + await expect(page.getByTestId('Test-Clustering-Metrics')).toContainText('Silueta') + const comparison = page.getByTestId('Test-Clustering-Comparison') + await expect(comparison).toContainText('Setosa') + await expect(page.getByTestId('Test-Clustering-Agreement')).toContainText('Los grupos se parecen bastante a las clases') + // Cada grupo con su clase mayoritaria; uno es todo Setosa + await expect(comparison.getByRole('row').filter({ hasText: 'Setosa (100 %)' })).toHaveCount(1) + await expect(comparison.getByRole('row').last()).toContainText('Pureza: 85,3 %') + await expect(page.getByTestId('Test-Clustering-Elbow').locator('canvas')).toBeVisible() + await expect(page.getByTestId('Test-Clustering-Profiles')).toContainText('petal_length') + + // Paso a paso: de los centroides iniciales a la última iteración + const iteration = page.getByTestId('Test-Clustering-Iteration') + const last = await iteration.textContent() + await page.getByTestId('Test-Clustering-Play').click() + await expect(iteration).toHaveText('Iteración 0') + await expect(iteration).toHaveText(last ?? '', { timeout: 10_000 }) + + // Con otro k, otros grupos + await controls.getByLabel('Número de grupos (k)').fill('2') + await page.getByTestId('Test-Clustering-Run').click() + await expect(page.getByTestId('Test-Clustering-Metrics')).toContainText(/Grupos\s*2/) + // Dos filas de cabecera, los dos grupos y el total; Versicolor y Virginica acaban en el mismo grupo: una mezcla + await expect(comparison.getByRole('row')).toHaveCount(5) + await expect(comparison.getByRole('row').filter({ hasText: 'mezcla' })).toContainText('Versicolor') +}) + +test('un fichero propio (ARFF) se agrupa y su columna de texto se usa para comparar', async ({ page }) => { + await page.goto('/playground/clustering/dataset/UPLOAD') + await page.locator('input#drop-zone-clustering').setInputFiles(path.join(__dirname, 'files', 'iris.arff')) + const controls = page.getByTestId('Test-Clustering-Controls') + await expect(controls).toContainText('150 filas') + await expect(controls.getByLabel('Columna con las clases reales')).toHaveValue('class') + await page.getByTestId('Test-Clustering-Run').click() + await expect(page.getByTestId('Test-Clustering-Comparison')).toContainText('Virginica') +}) + +test('desde /datasets se agrupa un conjunto de práctica: se carga con su ficha (clases numéricas, sin el identificador)', async ({ page }) => { + await page.goto('/datasets') + await page.getByRole('tab', { name: /Agrupamiento/ }).click() + await expect(page).toHaveURL(/\/datasets\?task=clustering$/) + // Los de ejemplo no tienen modelo que probar + await expect(page.getByTestId('Test-DatasetModel-IRIS')).toHaveCount(0) + await page.getByTestId('Test-DatasetTrain-n4l/breast-cancer.n4l/data/breast-cancer-wisconsin.csv').click() + await expect(page).toHaveURL(/\/playground\/clustering\/dataset\/UPLOAD$/) + + const controls = page.getByTestId('Test-Clustering-Controls') + await expect(controls.getByRole('heading')).toHaveText('breast-cancer-wisconsin.csv', { timeout: 30_000 }) + // «Class» (2 o 4) es la de las clases aunque sea un número, y el identificador no se usa para agrupar + await expect(controls.getByLabel('Columna con las clases reales')).toHaveValue('Class') + await expect(controls.getByLabel('Número de grupos (k)')).toHaveValue('2') + await expect(controls.getByRole('checkbox', { name: 'Sample_code_number' })).not.toBeChecked() + await page.getByTestId('Test-Clustering-Run').click() + await expect(page.getByTestId('Test-Clustering-Agreement')).toContainText('Los grupos son casi las mismas clases') +}) + +test('los resultados del agrupamiento no tienen problemas de accesibilidad (temas claro y oscuro)', async ({ page }) => { + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }) + await page.goto('/playground/clustering/dataset/WINE') + await page.getByTestId('Test-Clustering-Run').click() + await expect(page.getByTestId('Test-Clustering-Profiles')).toBeVisible() + await expandChartData(page) + expect(await axeViolations(page), `tema ${colorScheme === 'light' ? 'claro' : 'oscuro'}`).toEqual([]) + } +}) diff --git a/e2e/axe.ts b/e2e/axe.ts new file mode 100644 index 0000000..c2e7308 --- /dev/null +++ b/e2e/axe.ts @@ -0,0 +1,32 @@ +import { AxeBuilder } from '@axe-core/playwright' +import type { Page } from '@playwright/test' + +/** + * Lo que se exige (docs/accessibility.md): WCAG 2.2 A y AA (con las reglas de 2.0 y 2.1) y las buenas prácticas de axe, + * que piden además, p. ej., que los encabezados vayan en orden y que todo esté dentro de una región + */ +export const AXE_TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa', 'best-practice'] + +/** + * Los problemas de accesibilidad de lo que se ve en la página, uno por regla con sus primeros elementos (para que el + * mensaje del test diga dónde están). El visor de tfjs-vis no cuenta: es de la librería y está entre las excepciones + */ +export async function axeViolations(page: Page): Promise<string[]> { + // Desde arriba: con la página bajada, la barra de navegación (fija) tapa lo que pasa por debajo y axe lo cuenta como + // un objetivo demasiado pequeño, aunque quien usa la página lo ve entero en cuanto llega a él + await page.evaluate(() => window.scrollTo(0, 0)) + const { violations } = await new AxeBuilder({ page }).withTags(AXE_TAGS) + // Experimental en axe, así que no se ejecuta sola: el nombre accesible de cada control contiene el texto que se ve + // (WCAG 2.5.3), para quien lo maneja diciendo lo que ve (control por voz) + .options({ rules: { 'label-content-name-mismatch': { enabled: true } } }) + .exclude('#tfjs-visor-container') + .analyze() + return violations.map(({ id, impact, nodes }) => `${id} [${impact}]: ${nodes.slice(0, 3).map(({ target }) => target.join(' ')).join(' | ')}`) +} + +/** Despliega todas las tablas «Ver los datos» de las gráficas que se ven, para revisarlas también */ +export async function expandChartData(page: Page) { + const toggles = page.locator('[data-testid="Test-ChartData-Toggle"][aria-expanded="false"]:visible') + const count = await toggles.count() + for (let index = 0; index < count; index++) await toggles.first().click() +} diff --git a/e2e/deteccion.spec.ts b/e2e/deteccion.spec.ts new file mode 100644 index 0000000..2bd6757 --- /dev/null +++ b/e2e/deteccion.spec.ts @@ -0,0 +1,12 @@ +import { test, expect } from './fixtures' + +// Detección de objetos: lo que ha fallado alguna vez con los modelos de MediaPipe (se descargan de jsDelivr) + +test('FACE-DETECTOR: subir una imagen nada más abrir la página, con el modelo aún cargándose, no rompe MediaPipe', async ({ page }) => { + test.setTimeout(180_000) + await page.goto('/playground/object-detection/model/FACE-DETECTOR') + // Antes se volvía a cargar el modelo con cada imagen: los dos de MediaPipe a la vez se pisaban y abortaba + // (Module.arguments has been replaced…). El fixture comprueba que no hay errores de JavaScript + await page.locator('input#drop-zone-object-detection').setInputFiles('public/logo512.png') + await expect(page.getByTestId('Test-ImageDetections')).toBeVisible({ timeout: 120_000 }) +}) diff --git a/e2e/entrenamiento.spec.ts b/e2e/entrenamiento.spec.ts new file mode 100644 index 0000000..b1bee61 --- /dev/null +++ b/e2e/entrenamiento.spec.ts @@ -0,0 +1,150 @@ +import { test, expect } from './fixtures' + +// Las tres tareas que se entrenan en el navegador (en un worker), con pocas épocas para que no tarde. Las imágenes, con +// una: en CI (2 núcleos, WebGL por software y otra prueba a la vez) cada época tarda minutos. La de CIFAR-10 (en color +// y con una red más ancha) hace unas tres veces el trabajo de la de MNIST: en 2 núcleos con otra prueba a la vez, unos +// 4,5 min frente a 3, así que espera más (`trainTimeout`, lo que se espera al aviso de éxito) +const TRAINERS = [ + { name: 'clasificación tabular (Iris)', path: '/playground/tabular-classification/dataset/IRIS', epochs: '2' }, + { name: 'regresión (Auto MPG)', path: '/playground/regression/dataset/AUTO_MPG', epochs: '2' }, + { name: 'clasificación de imágenes (MNIST)', path: '/playground/image-classification/dataset/IMAGE-MNIST', epochs: '1' }, + { name: 'clasificación de fotos en color (CIFAR-10)', path: '/playground/image-classification/dataset/IMAGE-CIFAR10', epochs: '1', trainTimeout: 480_000 }, +] + +for (const { name, path, epochs, trainTimeout = 240_000 } of TRAINERS) { + test(`entrena ${name}, el modelo aparece en la lista y sigue ahí al recargar`, async ({ page }) => { + test.setTimeout(trainTimeout + 240_000) + await page.goto(path) + await page.getByRole('spinbutton', { name: 'N. épocas' }).fill(epochs) + await page.getByTestId('Test-TrainButton').click() + + // Mientras entrena, el botón pasa a ser el progreso con "Detener" + await expect(page.getByTestId('Test-TrainButton')).toBeHidden() + // El aviso de éxito se cierra solo + await expect(page.locator('.swal2-popup')).toContainText('Modelo entrenado con éxito', { timeout: trainTimeout }) + await expect(page.getByText(/Lista (de )?modelos generados \| 1/)).toBeVisible() + await expect(page.getByTestId('Test-TrainButton')).toBeVisible() + // Debajo del botón, cómo ha ido en palabras + await expect(page.getByTestId('Test-TrainingDiagnosis')).toContainText('Cómo ha ido el entrenamiento del modelo 1') + + // Se guarda en el navegador: al volver a la página sigue en la lista, con un aviso para borrarlo + await page.reload() + const notice = page.getByTestId('Test-StoredModels') + await expect(notice).toContainText('1 modelo', { timeout: 60_000 }) + await expect(page.getByText(/Lista (de )?modelos generados \| 1/)).toBeVisible() + await notice.getByTestId('Test-StoredModels-Delete').click() + await notice.getByTestId('Test-StoredModels-Confirm').click() + await expect(notice).toHaveCount(0) + await page.reload() + await expect(page.getByTestId('Test-TrainButton')).toBeVisible({ timeout: 60_000 }) + await page.waitForTimeout(1500) + await expect(page.getByTestId('Test-StoredModels')).toHaveCount(0) + }) +} + +test('una red mal montada se avisa en el editor de capas, no deja entrenar y se arregla con un botón', async ({ page }) => { + await page.goto('/playground/tabular-classification/dataset/IRIS') + const layers = page.locator('[data-guide="layers"]') + const check = page.getByTestId('Test-LayerCheck') + await expect(page.getByTestId('Test-TrainButton')).toBeVisible({ timeout: 60_000 }) + await expect(check).toHaveCount(0) + + // La salida de Iris con 5 neuronas (hay 3 clases) + const last = await layers.locator('.accordion-button').count() - 1 + await layers.locator('.accordion-button').nth(last).click() + await page.locator('#formUnitsLayer' + last).fill('5') + await expect(check.getByTestId('Test-LayerCheck-output-units')).toContainText('hay 3 clases') + await expect(layers.locator('.accordion-button').nth(last).getByTestId('Test-LayerFlag')).toHaveText('Error') + + await page.getByTestId('Test-TrainButton').click() + await expect(page.locator('.swal2-popup')).toContainText('así no se puede entrenar') + await page.locator('.swal2-confirm').click() + + await check.getByTestId('Test-LayerCheck-Fix').click() + await expect(check).toHaveCount(0) + await expect(page.locator('#formUnitsLayer' + last)).toHaveValue('3') +}) + +test('se comparan dos modelos: curvas superpuestas y qué hiperparámetro ha cambiado', async ({ page }) => { + test.setTimeout(300_000) + await page.goto('/playground/tabular-classification/dataset/IRIS') + await page.getByRole('spinbutton', { name: 'N. épocas' }).fill('2') + for (const [model, learningRate] of [[1, '0.01'], [2, '0.1']] as const) { + await page.locator('[data-guide="hp-learning-rate"] select').selectOption(learningRate) + await page.getByTestId('Test-TrainButton').click() + await expect(page.getByText(new RegExp(`Lista (de )?modelos generados \\| ${model}`))).toBeVisible({ timeout: 240_000 }) + await expect(page.getByTestId('Test-TrainButton')).toBeVisible() + // En escritorio el visor se abre al entrenar y tapa la derecha de la página + await page.locator('#tfjs-visor-container').getByRole('button', { name: 'Hide' }).click() + } + + // El aviso de «modelo entrenado» sale abajo a la derecha, donde está el interruptor: se espera a que se vaya + await expect(page.locator('.swal2-container')).toHaveCount(0, { timeout: 15_000 }) + await page.getByTestId('Test-TrainingCurves-Compare').check() + const comparison = page.getByTestId('Test-ModelComparison') + await expect(comparison.getByTestId('Test-ModelComparison-Summary')).toHaveText(/^Solo cambia «Tasa de aprendizaje»/) + await expect(comparison.locator('tr[data-changed="true"]')).toHaveCount(1) + await expect(comparison.locator('canvas').first()).toBeVisible() + + // Con uno solo marcado no hay nada que comparar + // La casilla (las gráficas también nombran a «Modelo 1» en su descripción) + await comparison.getByRole('checkbox', { name: 'Modelo 1' }).uncheck() + await expect(comparison).toContainText('Marca al menos dos modelos') +}) + +test('el informe de un modelo entrenado se abre en otra pestaña, listo para imprimir', async ({ page, context }) => { + test.setTimeout(300_000) + await page.goto('/playground/tabular-classification/dataset/IRIS') + await page.getByRole('spinbutton', { name: 'N. épocas' }).fill('3') + await page.getByTestId('Test-TrainButton').click() + await expect(page.getByText(/Lista (de )?modelos generados \| 1/)).toBeVisible({ timeout: 240_000 }) + await page.locator('#tfjs-visor-container').getByRole('button', { name: 'Hide' }).click() + + const [report] = await Promise.all([context.waitForEvent('page'), page.getByTestId('Test-ReportButton').click()]) + await expect(report.getByTestId('Test-Report')).toContainText('Clasificación tabular') + await expect(report.getByTestId('Test-Report')).toContainText('Modelo 1') + await expect(report.getByTestId('Test-Report-Layers').locator('li')).toHaveCount(3) + await expect(report.getByTestId('Test-Report-Parameters')).toContainText('N. épocas') + await expect(report.getByTestId('Test-Report-Results')).toContainText('loss') + await expect(report.getByTestId('Test-TrainingDiagnosis')).toBeVisible() + await expect(report.locator('.n4l-training-curve canvas').first()).toBeVisible() + // Al imprimir no salen la barra de navegación ni el pie + await report.emulateMedia({ media: 'print' }) + await expect(report.locator('.n4l-navbar')).toBeHidden() + await expect(report.getByTestId('Test-Report-Print')).toBeHidden() +}) + +test('un modelo entrenado con un paquete se descarga como .n4l y se abre en «Paquetes .n4l»: para probarlo y para entrenar', async ({ page }, testInfo) => { + test.setTimeout(480_000) + await page.goto('/playground/tabular-classification/dataset/IRIS') + await page.getByRole('spinbutton', { name: 'N. épocas' }).fill('2') + await page.getByTestId('Test-TrainButton').click() + await expect(page.locator('.swal2-popup')).toContainText('Modelo entrenado con éxito', { timeout: 240_000 }) + // En escritorio el visor se abre al entrenar y tapa la derecha de la página + await page.locator('#tfjs-visor-container').getByRole('button', { name: 'Hide' }).click() + + const [download] = await Promise.all([page.waitForEvent('download'), page.getByTestId('Test-N4LDownloadTrained-1').click()]) + expect(download.suggestedFilename()).toBe('iris-model-1-1.0.0.n4l') + const file = testInfo.outputPath(download.suggestedFilename()) + await download.saveAs(file) + + // Como modelo ya entrenado: con su nombre y su modelo (que recibe la entrada escalada) + await page.goto('/packages') + await page.locator('input#drop-zone-n4l').setInputFiles(file) + await expect(page.getByTestId('Test-N4LImported')).toContainText('Clasificación de flor iris (#1)') + await page.getByTestId('Test-N4LLocal-iris-model-1-tabular-classification').getByRole('link', { name: 'Probar el modelo' }).click() + await expect(page).toHaveURL(/\/playground\/tabular-classification\/model\/local-iris-model-1$/) + await expect(page.getByTestId('Test-Breadcrumb')).toContainText('Clasificación de flor iris (#1)', { timeout: 30_000 }) + await expect(page.locator('.swal2-popup')).toContainText('Modelo cargado con éxito', { timeout: 30_000 }) + const confirm = page.locator('.swal2-confirm') + if (await confirm.isVisible().catch(() => false)) await confirm.click() + await expect(page.locator('.swal2-container')).toHaveCount(0) + await page.locator('[data-guide="classify"] button').click() + await expect(page.getByText(/Clase predicha/).first()).toBeVisible({ timeout: 30_000 }) + + // Y para entrenar: con su conjunto y su red por defecto (la del modelo descargado) + await page.goto('/packages') + await page.getByTestId('Test-N4LLocal-iris-model-1-tabular-classification').getByRole('link', { name: 'Entrenar' }).click() + await expect(page).toHaveURL(/\/playground\/tabular-classification\/dataset\/local-iris-model-1$/) + await expect(page.getByTestId('Test-TrainButton')).toBeEnabled({ timeout: 60_000 }) +}) diff --git a/e2e/files/aire-alineado.csv b/e2e/files/aire-alineado.csv new file mode 100644 index 0000000..d644aad --- /dev/null +++ b/e2e/files/aire-alineado.csv @@ -0,0 +1,7 @@ +Date , Time , CO(GT), PT08.S1(CO), T , RH , zona , , +10/03/2004, 18.00.00, 2,6 , 1360 , 13,6, 48,9, centro, , +10/03/2004, 19.00.00, 2 , 1292 , 13,3, 47,7, centro, , +10/03/2004, 20.00.00, 2,2 , 1402 , 11,9, 54,0, norte , , +10/03/2004, 21.00.00, 2,2 , 1376 , 11,0, 60,0, norte , , +10/03/2004, 22.00.00, 1,6 , 1272 , 11,2, 59,6, sur , , +10/03/2004, 23.00.00, 1,2 , 1197 , 11,2, 59,2, sur , , diff --git a/e2e/files/aire-punto-y-coma.csv b/e2e/files/aire-punto-y-coma.csv new file mode 100644 index 0000000..3e4953e --- /dev/null +++ b/e2e/files/aire-punto-y-coma.csv @@ -0,0 +1,8 @@ +Date;Time;CO(GT);PT08.S1(CO);T;RH;zona;; +10/03/2004;18.00.00;2,6;1360;13,6;48,9;centro;; +10/03/2004;19.00.00;2;1292;13,3;47,7;centro;; +10/03/2004;20.00.00;2,2;1402;11,9;54,0;norte;; +10/03/2004;21.00.00;2,2;1376;11,0;60,0;norte;; +10/03/2004;22.00.00;1,6;1272;11,2;59,6;sur;; +10/03/2004;23.00.00;1,2;1197;11,2;59,2;sur;; +;;;;;;;; diff --git a/e2e/files/iris-pandas.json b/e2e/files/iris-pandas.json new file mode 100644 index 0000000..a862921 --- /dev/null +++ b/e2e/files/iris-pandas.json @@ -0,0 +1 @@ +{"sepal_length":{"0":5.1,"1":4.9,"2":4.7,"3":4.6,"4":5.0,"5":5.4,"6":4.6,"7":5.0,"8":4.4,"9":4.9,"10":5.4,"11":4.8,"12":4.8,"13":4.3,"14":5.8,"15":5.7,"16":5.4,"17":5.1,"18":5.7,"19":5.1,"20":5.4,"21":5.1,"22":4.6,"23":5.1,"24":4.8,"25":5.0,"26":5.0,"27":5.2,"28":5.2,"29":4.7,"30":4.8,"31":5.4,"32":5.2,"33":5.5,"34":4.9,"35":5.0,"36":5.5,"37":4.9,"38":4.4,"39":5.1,"40":5.0,"41":4.5,"42":4.4,"43":5.0,"44":5.1,"45":4.8,"46":5.1,"47":4.6,"48":5.3,"49":5.0,"50":7.0,"51":6.4,"52":6.9,"53":5.5,"54":6.5,"55":5.7,"56":6.3,"57":4.9,"58":6.6,"59":5.2,"60":5.0,"61":5.9,"62":6.0,"63":6.1,"64":5.6,"65":6.7,"66":5.6,"67":5.8,"68":6.2,"69":5.6,"70":5.9,"71":6.1,"72":6.3,"73":6.1,"74":6.4,"75":6.6,"76":6.8,"77":6.7,"78":6.0,"79":5.7,"80":5.5,"81":5.5,"82":5.8,"83":6.0,"84":5.4,"85":6.0,"86":6.7,"87":6.3,"88":5.6,"89":5.5,"90":5.5,"91":6.1,"92":5.8,"93":5.0,"94":5.6,"95":5.7,"96":5.7,"97":6.2,"98":5.1,"99":5.7,"100":6.3,"101":5.8,"102":7.1,"103":6.3,"104":6.5,"105":7.6,"106":4.9,"107":7.3,"108":6.7,"109":7.2,"110":6.5,"111":6.4,"112":6.8,"113":5.7,"114":5.8,"115":6.4,"116":6.5,"117":7.7,"118":7.7,"119":6.0,"120":6.9,"121":5.6,"122":7.7,"123":6.3,"124":6.7,"125":7.2,"126":6.2,"127":6.1,"128":6.4,"129":7.2,"130":7.4,"131":7.9,"132":6.4,"133":6.3,"134":6.1,"135":7.7,"136":6.3,"137":6.4,"138":6.0,"139":6.9,"140":6.7,"141":6.9,"142":5.8,"143":6.8,"144":6.7,"145":6.7,"146":6.3,"147":6.5,"148":6.2,"149":5.9},"sepal_width":{"0":3.5,"1":3.0,"2":3.2,"3":3.1,"4":3.6,"5":3.9,"6":3.4,"7":3.4,"8":2.9,"9":3.1,"10":3.7,"11":3.4,"12":3.0,"13":3.0,"14":4.0,"15":4.4,"16":3.9,"17":3.5,"18":3.8,"19":3.8,"20":3.4,"21":3.7,"22":3.6,"23":3.3,"24":3.4,"25":3.0,"26":3.4,"27":3.5,"28":3.4,"29":3.2,"30":3.1,"31":3.4,"32":4.1,"33":4.2,"34":3.1,"35":3.2,"36":3.5,"37":3.1,"38":3.0,"39":3.4,"40":3.5,"41":2.3,"42":3.2,"43":3.5,"44":3.8,"45":3.0,"46":3.8,"47":3.2,"48":3.7,"49":3.3,"50":3.2,"51":3.2,"52":3.1,"53":2.3,"54":2.8,"55":2.8,"56":3.3,"57":2.4,"58":2.9,"59":2.7,"60":2.0,"61":3.0,"62":2.2,"63":2.9,"64":2.9,"65":3.1,"66":3.0,"67":2.7,"68":2.2,"69":2.5,"70":3.2,"71":2.8,"72":2.5,"73":2.8,"74":2.9,"75":3.0,"76":2.8,"77":3.0,"78":2.9,"79":2.6,"80":2.4,"81":2.4,"82":2.7,"83":2.7,"84":3.0,"85":3.4,"86":3.1,"87":2.3,"88":3.0,"89":2.5,"90":2.6,"91":3.0,"92":2.6,"93":2.3,"94":2.7,"95":3.0,"96":2.9,"97":2.9,"98":2.5,"99":2.8,"100":3.3,"101":2.7,"102":3.0,"103":2.9,"104":3.0,"105":3.0,"106":2.5,"107":2.9,"108":2.5,"109":3.6,"110":3.2,"111":2.7,"112":3.0,"113":2.5,"114":2.8,"115":3.2,"116":3.0,"117":3.8,"118":2.6,"119":2.2,"120":3.2,"121":2.8,"122":2.8,"123":2.7,"124":3.3,"125":3.2,"126":2.8,"127":3.0,"128":2.8,"129":3.0,"130":2.8,"131":3.8,"132":2.8,"133":2.8,"134":2.6,"135":3.0,"136":3.4,"137":3.1,"138":3.0,"139":3.1,"140":3.1,"141":3.1,"142":2.7,"143":3.2,"144":3.3,"145":3.0,"146":2.5,"147":3.0,"148":3.4,"149":3.0},"petal_length":{"0":1.4,"1":1.4,"2":1.3,"3":1.5,"4":1.4,"5":1.7,"6":1.4,"7":1.5,"8":1.4,"9":1.5,"10":1.5,"11":1.6,"12":1.4,"13":1.1,"14":1.2,"15":1.5,"16":1.3,"17":1.4,"18":1.7,"19":1.5,"20":1.7,"21":1.5,"22":1.0,"23":1.7,"24":1.9,"25":1.6,"26":1.6,"27":1.5,"28":1.4,"29":1.6,"30":1.6,"31":1.5,"32":1.5,"33":1.4,"34":1.5,"35":1.2,"36":1.3,"37":1.5,"38":1.3,"39":1.5,"40":1.3,"41":1.3,"42":1.3,"43":1.6,"44":1.9,"45":1.4,"46":1.6,"47":1.4,"48":1.5,"49":1.4,"50":4.7,"51":4.5,"52":4.9,"53":4.0,"54":4.6,"55":4.5,"56":4.7,"57":3.3,"58":4.6,"59":3.9,"60":3.5,"61":4.2,"62":4.0,"63":4.7,"64":3.6,"65":4.4,"66":4.5,"67":4.1,"68":4.5,"69":3.9,"70":4.8,"71":4.0,"72":4.9,"73":4.7,"74":4.3,"75":4.4,"76":4.8,"77":5.0,"78":4.5,"79":3.5,"80":3.8,"81":3.7,"82":3.9,"83":5.1,"84":4.5,"85":4.5,"86":4.7,"87":4.4,"88":4.1,"89":4.0,"90":4.4,"91":4.6,"92":4.0,"93":3.3,"94":4.2,"95":4.2,"96":4.2,"97":4.3,"98":3.0,"99":4.1,"100":6.0,"101":5.1,"102":5.9,"103":5.6,"104":5.8,"105":6.6,"106":4.5,"107":6.3,"108":5.8,"109":6.1,"110":5.1,"111":5.3,"112":5.5,"113":5.0,"114":5.1,"115":5.3,"116":5.5,"117":6.7,"118":6.9,"119":5.0,"120":5.7,"121":4.9,"122":6.7,"123":4.9,"124":5.7,"125":6.0,"126":4.8,"127":4.9,"128":5.6,"129":5.8,"130":6.1,"131":6.4,"132":5.6,"133":5.1,"134":5.6,"135":6.1,"136":5.6,"137":5.5,"138":4.8,"139":5.4,"140":5.6,"141":5.1,"142":5.1,"143":5.9,"144":5.7,"145":5.2,"146":5.0,"147":5.2,"148":5.4,"149":5.1},"petal_width":{"0":0.2,"1":0.2,"2":0.2,"3":0.2,"4":0.2,"5":0.4,"6":0.3,"7":0.2,"8":0.2,"9":0.1,"10":0.2,"11":0.2,"12":0.1,"13":0.1,"14":0.2,"15":0.4,"16":0.4,"17":0.3,"18":0.3,"19":0.3,"20":0.2,"21":0.4,"22":0.2,"23":0.5,"24":0.2,"25":0.2,"26":0.4,"27":0.2,"28":0.2,"29":0.2,"30":0.2,"31":0.4,"32":0.1,"33":0.2,"34":0.1,"35":0.2,"36":0.2,"37":0.1,"38":0.2,"39":0.2,"40":0.3,"41":0.3,"42":0.2,"43":0.6,"44":0.4,"45":0.3,"46":0.2,"47":0.2,"48":0.2,"49":0.2,"50":1.4,"51":1.5,"52":1.5,"53":1.3,"54":1.5,"55":1.3,"56":1.6,"57":1.0,"58":1.3,"59":1.4,"60":1.0,"61":1.5,"62":1.0,"63":1.4,"64":1.3,"65":1.4,"66":1.5,"67":1.0,"68":1.5,"69":1.1,"70":1.8,"71":1.3,"72":1.5,"73":1.2,"74":1.3,"75":1.4,"76":1.4,"77":1.7,"78":1.5,"79":1.0,"80":1.1,"81":1.0,"82":1.2,"83":1.6,"84":1.5,"85":1.6,"86":1.5,"87":1.3,"88":1.3,"89":1.3,"90":1.2,"91":1.4,"92":1.2,"93":1.0,"94":1.3,"95":1.2,"96":1.3,"97":1.3,"98":1.1,"99":1.3,"100":2.5,"101":1.9,"102":2.1,"103":1.8,"104":2.2,"105":2.1,"106":1.7,"107":1.8,"108":1.8,"109":2.5,"110":2.0,"111":1.9,"112":2.1,"113":2.0,"114":2.4,"115":2.3,"116":1.8,"117":2.2,"118":2.3,"119":1.5,"120":2.3,"121":2.0,"122":2.0,"123":1.8,"124":2.1,"125":1.8,"126":1.8,"127":1.8,"128":2.1,"129":1.6,"130":1.9,"131":2.0,"132":2.2,"133":1.5,"134":1.4,"135":2.3,"136":2.4,"137":1.8,"138":1.8,"139":2.1,"140":2.4,"141":2.3,"142":1.9,"143":2.3,"144":2.5,"145":2.3,"146":1.9,"147":2.0,"148":2.3,"149":1.8},"class":{"0":"Setosa","1":"Setosa","2":"Setosa","3":"Setosa","4":"Setosa","5":"Setosa","6":"Setosa","7":"Setosa","8":"Setosa","9":"Setosa","10":"Setosa","11":"Setosa","12":"Setosa","13":"Setosa","14":"Setosa","15":"Setosa","16":"Setosa","17":"Setosa","18":"Setosa","19":"Setosa","20":"Setosa","21":"Setosa","22":"Setosa","23":"Setosa","24":"Setosa","25":"Setosa","26":"Setosa","27":"Setosa","28":"Setosa","29":"Setosa","30":"Setosa","31":"Setosa","32":"Setosa","33":"Setosa","34":"Setosa","35":"Setosa","36":"Setosa","37":"Setosa","38":"Setosa","39":"Setosa","40":"Setosa","41":"Setosa","42":"Setosa","43":"Setosa","44":"Setosa","45":"Setosa","46":"Setosa","47":"Setosa","48":"Setosa","49":"Setosa","50":"Versicolor","51":"Versicolor","52":"Versicolor","53":"Versicolor","54":"Versicolor","55":"Versicolor","56":"Versicolor","57":"Versicolor","58":"Versicolor","59":"Versicolor","60":"Versicolor","61":"Versicolor","62":"Versicolor","63":"Versicolor","64":"Versicolor","65":"Versicolor","66":"Versicolor","67":"Versicolor","68":"Versicolor","69":"Versicolor","70":"Versicolor","71":"Versicolor","72":"Versicolor","73":"Versicolor","74":"Versicolor","75":"Versicolor","76":"Versicolor","77":"Versicolor","78":"Versicolor","79":"Versicolor","80":"Versicolor","81":"Versicolor","82":"Versicolor","83":"Versicolor","84":"Versicolor","85":"Versicolor","86":"Versicolor","87":"Versicolor","88":"Versicolor","89":"Versicolor","90":"Versicolor","91":"Versicolor","92":"Versicolor","93":"Versicolor","94":"Versicolor","95":"Versicolor","96":"Versicolor","97":"Versicolor","98":"Versicolor","99":"Versicolor","100":"Virginica","101":"Virginica","102":"Virginica","103":"Virginica","104":"Virginica","105":"Virginica","106":"Virginica","107":"Virginica","108":"Virginica","109":"Virginica","110":"Virginica","111":"Virginica","112":"Virginica","113":"Virginica","114":"Virginica","115":"Virginica","116":"Virginica","117":"Virginica","118":"Virginica","119":"Virginica","120":"Virginica","121":"Virginica","122":"Virginica","123":"Virginica","124":"Virginica","125":"Virginica","126":"Virginica","127":"Virginica","128":"Virginica","129":"Virginica","130":"Virginica","131":"Virginica","132":"Virginica","133":"Virginica","134":"Virginica","135":"Virginica","136":"Virginica","137":"Virginica","138":"Virginica","139":"Virginica","140":"Virginica","141":"Virginica","142":"Virginica","143":"Virginica","144":"Virginica","145":"Virginica","146":"Virginica","147":"Virginica","148":"Virginica","149":"Virginica"}} \ No newline at end of file diff --git a/e2e/files/iris-zstd.parquet b/e2e/files/iris-zstd.parquet new file mode 100644 index 0000000..35bca3a Binary files /dev/null and b/e2e/files/iris-zstd.parquet differ diff --git a/e2e/files/iris.arff b/e2e/files/iris.arff new file mode 100644 index 0000000..705af91 --- /dev/null +++ b/e2e/files/iris.arff @@ -0,0 +1,160 @@ +% Iris (UCI) en ARFF para las pruebas +@relation iris + +@attribute 'sepal_length' numeric +@attribute 'sepal_width' numeric +@attribute 'petal_length' numeric +@attribute 'petal_width' numeric +@attribute class {Setosa,Versicolor,Virginica} + +@data +5.1,3.5,1.4,0.2,Setosa +4.9,3.0,1.4,0.2,Setosa +4.7,3.2,1.3,0.2,Setosa +4.6,3.1,1.5,0.2,Setosa +5.0,3.6,1.4,0.2,Setosa +5.4,3.9,1.7,0.4,Setosa +4.6,3.4,1.4,0.3,Setosa +5.0,3.4,1.5,0.2,Setosa +4.4,2.9,1.4,0.2,Setosa +4.9,3.1,1.5,0.1,Setosa +5.4,3.7,1.5,0.2,Setosa +4.8,3.4,1.6,0.2,Setosa +4.8,3.0,1.4,0.1,Setosa +4.3,3.0,1.1,0.1,Setosa +5.8,4.0,1.2,0.2,Setosa +5.7,4.4,1.5,0.4,Setosa +5.4,3.9,1.3,0.4,Setosa +5.1,3.5,1.4,0.3,Setosa +5.7,3.8,1.7,0.3,Setosa +5.1,3.8,1.5,0.3,Setosa +5.4,3.4,1.7,0.2,Setosa +5.1,3.7,1.5,0.4,Setosa +4.6,3.6,1.0,0.2,Setosa +5.1,3.3,1.7,0.5,Setosa +4.8,3.4,1.9,0.2,Setosa +5.0,3.0,1.6,0.2,Setosa +5.0,3.4,1.6,0.4,Setosa +5.2,3.5,1.5,0.2,Setosa +5.2,3.4,1.4,0.2,Setosa +4.7,3.2,1.6,0.2,Setosa +4.8,3.1,1.6,0.2,Setosa +5.4,3.4,1.5,0.4,Setosa +5.2,4.1,1.5,0.1,Setosa +5.5,4.2,1.4,0.2,Setosa +4.9,3.1,1.5,0.1,Setosa +5.0,3.2,1.2,0.2,Setosa +5.5,3.5,1.3,0.2,Setosa +4.9,3.1,1.5,0.1,Setosa +4.4,3.0,1.3,0.2,Setosa +5.1,3.4,1.5,0.2,Setosa +5.0,3.5,1.3,0.3,Setosa +4.5,2.3,1.3,0.3,Setosa +4.4,3.2,1.3,0.2,Setosa +5.0,3.5,1.6,0.6,Setosa +5.1,3.8,1.9,0.4,Setosa +4.8,3.0,1.4,0.3,Setosa +5.1,3.8,1.6,0.2,Setosa +4.6,3.2,1.4,0.2,Setosa +5.3,3.7,1.5,0.2,Setosa +5.0,3.3,1.4,0.2,Setosa +7.0,3.2,4.7,1.4,Versicolor +6.4,3.2,4.5,1.5,Versicolor +6.9,3.1,4.9,1.5,Versicolor +5.5,2.3,4.0,1.3,Versicolor +6.5,2.8,4.6,1.5,Versicolor +5.7,2.8,4.5,1.3,Versicolor +6.3,3.3,4.7,1.6,Versicolor +4.9,2.4,3.3,1.0,Versicolor +6.6,2.9,4.6,1.3,Versicolor +5.2,2.7,3.9,1.4,Versicolor +5.0,2.0,3.5,1.0,Versicolor +5.9,3.0,4.2,1.5,Versicolor +6.0,2.2,4.0,1.0,Versicolor +6.1,2.9,4.7,1.4,Versicolor +5.6,2.9,3.6,1.3,Versicolor +6.7,3.1,4.4,1.4,Versicolor +5.6,3.0,4.5,1.5,Versicolor +5.8,2.7,4.1,1.0,Versicolor +6.2,2.2,4.5,1.5,Versicolor +5.6,2.5,3.9,1.1,Versicolor +5.9,3.2,4.8,1.8,Versicolor +6.1,2.8,4.0,1.3,Versicolor +6.3,2.5,4.9,1.5,Versicolor +6.1,2.8,4.7,1.2,Versicolor +6.4,2.9,4.3,1.3,Versicolor +6.6,3.0,4.4,1.4,Versicolor +6.8,2.8,4.8,1.4,Versicolor +6.7,3.0,5.0,1.7,Versicolor +6.0,2.9,4.5,1.5,Versicolor +5.7,2.6,3.5,1.0,Versicolor +5.5,2.4,3.8,1.1,Versicolor +5.5,2.4,3.7,1.0,Versicolor +5.8,2.7,3.9,1.2,Versicolor +6.0,2.7,5.1,1.6,Versicolor +5.4,3.0,4.5,1.5,Versicolor +6.0,3.4,4.5,1.6,Versicolor +6.7,3.1,4.7,1.5,Versicolor +6.3,2.3,4.4,1.3,Versicolor +5.6,3.0,4.1,1.3,Versicolor +5.5,2.5,4.0,1.3,Versicolor +5.5,2.6,4.4,1.2,Versicolor +6.1,3.0,4.6,1.4,Versicolor +5.8,2.6,4.0,1.2,Versicolor +5.0,2.3,3.3,1.0,Versicolor +5.6,2.7,4.2,1.3,Versicolor +5.7,3.0,4.2,1.2,Versicolor +5.7,2.9,4.2,1.3,Versicolor +6.2,2.9,4.3,1.3,Versicolor +5.1,2.5,3.0,1.1,Versicolor +5.7,2.8,4.1,1.3,Versicolor +6.3,3.3,6.0,2.5,Virginica +5.8,2.7,5.1,1.9,Virginica +7.1,3.0,5.9,2.1,Virginica +6.3,2.9,5.6,1.8,Virginica +6.5,3.0,5.8,2.2,Virginica +7.6,3.0,6.6,2.1,Virginica +4.9,2.5,4.5,1.7,Virginica +7.3,2.9,6.3,1.8,Virginica +6.7,2.5,5.8,1.8,Virginica +7.2,3.6,6.1,2.5,Virginica +6.5,3.2,5.1,2.0,Virginica +6.4,2.7,5.3,1.9,Virginica +6.8,3.0,5.5,2.1,Virginica +5.7,2.5,5.0,2.0,Virginica +5.8,2.8,5.1,2.4,Virginica +6.4,3.2,5.3,2.3,Virginica +6.5,3.0,5.5,1.8,Virginica +7.7,3.8,6.7,2.2,Virginica +7.7,2.6,6.9,2.3,Virginica +6.0,2.2,5.0,1.5,Virginica +6.9,3.2,5.7,2.3,Virginica +5.6,2.8,4.9,2.0,Virginica +7.7,2.8,6.7,2.0,Virginica +6.3,2.7,4.9,1.8,Virginica +6.7,3.3,5.7,2.1,Virginica +7.2,3.2,6.0,1.8,Virginica +6.2,2.8,4.8,1.8,Virginica +6.1,3.0,4.9,1.8,Virginica +6.4,2.8,5.6,2.1,Virginica +7.2,3.0,5.8,1.6,Virginica +7.4,2.8,6.1,1.9,Virginica +7.9,3.8,6.4,2.0,Virginica +6.4,2.8,5.6,2.2,Virginica +6.3,2.8,5.1,1.5,Virginica +6.1,2.6,5.6,1.4,Virginica +7.7,3.0,6.1,2.3,Virginica +6.3,3.4,5.6,2.4,Virginica +6.4,3.1,5.5,1.8,Virginica +6.0,3.0,4.8,1.8,Virginica +6.9,3.1,5.4,2.1,Virginica +6.7,3.1,5.6,2.4,Virginica +6.9,3.1,5.1,2.3,Virginica +5.8,2.7,5.1,1.9,Virginica +6.8,3.2,5.9,2.3,Virginica +6.7,3.3,5.7,2.5,Virginica +6.7,3.0,5.2,2.3,Virginica +6.3,2.5,5.0,1.9,Virginica +6.5,3.0,5.2,2.0,Virginica +6.2,3.4,5.4,2.3,Virginica +5.9,3.0,5.1,1.8,Virginica diff --git a/e2e/files/iris.json b/e2e/files/iris.json new file mode 100644 index 0000000..5b8fee6 --- /dev/null +++ b/e2e/files/iris.json @@ -0,0 +1 @@ +[{"sepal_length":5.1,"sepal_width":3.5,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"},{"sepal_length":4.9,"sepal_width":3.0,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"},{"sepal_length":4.7,"sepal_width":3.2,"petal_length":1.3,"petal_width":0.2,"class":"Setosa"},{"sepal_length":4.6,"sepal_width":3.1,"petal_length":1.5,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.0,"sepal_width":3.6,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.4,"sepal_width":3.9,"petal_length":1.7,"petal_width":0.4,"class":"Setosa"},{"sepal_length":4.6,"sepal_width":3.4,"petal_length":1.4,"petal_width":0.3,"class":"Setosa"},{"sepal_length":5.0,"sepal_width":3.4,"petal_length":1.5,"petal_width":0.2,"class":"Setosa"},{"sepal_length":4.4,"sepal_width":2.9,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"},{"sepal_length":4.9,"sepal_width":3.1,"petal_length":1.5,"petal_width":0.1,"class":"Setosa"},{"sepal_length":5.4,"sepal_width":3.7,"petal_length":1.5,"petal_width":0.2,"class":"Setosa"},{"sepal_length":4.8,"sepal_width":3.4,"petal_length":1.6,"petal_width":0.2,"class":"Setosa"},{"sepal_length":4.8,"sepal_width":3.0,"petal_length":1.4,"petal_width":0.1,"class":"Setosa"},{"sepal_length":4.3,"sepal_width":3.0,"petal_length":1.1,"petal_width":0.1,"class":"Setosa"},{"sepal_length":5.8,"sepal_width":4.0,"petal_length":1.2,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.7,"sepal_width":4.4,"petal_length":1.5,"petal_width":0.4,"class":"Setosa"},{"sepal_length":5.4,"sepal_width":3.9,"petal_length":1.3,"petal_width":0.4,"class":"Setosa"},{"sepal_length":5.1,"sepal_width":3.5,"petal_length":1.4,"petal_width":0.3,"class":"Setosa"},{"sepal_length":5.7,"sepal_width":3.8,"petal_length":1.7,"petal_width":0.3,"class":"Setosa"},{"sepal_length":5.1,"sepal_width":3.8,"petal_length":1.5,"petal_width":0.3,"class":"Setosa"},{"sepal_length":5.4,"sepal_width":3.4,"petal_length":1.7,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.1,"sepal_width":3.7,"petal_length":1.5,"petal_width":0.4,"class":"Setosa"},{"sepal_length":4.6,"sepal_width":3.6,"petal_length":1.0,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.1,"sepal_width":3.3,"petal_length":1.7,"petal_width":0.5,"class":"Setosa"},{"sepal_length":4.8,"sepal_width":3.4,"petal_length":1.9,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.0,"sepal_width":3.0,"petal_length":1.6,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.0,"sepal_width":3.4,"petal_length":1.6,"petal_width":0.4,"class":"Setosa"},{"sepal_length":5.2,"sepal_width":3.5,"petal_length":1.5,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.2,"sepal_width":3.4,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"},{"sepal_length":4.7,"sepal_width":3.2,"petal_length":1.6,"petal_width":0.2,"class":"Setosa"},{"sepal_length":4.8,"sepal_width":3.1,"petal_length":1.6,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.4,"sepal_width":3.4,"petal_length":1.5,"petal_width":0.4,"class":"Setosa"},{"sepal_length":5.2,"sepal_width":4.1,"petal_length":1.5,"petal_width":0.1,"class":"Setosa"},{"sepal_length":5.5,"sepal_width":4.2,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"},{"sepal_length":4.9,"sepal_width":3.1,"petal_length":1.5,"petal_width":0.1,"class":"Setosa"},{"sepal_length":5.0,"sepal_width":3.2,"petal_length":1.2,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.5,"sepal_width":3.5,"petal_length":1.3,"petal_width":0.2,"class":"Setosa"},{"sepal_length":4.9,"sepal_width":3.1,"petal_length":1.5,"petal_width":0.1,"class":"Setosa"},{"sepal_length":4.4,"sepal_width":3.0,"petal_length":1.3,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.1,"sepal_width":3.4,"petal_length":1.5,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.0,"sepal_width":3.5,"petal_length":1.3,"petal_width":0.3,"class":"Setosa"},{"sepal_length":4.5,"sepal_width":2.3,"petal_length":1.3,"petal_width":0.3,"class":"Setosa"},{"sepal_length":4.4,"sepal_width":3.2,"petal_length":1.3,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.0,"sepal_width":3.5,"petal_length":1.6,"petal_width":0.6,"class":"Setosa"},{"sepal_length":5.1,"sepal_width":3.8,"petal_length":1.9,"petal_width":0.4,"class":"Setosa"},{"sepal_length":4.8,"sepal_width":3.0,"petal_length":1.4,"petal_width":0.3,"class":"Setosa"},{"sepal_length":5.1,"sepal_width":3.8,"petal_length":1.6,"petal_width":0.2,"class":"Setosa"},{"sepal_length":4.6,"sepal_width":3.2,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.3,"sepal_width":3.7,"petal_length":1.5,"petal_width":0.2,"class":"Setosa"},{"sepal_length":5.0,"sepal_width":3.3,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"},{"sepal_length":7.0,"sepal_width":3.2,"petal_length":4.7,"petal_width":1.4,"class":"Versicolor"},{"sepal_length":6.4,"sepal_width":3.2,"petal_length":4.5,"petal_width":1.5,"class":"Versicolor"},{"sepal_length":6.9,"sepal_width":3.1,"petal_length":4.9,"petal_width":1.5,"class":"Versicolor"},{"sepal_length":5.5,"sepal_width":2.3,"petal_length":4.0,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":6.5,"sepal_width":2.8,"petal_length":4.6,"petal_width":1.5,"class":"Versicolor"},{"sepal_length":5.7,"sepal_width":2.8,"petal_length":4.5,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":6.3,"sepal_width":3.3,"petal_length":4.7,"petal_width":1.6,"class":"Versicolor"},{"sepal_length":4.9,"sepal_width":2.4,"petal_length":3.3,"petal_width":1.0,"class":"Versicolor"},{"sepal_length":6.6,"sepal_width":2.9,"petal_length":4.6,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":5.2,"sepal_width":2.7,"petal_length":3.9,"petal_width":1.4,"class":"Versicolor"},{"sepal_length":5.0,"sepal_width":2.0,"petal_length":3.5,"petal_width":1.0,"class":"Versicolor"},{"sepal_length":5.9,"sepal_width":3.0,"petal_length":4.2,"petal_width":1.5,"class":"Versicolor"},{"sepal_length":6.0,"sepal_width":2.2,"petal_length":4.0,"petal_width":1.0,"class":"Versicolor"},{"sepal_length":6.1,"sepal_width":2.9,"petal_length":4.7,"petal_width":1.4,"class":"Versicolor"},{"sepal_length":5.6,"sepal_width":2.9,"petal_length":3.6,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":6.7,"sepal_width":3.1,"petal_length":4.4,"petal_width":1.4,"class":"Versicolor"},{"sepal_length":5.6,"sepal_width":3.0,"petal_length":4.5,"petal_width":1.5,"class":"Versicolor"},{"sepal_length":5.8,"sepal_width":2.7,"petal_length":4.1,"petal_width":1.0,"class":"Versicolor"},{"sepal_length":6.2,"sepal_width":2.2,"petal_length":4.5,"petal_width":1.5,"class":"Versicolor"},{"sepal_length":5.6,"sepal_width":2.5,"petal_length":3.9,"petal_width":1.1,"class":"Versicolor"},{"sepal_length":5.9,"sepal_width":3.2,"petal_length":4.8,"petal_width":1.8,"class":"Versicolor"},{"sepal_length":6.1,"sepal_width":2.8,"petal_length":4.0,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":6.3,"sepal_width":2.5,"petal_length":4.9,"petal_width":1.5,"class":"Versicolor"},{"sepal_length":6.1,"sepal_width":2.8,"petal_length":4.7,"petal_width":1.2,"class":"Versicolor"},{"sepal_length":6.4,"sepal_width":2.9,"petal_length":4.3,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":6.6,"sepal_width":3.0,"petal_length":4.4,"petal_width":1.4,"class":"Versicolor"},{"sepal_length":6.8,"sepal_width":2.8,"petal_length":4.8,"petal_width":1.4,"class":"Versicolor"},{"sepal_length":6.7,"sepal_width":3.0,"petal_length":5.0,"petal_width":1.7,"class":"Versicolor"},{"sepal_length":6.0,"sepal_width":2.9,"petal_length":4.5,"petal_width":1.5,"class":"Versicolor"},{"sepal_length":5.7,"sepal_width":2.6,"petal_length":3.5,"petal_width":1.0,"class":"Versicolor"},{"sepal_length":5.5,"sepal_width":2.4,"petal_length":3.8,"petal_width":1.1,"class":"Versicolor"},{"sepal_length":5.5,"sepal_width":2.4,"petal_length":3.7,"petal_width":1.0,"class":"Versicolor"},{"sepal_length":5.8,"sepal_width":2.7,"petal_length":3.9,"petal_width":1.2,"class":"Versicolor"},{"sepal_length":6.0,"sepal_width":2.7,"petal_length":5.1,"petal_width":1.6,"class":"Versicolor"},{"sepal_length":5.4,"sepal_width":3.0,"petal_length":4.5,"petal_width":1.5,"class":"Versicolor"},{"sepal_length":6.0,"sepal_width":3.4,"petal_length":4.5,"petal_width":1.6,"class":"Versicolor"},{"sepal_length":6.7,"sepal_width":3.1,"petal_length":4.7,"petal_width":1.5,"class":"Versicolor"},{"sepal_length":6.3,"sepal_width":2.3,"petal_length":4.4,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":5.6,"sepal_width":3.0,"petal_length":4.1,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":5.5,"sepal_width":2.5,"petal_length":4.0,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":5.5,"sepal_width":2.6,"petal_length":4.4,"petal_width":1.2,"class":"Versicolor"},{"sepal_length":6.1,"sepal_width":3.0,"petal_length":4.6,"petal_width":1.4,"class":"Versicolor"},{"sepal_length":5.8,"sepal_width":2.6,"petal_length":4.0,"petal_width":1.2,"class":"Versicolor"},{"sepal_length":5.0,"sepal_width":2.3,"petal_length":3.3,"petal_width":1.0,"class":"Versicolor"},{"sepal_length":5.6,"sepal_width":2.7,"petal_length":4.2,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":5.7,"sepal_width":3.0,"petal_length":4.2,"petal_width":1.2,"class":"Versicolor"},{"sepal_length":5.7,"sepal_width":2.9,"petal_length":4.2,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":6.2,"sepal_width":2.9,"petal_length":4.3,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":5.1,"sepal_width":2.5,"petal_length":3.0,"petal_width":1.1,"class":"Versicolor"},{"sepal_length":5.7,"sepal_width":2.8,"petal_length":4.1,"petal_width":1.3,"class":"Versicolor"},{"sepal_length":6.3,"sepal_width":3.3,"petal_length":6.0,"petal_width":2.5,"class":"Virginica"},{"sepal_length":5.8,"sepal_width":2.7,"petal_length":5.1,"petal_width":1.9,"class":"Virginica"},{"sepal_length":7.1,"sepal_width":3.0,"petal_length":5.9,"petal_width":2.1,"class":"Virginica"},{"sepal_length":6.3,"sepal_width":2.9,"petal_length":5.6,"petal_width":1.8,"class":"Virginica"},{"sepal_length":6.5,"sepal_width":3.0,"petal_length":5.8,"petal_width":2.2,"class":"Virginica"},{"sepal_length":7.6,"sepal_width":3.0,"petal_length":6.6,"petal_width":2.1,"class":"Virginica"},{"sepal_length":4.9,"sepal_width":2.5,"petal_length":4.5,"petal_width":1.7,"class":"Virginica"},{"sepal_length":7.3,"sepal_width":2.9,"petal_length":6.3,"petal_width":1.8,"class":"Virginica"},{"sepal_length":6.7,"sepal_width":2.5,"petal_length":5.8,"petal_width":1.8,"class":"Virginica"},{"sepal_length":7.2,"sepal_width":3.6,"petal_length":6.1,"petal_width":2.5,"class":"Virginica"},{"sepal_length":6.5,"sepal_width":3.2,"petal_length":5.1,"petal_width":2.0,"class":"Virginica"},{"sepal_length":6.4,"sepal_width":2.7,"petal_length":5.3,"petal_width":1.9,"class":"Virginica"},{"sepal_length":6.8,"sepal_width":3.0,"petal_length":5.5,"petal_width":2.1,"class":"Virginica"},{"sepal_length":5.7,"sepal_width":2.5,"petal_length":5.0,"petal_width":2.0,"class":"Virginica"},{"sepal_length":5.8,"sepal_width":2.8,"petal_length":5.1,"petal_width":2.4,"class":"Virginica"},{"sepal_length":6.4,"sepal_width":3.2,"petal_length":5.3,"petal_width":2.3,"class":"Virginica"},{"sepal_length":6.5,"sepal_width":3.0,"petal_length":5.5,"petal_width":1.8,"class":"Virginica"},{"sepal_length":7.7,"sepal_width":3.8,"petal_length":6.7,"petal_width":2.2,"class":"Virginica"},{"sepal_length":7.7,"sepal_width":2.6,"petal_length":6.9,"petal_width":2.3,"class":"Virginica"},{"sepal_length":6.0,"sepal_width":2.2,"petal_length":5.0,"petal_width":1.5,"class":"Virginica"},{"sepal_length":6.9,"sepal_width":3.2,"petal_length":5.7,"petal_width":2.3,"class":"Virginica"},{"sepal_length":5.6,"sepal_width":2.8,"petal_length":4.9,"petal_width":2.0,"class":"Virginica"},{"sepal_length":7.7,"sepal_width":2.8,"petal_length":6.7,"petal_width":2.0,"class":"Virginica"},{"sepal_length":6.3,"sepal_width":2.7,"petal_length":4.9,"petal_width":1.8,"class":"Virginica"},{"sepal_length":6.7,"sepal_width":3.3,"petal_length":5.7,"petal_width":2.1,"class":"Virginica"},{"sepal_length":7.2,"sepal_width":3.2,"petal_length":6.0,"petal_width":1.8,"class":"Virginica"},{"sepal_length":6.2,"sepal_width":2.8,"petal_length":4.8,"petal_width":1.8,"class":"Virginica"},{"sepal_length":6.1,"sepal_width":3.0,"petal_length":4.9,"petal_width":1.8,"class":"Virginica"},{"sepal_length":6.4,"sepal_width":2.8,"petal_length":5.6,"petal_width":2.1,"class":"Virginica"},{"sepal_length":7.2,"sepal_width":3.0,"petal_length":5.8,"petal_width":1.6,"class":"Virginica"},{"sepal_length":7.4,"sepal_width":2.8,"petal_length":6.1,"petal_width":1.9,"class":"Virginica"},{"sepal_length":7.9,"sepal_width":3.8,"petal_length":6.4,"petal_width":2.0,"class":"Virginica"},{"sepal_length":6.4,"sepal_width":2.8,"petal_length":5.6,"petal_width":2.2,"class":"Virginica"},{"sepal_length":6.3,"sepal_width":2.8,"petal_length":5.1,"petal_width":1.5,"class":"Virginica"},{"sepal_length":6.1,"sepal_width":2.6,"petal_length":5.6,"petal_width":1.4,"class":"Virginica"},{"sepal_length":7.7,"sepal_width":3.0,"petal_length":6.1,"petal_width":2.3,"class":"Virginica"},{"sepal_length":6.3,"sepal_width":3.4,"petal_length":5.6,"petal_width":2.4,"class":"Virginica"},{"sepal_length":6.4,"sepal_width":3.1,"petal_length":5.5,"petal_width":1.8,"class":"Virginica"},{"sepal_length":6.0,"sepal_width":3.0,"petal_length":4.8,"petal_width":1.8,"class":"Virginica"},{"sepal_length":6.9,"sepal_width":3.1,"petal_length":5.4,"petal_width":2.1,"class":"Virginica"},{"sepal_length":6.7,"sepal_width":3.1,"petal_length":5.6,"petal_width":2.4,"class":"Virginica"},{"sepal_length":6.9,"sepal_width":3.1,"petal_length":5.1,"petal_width":2.3,"class":"Virginica"},{"sepal_length":5.8,"sepal_width":2.7,"petal_length":5.1,"petal_width":1.9,"class":"Virginica"},{"sepal_length":6.8,"sepal_width":3.2,"petal_length":5.9,"petal_width":2.3,"class":"Virginica"},{"sepal_length":6.7,"sepal_width":3.3,"petal_length":5.7,"petal_width":2.5,"class":"Virginica"},{"sepal_length":6.7,"sepal_width":3.0,"petal_length":5.2,"petal_width":2.3,"class":"Virginica"},{"sepal_length":6.3,"sepal_width":2.5,"petal_length":5.0,"petal_width":1.9,"class":"Virginica"},{"sepal_length":6.5,"sepal_width":3.0,"petal_length":5.2,"petal_width":2.0,"class":"Virginica"},{"sepal_length":6.2,"sepal_width":3.4,"petal_length":5.4,"petal_width":2.3,"class":"Virginica"},{"sepal_length":5.9,"sepal_width":3.0,"petal_length":5.1,"petal_width":1.8,"class":"Virginica"}] \ No newline at end of file diff --git a/e2e/files/iris.jsonl b/e2e/files/iris.jsonl new file mode 100644 index 0000000..05cc027 --- /dev/null +++ b/e2e/files/iris.jsonl @@ -0,0 +1,150 @@ +{"sepal_length":5.1,"sepal_width":3.5,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":4.9,"sepal_width":3.0,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":4.7,"sepal_width":3.2,"petal_length":1.3,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":4.6,"sepal_width":3.1,"petal_length":1.5,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.0,"sepal_width":3.6,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.4,"sepal_width":3.9,"petal_length":1.7,"petal_width":0.4,"class":"Setosa"} +{"sepal_length":4.6,"sepal_width":3.4,"petal_length":1.4,"petal_width":0.3,"class":"Setosa"} +{"sepal_length":5.0,"sepal_width":3.4,"petal_length":1.5,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":4.4,"sepal_width":2.9,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":4.9,"sepal_width":3.1,"petal_length":1.5,"petal_width":0.1,"class":"Setosa"} +{"sepal_length":5.4,"sepal_width":3.7,"petal_length":1.5,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":4.8,"sepal_width":3.4,"petal_length":1.6,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":4.8,"sepal_width":3.0,"petal_length":1.4,"petal_width":0.1,"class":"Setosa"} +{"sepal_length":4.3,"sepal_width":3.0,"petal_length":1.1,"petal_width":0.1,"class":"Setosa"} +{"sepal_length":5.8,"sepal_width":4.0,"petal_length":1.2,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.7,"sepal_width":4.4,"petal_length":1.5,"petal_width":0.4,"class":"Setosa"} +{"sepal_length":5.4,"sepal_width":3.9,"petal_length":1.3,"petal_width":0.4,"class":"Setosa"} +{"sepal_length":5.1,"sepal_width":3.5,"petal_length":1.4,"petal_width":0.3,"class":"Setosa"} +{"sepal_length":5.7,"sepal_width":3.8,"petal_length":1.7,"petal_width":0.3,"class":"Setosa"} +{"sepal_length":5.1,"sepal_width":3.8,"petal_length":1.5,"petal_width":0.3,"class":"Setosa"} +{"sepal_length":5.4,"sepal_width":3.4,"petal_length":1.7,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.1,"sepal_width":3.7,"petal_length":1.5,"petal_width":0.4,"class":"Setosa"} +{"sepal_length":4.6,"sepal_width":3.6,"petal_length":1.0,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.1,"sepal_width":3.3,"petal_length":1.7,"petal_width":0.5,"class":"Setosa"} +{"sepal_length":4.8,"sepal_width":3.4,"petal_length":1.9,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.0,"sepal_width":3.0,"petal_length":1.6,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.0,"sepal_width":3.4,"petal_length":1.6,"petal_width":0.4,"class":"Setosa"} +{"sepal_length":5.2,"sepal_width":3.5,"petal_length":1.5,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.2,"sepal_width":3.4,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":4.7,"sepal_width":3.2,"petal_length":1.6,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":4.8,"sepal_width":3.1,"petal_length":1.6,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.4,"sepal_width":3.4,"petal_length":1.5,"petal_width":0.4,"class":"Setosa"} +{"sepal_length":5.2,"sepal_width":4.1,"petal_length":1.5,"petal_width":0.1,"class":"Setosa"} +{"sepal_length":5.5,"sepal_width":4.2,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":4.9,"sepal_width":3.1,"petal_length":1.5,"petal_width":0.1,"class":"Setosa"} +{"sepal_length":5.0,"sepal_width":3.2,"petal_length":1.2,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.5,"sepal_width":3.5,"petal_length":1.3,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":4.9,"sepal_width":3.1,"petal_length":1.5,"petal_width":0.1,"class":"Setosa"} +{"sepal_length":4.4,"sepal_width":3.0,"petal_length":1.3,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.1,"sepal_width":3.4,"petal_length":1.5,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.0,"sepal_width":3.5,"petal_length":1.3,"petal_width":0.3,"class":"Setosa"} +{"sepal_length":4.5,"sepal_width":2.3,"petal_length":1.3,"petal_width":0.3,"class":"Setosa"} +{"sepal_length":4.4,"sepal_width":3.2,"petal_length":1.3,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.0,"sepal_width":3.5,"petal_length":1.6,"petal_width":0.6,"class":"Setosa"} +{"sepal_length":5.1,"sepal_width":3.8,"petal_length":1.9,"petal_width":0.4,"class":"Setosa"} +{"sepal_length":4.8,"sepal_width":3.0,"petal_length":1.4,"petal_width":0.3,"class":"Setosa"} +{"sepal_length":5.1,"sepal_width":3.8,"petal_length":1.6,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":4.6,"sepal_width":3.2,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.3,"sepal_width":3.7,"petal_length":1.5,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":5.0,"sepal_width":3.3,"petal_length":1.4,"petal_width":0.2,"class":"Setosa"} +{"sepal_length":7.0,"sepal_width":3.2,"petal_length":4.7,"petal_width":1.4,"class":"Versicolor"} +{"sepal_length":6.4,"sepal_width":3.2,"petal_length":4.5,"petal_width":1.5,"class":"Versicolor"} +{"sepal_length":6.9,"sepal_width":3.1,"petal_length":4.9,"petal_width":1.5,"class":"Versicolor"} +{"sepal_length":5.5,"sepal_width":2.3,"petal_length":4.0,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":6.5,"sepal_width":2.8,"petal_length":4.6,"petal_width":1.5,"class":"Versicolor"} +{"sepal_length":5.7,"sepal_width":2.8,"petal_length":4.5,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":6.3,"sepal_width":3.3,"petal_length":4.7,"petal_width":1.6,"class":"Versicolor"} +{"sepal_length":4.9,"sepal_width":2.4,"petal_length":3.3,"petal_width":1.0,"class":"Versicolor"} +{"sepal_length":6.6,"sepal_width":2.9,"petal_length":4.6,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":5.2,"sepal_width":2.7,"petal_length":3.9,"petal_width":1.4,"class":"Versicolor"} +{"sepal_length":5.0,"sepal_width":2.0,"petal_length":3.5,"petal_width":1.0,"class":"Versicolor"} +{"sepal_length":5.9,"sepal_width":3.0,"petal_length":4.2,"petal_width":1.5,"class":"Versicolor"} +{"sepal_length":6.0,"sepal_width":2.2,"petal_length":4.0,"petal_width":1.0,"class":"Versicolor"} +{"sepal_length":6.1,"sepal_width":2.9,"petal_length":4.7,"petal_width":1.4,"class":"Versicolor"} +{"sepal_length":5.6,"sepal_width":2.9,"petal_length":3.6,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":6.7,"sepal_width":3.1,"petal_length":4.4,"petal_width":1.4,"class":"Versicolor"} +{"sepal_length":5.6,"sepal_width":3.0,"petal_length":4.5,"petal_width":1.5,"class":"Versicolor"} +{"sepal_length":5.8,"sepal_width":2.7,"petal_length":4.1,"petal_width":1.0,"class":"Versicolor"} +{"sepal_length":6.2,"sepal_width":2.2,"petal_length":4.5,"petal_width":1.5,"class":"Versicolor"} +{"sepal_length":5.6,"sepal_width":2.5,"petal_length":3.9,"petal_width":1.1,"class":"Versicolor"} +{"sepal_length":5.9,"sepal_width":3.2,"petal_length":4.8,"petal_width":1.8,"class":"Versicolor"} +{"sepal_length":6.1,"sepal_width":2.8,"petal_length":4.0,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":6.3,"sepal_width":2.5,"petal_length":4.9,"petal_width":1.5,"class":"Versicolor"} +{"sepal_length":6.1,"sepal_width":2.8,"petal_length":4.7,"petal_width":1.2,"class":"Versicolor"} +{"sepal_length":6.4,"sepal_width":2.9,"petal_length":4.3,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":6.6,"sepal_width":3.0,"petal_length":4.4,"petal_width":1.4,"class":"Versicolor"} +{"sepal_length":6.8,"sepal_width":2.8,"petal_length":4.8,"petal_width":1.4,"class":"Versicolor"} +{"sepal_length":6.7,"sepal_width":3.0,"petal_length":5.0,"petal_width":1.7,"class":"Versicolor"} +{"sepal_length":6.0,"sepal_width":2.9,"petal_length":4.5,"petal_width":1.5,"class":"Versicolor"} +{"sepal_length":5.7,"sepal_width":2.6,"petal_length":3.5,"petal_width":1.0,"class":"Versicolor"} +{"sepal_length":5.5,"sepal_width":2.4,"petal_length":3.8,"petal_width":1.1,"class":"Versicolor"} +{"sepal_length":5.5,"sepal_width":2.4,"petal_length":3.7,"petal_width":1.0,"class":"Versicolor"} +{"sepal_length":5.8,"sepal_width":2.7,"petal_length":3.9,"petal_width":1.2,"class":"Versicolor"} +{"sepal_length":6.0,"sepal_width":2.7,"petal_length":5.1,"petal_width":1.6,"class":"Versicolor"} +{"sepal_length":5.4,"sepal_width":3.0,"petal_length":4.5,"petal_width":1.5,"class":"Versicolor"} +{"sepal_length":6.0,"sepal_width":3.4,"petal_length":4.5,"petal_width":1.6,"class":"Versicolor"} +{"sepal_length":6.7,"sepal_width":3.1,"petal_length":4.7,"petal_width":1.5,"class":"Versicolor"} +{"sepal_length":6.3,"sepal_width":2.3,"petal_length":4.4,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":5.6,"sepal_width":3.0,"petal_length":4.1,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":5.5,"sepal_width":2.5,"petal_length":4.0,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":5.5,"sepal_width":2.6,"petal_length":4.4,"petal_width":1.2,"class":"Versicolor"} +{"sepal_length":6.1,"sepal_width":3.0,"petal_length":4.6,"petal_width":1.4,"class":"Versicolor"} +{"sepal_length":5.8,"sepal_width":2.6,"petal_length":4.0,"petal_width":1.2,"class":"Versicolor"} +{"sepal_length":5.0,"sepal_width":2.3,"petal_length":3.3,"petal_width":1.0,"class":"Versicolor"} +{"sepal_length":5.6,"sepal_width":2.7,"petal_length":4.2,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":5.7,"sepal_width":3.0,"petal_length":4.2,"petal_width":1.2,"class":"Versicolor"} +{"sepal_length":5.7,"sepal_width":2.9,"petal_length":4.2,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":6.2,"sepal_width":2.9,"petal_length":4.3,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":5.1,"sepal_width":2.5,"petal_length":3.0,"petal_width":1.1,"class":"Versicolor"} +{"sepal_length":5.7,"sepal_width":2.8,"petal_length":4.1,"petal_width":1.3,"class":"Versicolor"} +{"sepal_length":6.3,"sepal_width":3.3,"petal_length":6.0,"petal_width":2.5,"class":"Virginica"} +{"sepal_length":5.8,"sepal_width":2.7,"petal_length":5.1,"petal_width":1.9,"class":"Virginica"} +{"sepal_length":7.1,"sepal_width":3.0,"petal_length":5.9,"petal_width":2.1,"class":"Virginica"} +{"sepal_length":6.3,"sepal_width":2.9,"petal_length":5.6,"petal_width":1.8,"class":"Virginica"} +{"sepal_length":6.5,"sepal_width":3.0,"petal_length":5.8,"petal_width":2.2,"class":"Virginica"} +{"sepal_length":7.6,"sepal_width":3.0,"petal_length":6.6,"petal_width":2.1,"class":"Virginica"} +{"sepal_length":4.9,"sepal_width":2.5,"petal_length":4.5,"petal_width":1.7,"class":"Virginica"} +{"sepal_length":7.3,"sepal_width":2.9,"petal_length":6.3,"petal_width":1.8,"class":"Virginica"} +{"sepal_length":6.7,"sepal_width":2.5,"petal_length":5.8,"petal_width":1.8,"class":"Virginica"} +{"sepal_length":7.2,"sepal_width":3.6,"petal_length":6.1,"petal_width":2.5,"class":"Virginica"} +{"sepal_length":6.5,"sepal_width":3.2,"petal_length":5.1,"petal_width":2.0,"class":"Virginica"} +{"sepal_length":6.4,"sepal_width":2.7,"petal_length":5.3,"petal_width":1.9,"class":"Virginica"} +{"sepal_length":6.8,"sepal_width":3.0,"petal_length":5.5,"petal_width":2.1,"class":"Virginica"} +{"sepal_length":5.7,"sepal_width":2.5,"petal_length":5.0,"petal_width":2.0,"class":"Virginica"} +{"sepal_length":5.8,"sepal_width":2.8,"petal_length":5.1,"petal_width":2.4,"class":"Virginica"} +{"sepal_length":6.4,"sepal_width":3.2,"petal_length":5.3,"petal_width":2.3,"class":"Virginica"} +{"sepal_length":6.5,"sepal_width":3.0,"petal_length":5.5,"petal_width":1.8,"class":"Virginica"} +{"sepal_length":7.7,"sepal_width":3.8,"petal_length":6.7,"petal_width":2.2,"class":"Virginica"} +{"sepal_length":7.7,"sepal_width":2.6,"petal_length":6.9,"petal_width":2.3,"class":"Virginica"} +{"sepal_length":6.0,"sepal_width":2.2,"petal_length":5.0,"petal_width":1.5,"class":"Virginica"} +{"sepal_length":6.9,"sepal_width":3.2,"petal_length":5.7,"petal_width":2.3,"class":"Virginica"} +{"sepal_length":5.6,"sepal_width":2.8,"petal_length":4.9,"petal_width":2.0,"class":"Virginica"} +{"sepal_length":7.7,"sepal_width":2.8,"petal_length":6.7,"petal_width":2.0,"class":"Virginica"} +{"sepal_length":6.3,"sepal_width":2.7,"petal_length":4.9,"petal_width":1.8,"class":"Virginica"} +{"sepal_length":6.7,"sepal_width":3.3,"petal_length":5.7,"petal_width":2.1,"class":"Virginica"} +{"sepal_length":7.2,"sepal_width":3.2,"petal_length":6.0,"petal_width":1.8,"class":"Virginica"} +{"sepal_length":6.2,"sepal_width":2.8,"petal_length":4.8,"petal_width":1.8,"class":"Virginica"} +{"sepal_length":6.1,"sepal_width":3.0,"petal_length":4.9,"petal_width":1.8,"class":"Virginica"} +{"sepal_length":6.4,"sepal_width":2.8,"petal_length":5.6,"petal_width":2.1,"class":"Virginica"} +{"sepal_length":7.2,"sepal_width":3.0,"petal_length":5.8,"petal_width":1.6,"class":"Virginica"} +{"sepal_length":7.4,"sepal_width":2.8,"petal_length":6.1,"petal_width":1.9,"class":"Virginica"} +{"sepal_length":7.9,"sepal_width":3.8,"petal_length":6.4,"petal_width":2.0,"class":"Virginica"} +{"sepal_length":6.4,"sepal_width":2.8,"petal_length":5.6,"petal_width":2.2,"class":"Virginica"} +{"sepal_length":6.3,"sepal_width":2.8,"petal_length":5.1,"petal_width":1.5,"class":"Virginica"} +{"sepal_length":6.1,"sepal_width":2.6,"petal_length":5.6,"petal_width":1.4,"class":"Virginica"} +{"sepal_length":7.7,"sepal_width":3.0,"petal_length":6.1,"petal_width":2.3,"class":"Virginica"} +{"sepal_length":6.3,"sepal_width":3.4,"petal_length":5.6,"petal_width":2.4,"class":"Virginica"} +{"sepal_length":6.4,"sepal_width":3.1,"petal_length":5.5,"petal_width":1.8,"class":"Virginica"} +{"sepal_length":6.0,"sepal_width":3.0,"petal_length":4.8,"petal_width":1.8,"class":"Virginica"} +{"sepal_length":6.9,"sepal_width":3.1,"petal_length":5.4,"petal_width":2.1,"class":"Virginica"} +{"sepal_length":6.7,"sepal_width":3.1,"petal_length":5.6,"petal_width":2.4,"class":"Virginica"} +{"sepal_length":6.9,"sepal_width":3.1,"petal_length":5.1,"petal_width":2.3,"class":"Virginica"} +{"sepal_length":5.8,"sepal_width":2.7,"petal_length":5.1,"petal_width":1.9,"class":"Virginica"} +{"sepal_length":6.8,"sepal_width":3.2,"petal_length":5.9,"petal_width":2.3,"class":"Virginica"} +{"sepal_length":6.7,"sepal_width":3.3,"petal_length":5.7,"petal_width":2.5,"class":"Virginica"} +{"sepal_length":6.7,"sepal_width":3.0,"petal_length":5.2,"petal_width":2.3,"class":"Virginica"} +{"sepal_length":6.3,"sepal_width":2.5,"petal_length":5.0,"petal_width":1.9,"class":"Virginica"} +{"sepal_length":6.5,"sepal_width":3.0,"petal_length":5.2,"petal_width":2.0,"class":"Virginica"} +{"sepal_length":6.2,"sepal_width":3.4,"petal_length":5.4,"petal_width":2.3,"class":"Virginica"} +{"sepal_length":5.9,"sepal_width":3.0,"petal_length":5.1,"petal_width":1.8,"class":"Virginica"} diff --git a/e2e/files/iris.parquet b/e2e/files/iris.parquet new file mode 100644 index 0000000..5598be7 Binary files /dev/null and b/e2e/files/iris.parquet differ diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts new file mode 100644 index 0000000..b08cd24 --- /dev/null +++ b/e2e/fixtures.ts @@ -0,0 +1,27 @@ +import { test as base, expect } from '@playwright/test' + +/** + * Lo común a todas las pruebas: cookies rechazadas (sin el aviso tapando la página), la aplicación en español y la + * prueba falla si la página lanza un error de JavaScript. + */ +export const test = base.extend<{ pageErrors: string[] }>({ + context: async ({ context, baseURL }, provide) => { + await context.addCookies([{ name: 'n4l-accept-cookies', value: 'false', url: baseURL ?? 'http://localhost' }]) + await context.addInitScript(() => { + try { + localStorage.setItem('language', 'es') + } catch { + // Sin almacenamiento: el idioma lo decide el navegador (locale es-ES) + } + }) + await provide(context) + }, + pageErrors: [async ({ page }, provide) => { + const errors: string[] = [] + page.on('pageerror', (error) => errors.push(error.message)) + await provide(errors) + expect(errors, 'errores de JavaScript en la página').toEqual([]) + }, { auto: true }], +}) + +export { expect } diff --git a/e2e/movil.spec.ts b/e2e/movil.spec.ts new file mode 100644 index 0000000..49a9f36 --- /dev/null +++ b/e2e/movil.spec.ts @@ -0,0 +1,277 @@ +import { test, expect } from './fixtures' +import { axeViolations } from './axe' + +test('ninguna página se sale de la pantalla en horizontal', async ({ page }) => { + test.setTimeout(180_000) + const paths = [ + '/', + '/select-dataset/tabular-classification', + '/task/regression', + '/playground/tabular-classification/dataset/IRIS', + '/playground/regression/model/AUTO_MPG', + '/playground/image-classification/model/IMAGE-MNIST', + '/playground/clustering/dataset/WINE', + '/playground/time-series/dataset/MELBOURNE-TEMPERATURES', + '/playground/time-series/model/AIRLINE-PASSENGERS', + '/analyze', + '/datasets', + '/packages', + '/glossary', + '/manual', + '/settings', + '/accessibility', + '/learn', + '/contribute', + '/version', + '/terms-and-conditions', + '/404', + ] + for (const path of paths) { + await page.goto(path) + await expect(page.locator('main').first()).toBeVisible() + await page.waitForTimeout(1500) + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth) + expect(overflow, `desborde horizontal en ${path}`).toBeLessThanOrEqual(0) + } +}) + +test('al bajar, la barra de navegación sigue arriba y el índice de secciones aparece debajo de ella', async ({ page }) => { + await page.goto('/playground/regression/dataset/AUTO_MPG') + await expect(page.getByTestId('Test-TrainButton')).toBeVisible() + await page.evaluate(() => window.scrollTo(0, 3000)) + const navbar = page.locator('.n4l-navbar') + const bar = page.locator('.n4l-section-bar-wrapper') + await expect(bar).toHaveClass(/is-visible/) + // Al final de la transición (0,2 s), justo debajo de la barra de navegación + await expect.poll(async () => Math.round((await bar.boundingBox())!.y)).toBe(Math.round((await navbar.boundingBox())!.height)) + expect((await navbar.boundingBox())!.y).toBe(0) +}) + +test('el menú se cierra al ir a otra página, que empieza arriba', async ({ page }) => { + await page.goto('/') + await expect(page.getByTestId('Test-InitialMenu')).toBeVisible() + await page.evaluate(() => window.scrollTo({ top: 600, behavior: 'instant' })) + await expect.poll(() => page.evaluate(() => window.scrollY)).toBeGreaterThan(300) + const toggler = page.locator('.navbar-toggler') + await toggler.click() + await expect(toggler).toHaveAttribute('aria-expanded', 'true') + await page.locator('.n4l-navbar').getByRole('link', { name: 'Manual', exact: true }).click() + await expect(page).toHaveURL(/\/manual$/) + await expect(toggler).toHaveAttribute('aria-expanded', 'false') + await expect(page.locator('.navbar-collapse')).not.toHaveClass(/show/) + await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(0) +}) + +test('desde el menú se abre la página de una tarea, y el menú se cierra', async ({ page }) => { + await page.goto('/') + const toggler = page.locator('.navbar-toggler') + await toggler.click() + await page.locator('.n4l-navbar').getByRole('button', { name: 'Tareas' }).click() + await page.locator('.n4l-navbar').getByRole('link', { name: 'Agrupamiento' }).click() + await expect(page).toHaveURL(/\/task\/clustering$/) + await expect(toggler).toHaveAttribute('aria-expanded', 'false') + await expect(page.getByTestId('Test-Task-Design')).toContainText('Agrupar un conjunto de datos') +}) + +test('se dibuja un número con el dedo y el modelo lo reconoce', async ({ page }) => { + await page.goto('/playground/image-classification/model/IMAGE-MNIST') + // Con el modelo cargado la página ya no cambia de alto (el lienzo se queda donde se mide) y, cuando se va el aviso + // de "modelo cargado", los toques llegan al lienzo y no a su fondo + await expect(page.getByTestId('Test-LoadTestDataset')).toBeEnabled({ timeout: 60_000 }) + await expect(page.locator('.swal2-container')).toHaveCount(0) + const canvas = page.locator('#canvas') + await canvas.scrollIntoViewIfNeeded() + const box = (await canvas.boundingBox())! + // Un 7 con eventos táctiles de verdad (el lienzo usa eventos de puntero) + const path = [[0.25, 0.22], [0.75, 0.22], [0.6, 0.5], [0.45, 0.8]].map(([x, y]) => ({ x: box.x + box.width * x, y: box.y + box.height * y })) + const cdp = await page.context().newCDPSession(page) + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [path[0]] }) + for (let segment = 1; segment < path.length; segment++) { + for (let step = 1; step <= 8; step++) { + const from = path[segment - 1], to = path[segment] + await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: from.x + (to.x - from.x) * step / 8, y: from.y + (to.y - from.y) * step / 8 }] }) + } + } + await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }) + // El trazo está en el lienzo y dibujar no mueve la página + const inked = await canvas.evaluate((element) => { + const lienzo = element as HTMLCanvasElement + const data = lienzo.getContext('2d')!.getImageData(0, 0, lienzo.width, lienzo.height).data + let pixels = 0 + for (let i = 3; i < data.length; i += 4) if (data[i] > 128) pixels++ + return pixels + }) + expect(inked).toBeGreaterThan(1000) + expect(await canvas.evaluate((element) => getComputedStyle(element).touchAction)).toBe('none') + + await page.locator('.card', { has: canvas }).getByRole('button', { name: 'Clasificar' }).click() + await expect(page.getByText(/Clase predicha\s*7/)).toBeVisible({ timeout: 30_000 }) +}) + +test('al entrenar, el visor no tapa la página', async ({ page }) => { + test.setTimeout(240_000) + await page.goto('/playground/tabular-classification/dataset/IRIS') + await page.getByRole('spinbutton', { name: 'N. épocas' }).fill('1') + await page.getByTestId('Test-TrainButton').click() + await expect(page.locator('.swal2-popup')).toContainText('Modelo entrenado con éxito', { timeout: 200_000 }) + const visorLeft = await page.locator('#tfjs-visor-container .visor').evaluate((visor) => visor.getBoundingClientRect().left) + expect(visorLeft).toBeGreaterThanOrEqual(page.viewportSize()!.width) +}) + +test('al recargar la página (como al desbloquear el móvil), la guía sigue en su paso', async ({ page }) => { + // Lo que se leería en voz alta (se apunta de nuevo en cada carga) + await page.addInitScript(() => { + const spoken: string[] = [] + Object.assign(window, { spoken }) + window.speechSynthesis.speak = (utterance) => { spoken.push(utterance.text) } + }) + const spoken = () => page.evaluate(() => (window as unknown as { spoken: string[] }).spoken.join(' ')) + await page.goto('/playground/tabular-classification/model/CAR') + await page.getByTestId('Test-GuideButton').click() + const tooltip = page.getByTestId('Test-GuideTooltip') + for (let step = 2; step <= 4; step++) { + await tooltip.getByRole('button', { name: 'Siguiente' }).click() + await expect(tooltip).toContainText(`Paso ${step} de 18`) + } + + await page.reload() + // Se vuelve a abrir sola en el mismo paso, cuando ya están los datos que señala + await expect(tooltip).toContainText('Paso 4 de 18', { timeout: 30_000 }) + await expect(tooltip).toContainText('El conjunto de datos') + // Se lee el paso: enseguida si el navegador lo deja (Chrome mantiene la activación al recargar) o, si no, al tocar la + // página (eso lo prueba N4LGuide.test.tsx) + await tooltip.locator('p').click() + await expect.poll(spoken).toContain('El conjunto de datos.') + + // Cerrada a medias, al recargar ya no se abre sola y el botón sigue desde ese paso + await page.keyboard.press('Escape') + await expect(tooltip).toHaveCount(0) + await page.reload() + await expect(page.getByTestId('Test-GuideButton')).toHaveText('Continuar la guía (paso 4 de 18)') + await page.waitForTimeout(1500) + await expect(tooltip).toHaveCount(0) +}) + +test('el menú abierto en el móvil no tiene problemas de accesibilidad (temas claro y oscuro)', async ({ page }) => { + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }) + await page.goto('/') + const toggler = page.locator('.navbar-toggler') + await toggler.click() + await expect(toggler).toHaveAttribute('aria-expanded', 'true') + await page.locator('.n4l-navbar').getByRole('button', { name: 'Tareas' }).click() + await expect(page.locator('.n4l-navbar .dropdown-menu.show')).toBeVisible() + expect(await axeViolations(page), `menú móvil (tema ${colorScheme === 'light' ? 'claro' : 'oscuro'})`).toEqual([]) + // Con un ajuste abierto: la opción elegida, con el fondo suave y la marca + await page.locator('.n4l-navbar').getByRole('button', { name: /Idioma/ }).click() + await expect(page.locator('.n4l-navbar .dropdown-menu.show [aria-current="true"] .n4l-navbar-check')).toBeVisible() + expect(await axeViolations(page), `menú móvil con el idioma (tema ${colorScheme === 'light' ? 'claro' : 'oscuro'})`).toEqual([]) + } +}) + +test('el menú se abre sobre la página sin moverla, y tocar fuera de él o salir con el tabulador lo cierra', async ({ page }) => { + await page.goto('/glossary') + const heading = page.getByRole('heading', { level: 1 }) + await expect(heading).toBeVisible() + const before = (await heading.boundingBox())!.y + const toggler = page.locator('.navbar-toggler') + await toggler.click() + await expect(page.locator('.navbar-collapse')).toHaveClass(/show/) + // La página sigue en su sitio, oscurecida detrás del menú + expect((await heading.boundingBox())!.y).toBe(before) + const backdrop = page.getByTestId('Test-Navbar-Backdrop') + await expect(backdrop).toBeVisible() + // Al tocar la página (debajo del menú), se cierra + const viewport = page.viewportSize()! + await page.mouse.click(viewport.width / 2, viewport.height - 20) + await expect(toggler).toHaveAttribute('aria-expanded', 'false') + await expect(backdrop).toHaveCount(0) + + // Con el teclado: después del último enlace (GitHub), el foco sale del menú y este se cierra + await toggler.focus() + await page.keyboard.press('Enter') + await expect(toggler).toHaveAttribute('aria-expanded', 'true') + await page.getByRole('link', { name: 'GitHub (se abre en otra pestaña)' }).focus() + await page.keyboard.press('Tab') + await expect(toggler).toHaveAttribute('aria-expanded', 'false') +}) + +test('el menú del móvil con el teclado: dice si está abierto, lo de dentro va después del botón y Escape lo cierra', async ({ page }) => { + await page.goto('/') + await expect(page.getByTestId('Test-InitialMenu')).toBeVisible() + const toggler = page.locator('.navbar-toggler') + await toggler.focus() + await page.keyboard.press('Enter') + await expect(toggler).toHaveAttribute('aria-expanded', 'true') + // Lo siguiente con el tabulador ya es del menú + await page.keyboard.press('Tab') + expect(await page.evaluate(() => document.querySelector('#n4l-navbar-menu')?.contains(document.activeElement))).toBe(true) + // Con un desplegable abierto, Escape cierra el desplegable, no el menú + const tasks = page.locator('.n4l-navbar').getByRole('button', { name: 'Tareas' }) + await tasks.focus() + await page.keyboard.press('Enter') + await expect(tasks).toHaveAttribute('aria-expanded', 'true') + await page.keyboard.press('Escape') + await expect(tasks).toHaveAttribute('aria-expanded', 'false') + await expect(toggler).toHaveAttribute('aria-expanded', 'true') + // Y otra vez Escape cierra el menú, con el foco en su botón + await page.keyboard.press('Escape') + await expect(toggler).toHaveAttribute('aria-expanded', 'false') + await expect(toggler).toBeFocused() +}) + +test('/settings en el móvil: la lista de apartados y cada uno solo, con el foco donde toca y sin problemas de accesibilidad', async ({ page }) => { + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }) + await page.goto('/settings') + const list = page.getByRole('navigation', { name: 'Apartados de la configuración' }) + await expect(list.getByRole('link')).toHaveCount(9) + expect(await axeViolations(page), `lista (tema ${colorScheme === 'light' ? 'claro' : 'oscuro'})`).toEqual([]) + + // Al tocar un apartado se abre solo, arriba y con el foco en su título + await list.getByRole('link', { name: /Privacidad y cookies/ }).click() + await expect(page).toHaveURL(/\/settings#privacy$/) + await expect(page.getByTestId('Test-Settings-privacy').getByRole('heading', { name: 'Privacidad y cookies' })).toBeFocused() + await expect(list).toHaveCount(0) + expect(await page.evaluate(() => window.scrollY)).toBe(0) + expect(await axeViolations(page), `apartado (tema ${colorScheme === 'light' ? 'claro' : 'oscuro'})`).toEqual([]) + + // «Todos los apartados» (o el botón atrás del teléfono) vuelve a la lista, con el foco en el apartado del que se viene + await page.getByTestId('Test-Settings-Back').click() + await expect(page).toHaveURL(/\/settings$/) + await expect(page.getByTestId('Test-Settings-Item-privacy')).toBeFocused() + await page.getByTestId('Test-Settings-Item-data').click() + await page.goBack() + await expect(page.getByTestId('Test-Settings-Item-data')).toBeFocused() + } +}) + +test('/accessibility en el móvil: el índice de arriba lleva a cada apartado sin taparlo, y los botones dicen que abren otra pestaña', async ({ page }) => { + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }) + await page.goto('/accessibility') + const index = page.getByTestId('Test-Accessibility-Index') + await expect(index.getByRole('link')).toHaveCount(5) + expect(await axeViolations(page), `arriba (tema ${colorScheme === 'light' ? 'claro' : 'oscuro'})`).toEqual([]) + + // Al tocar un apartado, su título queda debajo de las barras (la de navegación y la del índice) y con el foco + await index.getByRole('link', { name: '4. Comunicar una barrera' }).click() + const heading = page.getByRole('heading', { level: 2, name: '4. Comunicar una barrera' }) + await expect(page.locator('#' + (await heading.locator('..').getAttribute('id')))).toBeFocused() + const bar = page.locator('.n4l-section-bar-wrapper') + await expect(bar).toHaveClass(/is-visible/) + await expect.poll(async () => (await heading.boundingBox())!.y).toBeGreaterThanOrEqual((await bar.boundingBox())!.y + (await bar.boundingBox())!.height) + expect(await axeViolations(page), `apartado (tema ${colorScheme === 'light' ? 'claro' : 'oscuro'})`).toEqual([]) + } + + // Los botones de contacto, a todo el ancho y con «(se abre en otra pestaña)» en su nombre + const issue = page.getByRole('link', { name: 'Comunicar una barrera en GitHub (con una plantilla) (se abre en otra pestaña)' }) + await expect(issue).toHaveAttribute('target', '_blank') + const width = await page.evaluate(() => document.querySelector('#feedback')!.getBoundingClientRect().width) + expect((await issue.boundingBox())!.width).toBeCloseTo(width, 0) + + // Con el ancla en la dirección (un enlace desde fuera), el título del apartado tampoco queda bajo las barras + await page.goto('/accessibility#preparation') + const preparation = page.getByRole('heading', { level: 2, name: /^5\. / }) + await expect.poll(async () => (await preparation.boundingBox())!.y).toBeGreaterThanOrEqual((await page.locator('.n4l-navbar').boundingBox())!.height) +}) diff --git a/e2e/navegacion.spec.ts b/e2e/navegacion.spec.ts new file mode 100644 index 0000000..cf6581a --- /dev/null +++ b/e2e/navegacion.spec.ts @@ -0,0 +1,638 @@ +import path from 'node:path' +import { test, expect } from './fixtures' + +test('la home enseña la tarjeta de la tarea elegida y baja hasta ella', async ({ page }) => { + await page.goto('/') + await page.getByTestId('Test-InitialMenu-LinearRegression').click() + await expect(page.getByTestId('Test-GoTo-SelectModel-LinearRegression')).toBeVisible() + // El separador de las tarjetas queda arriba, justo debajo de la barra de navegación, y con el foco + const divider = page.locator('.n4l-hr-row', { hasText: 'Tareas' }) + await expect(divider).toBeFocused() + const navbarHeight = (await page.locator('.n4l-navbar').boundingBox())!.height + await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThanOrEqual(navbarHeight) + await expect.poll(async () => (await divider.boundingBox())!.y).toBeLessThan(navbarHeight + 100) +}) + +test('la barra de navegación lleva a cada página y marca la actual', async ({ page }) => { + await page.goto('/') + const navbar = page.locator('.n4l-navbar') + for (const [name, path] of [['Manual', '/manual'], ['Glosario', '/glossary'], ['Conjuntos de datos', '/datasets'], ['AED', '/analyze'], ['Paquetes .n4l', '/packages']]) { + await navbar.getByRole('link', { name, exact: true }).click() + await expect(page).toHaveURL(new RegExp(path + '$')) + await expect(navbar.getByRole('link', { name, exact: true })).toHaveAttribute('aria-current', 'page') + } +}) + +test('un modelo se descarga como .n4l y se abre en «Paquetes .n4l»: se guarda en el navegador y se usa como los demás', async ({ page }, testInfo) => { + await page.goto('/playground/tabular-classification/model/IRIS') + const [download] = await Promise.all([page.waitForEvent('download'), page.getByTestId('Test-N4LDownload').click()]) + expect(download.suggestedFilename()).toBe('iris-1.0.0.n4l') + const file = testInfo.outputPath('iris-1.0.0.n4l') + await download.saveAs(file) + + // Ya no está en los menús de las tareas, sino en su página (en la barra de navegación) + await page.goto('/select-model/tabular-classification') + await expect(page.getByTestId('Test-MenuSelectModel-Open-IRIS')).toBeVisible() + await expect(page.getByTestId('Test-N4LLocalPackages')).toHaveCount(0) + await page.locator('.n4l-navbar').getByTestId('Test-Navbar-Packages').click() + await expect(page).toHaveURL(/\/packages$/) + const local = page.getByTestId('Test-N4LLocalPackages') + await expect(local).toContainText('Todavía no hay ninguno') + // Un fichero que no es un .n4l se rechaza diciendo por qué + await local.locator('input#drop-zone-n4l').setInputFiles({ name: 'roto.n4l', mimeType: 'application/octet-stream', buffer: Buffer.from('hola') }) + await expect(local.getByTestId('Test-N4LImportError')).toContainText('no es un fichero .n4l') + + await local.locator('input#drop-zone-n4l').setInputFiles(file) + await expect(local.getByTestId('Test-N4LImported')).toContainText('Clasificación de flor iris') + // Una tarjeta con sus tareas: probar su modelo o entrenar con su conjunto; la barra cuenta los guardados + await expect(page.getByTestId('Test-Navbar-Packages')).toContainText('1') + await expect(local.getByTestId('Test-N4LLocal-iris')).toContainText('Clasificación tabular') + await local.getByTestId('Test-N4LLocal-iris-tabular-classification').getByRole('link', { name: 'Probar el modelo' }).click() + await expect(page).toHaveURL(/\/playground\/tabular-classification\/model\/local-iris$/) + // La miga de pan lleva de vuelta a los paquetes + await expect(page.getByTestId('Test-Breadcrumb').getByRole('link', { name: 'Tus paquetes .n4l' })).toHaveAttribute('href', /\/packages$/) + // Con sus textos (los del paquete abierto) y su modelo + await expect(page.locator('[data-guide="form"]')).toContainText('Longitud sépalo', { timeout: 30_000 }) + await expect(page.getByTestId('Test-N4LDescription')).toContainText('Iris-Data') + + // Sigue ahí al volver (IndexedDB) y se puede quitar + await page.goto('/packages') + await page.getByTestId('Test-N4LLocal-iris').getByRole('button', { name: /Quitar/ }).click() + // Antes pregunta (no se puede deshacer): el foco va a «Cancelar» + const confirm = page.getByTestId('Test-N4LLocal-iris').getByRole('group', { name: /Se quitará/ }) + await expect(confirm.getByRole('button', { name: 'Cancelar' })).toBeFocused() + await confirm.getByRole('button', { name: 'Quitar' }).click() + await expect(page.getByTestId('Test-N4LLocal-iris')).toHaveCount(0) + await page.goto('/playground/tabular-classification/model/local-iris') + await expect(page).toHaveURL(/\/404$/) +}) + +test('«Tareas» en la cabecera abre la página de cada tarea: modelos ya entrenados o diseñar una red', async ({ page }) => { + await page.goto('/') + await page.locator('.n4l-navbar').getByRole('button', { name: 'Tareas' }).click() + await page.locator('.n4l-navbar').getByRole('link', { name: 'Clasificación de imágenes' }).click() + await expect(page).toHaveURL(/\/task\/image-classification$/) + await expect(page.locator('#tasks-nav-dropdown')).toHaveClass(/active/) + await expect(page.getByTestId('Test-Task-Pretrained')).toContainText('Modelos ya entrenados') + await expect(page.getByTestId('Test-Task-Design')).toContainText('Diseñar, crear y editar una arquitectura') + await page.getByTestId('Test-Task-Choose-dataset').click() + await expect(page).toHaveURL(/\/select-dataset\/image-classification$/) + // Y de vuelta, con la miga de pan de la tarea + await page.getByTestId('Test-Breadcrumb').getByRole('link', { name: 'Clasificación de imágenes' }).click() + await page.getByTestId('Test-Task-Choose-model').click() + await expect(page).toHaveURL(/\/select-model\/image-classification$/) +}) + +test('las migas de pan cambian de modelo y llevan a entrenar con su dataset', async ({ page }) => { + await page.goto('/playground/tabular-classification/model/IRIS') + const breadcrumb = page.getByTestId('Test-Breadcrumb') + await breadcrumb.locator('.n4l-breadcrumb-toggle').click() + await breadcrumb.locator('.dropdown-item', { hasText: 'Clasificación de coches' }).click() + await expect(page).toHaveURL(/\/playground\/tabular-classification\/model\/CAR$/) + await expect(breadcrumb.locator('.n4l-breadcrumb-toggle')).toContainText('Clasificación de coches') + + await breadcrumb.locator('.n4l-breadcrumb-toggle').click() + await breadcrumb.getByTestId('Test-Breadcrumb-OtherKind').click() + await expect(page).toHaveURL(/\/playground\/tabular-classification\/dataset\/CAR$/) + + // La tarea lleva a su página: modelos ya entrenados o diseñar una red + await breadcrumb.locator('.n4l-breadcrumb-task a').click() + await expect(page).toHaveURL(/\/task\/tabular-classification$/) +}) + +test('el AED analiza un conjunto de datos del proyecto', async ({ page }) => { + await page.goto('/analyze') + await page.locator('#analyze-project-dataset').selectOption('n4l/iris.n4l/data/iris.csv') + await expect(page.getByTestId('Test-AnalyzeInfo')).toContainText('150') + await expect(page.getByTestId('Test-AnalyzeTile-rows')).toContainText('150') + await expect(page.getByTestId('Test-AnalyzeProblem')).toBeVisible() + // El conjunto queda en la dirección y el resumen trae la distribución del objetivo y los avisos en sus tarjetas + await expect(page).toHaveURL(/\/analyze\?dataset=iris$/) + await expect(page.getByTestId('Test-AnalyzeTargetCard')).toContainText('class') + await expect(page.getByTestId('Test-AnalyzeWarningsCard')).toBeVisible() +}) + +// Ficheros propios en otros formatos o con otro separador: todos acaban siendo el mismo dataframe +const UPLOADS = [ + { file: 'iris.arff', shape: '150 filas × 5 columnas', numeric: 'Numéricas: 4' }, + { file: 'iris.json', shape: '150 filas × 5 columnas', numeric: 'Numéricas: 4' }, + { file: 'iris-pandas.json', shape: '150 filas × 5 columnas', numeric: 'Numéricas: 4' }, + { file: 'iris.jsonl', shape: '150 filas × 5 columnas', numeric: 'Numéricas: 4' }, + { file: 'iris.parquet', shape: '150 filas × 5 columnas', numeric: 'Numéricas: 4' }, + { file: 'iris-zstd.parquet', shape: '150 filas × 5 columnas', numeric: 'Numéricas: 4' }, + // ";" y coma decimal (Excel en español), y el mismo alineado con comas: sin las columnas vacías del final + { file: 'aire-punto-y-coma.csv', shape: '6 filas × 7 columnas', numeric: 'Numéricas: 4' }, + { file: 'aire-alineado.csv', shape: '6 filas × 7 columnas', numeric: 'Numéricas: 4' }, +] + +for (const { file, shape, numeric } of UPLOADS) { + test(`el AED lee ${file}`, async ({ page }) => { + await page.goto('/analyze') + await page.locator('input[type=file][accept*=".parquet"]').setInputFiles(path.join(__dirname, 'files', file)) + await expect(page.getByTestId('Test-AnalyzeInfo')).toContainText(shape) + await expect(page.getByTestId('Test-AnalyzeTile-columns')).toContainText(numeric) + }) +} + +test('desde /datasets un conjunto se abre en el AED', async ({ page }) => { + await page.goto('/datasets') + await page.getByTestId('Test-DatasetAnalyze-car').click() + await expect(page).toHaveURL(/\/analyze\?dataset=car$/) + await expect(page.getByTestId('Test-AnalyzeInfo')).toContainText('1728') + await expect(page.locator('#analyze-project-dataset')).toHaveValue('n4l/car.n4l/data/car.csv') +}) + +test('las series temporales de /datasets: su descripción, sus fechas y su análisis en el AED', async ({ page }) => { + await page.goto('/datasets?task=time-series') + await expect(page.getByTestId('Test-Dataset-AIRLINE-PASSENGERS')).toContainText('144 meses, objetivo: Passengers') + await expect(page.getByTestId('Test-Dataset-MELBOURNE-TEMPERATURES')).toContainText('días, objetivo: Temp') + // Se entrenan y tienen su modelo ya entrenado + await expect(page.getByTestId('Test-DatasetTrain-SUNSPOTS')).toHaveAttribute('href', '/playground/time-series/dataset/SUNSPOTS') + await expect(page.getByTestId('Test-DatasetModel-SUNSPOTS')).toHaveAttribute('href', '/playground/time-series/model/SUNSPOTS') + await page.getByTestId('Test-DatasetInfo-SUNSPOTS').click() + const modal = page.getByRole('dialog') + await expect(modal.getByTestId('Test-N4LDescription')).toContainText('mínimo de Dalton') + await modal.getByRole('tab', { name: 'Variables' }).click() + await expect(modal.getByTestId('Test-DatasetVariables')).toContainText('Fecha') + await modal.getByRole('tab', { name: 'Datos' }).click() + await expect(modal.getByText('2820 filas × 2 columnas')).toBeVisible() + await modal.getByRole('link', { name: 'Analizar' }).click() + await expect(page).toHaveURL(/\/analyze\?dataset=monthly-sunspots$/) + await expect(page.getByTestId('Test-AnalyzeInfo')).toContainText('2820') +}) + +test('el modal de un conjunto de /datasets enseña sus datos y sus estadísticas', async ({ page }) => { + await page.goto('/datasets') + await page.getByTestId('Test-DatasetInfo-IRIS').click() + const modal = page.getByRole('dialog') + await modal.getByRole('tab', { name: 'Datos' }).click() + await expect(modal.getByText('150 filas × 5 columnas')).toBeVisible() + await expect(modal.locator('.js-plotly-plot')).toBeVisible() + await modal.getByRole('tab', { name: 'Estadísticas' }).click() + await expect(modal.locator('.tab-pane.active .js-plotly-plot')).toBeVisible() + await page.keyboard.press('Escape') + + // Con varios ficheros se elige cuál (el vino: tinto y blanco) + await page.getByRole('tab', { name: 'Regresión' }).click() + await page.getByTestId('Test-DatasetInfo-WINE').click() + await modal.getByRole('tab', { name: 'Datos' }).click() + await expect(modal.getByText('1599 filas × 12 columnas')).toBeVisible() + await modal.locator('.tab-pane.active select').selectOption({ label: 'wine-quality-white.csv' }) + await expect(modal.getByText('4898 filas × 12 columnas')).toBeVisible() +}) + +test('la barra de navegación se queda fija arriba al bajar', async ({ page }) => { + await page.goto('/glossary') + // Se insiste hasta que la página es larga y baja de verdad + await expect.poll(async () => { + await page.evaluate(() => window.scrollTo(0, 3000)) + return page.evaluate(() => window.scrollY) + }).toBeGreaterThan(500) + const box = await page.locator('.n4l-navbar').boundingBox() + expect(box?.y).toBe(0) + await expect(page.locator('.n4l-navbar').getByRole('link', { name: 'Glosario', exact: true })).toBeInViewport() +}) + +test('el glosario busca términos y cada uno tiene su enlace', async ({ page }) => { + await page.goto('/glossary') + await page.getByRole('searchbox').fill('relu') + await expect(page.getByTestId('Test-GlossaryResults')).toContainText('términos') + await expect(page.locator('#glossary-activation-relu')).toBeVisible() + await expect(page.locator('#glossary-optimizer-adam')).toHaveCount(0) + + // Un enlace directo lleva al término (con su fórmula y su gráfica) + await page.goto('/') + await page.goto('/glossary#glossary-activation-sigmoid') + const sigmoid = page.locator('#glossary-activation-sigmoid') + await expect(sigmoid).toBeInViewport() + await expect(sigmoid.locator('.katex')).toBeVisible() + await expect(sigmoid.locator('img')).toHaveJSProperty('complete', true) +}) + +test('el diseño de capas se maximiza a pantalla completa y Escape lo devuelve a su sitio', async ({ page }) => { + await page.goto('/playground/regression/dataset/AUTO_MPG') + const card = page.locator('.card', { has: page.getByRole('heading', { name: 'Diseño de capas' }) }) + const graph = card.locator('#vis-network canvas') + await expect(graph).toBeVisible() + expect((await graph.boundingBox())?.height).toBe(250) + + await card.getByRole('button', { name: 'Maximizar' }).click() + const viewport = page.viewportSize()! + await expect.poll(() => card.boundingBox()).toEqual({ x: 0, y: 0, width: viewport.width, height: viewport.height }) + // El grafo crece con la tarjeta + await expect.poll(async () => (await graph.boundingBox())?.height ?? 0).toBeGreaterThan(400) + + await page.keyboard.press('Escape') + await expect(card.getByRole('button', { name: 'Maximizar' })).toBeVisible() + await expect.poll(async () => (await graph.boundingBox())?.height).toBe(250) +}) + +test('la revisión de un modelo de regresión enseña el análisis de su conjunto de datos', async ({ page }) => { + await page.goto('/playground/regression/model/AUTO_MPG') + await page.getByTestId('Test-ModelReviewDataset-AnalysisTab').click() + await expect(page.getByTestId('Test-AnalyzeTile-rows')).toContainText('396') + await expect(page.getByTestId('Test-AnalyzeTargetCard')).toContainText('mpg') + await expect(page.getByTestId('Test-AnalyzeWarningsCard')).toBeVisible() + await expect(page.getByTestId('Test-AnalyzeEssentialsLink')).toHaveAttribute('href', '/analyze?dataset=auto-mpg') + // La tarjeta del gráfico de dispersión ya no está: la dispersión va en el análisis + await expect(page.getByRole('heading', { name: 'Gráfico de dispersión' })).toHaveCount(0) +}) + +test('la guía del modelo CAR solo empieza con su botón y explica la página paso a paso en voz alta', async ({ page }) => { + // Lo que se leería en voz alta + await page.addInitScript(() => { + const spoken: string[] = [] + Object.assign(window, { spoken }) + window.speechSynthesis.speak = (utterance) => { spoken.push(utterance.text) } + }) + await page.goto('/playground/tabular-classification/model/CAR') + const button = page.getByTestId('Test-GuideButton') + await expect(button).toBeVisible() + // Encima de "Resumen del modelo" y sin arrancar sola + const summary = page.locator('[data-guide="model-summary"]') + expect((await button.boundingBox())!.y).toBeLessThan((await summary.boundingBox())!.y) + const tooltip = page.getByTestId('Test-GuideTooltip') + await page.waitForTimeout(1500) + await expect(tooltip).toHaveCount(0) + + await button.click() + await expect(tooltip).toContainText('Paso 1 de 18') + await expect(tooltip).toContainText('Clasificación de coches') + const spoken = () => page.evaluate(() => (window as unknown as { spoken: string[] }).spoken.join(' ')) + await expect.poll(spoken).toContain('Clasificación de coches.') + + // Paso a paso hasta la seguridad, que se señala en la página + for (let step = 2; step <= 13; step++) { + await tooltip.getByRole('button', { name: 'Siguiente' }).click() + await expect(tooltip).toContainText(`Paso ${step} de 18`) + } + await expect(tooltip).toContainText('Seguridad') + await expect(page.locator('[data-guide="field-Safety"]')).toBeInViewport() + await expect.poll(spoken).toContain('con seguridad baja, el coche siempre es inaceptable.') + + await page.keyboard.press('Escape') + await expect(tooltip).toHaveCount(0) +}) + +// Una guía de cada tarea, entera, en la página de un modelo y en la de entrenar: cada paso encuentra su elemento (si no, +// se saltaría y el contador daría un salto). Los modelos de detección y MobileNet se descargan de internet: sus guías +// las prueban modelReviewGuide.test.ts +const GUIDES = [ + { path: '/playground/tabular-classification/model/LYMPHOGRAPHY', ready: '[data-guide="form"]' }, + { path: '/playground/regression/model/AUTO_MPG', ready: '[data-guide="field-weight"]' }, + { path: '/playground/image-classification/model/IMAGE-MNIST', ready: '[data-guide="model-summary"]' }, + { path: '/playground/time-series/model/AIRLINE-PASSENGERS', ready: '[data-guide="future"]' }, + { path: '/playground/tabular-classification/dataset/IRIS', ready: '[data-guide="hp-learning-rate"]' }, + { path: '/playground/regression/dataset/AUTO_MPG', ready: '[data-guide="hp-learning-rate"]' }, + { path: '/playground/image-classification/dataset/IMAGE-MNIST', ready: '[data-guide="layers"]' }, + { path: '/playground/time-series/dataset/MELBOURNE-TEMPERATURES', ready: '[data-guide="windows"]' }, + { path: '/glossary', ready: '.n4l-glossary-search' }, +] +for (const { path, ready } of GUIDES) { + test(`la guía de ${path.split('/').slice(-2).join('/')} recorre todos sus pasos en orden`, async ({ page }) => { + test.setTimeout(120_000) + await page.addInitScript(() => { window.speechSynthesis.speak = () => {} }) + await page.goto(path) + // Con los datos ya cargados: los pasos de cada atributo dependen de ellos + await expect(page.locator(ready)).toBeVisible({ timeout: 60_000 }) + await page.getByTestId('Test-GuideButton').click() + const tooltip = page.getByTestId('Test-GuideTooltip') + await expect(tooltip).toContainText(/Paso 1 de \d+/) + const total = Number((await tooltip.innerText()).match(/Paso 1 de (\d+)/)![1]) + for (let step = 2; step <= total; step++) { + await tooltip.getByRole('button', { name: 'Siguiente' }).click() + await expect(tooltip).toContainText(`Paso ${step} de ${total}`) + } + await tooltip.getByRole('button', { name: 'Terminar', exact: true }).click() + await expect(tooltip).toHaveCount(0) + await expect(page.getByTestId('Test-GuideButton')).toHaveText('Guía') + }) +} + +test('el pie lleva a la configuración, y el tema elegido allí se mantiene al recargar', async ({ page }) => { + await page.goto('/') + await page.locator('footer').getByRole('link', { name: 'Configuración', exact: true }).click() + await expect(page).toHaveURL(/\/settings$/) + const theme = page.getByTestId('Test-Settings-appearance').getByLabel('Tema') + await theme.selectOption('dark') + await expect(page.locator('html')).toHaveAttribute('data-bs-theme', 'dark') + await page.reload() + await expect(page.locator('html')).toHaveAttribute('data-bs-theme', 'dark') + await expect(page.getByTestId('Test-Settings-appearance').getByLabel('Tema')).toHaveValue('dark') + // La barra de navegación también lo sabe + await page.locator('.n4l-navbar').getByRole('button', { name: 'Tema' }).click() + await expect(page.locator('.n4l-navbar .dropdown-item.active')).toContainText('Oscuro') +}) + +test('el modelo CAR enseña el análisis de su conjunto de datos', async ({ page }) => { + await page.goto('/playground/tabular-classification/model/CAR') + await page.getByTestId('Test-ModelReviewDataset-AnalysisTab').click() + await expect(page.getByTestId('Test-AnalyzeTile-rows')).toContainText('1728') + // Clasificación: el reparto de las clases y los avisos (las clases de car.csv están muy desequilibradas) + await expect(page.getByTestId('Test-AnalyzeTargetCard')).toBeVisible() + await expect(page.getByTestId('Test-AnalyzeWarningsCard')).toBeVisible() + await expect(page.getByTestId('Test-AnalyzeEssentialsLink')).toHaveAttribute('href', '/analyze?dataset=car') +}) + +test('la 404 tiene de fondo una red neuronal, que se quita al volver al inicio', async ({ page }) => { + await page.goto('/esta-ruta-no-existe') + await expect(page).toHaveURL(/\/404$/) + const network = page.getByTestId('Test-NotFoundNetwork') + await expect(network).toBeAttached() + // Ocupa todo el fondo de la página, detrás del contenido (que sigue pudiéndose pulsar) + const [canvasBox, pageBox] = await Promise.all([network.boundingBox(), page.getByTestId('Test-NotFoundPage').boundingBox()]) + expect(canvasBox).toEqual(pageBox) + await page.mouse.move(200, 300) + await page.getByRole('link', { name: 'Volver al inicio' }).click() + await expect(page.getByTestId('Test-InitialMenu-LinearRegression')).toBeVisible() + await expect(network).not.toBeAttached() +}) + +test('el aviso de cookies explica qué se mide, rechazar es tan fácil como aceptar y sin aceptar no se carga Google Analytics', async ({ page }) => { + // Sin la decisión que ponen las pruebas; lo que vaya a Google se intercepta: nada sale de la prueba + await page.context().clearCookies() + const google: string[] = [] + await page.route(/googletagmanager\.com|google-analytics\.com/, (route) => { + google.push(route.request().url()) + return route.fulfill({ status: 204, body: '' }) + }) + await page.goto('/playground/tabular-classification/model/CAR') + const banner = page.getByTestId('Test-CookiesBanner') + await expect(banner).toBeVisible() + await banner.getByText('Qué se mide y qué no').click() + await expect(banner.getByTestId('Test-AnalyticsDisclosure')).toContainText('Nunca se envía') + const [reject, accept] = await Promise.all([page.getByTestId('Test-CookiesReject').boundingBox(), page.getByTestId('Test-CookiesAccept').boundingBox()]) + expect(reject!.width).toBe(accept!.width) + expect(reject!.height).toBe(accept!.height) + expect(google).toEqual([]) + + await page.getByTestId('Test-CookiesAccept').click() + await expect(banner).toBeHidden() + await expect.poll(() => google.some((url) => url.includes('googletagmanager.com/gtag/js'))).toBe(true) + // La página en la que se aceptó queda registrada, con su contexto y sin publicidad + const dataLayer = await page.evaluate(() => (window as unknown as { dataLayer: unknown[][] }).dataLayer.map((args) => Array.from(args))) + expect(dataLayer).toContainEqual(['consent', 'default', expect.objectContaining({ ad_storage: 'denied', analytics_storage: 'granted' })]) + expect(dataLayer).toContainEqual(['event', 'page_view', expect.objectContaining({ page_type: 'playground', task: 'tabular-classification', mode: 'pretrained', item: 'CAR' })]) +}) + +test('el paso a paso enseña un ejemplo hacia delante y hacia atrás, y con más ejemplos la pérdida baja', async ({ page }) => { + // Oculto por defecto: se activa en /settings + await page.goto('/playground/tabular-classification/dataset/IRIS') + await expect(page.getByTestId('Test-TrainButton')).toBeVisible() + await expect(page.getByTestId('Test-StepByStep')).toHaveCount(0) + await page.goto('/settings#learning') + await page.getByTestId('Test-Settings-learning').getByRole('checkbox').check() + await page.goto('/playground/tabular-classification/dataset/IRIS') + const card = page.getByTestId('Test-StepByStep') + const phase = card.getByTestId('Test-StepByStep-Phase') + await expect(phase).toHaveText('La entrada') + // 4 + 10 + 10 + 3 neuronas: entrada, tres capas hacia delante, error, tres hacia atrás y actualización + const titles = [await phase.innerText()] + for (let i = 0; i < 8; i++) { + await card.getByTestId('Test-StepByStep-Next').click() + titles.push(await phase.innerText()) + } + expect(titles).toEqual(['La entrada', 'Hacia delante: capa 1', 'Hacia delante: capa 2', 'Hacia delante: capa 3', 'El error', + 'Hacia atrás: capa 3', 'Hacia atrás: capa 2', 'Hacia atrás: capa 1', 'Actualizar los pesos']) + // En la actualización, cuánto cambian el sesgo y el peso que más se mueve + await expect(card.getByTestId('Test-StepByStep-Formula')).toContainText('El peso que más cambia') + for (let i = 0; i < 5; i++) await card.getByTestId('Test-StepByStep-Ten').click() + const history = await card.getByTestId('Test-StepByStep-History').innerText() + const [, first, last] = history.match(/de ([\d,]+) a ([\d,]+)/)!.map((value) => Number(value.replace(',', '.'))) + expect(last).toBeLessThan(first) + + // CAR, con su red por defecto, es demasiado grande para seguirla + await page.goto('/playground/tabular-classification/dataset/CAR') + await expect(page.getByTestId('Test-StepByStep-TooBig')).toContainText('234 neuronas') + + // En la página de un modelo ya entrenado, con sus pesos: IRIS (4 + 10 + 3) cabe; WINE (11 + 128 + 64 + 32 + 1) no + await page.goto('/playground/tabular-classification/model/IRIS') + const model = page.getByTestId('Test-StepByStep') + await expect(model).toContainText('Así calcula este modelo ya entrenado su respuesta') + for (let i = 0; i < 3; i++) await model.getByTestId('Test-StepByStep-Next').click() + await expect(model.getByTestId('Test-StepByStep-Phase')).toHaveText('El error') + await page.goto('/playground/regression/model/WINE') + await expect(page.getByTestId('Test-StepByStep-TooBig')).toContainText('236 neuronas') +}) + +test('un conjunto de datos propio se prepara en tres pasos y después se puede entrenar', async ({ page }) => { + const upload = (file: string) => page.locator('input[type=file]:not([data-testid="Test-SessionImport"])').first() + .setInputFiles(path.join(__dirname, '..', 'public', file)) + const ok = async () => { + const confirm = page.locator('.swal2-confirm') + if (await confirm.isVisible().catch(() => false)) await confirm.click() + } + + // Clasificación: la última columna es la clase; antes de procesar no se puede entrenar + await page.goto('/playground/tabular-classification/dataset/UPLOAD') + await upload('n4l/car.n4l/data/car.csv') + await ok() + const form = page.getByTestId('Test-DatasetProcess-Form') + await expect(page.getByTestId('Test-DatasetProcess-TargetInfo')).toContainText('«Result» tiene 4 clases') + await expect(page.getByTestId('Test-DatasetProcess-Summary')).toContainText('Entrarán 6 columnas') + await form.getByTestId('Test-DatasetProcess-Column-Doors').getByRole('checkbox').uncheck() + await expect(page.getByTestId('Test-DatasetProcess-Summary')).toContainText('Entrarán 5 columnas') + await form.getByTestId('Test-DatasetProcess-Submit').click() + await ok() + await expect(page.getByTestId('Test-DatasetProcess-Done')).toContainText('1728 filas, 5 columnas de entrada') + await expect(page.getByTestId('Test-TrainButton')).toBeEnabled() + + // Regresión: un objetivo de texto no se puede predecir; hasta procesar, no se entrena + await page.goto('/playground/regression/dataset/UPLOAD') + await upload('n4l/auto-mpg.n4l/data/auto-mpg.csv') + await ok() + await expect(page.getByTestId('Test-TrainButton')).toBeDisabled() + await expect(page.getByTestId('Test-DatasetProcess-TargetInfo')).toContainText('«mpg» va de') + await page.getByTestId('Test-DatasetProcess-Submit').click() + await ok() + await expect(page.getByTestId('Test-DatasetProcess-Done')).toContainText('396 filas, 6 columnas de entrada y «mpg»') + await expect(page.getByTestId('Test-TrainButton')).toBeEnabled() + // El conjunto se actualiza en su sitio: no sale repetido en el selector de fichero, y se ve lo que recibe la red + await expect(page.locator('#regression-dataset-file')).toHaveCount(0) + const views = page.locator('[data-guide="dataset"]') + await views.getByTestId('Test-DatasetViews').getByText('Escalado (entrada de la red)').click() + await expect(views.getByTestId('Test-DatasetViews-Help')).toContainText('exactamente lo que recibe la red') +}) + +test('con el ahorro de datos activado, se pregunta antes de descargar un modelo grande (y solo la primera vez)', async ({ page }) => { + // Lo que diría Chrome con "Ahorro de datos" (Network Information API) + await page.addInitScript(() => { + Object.defineProperty(navigator, 'connection', { configurable: true, get: () => ({ saveData: true, effectiveType: '4g' }) }) + }) + const modelRequests: string[] = [] + page.on('request', (request) => { if (request.url().includes('mnist.n4l/models/cnn/model.json')) modelRequests.push(request.url()) }) + + await page.goto('/playground/image-classification/model/IMAGE-MNIST') + const consent = page.getByTestId('Test-DownloadConsent') + await expect(consent).toContainText('Este modelo descarga unos 4,6 MB') + await expect(consent).toContainText('ahorro de datos') + await page.waitForTimeout(1000) + expect(modelRequests).toEqual([]) + + await consent.getByTestId('Test-DownloadConsent-Accept').click() + await expect(page.getByTestId('Test-LoadTestDataset')).toBeEnabled({ timeout: 60_000 }) + expect(modelRequests.length).toBeGreaterThan(0) + + await page.reload() + await expect(page.getByTestId('Test-LoadTestDataset')).toBeEnabled({ timeout: 60_000 }) + await expect(consent).toHaveCount(0) +}) + +test('MNIST: cada imagen de ejemplo, un dígito escrito con una fuente, se clasifica como ese dígito', async ({ page }) => { + await page.goto('/playground/image-classification/model/IMAGE-MNIST') + await expect(page.getByTestId('Test-LoadTestDataset')).toBeEnabled({ timeout: 60_000 }) + for (let digit = 0; digit < 10; digit++) { + // El botón de cada ejemplo dice qué es, lo mismo que ve quien mira la imagen + await page.getByRole('button', { name: `Clasificar el ejemplo ${digit + 1}: ${digit}`, exact: true }).click() + await expect(page.getByText(new RegExp(`Clase predicha\\s*${digit}`))).toBeVisible({ timeout: 30_000 }) + } +}) + +test('CIFAR-10: fotos en color de 32×32, sin lienzo; cada ejemplo se clasifica como su clase y se ven las de prueba', async ({ page }) => { + await page.goto('/playground/image-classification/model/IMAGE-CIFAR10') + await expect(page.getByTestId('Test-LoadTestDataset')).toBeEnabled({ timeout: 60_000 }) + // En color no se dibuja: se sube una foto + await expect(page.locator('[data-guide="draw"]')).toHaveCount(0) + await expect(page.locator('[data-guide="upload"]')).toBeVisible() + const classes = ['avión', 'automóvil', 'pájaro', 'gato', 'ciervo', 'perro', 'rana', 'caballo', 'barco', 'camión'] + for (const [index, name] of classes.entries()) { + await page.getByRole('button', { name: `Clasificar el ejemplo ${index + 1}: ${name}`, exact: true }).click() + await expect(page.getByText(new RegExp(`Clase predicha\\s*${name}`))).toBeVisible({ timeout: 30_000 }) + } + // Una de las de prueba, con su clase real + await page.getByTestId('Test-LoadTestDataset').click() + const testImages = page.locator('[data-guide="test-images"]') + await testImages.locator('.n4l-instance-select, button, input').first().click({ timeout: 60_000 }) + await page.getByRole('listbox').getByRole('option').first().click() + await expect(page.locator('[data-guide="result"]')).toContainText('Clase real', { timeout: 30_000 }) +}) + +test('KMNIST enseña cada carácter como se escribe hoy junto a sus formas antiguas, y cualquiera se clasifica', async ({ page }) => { + await page.goto('/playground/image-classification/model/IMAGE-KMNIST') + const su = page.getByTestId('Test-CharacterExamples').getByRole('group', { name: 'す (su)' }) + await expect(su).toContainText('Hoy') + await expect(su).toContainText('Antes') + await expect(su.getByRole('button', { name: /^Clasificar す antiguo, que viene de/ })).toHaveCount(3) + // La de hoy y una antigua que no se le parece: la red aprendió las dos + await expect(su.getByRole('button', { name: 'Clasificar す como se escribe hoy' })).toBeEnabled({ timeout: 60_000 }) + await su.getByRole('button', { name: 'Clasificar す como se escribe hoy' }).click() + await expect(page.getByText(/Clase predicha\s*す/)).toBeVisible({ timeout: 30_000 }) + // は escrito a partir de 者: no se parece en nada al de hoy + await page.getByTestId('Test-CharacterExamples').getByRole('button', { name: 'Clasificar は antiguo, que viene de 者' }).click() + await expect(page.getByText(/Clase predicha\s*は/)).toBeVisible({ timeout: 30_000 }) + + // En la información del conjunto: los diez, con su lectura, el kanji del que vienen y sus formas antiguas + await page.goto('/datasets?task=image-classification') + await page.getByTestId('Test-DatasetInfo-IMAGE-KMNIST').click() + const forms = page.getByRole('dialog').getByTestId('Test-CharacterForms') + await expect(forms.getByRole('row')).toHaveCount(11) + // は se escribía de otras 11 formas, cada una con su kanji + await expect(forms.getByRole('row').filter({ hasText: 'ha, 波' }).getByRole('img')).toHaveCount(11) + await expect(forms.getByRole('img', { name: 'は antiguo, que viene de 八' })).toBeVisible() +}) + +test('«Empieza aquí»: los pasos se marcan solos al hacerlos y se avisa del siguiente', async ({ page }) => { + await page.goto('/') + await page.getByTestId('Test-StartHere').getByRole('link', { name: 'Empieza aquí' }).click() + await expect(page.getByTestId('Test-Learn-Progress')).toHaveText('0 de 10 pasos hechos') + await expect(page.getByTestId('Test-Learn-Challenges-Progress')).toHaveText('0 de 5 retos superados') + + // El primero: entrenar una red en el laboratorio + await page.getByTestId('Test-Learn-Go-lab').click() + await expect(page).toHaveURL(/\/lab$/) + await page.getByTestId('Test-Lab-Run').click() + const toast = page.getByTestId('Test-LearningToast') + await expect(toast).toContainText('Paso 1 de 10 hecho') + await expect(toast).toContainText('Siguiente: Las palabras clave') + await page.getByTestId('Test-Lab-Run').click() + + await toast.getByRole('link').click() + await expect(page.getByTestId('Test-Learn-Progress')).toHaveText('1 de 10 pasos hechos') + await expect(page.getByTestId('Test-Learn-Step-lab')).toHaveAttribute('data-done', 'true') + await page.reload() + await expect(page.getByTestId('Test-Learn-Progress')).toHaveText('1 de 10 pasos hechos') +}) + +test('un ejercicio se comparte con un enlace (y su QR): quien lo abre tiene la misma red e hiperparámetros', async ({ page, context }) => { + await page.goto('/playground/tabular-classification/dataset/IRIS') + await expect(page.getByTestId('Test-TrainButton')).toBeVisible({ timeout: 60_000 }) + await page.getByRole('spinbutton', { name: 'N. épocas' }).fill('7') + await page.locator('[data-guide="hp-learning-rate"] select').selectOption('0.1') + + await page.getByTestId('Test-SessionShare').click() + const modal = page.getByTestId('Test-SessionShare-Modal') + await expect(modal.getByTestId('Test-SessionShare-QR')).toBeVisible() + const link = await modal.getByTestId('Test-SessionShare-Link').inputValue() + expect(link).toMatch(/\/playground\/tabular-classification\/dataset\/IRIS#n4z=/) + + const other = await context.newPage() + await other.goto(link) + await expect(other.locator('.swal2-popup')).toContainText('Configuración importada', { timeout: 60_000 }) + await expect(other.getByRole('spinbutton', { name: 'N. épocas' })).toHaveValue('7') + await expect(other.locator('[data-guide="hp-learning-rate"] select')).toHaveValue('0.1') + // Se quita de la dirección: al recargar no se vuelve a aplicar + await expect(other).toHaveURL(/\/IRIS$/) +}) + +test('al cambiar de página se empieza arriba (con el foco en el título), atrás vuelve a donde se estaba y un enlace a una sección lleva a ella', async ({ page }) => { + const scrollY = () => page.evaluate(() => window.scrollY) + await page.goto('/glossary') + await expect(page.locator('main h1')).toBeVisible() + await page.evaluate(() => window.scrollTo({ top: 2000, behavior: 'instant' })) + await expect.poll(scrollY).toBeGreaterThan(1500) + const position = await scrollY() + + await page.locator('.n4l-navbar').getByRole('link', { name: 'Manual', exact: true }).click() + await expect(page).toHaveURL(/\/manual\/?$/) + await expect.poll(scrollY).toBe(0) + await expect(page.locator('main h1').first()).toBeFocused() + + await page.goBack() + await expect(page).toHaveURL(/\/glossary$/) + await expect.poll(async () => Math.abs((await scrollY()) - position)).toBeLessThan(5) + + await page.goto('/settings') + await page.getByRole('tab', { name: 'Privacidad y cookies' }).click() + await expect(page).toHaveURL(/\/settings#privacy$/) + await page.evaluate(() => window.scrollTo({ top: document.body.scrollHeight, behavior: 'instant' })) + await page.getByRole('link', { name: 'Más información sobre las cookies' }).click() + await expect(page).toHaveURL(/\/terms-and-conditions#cookies$/) + // La sección, arriba y debajo de la barra de navegación + await expect.poll(async () => page.locator('#cookies').evaluate((element) => Math.round(element.getBoundingClientRect().top))).toBeGreaterThan(0) + await expect.poll(async () => page.locator('#cookies').evaluate((element) => Math.round(element.getBoundingClientRect().top))).toBeLessThan(200) +}) + +test('desde /datasets se entrena con un conjunto de práctica: el entrenador lo carga como si se hubiera subido', async ({ page }) => { + await page.goto('/datasets') + // La pestaña va en la dirección: se puede enlazar y se mantiene al recargar + await page.getByRole('tab', { name: 'Regresión' }).click() + await expect(page).toHaveURL(/\/datasets\?task=regression$/) + await page.reload() + await expect(page.getByRole('tab', { name: 'Regresión' })).toHaveAttribute('aria-selected', 'true') + + await page.getByRole('tab', { name: 'Clasificación tabular' }).click() + await page.getByTestId('Test-DatasetTrain-n4l/wine.n4l/data/wine.csv').click() + await expect(page).toHaveURL(/\/playground\/tabular-classification\/dataset\/UPLOAD$/) + // El aviso de «subido» se cierra solo: lo que importa es que el formulario ya tiene el CSV + await expect(page.getByTestId('Test-DatasetProcess-TargetInfo')).toContainText('«Target» tiene 3 clases', { timeout: 30_000 }) +}) + +test('sin conexión se sigue usando lo que ya se había abierto (service worker)', async ({ page, context }) => { + test.setTimeout(180_000) + await page.goto('/playground/tabular-classification/dataset/IRIS') + await expect(page.getByTestId('Test-TrainButton')).toBeVisible({ timeout: 60_000 }) + // Con el service worker ya activo, se recarga para que todo pase por él (y se guarde) + await page.evaluate(async () => { await navigator.serviceWorker.ready }) + await page.reload() + await expect(page.getByTestId('Test-TrainButton')).toBeVisible({ timeout: 60_000 }) + await page.waitForTimeout(2000) + + // Al perder la conexión se avisa + await context.setOffline(true) + await expect(page.getByTestId('Test-OfflineBar')).toBeVisible() + // Y la página se vuelve a abrir sin conexión, con sus datos + await page.reload() + await expect(page.getByTestId('Test-TrainButton')).toBeVisible({ timeout: 60_000 }) + await expect(page.locator('[data-guide="dataset"]')).toContainText('sepal_length') + await context.setOffline(false) +}) diff --git a/e2e/series.spec.ts b/e2e/series.spec.ts new file mode 100644 index 0000000..e6b85f4 --- /dev/null +++ b/e2e/series.spec.ts @@ -0,0 +1,112 @@ +import { test, expect } from './fixtures' +import { axeViolations, expandChartData } from './axe' + +// Series temporales: predecir los siguientes valores con los anteriores, entrenando la red en el navegador + +test('desde la portada se entrena con los pasajeros de avión: la red mejora las predicciones sencillas y predice 1961', async ({ page }) => { + await page.goto('/') + await page.getByTestId('Test-InitialMenu-TimeSeries').click() + await page.getByTestId('Test-GoTo-SelectDataset-TimeSeries').click() + await expect(page).toHaveURL(/\/select-dataset\/time-series$/) + await page.getByTestId('Test-MenuSelectDataset-Open-AIRLINE-PASSENGERS').click() + + await expect(page.getByTestId('Test-TimeSeries-Summary')).toContainText('144 valores, de 1949-01 a 1960-12, un valor al mes') + // La prueba es lo último de la serie, sin barajar + await expect(page.getByTestId('Test-TimeSeries-Split')).toContainText('Prueba: 1958-08 – 1960-12 (29 valores)') + await expect(page.getByTestId('Test-TimeSeries-Windows').getByRole('row').nth(1)).toContainText('1951-01') + + await page.locator('#time-series-epochs').fill('60') + await page.getByTestId('Test-TrainButton').click() + await expect(page.getByTestId('Test-TimeSeries-Model-1')).toBeVisible({ timeout: 60_000 }) + const verdict = page.getByTestId('Test-TimeSeries-Verdict') + await expect(verdict).toContainText('menos que la mejor predicción sencilla') + await expect(page.getByTestId('Test-TimeSeries-Errors-Seasonal')).toContainText('Estacional: el de hace 12 valores') + await expect(page.getByTestId('Test-TimeSeries-Future').getByRole('row').nth(1)).toContainText('1961-01') + await expect(page.getByTestId('Test-TimeSeries-ForecastChart').locator('canvas')).toBeVisible() + + // Seguida: desde el final del entrenamiento, con lo ya predicho + await page.locator('label[for="time-series-mode-recursive"]').click() + await expect(page.getByTestId('Test-TimeSeries-Errors-Naive')).toContainText('Ingenua: el último conocido, repetido') + + // El modelo se guarda en el navegador + await page.reload() + await expect(page.getByTestId('Test-TimeSeries-Model-1')).toBeVisible({ timeout: 30_000 }) + await expect(verdict).toBeVisible() +}) + +test('desde la portada, el modelo ya entrenado de las manchas solares: su descripción, cómo predice la prueba y los meses siguientes', async ({ page }) => { + await page.goto('/') + await page.getByTestId('Test-InitialMenu-TimeSeries').click() + await page.getByTestId('Test-GoTo-SelectModel-TimeSeries').click() + await expect(page).toHaveURL(/\/select-model\/time-series$/) + await expect(page.getByTestId('Test-MenuSelectModel-Option-SUNSPOTS')).toContainText('2820 meses, objetivo: Sunspots') + // Su descripción, como la de los demás modelos: la del paquete, con sus métricas + await page.getByTestId('Test-MenuSelectModel-Option-SUNSPOTS').getByRole('button', { name: /^Descripción/ }).click() + const modal = page.getByRole('dialog') + await expect(modal).toContainText('mínimo de Dalton') + await modal.getByRole('link', { name: 'Abrir' }).click() + await expect(page).toHaveURL(/\/playground\/time-series\/model\/SUNSPOTS$/) + // Como en las demás tareas: su ficha, con cómo predice lo que no vio + await expect(page.getByTestId('Test-TimeSeries-TestMetrics')).toContainText('se equivoca de media en 13,25 a un paso; repitiendo el valor anterior, en 14,84') + await page.getByTestId('Test-ModelReviewDataset-WindowsTab').click() + await expect(page.getByTestId('Test-TimeSeries-Preparation')).toContainText('Se entrenó con la serie hasta 1936-12') + // Predecir un valor: el primero de la prueba, con los 24 meses anteriores + await expect(page.getByTestId('Test-TimeSeries-PredictForm').getByRole('spinbutton')).toHaveCount(24) + await page.getByTestId('Test-TimeSeries-PredictButton').click() + await expect(page.getByTestId('Test-TimeSeries-PredictResult')).toContainText('Valor predicho de Sunspots (1937-01)') + await expect(page.getByTestId('Test-TimeSeries-PredictActual')).toContainText('Valor real') + // A un paso mejora un poco la ingenua; seguida, se va alejando (dos años no bastan para un ciclo de once) + await expect(page.getByTestId('Test-TimeSeries-Verdict')).toContainText('menos que la mejor predicción sencilla', { timeout: 30_000 }) + await expect(page.getByTestId('Test-TimeSeries-Errors-Seasonal')).toHaveCount(0) + await expect(page.getByTestId('Test-TimeSeries-Future').getByRole('row').nth(1)).toContainText('1984-01') + // En la descripción, sus métricas del manifiesto + await page.getByTestId('Test-N4LDescription').getByText('Modelo ya entrenado').click() + await expect(page.getByTestId('Test-N4LDescription')).toContainText('se equivoca 13,3 manchas de media a un paso') + + await page.getByTestId('Test-TimeSeries-TrainYours').click() + await expect(page).toHaveURL(/\/playground\/time-series\/dataset\/SUNSPOTS$/) +}) + +test('una serie propia (cada día, con fechas) se entrena con una capa LSTM y se predicen los días siguientes', async ({ page }) => { + // 140 días con un patrón semanal y algo de tendencia + const start = Date.UTC(2024, 0, 1) + const rows = Array.from({ length: 140 }, (_value, i) => { + const date = new Date(start + i * 86_400_000).toISOString().slice(0, 10) + return `${date},${(50 + 10 * Math.sin((2 * Math.PI * i) / 7) + i / 10).toFixed(2)}` + }) + await page.goto('/playground/time-series/dataset/UPLOAD') + await page.locator('input#drop-zone-time-series').setInputFiles({ name: 'ventas.csv', mimeType: 'text/csv', buffer: Buffer.from(['Fecha,Ventas', ...rows].join('\n')) }) + await expect(page.getByLabel('Columna con los valores')).toHaveValue('Ventas') + await expect(page.getByLabel('Columna con la fecha')).toHaveValue('Fecha') + await expect(page.getByTestId('Test-TimeSeries-Summary')).toContainText('140 valores, de 2024-01-01 a 2024-05-19, un valor al día') + // Una semana: la ventana y la estación por defecto + await expect(page.getByLabel('Ventana (valores anteriores)')).toHaveValue('7') + await expect(page.getByLabel('Estación (valores)')).toHaveValue('7') + + await page.getByRole('button', { name: /Capa 1/ }).click() + await page.locator('#time-series-layer-class-0').selectOption('lstm') + await expect(page.getByRole('button', { name: /Capa 1/ })).toContainText('LSTM') + await page.locator('#time-series-epochs').fill('5') + await page.getByTestId('Test-TrainButton').click() + await expect(page.getByTestId('Test-TimeSeries-Model-1')).toContainText('LSTM', { timeout: 60_000 }) + await expect(page.getByTestId('Test-TimeSeries-Errors-Model')).toBeVisible() + await expect(page.getByTestId('Test-TimeSeries-Future').getByRole('row').nth(1)).toContainText('2024-05-20') +}) + +test('los resultados de una serie no tienen problemas de accesibilidad (temas claro y oscuro)', async ({ page }) => { + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }) + await page.goto('/playground/time-series/dataset/SUNSPOTS') + await page.locator('#time-series-epochs').fill('2') + await page.getByTestId('Test-TrainButton').click() + await expect(page.getByTestId('Test-TimeSeries-Verdict')).toBeVisible({ timeout: 60_000 }) + // El aviso de «modelo entrenado» se cierra solo + await expect(page.locator('.swal2-container')).toHaveCount(0, { timeout: 10_000 }) + // El visor de tfjs-vis (de la librería, no de la aplicación) se aparta, como en los demás entrenadores + await page.locator('#tfjs-visor-container').getByRole('button', { name: 'Hide' }).click() + // También con los datos de las gráficas a la vista + await expandChartData(page) + await expect(page.getByTestId('Test-ChartData').getByRole('table').first()).toBeVisible() + expect(await axeViolations(page), `tema ${colorScheme === 'light' ? 'claro' : 'oscuro'}`).toEqual([]) + } +}) diff --git a/e2e/sin-conexion.spec.ts b/e2e/sin-conexion.spec.ts new file mode 100644 index 0000000..091f08c --- /dev/null +++ b/e2e/sin-conexion.spec.ts @@ -0,0 +1,21 @@ +import { test, expect } from './fixtures' + +// El service worker de la versión publicada (public/sw.js, docs/offline.md): los e2e van contra `vite preview`, que la sirve + +test('los modelos preentrenados se guardan en su propia caché del navegador (n4l-models-v1), no con la aplicación', async ({ page }) => { + await page.goto('/') + // Toma el control de la página en cuanto se activa (clients.claim) + await page.waitForFunction(() => navigator.serviceWorker?.controller !== null && navigator.serviceWorker?.controller !== undefined, null, { timeout: 30_000 }) + const model = '/models/02-object-detection/face-api-js/v1.7.14/tiny_face_detector_model-weights_manifest.json' + const where = await page.evaluate(async (path) => { + await (await fetch(path)).text() + // Los modelos de la aplicación se guardan al recibirlos: se espera un momento + for (let attempt = 0; attempt < 50; attempt++) { + const inModels = await (await caches.open('n4l-models-v1')).match(path) + if (inModels !== undefined) return { models: true, runtime: (await (await caches.open('n4l-runtime-v1')).match(path)) !== undefined } + await new Promise((resolve) => setTimeout(resolve, 100)) + } + return { models: false, runtime: false } + }, model) + expect(where).toEqual({ models: true, runtime: false }) +}) diff --git a/e2e/teclado.spec.ts b/e2e/teclado.spec.ts new file mode 100644 index 0000000..d83ee7f --- /dev/null +++ b/e2e/teclado.spec.ts @@ -0,0 +1,314 @@ +import path from 'node:path' +import type { Locator, Page } from '@playwright/test' +import { test, expect } from './fixtures' + +// Sin ratón (WCAG 2.1.1): los flujos principales solo con el tabulador, Enter, Espacio y las flechas, como quien usa el +// teclado, un conmutador o un lector de pantalla. Si algo no se puede alcanzar o activar así, la prueba falla. + +/** El tabulador hasta llegar a `target` (o a algo de dentro); falla si no se llega en `max` pulsaciones */ +async function tabTo(page: Page, target: Locator, max = 200) { + await expect(target).toBeVisible() + for (let index = 0; index < max; index++) { + await page.keyboard.press('Tab') + const isFocused = await target.evaluate((element) => element.contains(document.activeElement)).catch(() => false) + if (isFocused) return + } + throw new Error(`con el tabulador no se llega a ${target}`) +} + +/** Lo que tiene el foco: su etiqueta y su texto, para los mensajes de las pruebas */ +const focused = (page: Page) => page.evaluate(() => { + const element = document.activeElement + return element === null ? '' : `${element.tagName.toLowerCase()} ${element.textContent?.trim().slice(0, 40) ?? ''}` +}) + +test('«Saltar al contenido» es lo primero al tabular y lleva a la página sin pasar por el menú', async ({ page }) => { + await page.goto('/glossary') + await expect(page.locator('main h1')).toBeVisible() + await page.keyboard.press('Tab') + const skip = page.getByTestId('Test-SkipLink') + await expect(skip).toBeFocused() + await expect(skip).toHaveText('Saltar al contenido') + // Oculto hasta que recibe el foco; entonces se ve + expect((await skip.boundingBox())?.width ?? 0).toBeGreaterThan(50) + await page.keyboard.press('Enter') + await expect(page.locator('main')).toBeFocused() + // La dirección no cambia (no es otra navegación) y lo siguiente ya es de la página, no de la barra de navegación + await expect(page).toHaveURL(/\/glossary$/) + await page.keyboard.press('Tab') + expect(await page.evaluate(() => document.querySelector('main')?.contains(document.activeElement)), await focused(page)).toBe(true) +}) + +test('cada página tiene su título: lo que se ve en la pestaña y lo primero que se anuncia', async ({ page }) => { + await page.goto('/playground/time-series/dataset/AIRLINE-PASSENGERS') + await expect(page).toHaveTitle('Pasajeros de avión - Entrenar un modelo - Series temporales - Nets4Learning') + await page.locator('.n4l-navbar').getByRole('link', { name: 'Glosario', exact: true }).click() + await expect(page).toHaveTitle('Glosario - Nets4Learning') + await page.goto('/datasets?task=time-series') + await expect(page).toHaveTitle('Conjuntos de datos - Series temporales - Nets4Learning') + await page.goto('/no-existe') + await expect(page).toHaveTitle('Página no encontrada - Nets4Learning') +}) + +test('solo con el teclado: de la portada a entrenar una serie temporal y ver su resultado', async ({ page }) => { + await page.goto('/') + await tabTo(page, page.getByTestId('Test-InitialMenu-TimeSeries')) + await page.keyboard.press('Enter') + await tabTo(page, page.getByTestId('Test-GoTo-SelectDataset-TimeSeries')) + await page.keyboard.press('Enter') + await expect(page).toHaveURL(/\/select-dataset\/time-series$/) + // En la página nueva, el foco empieza en su título + await expect(page.locator('main h1')).toBeFocused() + + await tabTo(page, page.getByTestId('Test-MenuSelectDataset-Open-SUNSPOTS')) + await page.keyboard.press('Enter') + await expect(page).toHaveURL(/\/playground\/time-series\/dataset\/SUNSPOTS$/) + + await tabTo(page, page.locator('#time-series-epochs')) + await page.keyboard.press('ControlOrMeta+A') + await page.keyboard.type('2') + await expect(page.locator('#time-series-epochs')).toHaveValue('2') + await tabTo(page, page.getByTestId('Test-TrainButton')) + await page.keyboard.press('Enter') + await expect(page.getByTestId('Test-TimeSeries-Verdict')).toBeVisible({ timeout: 60_000 }) + // El aviso de «modelo entrenado» no se lleva el foco: sigue donde estaba + await expect(page.getByTestId('Test-TrainButton')).toBeFocused() +}) + +test('solo con el teclado: se añade una capa, se despliega y se borra', async ({ page }) => { + await page.goto('/playground/tabular-classification/dataset/IRIS') + const layers = page.locator('[data-guide="layers"] .accordion-item') + await expect(layers.first()).toBeVisible({ timeout: 30_000 }) + const count = await layers.count() + + await tabTo(page, page.getByRole('button', { name: 'Añadir capa al final' })) + await page.keyboard.press('Enter') + await expect(layers).toHaveCount(count + 1) + + // La nueva va al final + const header = layers.nth(count).locator('.accordion-button') + await tabTo(page, header) + await page.keyboard.press('Enter') + await expect(header).toHaveAttribute('aria-expanded', 'true') + await tabTo(page, layers.nth(count).getByRole('button', { name: /Eliminar capa/ })) + await page.keyboard.press('Space') + await expect(layers).toHaveCount(count) + await expect(page.getByTestId('Test-Announcer')).toContainText('Puedes deshacerlo') + + // Se puede deshacer: vuelve la capa y el foco va a ella + const undo = page.getByTestId('Test-LayerUndo') + await page.keyboard.down('Shift') + for (let index = 0; index < 30 && !(await undo.evaluate((element) => element === document.activeElement)); index++) await page.keyboard.press('Tab') + await page.keyboard.up('Shift') + await expect(undo).toBeFocused() + await page.keyboard.press('Enter') + await expect(layers).toHaveCount(count + 1) + await expect(layers.nth(count).locator('.accordion-button')).toBeFocused() + await expect(page.getByTestId('Test-LayerRemoved')).toHaveCount(0) +}) + +test('solo con el teclado: un modelo ya entrenado clasifica un ejemplo', async ({ page }) => { + await page.goto('/playground/tabular-classification/model/IRIS') + await expect(page.locator('.swal2-popup')).toContainText('Modelo cargado con éxito', { timeout: 30_000 }) + await tabTo(page, page.locator('[data-guide="classify"] button')) + await page.keyboard.press('Enter') + await expect(page.getByText(/Clase predicha/).first()).toBeVisible({ timeout: 30_000 }) +}) + +test('solo con el teclado: se analiza en el AED un conjunto del proyecto', async ({ page }) => { + await page.goto('/analyze') + await tabTo(page, page.locator('#analyze-project-dataset')) + // Con el selector cerrado, la flecha elige la opción siguiente; si se abre la lista, Enter la elige + await page.keyboard.press('ArrowDown') + await page.keyboard.press('Enter') + await expect(page).toHaveURL(/\/analyze\?dataset=/) + await expect(page.getByTestId('Test-AnalyzeInfo')).toBeVisible({ timeout: 30_000 }) + // Mientras cargaba se desactivó: el foco vuelve al selector, no al principio de la página + await expect(page.locator('#analyze-project-dataset')).toBeFocused() +}) + +test('solo con el teclado: se sube un fichero propio al AED', async ({ page }) => { + await page.goto('/analyze') + // La zona de arrastrar y soltar se alcanza con el tabulador y abre el selector de ficheros con Enter + const zone = page.locator('#dataset-upload').locator('..') + await tabTo(page, zone) + const [chooser] = await Promise.all([page.waitForEvent('filechooser'), page.keyboard.press('Enter')]) + await chooser.setFiles(path.join(__dirname, 'files', 'iris.arff')) + await expect(page.getByTestId('Test-AnalyzeInfo')).toContainText('150 filas × 5 columnas') +}) + +test('solo con el teclado: un modal se abre con el foco dentro, no se sale con el tabulador y Escape lo cierra y devuelve el foco', async ({ page }) => { + await page.goto('/select-model/object-detection') + const opener = page.getByTestId('Test-MenuSelectModel-Option-COCO-SSD').getByRole('button', { name: /^Descripción/ }) + await tabTo(page, opener) + await page.keyboard.press('Enter') + const modal = page.getByRole('dialog') + await expect(modal).toBeVisible() + await expect.poll(() => modal.evaluate((element) => element.contains(document.activeElement))).toBe(true) + for (let index = 0; index < 12; index++) { + await page.keyboard.press('Tab') + expect(await modal.evaluate((element) => element.contains(document.activeElement)), await focused(page)).toBe(true) + } + await page.keyboard.press('Escape') + await expect(modal).toHaveCount(0) + await expect(opener).toBeFocused() +}) + +test('solo con el teclado: los desplegables de la barra y de las migas de pan', async ({ page }) => { + await page.goto('/playground/tabular-classification/model/IRIS') + // «Tareas»: Enter lo abre, las flechas recorren sus elementos y Escape lo cierra volviendo al botón + const tasks = page.locator('.n4l-navbar').getByRole('button', { name: 'Tareas' }) + await tabTo(page, tasks) + await page.keyboard.press('Enter') + await expect(tasks).toHaveAttribute('aria-expanded', 'true') + await page.keyboard.press('ArrowDown') + await expect(page.locator('.n4l-navbar .dropdown-menu.show .dropdown-item').first()).toBeFocused() + await page.keyboard.press('Escape') + await expect(tasks).toHaveAttribute('aria-expanded', 'false') + await expect(tasks).toBeFocused() + + // La miga de pan cambia de modelo + const toggle = page.getByTestId('Test-Breadcrumb').locator('.n4l-breadcrumb-toggle') + await tabTo(page, toggle) + await page.keyboard.press('Enter') + const car = page.getByTestId('Test-Breadcrumb').locator('.dropdown-item', { hasText: 'Clasificación de coches' }) + for (let index = 0; index < 10 && !(await car.evaluate((element) => element === document.activeElement)); index++) await page.keyboard.press('ArrowDown') + await expect(car).toBeFocused() + await page.keyboard.press('Enter') + await expect(page).toHaveURL(/\/playground\/tabular-classification\/model\/CAR$/) +}) + +test('solo con el teclado: pestañas con las flechas y páginas de una tabla', async ({ page }) => { + await page.goto('/playground/time-series/model/SUNSPOTS') + const card = page.getByTestId('Test-ModelReviewDataset') + const tabs = card.getByRole('tab') + await expect(tabs.first()).toBeVisible({ timeout: 30_000 }) + // La tabla de los valores, con sus páginas + const pages = card.getByRole('navigation', { name: 'Páginas de la tabla' }) + await tabTo(page, pages.getByRole('button', { name: 'Página siguiente' })) + await page.keyboard.press('Enter') + await expect(pages.locator('[aria-current="page"]')).toContainText('2') + + // Las pestañas: la flecha pasa a la siguiente + await tabs.first().focus() + await page.keyboard.press('ArrowRight') + await expect(tabs.nth(1)).toBeFocused() + await expect(tabs.nth(1)).toHaveAttribute('aria-selected', 'true') +}) + +test('solo con el teclado: el aviso de una red mal montada se arregla con su botón', async ({ page }) => { + await page.goto('/playground/tabular-classification/dataset/IRIS') + const layers = page.locator('[data-guide="layers"]') + await expect(page.getByTestId('Test-TrainButton')).toBeVisible({ timeout: 60_000 }) + const last = await layers.locator('.accordion-button').count() - 1 + await tabTo(page, layers.locator('.accordion-button').nth(last)) + await page.keyboard.press('Enter') + await tabTo(page, page.locator('#formUnitsLayer' + last)) + await page.keyboard.press('ControlOrMeta+A') + await page.keyboard.type('5') + // El lector de pantalla oye el problema al aparecer + await expect(page.getByTestId('Test-Announcer')).toContainText('hay 3 clases') + const fix = page.getByTestId('Test-LayerCheck').getByTestId('Test-LayerCheck-Fix').first() + await page.keyboard.down('Shift') + for (let index = 0; index < 60 && !(await fix.evaluate((element) => element === document.activeElement)); index++) await page.keyboard.press('Tab') + await page.keyboard.up('Shift') + await expect(fix).toBeFocused() + await page.keyboard.press('Enter') + await expect(page.getByTestId('Test-LayerCheck')).toHaveCount(0) + await expect(page.getByTestId('Test-Announcer')).toContainText('Las capas ya no tienen nada que revisar') +}) + +test('solo con el teclado: la guía se abre con el foco dentro, las flechas pasan de paso y Escape la cierra', async ({ page }) => { + await page.addInitScript(() => { + window.speechSynthesis.speak = () => {} + }) + await page.goto('/playground/tabular-classification/model/CAR') + const button = page.getByTestId('Test-GuideButton') + await tabTo(page, button) + await page.keyboard.press('Enter') + const tooltip = page.getByTestId('Test-GuideTooltip') + await expect(tooltip).toContainText('Paso 1 de') + // El foco, en el título del paso; el diálogo se llama como él + await expect(tooltip.getByRole('heading', { level: 2 })).toBeFocused() + await expect(tooltip).toHaveAccessibleName(/Clasificación de coches/) + await expect(page.getByTestId('Test-Announcer')).toContainText('Paso 1 de') + + await page.keyboard.press('ArrowRight') + await expect(tooltip).toContainText('Paso 2 de') + await expect(page.getByTestId('Test-Announcer')).toContainText('Paso 2 de') + await page.keyboard.press('ArrowLeft') + await expect(tooltip).toContainText('Paso 1 de') + + await page.keyboard.press('Escape') + await expect(tooltip).toHaveCount(0) + await expect(button).toBeFocused() +}) + +test('solo con el teclado: el aviso de cookies se alcanza enseguida, se decide y, al abrirlo desde el pie, el foco va y vuelve', async ({ page }) => { + await page.context().clearCookies() + await page.goto('/glossary') + const banner = page.getByTestId('Test-CookiesBanner') + await expect(banner).toBeVisible() + // Justo después de «Saltar al contenido», antes de la barra de navegación + await page.keyboard.press('Tab') + await expect(page.getByTestId('Test-SkipLink')).toBeFocused() + await page.keyboard.press('Tab') + expect(await banner.evaluate((element) => element.contains(document.activeElement)), await focused(page)).toBe(true) + await tabTo(page, banner.getByTestId('Test-CookiesReject'), 10) + await page.keyboard.press('Enter') + await expect(banner).toHaveCount(0) + // El foco no se pierde: va a la página + expect(await page.evaluate(() => document.querySelector('main')?.contains(document.activeElement)), await focused(page)).toBe(true) + + // Desde el pie: el foco entra en el aviso y, al cerrarlo, vuelve al enlace + const preferences = page.locator('.n4l-footer').getByRole('link', { name: 'Preferencias de cookies', exact: true }) + await preferences.focus() + await page.keyboard.press('Enter') + await expect(banner.getByRole('heading', { level: 2 })).toBeFocused() + await tabTo(page, banner.getByRole('button', { name: 'Cerrar sin cambiar nada' }), 20) + await page.keyboard.press('Enter') + await expect(banner).toHaveCount(0) + await expect(preferences).toBeFocused() +}) + +test('solo con el teclado: «Ver los datos» de una gráfica despliega su tabla, que se recorre con el teclado', async ({ page }) => { + await page.goto('/analyze?dataset=iris') + await expect(page.getByTestId('Test-AnalyzeInfo')).toBeVisible({ timeout: 30_000 }) + const data = page.getByTestId('Test-ChartData').first() + const toggle = data.getByTestId('Test-ChartData-Toggle') + await tabTo(page, toggle) + await expect(toggle).toHaveAttribute('aria-expanded', 'false') + await page.keyboard.press('Enter') + await expect(toggle).toHaveAttribute('aria-expanded', 'true') + const table = data.getByRole('table') + await expect(table).toBeVisible() + // Encabezados de columna y de fila, y la región se alcanza con el tabulador (por si hay que desplazarla) + await expect(table.getByRole('columnheader').first()).toBeVisible() + await expect(table.getByRole('rowheader').first()).toBeVisible() + await page.keyboard.press('Tab') + await expect(data.getByRole('region')).toBeFocused() +}) + +test('solo con el teclado: los apartados de /settings son pestañas verticales que se recorren con las flechas', async ({ page }) => { + await page.goto('/settings') + const tabs = page.getByRole('tablist', { name: 'Apartados de la configuración' }) + await expect(tabs).toHaveAttribute('aria-orientation', 'vertical') + const first = tabs.getByRole('tab').first() + await tabTo(page, first) + await page.keyboard.press('ArrowDown') + const accessibility = tabs.getByRole('tab', { name: 'Accesibilidad' }) + await expect(accessibility).toBeFocused() + await expect(accessibility).toHaveAttribute('aria-selected', 'true') + await expect(page).toHaveURL(/\/settings#accessibility$/) + // Lo siguiente con el tabulador ya es el apartado abierto + await page.keyboard.press('Tab') + expect(await page.evaluate(() => document.querySelector('[data-testid="Test-Settings-accessibility"]')?.contains(document.activeElement)), await focused(page)).toBe(true) + + // Un enlace a un apartado (desde la declaración de accesibilidad) lo abre + await page.goto('/accessibility') + await page.getByRole('link', { name: 'Ir a los ajustes de accesibilidad' }).click() + await expect(page.getByRole('tab', { name: 'Accesibilidad' })).toHaveAttribute('aria-selected', 'true') + // El enlace lleva a la pestaña, con el foco en ella (el lector la anuncia) + await expect(page.getByRole('tab', { name: 'Accesibilidad' })).toBeFocused() + await expect(page.getByTestId('Test-Settings-accessibility')).toBeVisible() +}) diff --git a/e2e/vision.spec.ts b/e2e/vision.spec.ts new file mode 100644 index 0000000..76a6c5d --- /dev/null +++ b/e2e/vision.spec.ts @@ -0,0 +1,89 @@ +import type { Page } from '@playwright/test' +import { test, expect } from './fixtures' + +// Visión baja (WCAG 1.4.10, 1.4.12, 1.3.4): con 320 px de ancho (lo que queda de 1280 px con el zoom al 400 %), con +// el móvil en horizontal y con el espaciado de texto máximo de WCAG, ninguna página obliga a desplazarse en horizontal. +// Solo pueden hacerlo las tablas de datos y lo que tiene su propio desplazamiento (y se puede enfocar). + +const PAGES = [ + '/', + '/task/tabular-classification', + '/select-dataset/tabular-classification', + '/playground/tabular-classification/dataset/IRIS', + '/playground/regression/model/AUTO_MPG', + '/playground/time-series/model/SUNSPOTS', + '/playground/clustering/dataset/IRIS', + '/analyze?dataset=iris', + '/datasets', + '/glossary', + '/manual', + '/settings', + '/packages', +] + +/** Lo que se sale por la derecha y no está dentro de algo con su propio desplazamiento horizontal */ +const overflowing = (page: Page) => page.evaluate(() => { + const width = document.documentElement.clientWidth + const scrolls = (element: Element | null): boolean => { + for (let node = element?.parentElement ?? null; node !== null && node !== document.body; node = node.parentElement) { + const { overflowX } = getComputedStyle(node) + if (overflowX === 'auto' || overflowX === 'scroll' || overflowX === 'hidden' || overflowX === 'clip') return true + } + return false + } + const describe = (element: Element) => `${element.tagName.toLowerCase()}${element.id ? '#' + element.id : ''}.${String(element.className).split(' ').slice(0, 2).join('.')}` + return { + scrollWidth: document.documentElement.scrollWidth, + width, + offenders : Array.from(document.querySelectorAll('main *, nav *, footer *')) + .filter((element) => { + const rect = element.getBoundingClientRect() + return rect.width > 0 && rect.right > width + 1 && !scrolls(element) + }) + .slice(0, 5) + .map(describe), + } +}) + +async function expectNoHorizontalScroll(page: Page, path: string) { + await page.goto(path) + await expect(page.locator('main').first()).toBeVisible() + await page.waitForTimeout(1500) + const { scrollWidth, width, offenders } = await overflowing(page) + expect(scrollWidth, `${path}: ${offenders.join(', ')}`).toBeLessThanOrEqual(width + 1) +} + +test.describe('con 320 px de ancho (zoom al 400 %)', () => { + test.use({ viewport: { width: 320, height: 640 } }) + for (const path of PAGES) { + test(`${path} no se sale en horizontal`, async ({ page }) => { + await expectNoHorizontalScroll(page, path) + }) + } +}) + +test.describe('con el móvil en horizontal (1.3.4)', () => { + test.use({ viewport: { width: 740, height: 360 } }) + for (const path of ['/', '/playground/image-classification/model/IMAGE-MNIST', '/playground/tabular-classification/dataset/IRIS']) { + test(`${path} se usa igual`, async ({ page }) => { + await expectNoHorizontalScroll(page, path) + }) + } +}) + +test.describe('con el espaciado de texto máximo de WCAG (1.4.12) y el texto al 200 %', () => { + test.use({ viewport: { width: 1280, height: 800 } }) + for (const path of ['/', '/playground/tabular-classification/dataset/IRIS', '/analyze?dataset=iris', '/settings']) { + test(`${path} no se sale ni se corta`, async ({ page }) => { + await page.addInitScript(() => { + try { + localStorage.setItem('n4l-display', JSON.stringify({ spacing: true, textSize: 200 })) + } catch { + // Sin almacenamiento no se aplicaría + } + }) + await expectNoHorizontalScroll(page, path) + await expect(page.locator('html')).toHaveClass(/n4l-text-spacing/) + }) + } +}) diff --git a/eslint.config.ts b/eslint.config.ts index 3878f2d..3733dc4 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -1,45 +1,50 @@ -import js from "@eslint/js" -import globals from "globals" -import reactHooks from "eslint-plugin-react-hooks" -import reactRefresh from "eslint-plugin-react-refresh" -import tseslint from "typescript-eslint" -import { defineConfig, globalIgnores } from "eslint/config" -import stylistic from "@stylistic/eslint-plugin" +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import { defineConfig, globalIgnores } from 'eslint/config' +import stylistic from '@stylistic/eslint-plugin' +import jsxA11y from 'eslint-plugin-jsx-a11y' export default defineConfig([ - globalIgnores(["dist"]), + globalIgnores(['dist', 'playwright-report', 'test-results']), { - files : ["**/*.{ts,tsx}"], + files : ['**/*.{ts,tsx}'], plugins: { - "@stylistic": stylistic, + '@stylistic': stylistic, }, extends: [ js.configs.recommended, tseslint.configs.recommended, reactHooks.configs.flat.recommended, reactRefresh.configs.vite, + // Accesibilidad del JSX (docs/accessibility.md): textos alternativos, nombres de los controles, ARIA válido… + jsxA11y.flatConfigs.recommended, ], languageOptions: { ecmaVersion: 2020, globals : globals.browser, }, rules: { - "@typescript-eslint/no-explicit-any" : "off", - "@typescript-eslint/ban-ts-comment" : "warn", - "@typescript-eslint/no-unsafe-function-type": "warn", - "@typescript-eslint/no-unused-vars" : [ - "error", + '@typescript-eslint/no-explicit-any' : 'off', + '@typescript-eslint/ban-ts-comment' : 'warn', + '@typescript-eslint/no-unsafe-function-type': 'warn', + '@typescript-eslint/no-unused-vars' : [ + 'error', { - args : "all", - argsIgnorePattern : "^_", - caughtErrors : "all", - caughtErrorsIgnorePattern : "^_", - destructuredArrayIgnorePattern: "^_", - varsIgnorePattern : "^_", + args : 'all', + argsIgnorePattern : '^_', + caughtErrors : 'all', + caughtErrorsIgnorePattern : '^_', + destructuredArrayIgnorePattern: '^_', + varsIgnorePattern : '^_', ignoreRestSiblings : true, }, ], - "@stylistic/key-spacing": ["error", { align: "colon" }], + '@stylistic/key-spacing': ['error', { align: 'colon' }], + // Comillas simples en el código (en los atributos de JSX no cambia nada); dobles solo para no escapar una simple + '@stylistic/quotes' : ['error', 'single', { avoidEscape: true }], }, }, ]) diff --git a/index.html b/index.html index 1e77c83..7b27ac9 100644 --- a/index.html +++ b/index.html @@ -10,10 +10,84 @@ <meta name="theme-color" content="#1f1a7a" /> <meta name="description" content="Nets4Learning: aprende inteligencia artificial entrenando y explicando redes neuronales en el navegador." /> <title>Nets4Learning + + -
+
+
+ +
+ Nets4Learning +
+
diff --git a/package.json b/package.json index 0f3cd75..e2790e0 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,8 @@ }, "scripts": { "dev": "vite", + "dev:host": "vite --host 0.0.0.0", + "dev:https": "vite --mode https --host 0.0.0.0", "build": "tsc -b && vite build", "build:simidat": "tsc -b && vite build --mode simidat", "build:netlify": "tsc -b && vite build --mode netlify", @@ -17,6 +19,7 @@ "test": "vitest", "test:ui": "vitest --ui", "test:coverage": "vitest run --coverage", + "test:e2e": "playwright test", "lint:fix": "eslint --fix src/utils/**/*.{ts,tsx}", "lint": "eslint .", "version": "conventional-changelog -i CHANGELOG.md -s -r 0 && git add CHANGELOG.md", @@ -34,26 +37,32 @@ "@tensorflow/tfjs": "^4.22.0", "@tensorflow/tfjs-backend-wasm": "^4.22.0", "@tensorflow/tfjs-backend-webgl": "^4.22.0", + "@tensorflow/tfjs-backend-webgpu": "^4.22.0", "@tensorflow/tfjs-converter": "^4.22.0", "@tensorflow/tfjs-core": "^4.22.0", "@tensorflow/tfjs-vis": "^1.5.1", + "@tsparticles/engine": "^4.4.0", + "@tsparticles/particles": "^4.4.0", "@types/react-plotly.js": "^2.6.4", "@vladmandic/face-api": "^1.7.15", "bootstrap": "^5.3.8", "chart.js": "^4.5.1", "d3-random": "^3.0.1", "danfojs": "^1.2.0", - "fingerpose": "^0.1.0", - "handsign-multilingual": "^0.3.0", + "handsign-multilingual": "^0.5.0", + "hyparquet": "^1.31.2", + "hyparquet-compressors": "^1.1.2", "i18next": "^25.7.3", "i18next-http-backend": "^3.0.2", "jszip": "^3.10.1", "jszip-utils": "^0.1.0", "katex": "^0.16.27", - "mathjs": "^11.12.0", + "mathjs": "^12.4.3", "ml-regression-multivariate-linear": "^2.0.4", "npyjs": "^1.0.4", + "papaparse": "5.5.3", "plotly.js-dist-min": "2.8.0", + "qrcode-generator": "^2.0.4", "react": "^19.2.3", "react-bootstrap": "^2.10.10", "react-bootstrap-icons": "^1.11.6", @@ -70,7 +79,6 @@ "react-syntax-highlighter": "^16.1.0", "react-vis-graph-wrapper": "^0.1.3", "react-webcam": "^7.2.0", - "recharts": "^3.8.1", "rehype-format": "^5.0.1", "rehype-katex": "^7.0.1", "rehype-raw": "^7.0.0", @@ -81,25 +89,29 @@ "sweetalert2-react-content": "^5.1.1" }, "devDependencies": { + "@axe-core/playwright": "^4.13.0", "@commitlint/cli": "^20.2.0", "@commitlint/config-conventional": "^20.2.0", "@eslint/js": "^9.39.2", + "@playwright/test": "1.62.1", "@stylistic/eslint-plugin": "^5.6.1", "@tensorflow/tfjs-node": "^4.22.0", "@testing-library/jest-dom": "^6.9.1", "@testing-library/react": "^16.3.1", "@testing-library/user-event": "^14.6.1", "@types/d3-random": "^3.0.4", - "@types/fingerpose": "^0.1.1", "@types/node": "^24.10.4", + "@types/papaparse": "^5.5.2", "@types/plotly.js": "^3.0.8", "@types/react": "^19.2.7", "@types/react-dom": "^19.2.3", "@types/react-syntax-highlighter": "^15.5.13", + "@vitejs/plugin-basic-ssl": "^2.3.0", "@vitejs/plugin-react": "^5.1.1", "@vitest/ui": "^4.0.16", "conventional-changelog-cli": "^5.0.0", "eslint": "^9.39.2", + "eslint-plugin-jsx-a11y": "^6.10.2", "eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-refresh": "^0.4.26", "eslint-plugin-stylistic": "0.0.0-0", diff --git a/patches/@vladmandic__face-api@1.7.15.patch b/patches/@vladmandic__face-api@1.7.15.patch new file mode 100644 index 0000000..032dc1b --- /dev/null +++ b/patches/@vladmandic__face-api@1.7.15.patch @@ -0,0 +1,102 @@ +diff --git a/src/ageGenderNet/AgeGenderNet.ts b/src/ageGenderNet/AgeGenderNet.ts +index 6a7370c7830976099c840fdf3426bf897fee8802..b0537079f51c33b15b3b1f7349a9b641ef7858de 100644 +--- a/src/ageGenderNet/AgeGenderNet.ts ++++ b/src/ageGenderNet/AgeGenderNet.ts +@@ -63,8 +63,7 @@ export class AgeGenderNet extends NeuralNetwork { + + const predictionsByBatch = await Promise.all( + ageAndGenderTensors.map(async ({ ageTensor, genderTensor }) => { +- const age = (ageTensor.dataSync())[0]; +- const probMale = (genderTensor.dataSync())[0]; ++ const [age, probMale] = (await Promise.all([ageTensor.data(), genderTensor.data()])).map((data) => data[0]); + const isMale = probMale > 0.5; + const gender = isMale ? Gender.MALE : Gender.FEMALE; + const genderProbability = isMale ? probMale : (1 - probMale); +diff --git a/src/faceExpressionNet/FaceExpressionNet.ts b/src/faceExpressionNet/FaceExpressionNet.ts +index 44d7ab51b6c2d2a9e1659fc1eaef9ec1aa2ccd74..cd44039fc38e31d66a2408bafb4b28f226a124a4 100644 +--- a/src/faceExpressionNet/FaceExpressionNet.ts ++++ b/src/faceExpressionNet/FaceExpressionNet.ts +@@ -23,7 +23,7 @@ export class FaceExpressionNet extends FaceProcessor + const netInput = await toNetInput(input); + const out = await this.forwardInput(netInput); + const probabilitesByBatch = await Promise.all(tf.unstack(out).map(async (t) => { +- const data = t.dataSync(); ++ const data = await t.data(); + t.dispose(); + return data; + })); +diff --git a/src/faceLandmarkNet/FaceLandmark68NetBase.ts b/src/faceLandmarkNet/FaceLandmark68NetBase.ts +index d670b7aaa3edbcf50e654a5d413d092df67c46a2..fd2ac67d9038855e10c43411831b1697830d480a 100644 +--- a/src/faceLandmarkNet/FaceLandmark68NetBase.ts ++++ b/src/faceLandmarkNet/FaceLandmark68NetBase.ts +@@ -72,7 +72,7 @@ export abstract class FaceLandmark68NetBase< + + const landmarksForBatch = await Promise.all(landmarkTensors.map( + async (landmarkTensor, batchIdx) => { +- const landmarksArray = Array.from(landmarkTensor.dataSync()); ++ const landmarksArray = Array.from(await landmarkTensor.data()); + const xCoords = landmarksArray.filter((_, i) => isEven(i)); + const yCoords = landmarksArray.filter((_, i) => !isEven(i)); + +diff --git a/src/ssdMobilenetv1/SsdMobilenetv1.ts b/src/ssdMobilenetv1/SsdMobilenetv1.ts +index 6bade3a9fcab8cab875cbb9ed044466d083b49ad..8d9cdf4570267d376079dcacd025a81e9bc1ecad 100644 +--- a/src/ssdMobilenetv1/SsdMobilenetv1.ts ++++ b/src/ssdMobilenetv1/SsdMobilenetv1.ts +@@ -44,14 +44,16 @@ export class SsdMobilenetv1 extends NeuralNetwork { + _boxes[i].dispose(); + _scores[i].dispose(); + } +- const scoresData = Array.from(scores.dataSync()); ++ const [scoresData, boxesData] = await Promise.all([ ++ scores.data().then((data) => Array.from(data)), ++ boxes.array(), ++ ]); + const iouThreshold = 0.5; +- const indices = nonMaxSuppression(boxes, scoresData as number[], maxResults, iouThreshold, minConfidence); ++ const indices = nonMaxSuppression(boxesData, scoresData, maxResults, iouThreshold, minConfidence); + const reshapedDims = netInput.getReshapedInputDimensions(0); + const inputSize = netInput.inputSize as number; + const padX = inputSize / reshapedDims.width; + const padY = inputSize / reshapedDims.height; +- const boxesData = boxes.arraySync(); + const results = indices + .map((idx) => { + const [top, bottom] = [ +diff --git a/src/ssdMobilenetv1/nonMaxSuppression.ts b/src/ssdMobilenetv1/nonMaxSuppression.ts +index 8c3813dd16e90e5f2492cbfcf708d20ea9475fea..02d9e59817771015c049f9f612ffc8f6cfa6f4e8 100644 +--- a/src/ssdMobilenetv1/nonMaxSuppression.ts ++++ b/src/ssdMobilenetv1/nonMaxSuppression.ts +@@ -1,7 +1,4 @@ +-import * as tf from '../../dist/tfjs.esm'; +- +-function IOU(boxes: tf.Tensor2D, i: number, j: number) { +- const boxesData = boxes.arraySync(); ++function IOU(boxesData: number[][], i: number, j: number) { + const yminI = Math.min(boxesData[i][0], boxesData[i][2]); + const xminI = Math.min(boxesData[i][1], boxesData[i][3]); + const ymaxI = Math.max(boxesData[i][0], boxesData[i][2]); +@@ -22,13 +19,13 @@ function IOU(boxes: tf.Tensor2D, i: number, j: number) { + } + + export function nonMaxSuppression( +- boxes: tf.Tensor2D, ++ boxesData: number[][], + scores: number[], + maxOutputSize: number, + iouThreshold: number, + scoreThreshold: number, + ): number[] { +- const numBoxes = boxes.shape[0]; ++ const numBoxes = boxesData.length; + const outputSize = Math.min(maxOutputSize, numBoxes); + + const candidates = scores +@@ -43,7 +40,7 @@ export function nonMaxSuppression( + if (selected.length >= outputSize) return; + const originalScore = c.score; + for (let j = selected.length - 1; j >= 0; --j) { +- const iou = IOU(boxes, c.boxIndex, selected[j]); ++ const iou = IOU(boxesData, c.boxIndex, selected[j]); + if (iou === 0.0) continue; + c.score *= suppressFunc(iou); + if (c.score <= scoreThreshold) break; diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..727f87e --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,37 @@ +import { defineConfig, devices } from '@playwright/test' + +// Pruebas de extremo a extremo (carpeta e2e/) en Chrome contra la build de producción servida con `vite preview`: la +// misma que se publica en Netlify (base "/"). En local, si ya hay algo escuchando en el puerto, se reutiliza. +// Uso: pnpm test:e2e (la primera vez, `pnpm exec playwright install chromium`) +const PORT = 4173 +const OUT_DIR = 'node_modules/.cache/n4l-e2e' + +export default defineConfig({ + testDir : 'e2e', + // Entrenar redes en el navegador lleva su tiempo, sobre todo en CI (WebGL por software) + timeout : 120_000, + expect : { timeout: 15_000 }, + fullyParallel: true, + forbidOnly : !!process.env.CI, + retries : process.env.CI ? 1 : 0, + workers : process.env.CI ? 2 : undefined, + reporter : process.env.CI ? [['github'], ['html', { open: 'never' }]] : [['list']], + use : { + baseURL : `http://localhost:${PORT}`, + locale : 'es-ES', + trace : 'retain-on-failure', + screenshot: 'only-on-failure', + }, + projects: [ + { name: 'escritorio', use: { ...devices['Desktop Chrome'] }, testIgnore: /movil\.spec\.ts/ }, + { name: 'movil', use: { ...devices['Pixel 7'] }, testMatch: /movil\.spec\.ts/ }, + ], + webServer: { + // `exec`: el servidor sustituye al shell y Playwright puede pararlo al acabar (con `pnpm exec` quedaba suelto y la + // ejecución no terminaba). `vite` se encuentra porque pnpm (test:e2e) pone node_modules/.bin en el PATH + command : `vite build --mode netlify --outDir ${OUT_DIR} --emptyOutDir && exec vite preview --mode netlify --outDir ${OUT_DIR} --port ${PORT} --strictPort`, + url : `http://localhost:${PORT}`, + reuseExistingServer: !process.env.CI, + timeout : 240_000, + }, +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 52dfa09..c27f387 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -164,7 +164,10 @@ settings: overrides: danfojs>@tensorflow/tfjs: ^4.22.0 - danfojs>mathjs: ^11.12.0 + danfojs>mathjs: ^12.4.3 + +patchedDependencies: + '@vladmandic/face-api@1.7.15': 1ec24e4d9002c522523e5c010aaad4a200d243a86622f7d9aa620936e6634c85 importers: @@ -203,6 +206,9 @@ importers: '@tensorflow/tfjs-backend-webgl': specifier: ^4.22.0 version: 4.22.0(@tensorflow/tfjs-core@4.22.0(encoding@0.1.13)) + '@tensorflow/tfjs-backend-webgpu': + specifier: ^4.22.0 + version: 4.22.0(@tensorflow/tfjs-core@4.22.0(encoding@0.1.13)) '@tensorflow/tfjs-converter': specifier: ^4.22.0 version: 4.22.0(@tensorflow/tfjs-core@4.22.0(encoding@0.1.13)) @@ -212,12 +218,18 @@ importers: '@tensorflow/tfjs-vis': specifier: ^1.5.1 version: 1.5.1(@tensorflow/tfjs-core@4.22.0(encoding@0.1.13))(encoding@0.1.13) + '@tsparticles/engine': + specifier: ^4.4.0 + version: 4.4.0 + '@tsparticles/particles': + specifier: ^4.4.0 + version: 4.4.0 '@types/react-plotly.js': specifier: ^2.6.4 version: 2.6.4 '@vladmandic/face-api': specifier: ^1.7.15 - version: 1.7.15 + version: 1.7.15(patch_hash=1ec24e4d9002c522523e5c010aaad4a200d243a86622f7d9aa620936e6634c85) bootstrap: specifier: ^5.3.8 version: 5.3.8(@popperjs/core@2.11.8) @@ -230,12 +242,15 @@ importers: danfojs: specifier: ^1.2.0 version: 1.2.0(encoding@0.1.13)(seedrandom@3.0.5) - fingerpose: - specifier: ^0.1.0 - version: 0.1.0 handsign-multilingual: - specifier: ^0.3.0 - version: 0.3.0 + specifier: ^0.5.0 + version: 0.5.0 + hyparquet: + specifier: ^1.31.2 + version: 1.31.2 + hyparquet-compressors: + specifier: ^1.1.2 + version: 1.1.2 i18next: specifier: ^25.7.3 version: 25.10.10(typescript@5.9.3) @@ -252,17 +267,23 @@ importers: specifier: ^0.16.27 version: 0.16.47 mathjs: - specifier: ^11.12.0 - version: 11.12.0 + specifier: ^12.4.3 + version: 12.4.3 ml-regression-multivariate-linear: specifier: ^2.0.4 version: 2.0.4 npyjs: specifier: ^1.0.4 version: 1.1.0(encoding@0.1.13) + papaparse: + specifier: 5.5.3 + version: 5.5.3 plotly.js-dist-min: specifier: 2.8.0 version: 2.8.0 + qrcode-generator: + specifier: ^2.0.4 + version: 2.0.4 react: specifier: ^19.2.3 version: 19.2.7 @@ -311,9 +332,6 @@ importers: react-webcam: specifier: ^7.2.0 version: 7.2.0(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - recharts: - specifier: ^3.8.1 - version: 3.8.1(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react-is@17.0.2)(react@19.2.7)(redux@5.0.1) rehype-format: specifier: ^5.0.1 version: 5.0.1 @@ -339,6 +357,9 @@ importers: specifier: ^5.1.1 version: 5.1.2(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(sweetalert2@11.26.25) devDependencies: + '@axe-core/playwright': + specifier: ^4.13.0 + version: 4.13.0(playwright-core@1.62.1) '@commitlint/cli': specifier: ^20.2.0 version: 20.5.3(@types/node@24.13.2)(conventional-commits-filter@5.0.0)(conventional-commits-parser@6.4.0)(typescript@5.9.3) @@ -348,6 +369,9 @@ importers: '@eslint/js': specifier: ^9.39.2 version: 9.39.4 + '@playwright/test': + specifier: 1.62.1 + version: 1.62.1 '@stylistic/eslint-plugin': specifier: ^5.6.1 version: 5.10.0(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0)) @@ -366,12 +390,12 @@ importers: '@types/d3-random': specifier: ^3.0.4 version: 3.0.4 - '@types/fingerpose': - specifier: ^0.1.1 - version: 0.1.1 '@types/node': specifier: ^24.10.4 version: 24.13.2 + '@types/papaparse': + specifier: ^5.5.2 + version: 5.5.2 '@types/plotly.js': specifier: ^3.0.8 version: 3.0.10 @@ -384,6 +408,9 @@ importers: '@types/react-syntax-highlighter': specifier: ^15.5.13 version: 15.5.13 + '@vitejs/plugin-basic-ssl': + specifier: ^2.3.0 + version: 2.3.0(vite@7.3.5(@types/node@24.13.2)(jiti@2.7.0)) '@vitejs/plugin-react': specifier: ^5.1.1 version: 5.2.0(supports-color@7.2.0)(vite@7.3.5(@types/node@24.13.2)(jiti@2.7.0)) @@ -396,6 +423,9 @@ importers: eslint: specifier: ^9.39.2 version: 9.39.4(jiti@2.7.0)(supports-color@7.2.0) + eslint-plugin-jsx-a11y: + specifier: ^6.10.2 + version: 6.10.2(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0)) eslint-plugin-react-hooks: specifier: ^7.0.1 version: 7.1.1(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0) @@ -447,6 +477,11 @@ packages: '@asamuzakjp/nwsapi@2.3.9': resolution: {integrity: sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==} + '@axe-core/playwright@4.13.0': + resolution: {integrity: sha512-6YLx+kxXu5GJceG4ozFg+33a2EMTdjYwWGloJ3sb9Kta5pp+ZNS53uxGVog5JetIY8s++P5UrtX+cri+u0VAVg==} + peerDependencies: + playwright-core: '>= 1.0.0' + '@babel/code-frame@7.29.7': resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} engines: {node: '>=6.9.0'} @@ -978,6 +1013,11 @@ packages: '@mediapipe/pose@0.5.1675469404': resolution: {integrity: sha512-DFZsNWTsSphRIZppnUCuunzBiHP2FdJXR9ehc7mMi4KG+oPaOH0Em3d6kr7Py+TSyTXC1doH88KcF28k2sBxsQ==} + '@playwright/test@1.62.1': + resolution: {integrity: sha512-DTcUc8qii+cpHvtOwggMtBRMjKZHXYWdw8syRYu2vtzuq4Wxphqq4NfCs5Zt44L6mA8rfDfj+PHnxFc/FeK6mQ==} + engines: {node: '>=20'} + hasBin: true + '@plotly/d3-sankey-circular@0.33.1': resolution: {integrity: sha512-FgBV1HEvCr3DV7RHhDsPXyryknucxtfnLwPtCKKxdolKyTFYoLX/ibEfX39iFYIL7DYbVeRtP43dbFcrHNE+KQ==} @@ -1016,17 +1056,6 @@ packages: peerDependencies: react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1 - '@reduxjs/toolkit@2.12.0': - resolution: {integrity: sha512-KiT+RzZbp6mQET+Mg+h2c97+9j1sNflUxQkIHI7Yuzf6Peu+OYpmkn6nbHWmLLWj+1ZODUJFwGZ7gx3L9R9EOw==} - peerDependencies: - react: ^16.9.0 || ^17.0.0 || ^18 || ^19 - react-redux: ^7.2.1 || ^8.1.3 || ^9.0.0 - peerDependenciesMeta: - react: - optional: true - react-redux: - optional: true - '@restart/hooks@0.4.16': resolution: {integrity: sha512-f7aCv7c+nU/3mF7NWLtVVr0Ra80RqsO89hO72r+Y/nvQr5+q0UFGkocElTH6MJApvReVh6JHUFYn2cw1WdHF3w==} peerDependencies: @@ -1204,9 +1233,6 @@ packages: '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} - '@standard-schema/utils@0.3.0': - resolution: {integrity: sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==} - '@stylistic/eslint-plugin@5.10.0': resolution: {integrity: sha512-nPK52ZHvot8Ju/0A4ucSX1dcPV2/1clx0kLcH5wDmrE4naKso7TUC/voUyU1O9OTKTrR6MYip6LP0ogEMQ9jPQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1415,6 +1441,92 @@ packages: peerDependencies: '@testing-library/dom': '>=7.21.4' + '@tsparticles/animation-utils@4.4.0': + resolution: {integrity: sha512-yl4iE9SSuJ2n8B096t/vn4bWN+wWIkDm11OfTsIM3/64bJLB/5T92n6iOm/XLC3r6g8M8XuDi6ntTnpOcwsGxg==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/basic@4.4.0': + resolution: {integrity: sha512-lTbKBPzab0alPy+4Wm/xehrVpT1FrpEMaQcTU2eTV0c0G++5/kOINEWkC7GL7/cHovycukxB+tOMYVT54bSprA==} + + '@tsparticles/canvas-utils@4.4.0': + resolution: {integrity: sha512-3zVr95OZ05BExgVYNT8WPqA/wFp83TiEJo66rZCZ/nZd1Ny8UCYLMKBcbUPBvGS2GB87UMK8+ygleZnlFhGTtw==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/engine@4.4.0': + resolution: {integrity: sha512-zUDykZ7qBqHYMXr6NveXg51kBlvfaQKMmWkMJ8nT7fC4dXdNayb1+TxOfAoqH9/U/u0Eyr0YE+72ai/ymS0uww==} + + '@tsparticles/interaction-particles-collisions@4.4.0': + resolution: {integrity: sha512-DLfnAf6lXy/IlsWPZBAXS6/pll5400yPxi6DRyHe0UBnbPVRzCRXAuoGaqhEsrth47BQdoyaqVG7sh38m9Oldg==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + '@tsparticles/plugin-interactivity': 4.4.0 + + '@tsparticles/interaction-particles-links@4.4.0': + resolution: {integrity: sha512-n2OkzB8BjQkzFrtiVq8O42/Tf+/Psng+K71MhJDI+czkwLo3PdmG51MCsy2w9ywCvGwWci2nwxMQ1qZL7nPONg==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + '@tsparticles/plugin-interactivity': 4.4.0 + + '@tsparticles/particles@4.4.0': + resolution: {integrity: sha512-ZIvU44TUOKtBJrUPWtM1hYABX+GBGITC/IdaE9FNblNuxs5utGPKtafc0R9zpN/NNM3TmSsGAiKaLFWMo5OgRA==} + + '@tsparticles/plugin-blend@4.4.0': + resolution: {integrity: sha512-X/SG2WIasgHqA+fLZFu6MMv3z5VY5uX4VIfKjXz1qxZjEjn0w4kzZrbtZBxXxRKdrm8Dg8Qu2mmBokNZ8Bny3g==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/plugin-hex-color@4.4.0': + resolution: {integrity: sha512-sbRW6fi/YOS/hvFi6GCQiKI2zMCrmydrhlzqWyw2UUyg4Rr3FviQbIC2VRZrMc30Cm6kSkR3SovXIFDpZzO94Q==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/plugin-hsl-color@4.4.0': + resolution: {integrity: sha512-nw/7cGoU99y8veeYD7yA7ygNyrGr461V9xx+ed+jrj0LyXQbLF3d/r78ovMseoHxm4SWa9pmtoQxS3fBHIgecw==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/plugin-interactivity@4.4.0': + resolution: {integrity: sha512-jquoxlT4ra1Mc4glVlIfPubmchyIq5IZ25RdnvAop1uuc+6tu4N1zq5SSeyRO8MhJ94xevsNe6ozjmqvZ9CzKA==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/plugin-move@4.4.0': + resolution: {integrity: sha512-o05YP6bWxljbxmsQoqbay8sn4GtHIiTQZhZmcIyxJw/q+oSCNKHWALElSAqa1H7Dp/7ltnmd4rH4pgbQtHnfEw==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/plugin-rgb-color@4.4.0': + resolution: {integrity: sha512-s7YlsrcjndVLiOgKNPQaPcEQmmZeZqHec0lpSbt8BgR2pQmjFvCMSzHDA/aaqZ6JX8iVqvj+bT8uqT5XQDq70Q==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/shape-circle@4.4.0': + resolution: {integrity: sha512-pCdCenLohHwaeeuMCw9bh1icGB+CKwBYx67L5dTBw6aig7LRvL+Kd1PKClJTgXkx8Mb1Xb7KLNmSYgh/ABRtEQ==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/updater-opacity@4.4.0': + resolution: {integrity: sha512-StQAExNqeOHANRAMXHdaKKEBD1DrRwBZ3TQF6DPtERtoElj8BvMlPHq38W0TSzfvR0lFP91p2Pzo5txVzVJ3Gg==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/updater-out-modes@4.4.0': + resolution: {integrity: sha512-IzHaYhOVI6mBFqub1ivd/5UMkvn5Pb/j9xS8edT7XeSNYqO3UeomLJci0KE6Xsm+4K/kBLGbCRW5+Tf+kV4E0g==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/updater-paint@4.4.0': + resolution: {integrity: sha512-v7liuaT9BwHsd1hCfJF2d93M2gD3lSfsfIfKjPihAYo73hS43Wq7Cf1F0yjEiR3yXryRGH1QmYYdhonKAvyDKw==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/updater-size@4.4.0': + resolution: {integrity: sha512-Qq8QjC0MMjlaHjtpWUROSqe14eKVphq92n0VR4/d4WY+pnSG1U1VJzF43Kyfb4IyV06b29F0TUROIG7Ivqk36g==} + peerDependencies: + '@tsparticles/engine': 4.4.0 + '@turf/area@7.3.5': resolution: {integrity: sha512-sSn80wPT7XfBIDN3vurCPxhk9W4U8ozS/XImSqeLN8qveTICOxzZkhsGDMp0CuncaN+plWut4a2TdNM7mzZB6Q==} @@ -1451,36 +1563,9 @@ packages: '@types/clone@0.1.30': resolution: {integrity: sha512-vcxBr+ybljeSiasmdke1cQ9ICxoEwaBgM1OQ/P5h4MPj/kRyLcDl5L8PrftlbyV1kBbJIs3M3x1A1+rcWd4mEA==} - '@types/d3-array@3.2.2': - resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==} - - '@types/d3-color@3.1.3': - resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==} - - '@types/d3-ease@3.0.2': - resolution: {integrity: sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==} - - '@types/d3-interpolate@3.0.4': - resolution: {integrity: sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==} - - '@types/d3-path@3.1.1': - resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==} - '@types/d3-random@3.0.4': resolution: {integrity: sha512-UHYId5WTCx4L4YNel7NU00XUXXgvgpgZOvp10PuvsQENjMDXhh2RyFc0KBjO7B45ne4Ha1yVH7ii0vnzKkuzWA==} - '@types/d3-scale@4.0.9': - resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==} - - '@types/d3-shape@3.1.8': - resolution: {integrity: sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==} - - '@types/d3-time@3.0.4': - resolution: {integrity: sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==} - - '@types/d3-timer@3.0.2': - resolution: {integrity: sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==} - '@types/debug@4.1.13': resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==} @@ -1500,9 +1585,6 @@ packages: resolution: {integrity: sha512-vsxcbfLDdjytnCnHXtinE40Xl46Wr7l/VGRGt7ewJwCPMKEHOdEsTxXX8xwgoR7cbc+6dE8SB4jlMrOV2zAg7g==} deprecated: This is a stub types definition. fast-json-stable-stringify provides its own type definitions, so you do not need this installed. - '@types/fingerpose@0.1.1': - resolution: {integrity: sha512-GUyd2r2lszaderkJY/WhVB9DkfU2QuVKmJ0w+5EL17QOA3DYBO3JtYZfwijLYO0vUBuDbbifJ5a+s4onXHCwlA==} - '@types/geojson-vt@3.2.5': resolution: {integrity: sha512-qDO7wqtprzlpe8FfQ//ClPV9xiuoh2nkIgiouIptON9w5jvD/fA4szvP9GBlDVdJ5dldAl0kX/sy3URbWwLx0g==} @@ -1554,6 +1636,9 @@ packages: '@types/offscreencanvas@2019.7.3': resolution: {integrity: sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A==} + '@types/papaparse@5.5.2': + resolution: {integrity: sha512-gFnFp/JMzLHCwRf7tQHrNnfhN4eYBVYYI897CGX4MY1tzY9l2aLkVyx2IlKZ/SAqDbB3I1AOZW5gTMGGsqWliA==} + '@types/pbf@3.0.5': resolution: {integrity: sha512-j3pOPiEcWZ34R6a6mN07mUkM4o4Lwf6hPNt8eilOeZhTFbxFXmKhvXl9Y28jotFPaI1bpPDJsbCprUoNke6OrA==} @@ -1597,9 +1682,6 @@ packages: '@types/unist@3.0.3': resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} - '@types/use-sync-external-store@0.0.6': - resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==} - '@types/warning@3.0.4': resolution: {integrity: sha512-CqN8MnISMwQbLJXO3doBAV4Yw9hx9/Pyr2rZ78+NfaCnhyRA/nKrpyk6E7mKw17ZOaQdLpK9GiUjrqLzBlN3sg==} @@ -1665,6 +1747,12 @@ packages: '@ungap/structured-clone@1.3.1': resolution: {integrity: sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==} + '@vitejs/plugin-basic-ssl@2.3.0': + resolution: {integrity: sha512-bdyo8rB3NnQbikdMpHaML9Z1OZPBu6fFOBo+OtxsBlvMJtysWskmBcnbIDhUqgC8tcxNv/a+BcV5U+2nQMm1OQ==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + peerDependencies: + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + '@vitejs/plugin-react@5.2.0': resolution: {integrity: sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -1798,6 +1886,10 @@ packages: array-bounds@1.0.1: resolution: {integrity: sha512-8wdW3ZGk6UjMPJx/glyEt0sLzzwAE1bhToPsO1W2pbpR2gULyxe3BjSiuJFheP50T/GgODVPz2fuMUmIywt8cQ==} + array-buffer-byte-length@1.0.2: + resolution: {integrity: sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==} + engines: {node: '>= 0.4'} + array-find-index@1.0.2: resolution: {integrity: sha512-M1HQyIXcBGtVywBt8WVdim+lrNaK7VHp99Qt5pSNziXznKHViIBbXWtfRTpEFpF/c4FdfxNAsCCwPp5phBYJtw==} engines: {node: '>=0.10.0'} @@ -1809,12 +1901,28 @@ packages: array-ify@1.0.0: resolution: {integrity: sha512-c5AMf34bKdvPhQ7tBGhqkgKNUzMr4WUs+WDtC2ZUGOUncbxKMTvqxYctiseW3+L4bA8ec+GcZ6/A/FW4m8ukng==} + array-includes@3.2.0: + resolution: {integrity: sha512-VXY5eFRarnXcYxwBjJzPmEhH55+rmP79/+ueDhi0F+TuqfHCItagIHqxeUZrmgrOPa31QTh9H85DjX3FfJ0FTg==} + engines: {node: '>= 0.4'} + array-normalize@1.1.4: resolution: {integrity: sha512-fCp0wKFLjvSPmCn4F5Tiw4M3lpMZoHlCjfcs7nNzuj3vqQQ1/a8cgB9DXcpDSn18c+coLnaW7rqfcYCvKbyJXg==} array-range@1.0.1: resolution: {integrity: sha512-shdaI1zT3CVNL2hnx9c0JMc0ZogGaxDs5e85akgHWKYa0yVbIyp06Ind3dVkTj/uuFrzaHBOyqFzo+VV6aXgtA==} + array.prototype.flat@1.3.3: + resolution: {integrity: sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==} + engines: {node: '>= 0.4'} + + array.prototype.flatmap@1.3.3: + resolution: {integrity: sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==} + engines: {node: '>= 0.4'} + + arraybuffer.prototype.slice@1.0.4: + resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==} + engines: {node: '>= 0.4'} + asap@2.0.6: resolution: {integrity: sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==} @@ -1822,10 +1930,17 @@ packages: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} + ast-types-flow@0.0.8: + resolution: {integrity: sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==} + astral-regex@2.0.0: resolution: {integrity: sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==} engines: {node: '>=8'} + async-function@1.0.0: + resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==} + engines: {node: '>= 0.4'} + asynckit@0.4.0: resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} @@ -1833,6 +1948,18 @@ packages: resolution: {integrity: sha512-0bDNnY/u6pPwHDMoF0FieU354oBi0a8rD9FcsLwzcGWbc8KS8KPIi7y+s13OlVY+gMWc/9xEMUgNE6Qm8ZllYQ==} engines: {node: '>=4'} + available-typed-arrays@1.0.7: + resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==} + engines: {node: '>= 0.4'} + + axe-core@4.13.0: + resolution: {integrity: sha512-UzGt8zg7Ny8djbYMhxl2zuEevVa7r2gJjYY5Lwr1xM7+XU2nd6CkIWFTVcCIbAP63vSz71NaVyyuSk9lHKcy0A==} + engines: {node: '>=4'} + + axobject-query@4.1.0: + resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==} + engines: {node: '>= 0.4'} + bail@2.0.2: resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==} @@ -1894,6 +2021,14 @@ packages: resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} engines: {node: '>= 0.4'} + call-bind@1.0.9: + resolution: {integrity: sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==} + engines: {node: '>= 0.4'} + + call-bound@1.0.4: + resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==} + engines: {node: '>= 0.4'} + callsites@3.1.0: resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} engines: {node: '>=6'} @@ -2253,10 +2388,6 @@ packages: engines: {node: '>=12'} hasBin: true - d3-ease@3.0.1: - resolution: {integrity: sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==} - engines: {node: '>=12'} - d3-force@1.2.1: resolution: {integrity: sha512-HHvehyaiUlVo5CxBJ0yF/xny4xoaxFxDnBXNvNcfW9adORGZfyNF1dj6DGLKyk4Yh3brP/1h3rnDzdIAwL08zg==} @@ -2373,14 +2504,13 @@ packages: d3-timer@2.0.0: resolution: {integrity: sha512-TO4VLh0/420Y/9dO3+f9abDEFYeCUr2WZRlxJvbp4HPTQcSylXNiL6yZa9FIUvV1yRiFufl1bszTCLDqv9PWNA==} - d3-timer@3.0.1: - resolution: {integrity: sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==} - engines: {node: '>=12'} - d@1.0.2: resolution: {integrity: sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==} engines: {node: '>=0.12'} + damerau-levenshtein@1.0.8: + resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==} + danfojs@1.2.0: resolution: {integrity: sha512-UjXDx+U6tr2/5sMhbnw+pWZSM1D6wXzMfEDjEIiP/iItvnvmwL2lZPFB8DiPGRJej+bHhGMNoB81Z46f9iiW8w==} @@ -2388,6 +2518,18 @@ packages: resolution: {integrity: sha512-euIQENZg6x8mj3fO6o9+fOW8MimUI4PpD/fZBhJfeioZVy9TUpM4UY7KjQNVZFlqwJ0UdzRDzkycB997HEq1BQ==} engines: {node: '>=20'} + data-view-buffer@1.0.2: + resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==} + engines: {node: '>= 0.4'} + + data-view-byte-length@1.0.2: + resolution: {integrity: sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==} + engines: {node: '>= 0.4'} + + data-view-byte-offset@1.0.1: + resolution: {integrity: sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==} + engines: {node: '>= 0.4'} + debug@2.6.9: resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==} peerDependencies: @@ -2417,9 +2559,6 @@ packages: resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==} engines: {node: '>=0.10.0'} - decimal.js-light@2.5.1: - resolution: {integrity: sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==} - decimal.js@10.6.0: resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} @@ -2437,6 +2576,14 @@ packages: resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} engines: {node: '>=0.10.0'} + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + defined@1.0.1: resolution: {integrity: sha512-hsBd2qSVCRE+5PmNdHt1uzyrFu5d3RwmFDKzyNZMFq/EwDNJF7Ee5+D5oEKF0hU6LhtoUF1macFvOe4AskQC1Q==} @@ -2512,6 +2659,9 @@ packages: emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + emoji-regex@9.2.2: + resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} + encoding@0.1.13: resolution: {integrity: sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==} @@ -2537,6 +2687,14 @@ packages: error-ex@1.3.4: resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==} + es-abstract-get@1.0.0: + resolution: {integrity: sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg==} + engines: {node: '>= 0.4'} + + es-abstract@1.24.2: + resolution: {integrity: sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==} + engines: {node: '>= 0.4'} + es-define-property@1.0.1: resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} engines: {node: '>= 0.4'} @@ -2556,6 +2714,14 @@ packages: resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} engines: {node: '>= 0.4'} + es-shim-unscopables@1.1.0: + resolution: {integrity: sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==} + engines: {node: '>= 0.4'} + + es-to-primitive@1.3.4: + resolution: {integrity: sha512-yPDz7wqpg1/mmHLmS3tcfTfbw5f1eryXvyghYBffGdERwe+mV7ZcWzTR8LR17Kvqt3qfPurjlonmnq3MKXIOXw==} + engines: {node: '>= 0.4'} + es-toolkit@1.47.1: resolution: {integrity: sha512-5RAqEwf4P4E17p+W75KLOWw/nOvKZzSQpxM32IpI2KZLaVonjTrZ0Ai5ghMaVI9eKC2p8eoQgcBdkEDgzFk6+Q==} @@ -2604,6 +2770,12 @@ packages: engines: {node: '>=6.0'} hasBin: true + eslint-plugin-jsx-a11y@6.10.2: + resolution: {integrity: sha512-scB3nz4WmG75pV8+3eRUQOHZlNSUhFNq37xnpgRkCCELU3XMvXAxLk1eqWWyE22Ki4Q01Fnsw9BA3cJHDPgn2Q==} + engines: {node: '>=4.0'} + peerDependencies: + eslint: ^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9 + eslint-plugin-react-hooks@7.1.1: resolution: {integrity: sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==} engines: {node: '>=18'} @@ -2686,9 +2858,6 @@ packages: event-emitter@0.3.5: resolution: {integrity: sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==} - eventemitter3@5.0.4: - resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==} - events@3.3.0: resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==} engines: {node: '>=0.8.x'} @@ -2763,9 +2932,6 @@ packages: resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} engines: {node: '>=10'} - fingerpose@0.1.0: - resolution: {integrity: sha512-OXIRuRTgukBOo4xUO+vPchzHftZOPxO7VRh4HDjTg5NGr4gSkiY+LQShjsKAzmpRiRdmTgDh0dNsGpWa1Jsx3Q==} - flat-cache@4.0.1: resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} engines: {node: '>=16'} @@ -2782,6 +2948,10 @@ packages: font-measure@1.2.2: resolution: {integrity: sha512-mRLEpdrWzKe9hbfaF3Qpr06TAjquuBVP5cHy4b3hyeNdjc9i0PO6HniGsX5vjL5OWv7+Bd++NiooNpT/s8BvIA==} + for-each@0.3.5: + resolution: {integrity: sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==} + engines: {node: '>= 0.4'} + form-data@4.0.6: resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==} engines: {node: '>= 6'} @@ -2803,6 +2973,11 @@ packages: fs.realpath@1.0.0: resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} + fsevents@2.3.2: + resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -2811,11 +2986,25 @@ packages: function-bind@1.1.2: resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + function.prototype.name@1.2.0: + resolution: {integrity: sha512-jObKIik1P2QjPHP5nz5BaOtUlfgS0fWo8IUByNXkM+o+02sJOi94em77GwJKQSJ3gfPHdgzLNrHc1uokV4P/ew==} + engines: {node: '>= 0.4'} + + functions-have-names@1.2.3: + resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==} + + fzstd@0.1.1: + resolution: {integrity: sha512-dkuVSOKKwh3eas5VkJy1AW1vFpet8TA/fGmVA5krThl8YcOVE/8ZIoEA1+U1vEn5ckxxhLirSdY837azmbaNHA==} + gauge@3.0.2: resolution: {integrity: sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==} engines: {node: '>=10'} deprecated: This package is no longer supported. + generator-function@2.0.1: + resolution: {integrity: sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==} + engines: {node: '>= 0.4'} + gensync@1.0.0-beta.2: resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} engines: {node: '>=6.9.0'} @@ -2845,6 +3034,10 @@ packages: resolution: {integrity: sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==} engines: {node: '>=10'} + get-symbol-description@1.1.0: + resolution: {integrity: sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==} + engines: {node: '>= 0.4'} + git-raw-commits@5.0.1: resolution: {integrity: sha512-Y+csSm2GD/PCSh6Isd/WiMjNAydu0VBiG9J7EdQsNA5P9uXvLayqjmTsNlK5Gs9IhblFZqOU0yid5Il5JPoLiQ==} engines: {node: '>=18'} @@ -2896,6 +3089,10 @@ packages: resolution: {integrity: sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==} engines: {node: '>=18'} + globalthis@1.0.4: + resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} + engines: {node: '>= 0.4'} + glsl-inject-defines@1.0.3: resolution: {integrity: sha512-W49jIhuDtF6w+7wCMcClk27a2hq8znvHtlGnrYkSWEr8tHe9eA2dcnohlcAmxLYBSpSSdzOkRdyPTrx9fw49+A==} @@ -2960,8 +3157,12 @@ packages: engines: {node: '>=0.4.7'} hasBin: true - handsign-multilingual@0.3.0: - resolution: {integrity: sha512-UbSyiYAAcI3squisXWS77nzICTXV1V9+DVzQ12Yij1b74HWhXYDsI3bDyyHsN9gnuoAGdRlILvByUNQ249mNqw==} + handsign-multilingual@0.5.0: + resolution: {integrity: sha512-/gp/0GqRVjYDT4gVQjCIj9zJLC2fRi8xXSHFqow5nqchNrdxUhOudIFORLa/kdOfyrQIL3uTjwKB03jWKTxBoQ==} + + has-bigints@1.1.0: + resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==} + engines: {node: '>= 0.4'} has-flag@4.0.0: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} @@ -2973,6 +3174,13 @@ packages: has-passive-events@1.0.0: resolution: {integrity: sha512-2vSj6IeIsgvsRMyeQ0JaCX5Q3lX4zMn5HpoVc7MEhQ6pv8Iq9rsXjsp+E5ZwaT7T0xhMT0KmU8gtt1EFVdbJiw==} + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + + has-proto@1.2.0: + resolution: {integrity: sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==} + engines: {node: '>= 0.4'} + has-symbols@1.1.0: resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} engines: {node: '>= 0.4'} @@ -3090,9 +3298,18 @@ packages: resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} engines: {node: '>= 14'} + hyparquet-compressors@1.1.2: + resolution: {integrity: sha512-0Hx6w0ZpVpNCefKy5xBYLTp6rKeZn/tsUzuliNzfKqSCdLcTQSfwATEoeedS703Y17k1qNS61HwRME5aOeNkPg==} + + hyparquet@1.31.2: + resolution: {integrity: sha512-dpVTCGkPPIdfDExa7YZGaJpuBTmLFDKGeZ6meHUj1mz/Q3qmaQHGLLqCyPBkQjfxrYNb08YTax682qeGO+zkVA==} + hyphenate-style-name@1.1.0: resolution: {integrity: sha512-WDC/ui2VVRrz3jOVi+XtjqkDjiVjTtFaAGiW37k6b+ohyQ5wYDOGkvCZa8+H0nx3gyvv0+BST9xuOgIyGQ00gw==} + hysnappy@1.1.1: + resolution: {integrity: sha512-/V9XcN2NtRyWjR4LYMfvnvasVVF8jbT/ej0eofBQjZel91E3D813FQ3mQC6gDSMMTCq/FJh28XHeyqr3I/oBRw==} + i18next-http-backend@3.0.6: resolution: {integrity: sha512-mBOqy8993jtqAoj6XaI1XeC/8/9v6EPS+681ziegrPvTB0DoaCY7PpTS0SpY56qLMoS4OI1TZEM2Zf59zNh05w==} @@ -3126,12 +3343,6 @@ packages: immediate@3.0.6: resolution: {integrity: sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==} - immer@10.2.0: - resolution: {integrity: sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==} - - immer@11.1.8: - resolution: {integrity: sha512-/tbkHMW7y10Lx6i1crLjD4/OhNkRG+Fo7byZHtah0547nIeXYcpIXaUh0IAQY6gO5459qpGGYapcEOHtFXkIuA==} - import-fresh@3.3.1: resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==} engines: {node: '>=6'} @@ -3172,6 +3383,10 @@ packages: inline-style-prefixer@3.0.8: resolution: {integrity: sha512-ne8XIyyqkRaNJ1JfL1NYzNdCNxq+MCBQhC8NgOQlzNm2vv3XxlP0VSLQUbSRCF6KPEoveCVEpayHoHzcMyZsMQ==} + internal-slot@1.1.0: + resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==} + engines: {node: '>= 0.4'} + internmap@1.0.1: resolution: {integrity: sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==} @@ -3191,23 +3406,59 @@ packages: is-any-array@3.0.0: resolution: {integrity: sha512-o4h+tylWykC4BD1vaejp6gDxoM13bwW8FGuNs4yIKpj8xbBJcRxJx8vZpq0dCr7ZDEfeKjmsi/euolKhX6f/ww==} + is-array-buffer@3.0.5: + resolution: {integrity: sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==} + engines: {node: '>= 0.4'} + is-arrayish@0.2.1: resolution: {integrity: sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==} + is-async-function@2.1.1: + resolution: {integrity: sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==} + engines: {node: '>= 0.4'} + + is-bigint@1.1.0: + resolution: {integrity: sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==} + engines: {node: '>= 0.4'} + + is-boolean-object@1.2.2: + resolution: {integrity: sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==} + engines: {node: '>= 0.4'} + is-browser@2.1.0: resolution: {integrity: sha512-F5rTJxDQ2sW81fcfOR1GnCXT6sVJC104fCyfj+mjpwNEwaPYSn5fte5jiHmBg3DHsIoL/l8Kvw5VN5SsTRcRFQ==} + is-callable@1.2.7: + resolution: {integrity: sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==} + engines: {node: '>= 0.4'} + is-core-module@2.16.2: resolution: {integrity: sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==} engines: {node: '>= 0.4'} + is-data-view@1.0.2: + resolution: {integrity: sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==} + engines: {node: '>= 0.4'} + + is-date-object@1.1.0: + resolution: {integrity: sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==} + engines: {node: '>= 0.4'} + is-decimal@2.0.1: resolution: {integrity: sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==} + is-document.all@1.0.0: + resolution: {integrity: sha512-+XSoyS05OdBbhFuELhgTCpFNHkpBOJqtsZfUFFpe5QTw+9Sjbh8zitxhQkYAo6wV7e1Vb8cAPvpCk9jGam/82g==} + engines: {node: '>= 0.4'} + is-extglob@2.1.1: resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} engines: {node: '>=0.10.0'} + is-finalizationregistry@1.1.1: + resolution: {integrity: sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==} + engines: {node: '>= 0.4'} + is-finite@1.1.0: resolution: {integrity: sha512-cdyMtqX/BOqqNBBiKlIVkytNHm49MtMlYyn1zxzvJKWmFMlGzm+ry5BBfYyeY9YmNKbRSo/o7OX9w9ale0wg3w==} engines: {node: '>=0.10.0'} @@ -3220,6 +3471,10 @@ packages: resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} engines: {node: '>=8'} + is-generator-function@1.1.2: + resolution: {integrity: sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==} + engines: {node: '>= 0.4'} + is-glob@4.0.3: resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} engines: {node: '>=0.10.0'} @@ -3233,9 +3488,21 @@ packages: is-lite@1.2.1: resolution: {integrity: sha512-pgF+L5bxC+10hLBgf6R2P4ZZUBOQIIacbdo8YvuCP8/JvsWxG7aZ9p10DYuLtifFci4l3VITphhMlMV4Y+urPw==} + is-map@2.0.3: + resolution: {integrity: sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==} + engines: {node: '>= 0.4'} + is-mobile@4.0.0: resolution: {integrity: sha512-mlcHZA84t1qLSuWkt2v0I2l61PYdyQDt4aG1mLIXF5FDMm4+haBCxCPYSr/uwqQNRk1MiTizn0ypEuRAOLRAew==} + is-negative-zero@2.0.3: + resolution: {integrity: sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==} + engines: {node: '>= 0.4'} + + is-number-object@1.1.1: + resolution: {integrity: sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==} + engines: {node: '>= 0.4'} + is-obj@1.0.1: resolution: {integrity: sha512-l4RyHgRqGN4Y3+9JHVrNqO+tN0rV5My76uW5/nuO4K1b6vw5G8d/cmFjP9tRfEsdhZNt0IFdZuK/c2Vr4Nb+Qg==} engines: {node: '>=0.10.0'} @@ -3255,6 +3522,18 @@ packages: is-potential-custom-element-name@1.0.1: resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + is-regex@1.2.1: + resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} + engines: {node: '>= 0.4'} + + is-set@2.0.3: + resolution: {integrity: sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==} + engines: {node: '>= 0.4'} + + is-shared-array-buffer@1.0.4: + resolution: {integrity: sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==} + engines: {node: '>= 0.4'} + is-stream@1.1.0: resolution: {integrity: sha512-uQPm8kcs47jx38atAcWTVxyltQYoPT68y9aWYdV6yWXSyW8mzSat0TL6CiWdZeCdF3KrAvpVtnHbTv4RN+rqdQ==} engines: {node: '>=0.10.0'} @@ -3262,9 +3541,33 @@ packages: is-string-blank@1.0.1: resolution: {integrity: sha512-9H+ZBCVs3L9OYqv8nuUAzpcT9OTgMD1yAWrG7ihlnibdkbtB850heAmYWxHuXc4CHy4lKeK69tN+ny1K7gBIrw==} + is-string@1.1.1: + resolution: {integrity: sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==} + engines: {node: '>= 0.4'} + is-svg-path@1.0.2: resolution: {integrity: sha512-Lj4vePmqpPR1ZnRctHv8ltSh1OrSxHkhUkd7wi+VQdcdP15/KvQFyk7LhNuM7ZW0EVbJz8kZLVmL9quLrfq4Kg==} + is-symbol@1.1.1: + resolution: {integrity: sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==} + engines: {node: '>= 0.4'} + + is-typed-array@1.1.15: + resolution: {integrity: sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==} + engines: {node: '>= 0.4'} + + is-weakmap@2.0.2: + resolution: {integrity: sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==} + engines: {node: '>= 0.4'} + + is-weakref@1.1.1: + resolution: {integrity: sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==} + engines: {node: '>= 0.4'} + + is-weakset@2.0.4: + resolution: {integrity: sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==} + engines: {node: '>= 0.4'} + isarray@0.0.1: resolution: {integrity: sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==} @@ -3349,6 +3652,10 @@ packages: engines: {node: '>=6'} hasBin: true + jsx-ast-utils@3.3.5: + resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==} + engines: {node: '>=4.0'} + jszip-utils@0.1.0: resolution: {integrity: sha512-tBNe0o3HAf8vo0BrOYnLPnXNo5A3KsRMnkBFYjh20Y3GPYGfgyoclEMgvVchx0nnL+mherPi74yLPIusHUQpZg==} @@ -3375,6 +3682,13 @@ packages: resolution: {integrity: sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==} engines: {node: '>=0.10.0'} + language-subtag-registry@0.3.23: + resolution: {integrity: sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==} + + language-tags@1.0.9: + resolution: {integrity: sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA==} + engines: {node: '>=0.10'} + levn@0.4.1: resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} engines: {node: '>= 0.8.0'} @@ -3467,9 +3781,9 @@ packages: resolution: {integrity: sha512-9W0yGtkaMAkf74XGYVy4Dqw3YUMnTNB2eeiw9aQbUl4A3KmuCEHTt2DgAB07ENzOYAjsYSAYufkAq0Zd+jU7zA==} engines: {node: '>=0.10.0'} - mathjs@11.12.0: - resolution: {integrity: sha512-UGhVw8rS1AyedyI55DGz9q1qZ0p98kyKPyc9vherBkoueLntPfKtPBh14x+V4cdUWK0NZV2TBwqRFlvadscSuw==} - engines: {node: '>= 14'} + mathjs@12.4.3: + resolution: {integrity: sha512-oHdGPDbp7gO873xxG90RLq36IuicuKvbpr/bBG5g9c8Obm/VsKVrK9uoRZZHUodohzlnmCEqfDzbR3LH6m+aAQ==} + engines: {node: '>= 18'} hasBin: true mdast-util-find-and-replace@3.0.2: @@ -3765,6 +4079,26 @@ packages: resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} engines: {node: '>=0.10.0'} + object-inspect@1.13.4: + resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==} + engines: {node: '>= 0.4'} + + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + + object.assign@4.1.7: + resolution: {integrity: sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==} + engines: {node: '>= 0.4'} + + object.fromentries@2.0.8: + resolution: {integrity: sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==} + engines: {node: '>= 0.4'} + + object.values@1.2.1: + resolution: {integrity: sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==} + engines: {node: '>= 0.4'} + obug@2.1.3: resolution: {integrity: sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==} engines: {node: '>=12.20.0'} @@ -3779,6 +4113,10 @@ packages: resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} engines: {node: '>= 0.8.0'} + own-keys@1.0.2: + resolution: {integrity: sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg==} + engines: {node: '>= 0.4'} + p-limit@2.3.0: resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==} engines: {node: '>=6'} @@ -3877,6 +4215,16 @@ packages: resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} engines: {node: '>=12'} + playwright-core@1.62.1: + resolution: {integrity: sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.62.1: + resolution: {integrity: sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==} + engines: {node: '>=20'} + hasBin: true + plotly.js-dist-min@2.8.0: resolution: {integrity: sha512-6OOg/D7OEffYq1WJt4XKNHzJAd9uN3kCuKZcCr0RGvnSB3wvP7fDmfsUpxZR2q0M+3j7SKejJ8qv1HGkarnObg==} @@ -3894,6 +4242,10 @@ packages: resolution: {integrity: sha512-Wb4p1J4zyFTbM+u6WuO4XstYx4Ky9Cewe4DWrel7B0w6VVICvPwdOpotjzcf6eD8TsckVnIMNONQyPIUFOUbCQ==} deprecated: You can find the new Popper v2 at @popperjs/core, this package is dedicated to the legacy v1 + possible-typed-array-names@1.1.0: + resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} + engines: {node: '>= 0.4'} + postcss@8.5.15: resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==} engines: {node: ^10 || ^12 || >=14} @@ -3950,6 +4302,9 @@ packages: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} + qrcode-generator@2.0.4: + resolution: {integrity: sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==} + quickselect@2.0.0: resolution: {integrity: sha512-RKJ22hX8mHe3Y6wH/N3wCM6BWtjaxIyyUIkpHOvfFnxdI4yD4tBXEBKSbriGujF6jnSVkJrffuo6vxACiSSxIw==} @@ -4062,18 +4417,6 @@ packages: plotly.js: '>1.34.0' react: '>0.13.0' - react-redux@9.3.0: - resolution: {integrity: sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==} - peerDependencies: - '@types/react': ^18.2.25 || ^19 - react: ^18.0 || ^19 - redux: ^5.0.0 - peerDependenciesMeta: - '@types/react': - optional: true - redux: - optional: true - react-refresh@0.18.0: resolution: {integrity: sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==} engines: {node: '>=0.10.0'} @@ -4139,25 +4482,13 @@ packages: resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} engines: {node: '>= 6'} - recharts@3.8.1: - resolution: {integrity: sha512-mwzmO1s9sFL0TduUpwndxCUNoXsBw3u3E/0+A+cLcrSfQitSG62L32N69GhqUrrT5qKcAE3pCGVINC6pqkBBQg==} - engines: {node: '>=18'} - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - react-dom: ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - react-is: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - redent@3.0.0: resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==} engines: {node: '>=8'} - redux-thunk@3.1.0: - resolution: {integrity: sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==} - peerDependencies: - redux: ^5.0.0 - - redux@5.0.1: - resolution: {integrity: sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==} + reflect.getprototypeof@1.0.10: + resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==} + engines: {node: '>= 0.4'} refractor@5.0.0: resolution: {integrity: sha512-QXOrHQF5jOpjjLfiNk5GFnWhRXvxjUVnlFxkeDmewR5sXkr3iM46Zo+CnRR8B+MDVqkULW4EcLVcRBNOPXHosw==} @@ -4165,6 +4496,10 @@ packages: regenerator-runtime@0.13.11: resolution: {integrity: sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==} + regexp.prototype.flags@1.5.4: + resolution: {integrity: sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==} + engines: {node: '>= 0.4'} + regl-error2d@2.0.12: resolution: {integrity: sha512-r7BUprZoPO9AbyqM5qlJesrSRkl+hZnVKWKsVp7YhOl/3RIpi4UDGASGJY0puQ96u5fBYw/OlqV24IGcgJ0McA==} @@ -4215,9 +4550,6 @@ packages: require-main-filename@2.0.0: resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==} - reselect@5.1.1: - resolution: {integrity: sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==} - resolve-from@4.0.0: resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} engines: {node: '>=4'} @@ -4255,12 +4587,24 @@ packages: rw@1.3.3: resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==} + safe-array-concat@1.1.4: + resolution: {integrity: sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==} + engines: {node: '>=0.4'} + safe-buffer@5.1.2: resolution: {integrity: sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==} safe-buffer@5.2.1: resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + safe-push-apply@1.0.0: + resolution: {integrity: sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==} + engines: {node: '>= 0.4'} + + safe-regex-test@1.1.0: + resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==} + engines: {node: '>= 0.4'} + safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} @@ -4299,6 +4643,18 @@ packages: set-cookie-parser@2.7.2: resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==} + set-function-length@1.2.2: + resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==} + engines: {node: '>= 0.4'} + + set-function-name@2.0.2: + resolution: {integrity: sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==} + engines: {node: '>= 0.4'} + + set-proto@1.0.0: + resolution: {integrity: sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==} + engines: {node: '>= 0.4'} + setimmediate@1.0.5: resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==} @@ -4313,6 +4669,22 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} + side-channel-list@1.0.1: + resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} + engines: {node: '>= 0.4'} + + side-channel-map@1.0.1: + resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==} + engines: {node: '>= 0.4'} + + side-channel-weakmap@1.0.2: + resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==} + engines: {node: '>= 0.4'} + + side-channel@1.1.1: + resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} + engines: {node: '>= 0.4'} + siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} @@ -4368,7 +4740,11 @@ packages: std-env@4.1.0: resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==} - stream-parser@0.3.1: + stop-iteration-iterator@1.1.0: + resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==} + engines: {node: '>= 0.4'} + + stream-parser@0.3.1: resolution: {integrity: sha512-bJ/HgKq41nlKvlhccD5kaCr/P+Hu0wPNKPJOH7en+YrJu/9EgqUF+88w5Jb6KNcjOFMhfX4B2asfeAtIGuHObQ==} stream-shift@1.0.3: @@ -4381,6 +4757,22 @@ packages: resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} engines: {node: '>=8'} + string.prototype.includes@2.0.1: + resolution: {integrity: sha512-o7+c9bW6zpAdJHTtujeePODAhkuicdAryFsfVKwA+wGw89wJ4GTY484WTucM9hLtDEOpOvI+aHnzqnC5lHp4Rg==} + engines: {node: '>= 0.4'} + + string.prototype.trim@1.2.11: + resolution: {integrity: sha512-PwvK7BU+CMTJGYQCTZb5RWXIML92lftJLhQz1tBzgKiqGxJaMlBAa48POXaNAC2s4y8jr3EFqrkF9+44neS46w==} + engines: {node: '>= 0.4'} + + string.prototype.trimend@1.0.10: + resolution: {integrity: sha512-2+3aDAOmPTmuFwjDnmJG2ctEkQKVki7vOSqaxkv42Mowj1V6PnvuwFCRrR5lChUux1TBskPjfkeTOhqczDMxTw==} + engines: {node: '>= 0.4'} + + string.prototype.trimstart@1.0.8: + resolution: {integrity: sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==} + engines: {node: '>= 0.4'} + string_decoder@0.10.31: resolution: {integrity: sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ==} @@ -4482,9 +4874,6 @@ packages: tiny-emitter@2.1.0: resolution: {integrity: sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q==} - tiny-invariant@1.3.3: - resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==} - tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} @@ -4579,6 +4968,22 @@ packages: type@2.7.3: resolution: {integrity: sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==} + typed-array-buffer@1.0.3: + resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==} + engines: {node: '>= 0.4'} + + typed-array-byte-length@1.0.3: + resolution: {integrity: sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==} + engines: {node: '>= 0.4'} + + typed-array-byte-offset@1.0.5: + resolution: {integrity: sha512-0FHJvLPqZ7KJzp17O13jfsAjsqazgrxBu2zEK95PmUz8lv2+GjRuxUInCr2Rk9Dms3ihN21zJ929ZO43yJ95QQ==} + engines: {node: '>= 0.4'} + + typed-array-length@1.0.8: + resolution: {integrity: sha512-phPGCwqr2+Qo0fwniCE8e4pKnGu/yFb5nD5Y8bf0EEeiI5GklnACYA9GFy/DrAeRrKHXvHn+1SUsOWgJp6RO+g==} + engines: {node: '>= 0.4'} + typed-function@4.2.2: resolution: {integrity: sha512-VwaXim9Gp1bngi/q3do8hgttYn2uC3MoT/gfuMWylnj1IeZBUAyPddHZlo1K05BDoj8DYPpMdiHqH1dDYdJf2A==} engines: {node: '>= 18'} @@ -4610,6 +5015,10 @@ packages: engines: {node: '>=0.8.0'} hasBin: true + unbox-primitive@1.1.0: + resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==} + engines: {node: '>= 0.4'} + uncontrollable@7.2.1: resolution: {integrity: sha512-svtcfoTADIB0nT9nltgjujTi7BzVmwjZClOmskKu/E8FW9BXzg9os8OLr4f8Dlnk0rYWJIWr4wv9eKUXiQvQwQ==} peerDependencies: @@ -4837,9 +5246,6 @@ packages: vfile@6.0.3: resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==} - victory-vendor@37.3.6: - resolution: {integrity: sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==} - vis-data@7.1.10: resolution: {integrity: sha512-23juM9tdCaHTX5vyIQ7XBzsfZU0Hny+gSTwniLrfFcmw9DOm7pi3+h9iEBsoZMp5rX6KNqWwc1MF0fkAmWVuoQ==} peerDependencies: @@ -4997,9 +5403,25 @@ packages: whatwg-url@5.0.0: resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} + which-boxed-primitive@1.1.1: + resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==} + engines: {node: '>= 0.4'} + + which-builtin-type@1.2.1: + resolution: {integrity: sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==} + engines: {node: '>= 0.4'} + + which-collection@1.0.2: + resolution: {integrity: sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==} + engines: {node: '>= 0.4'} + which-module@2.0.1: resolution: {integrity: sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==} + which-typed-array@1.1.24: + resolution: {integrity: sha512-wk4Mf4pR5mRP7eYuuTBCIQ9d0ud2Fv2jRLQpfgnRjbOxAFHmjKFValgTpitVKzJJS8ajnYQV2Du1SZ8j6b/EUQ==} + engines: {node: '>= 0.4'} + which@2.0.2: resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} engines: {node: '>= 8'} @@ -5149,6 +5571,11 @@ snapshots: '@asamuzakjp/nwsapi@2.3.9': {} + '@axe-core/playwright@4.13.0(playwright-core@1.62.1)': + dependencies: + axe-core: 4.13.0 + playwright-core: 1.62.1 + '@babel/code-frame@7.29.7': dependencies: '@babel/helper-validator-identifier': 7.29.7 @@ -5657,6 +6084,10 @@ snapshots: '@mediapipe/pose@0.5.1675469404': {} + '@playwright/test@1.62.1': + dependencies: + playwright: 1.62.1 + '@plotly/d3-sankey-circular@0.33.1': dependencies: d3-array: 1.2.4 @@ -5729,18 +6160,6 @@ snapshots: dependencies: react: 19.2.7 - '@reduxjs/toolkit@2.12.0(react-redux@9.3.0(@types/react@19.2.17)(react@19.2.7)(redux@5.0.1))(react@19.2.7)': - dependencies: - '@standard-schema/spec': 1.1.0 - '@standard-schema/utils': 0.3.0 - immer: 11.1.8 - redux: 5.0.1 - redux-thunk: 3.1.0(redux@5.0.1) - reselect: 5.1.1 - optionalDependencies: - react: 19.2.7 - react-redux: 9.3.0(@types/react@19.2.17)(react@19.2.7)(redux@5.0.1) - '@restart/hooks@0.4.16(react@19.2.7)': dependencies: dequal: 2.0.3 @@ -5858,8 +6277,6 @@ snapshots: '@standard-schema/spec@1.1.0': {} - '@standard-schema/utils@0.3.0': {} - '@stylistic/eslint-plugin@5.10.0(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0))': dependencies: '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0)) @@ -6126,6 +6543,95 @@ snapshots: dependencies: '@testing-library/dom': 10.4.1 + '@tsparticles/animation-utils@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/basic@4.4.0': + dependencies: + '@tsparticles/engine': 4.4.0 + '@tsparticles/plugin-blend': 4.4.0(@tsparticles/engine@4.4.0) + '@tsparticles/plugin-hex-color': 4.4.0(@tsparticles/engine@4.4.0) + '@tsparticles/plugin-hsl-color': 4.4.0(@tsparticles/engine@4.4.0) + '@tsparticles/plugin-move': 4.4.0(@tsparticles/engine@4.4.0) + '@tsparticles/plugin-rgb-color': 4.4.0(@tsparticles/engine@4.4.0) + '@tsparticles/shape-circle': 4.4.0(@tsparticles/engine@4.4.0) + '@tsparticles/updater-opacity': 4.4.0(@tsparticles/engine@4.4.0) + '@tsparticles/updater-out-modes': 4.4.0(@tsparticles/engine@4.4.0) + '@tsparticles/updater-paint': 4.4.0(@tsparticles/engine@4.4.0) + '@tsparticles/updater-size': 4.4.0(@tsparticles/engine@4.4.0) + + '@tsparticles/canvas-utils@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/engine@4.4.0': {} + + '@tsparticles/interaction-particles-collisions@4.4.0(@tsparticles/engine@4.4.0)(@tsparticles/plugin-interactivity@4.4.0(@tsparticles/engine@4.4.0))': + dependencies: + '@tsparticles/engine': 4.4.0 + '@tsparticles/plugin-interactivity': 4.4.0(@tsparticles/engine@4.4.0) + + '@tsparticles/interaction-particles-links@4.4.0(@tsparticles/engine@4.4.0)(@tsparticles/plugin-interactivity@4.4.0(@tsparticles/engine@4.4.0))': + dependencies: + '@tsparticles/canvas-utils': 4.4.0(@tsparticles/engine@4.4.0) + '@tsparticles/engine': 4.4.0 + '@tsparticles/plugin-interactivity': 4.4.0(@tsparticles/engine@4.4.0) + + '@tsparticles/particles@4.4.0': + dependencies: + '@tsparticles/basic': 4.4.0 + '@tsparticles/engine': 4.4.0 + '@tsparticles/interaction-particles-collisions': 4.4.0(@tsparticles/engine@4.4.0)(@tsparticles/plugin-interactivity@4.4.0(@tsparticles/engine@4.4.0)) + '@tsparticles/interaction-particles-links': 4.4.0(@tsparticles/engine@4.4.0)(@tsparticles/plugin-interactivity@4.4.0(@tsparticles/engine@4.4.0)) + '@tsparticles/plugin-interactivity': 4.4.0(@tsparticles/engine@4.4.0) + + '@tsparticles/plugin-blend@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/plugin-hex-color@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/plugin-hsl-color@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/plugin-interactivity@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/plugin-move@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/plugin-rgb-color@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/shape-circle@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/updater-opacity@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/animation-utils': 4.4.0(@tsparticles/engine@4.4.0) + '@tsparticles/engine': 4.4.0 + + '@tsparticles/updater-out-modes@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/updater-paint@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/engine': 4.4.0 + + '@tsparticles/updater-size@4.4.0(@tsparticles/engine@4.4.0)': + dependencies: + '@tsparticles/animation-utils': 4.4.0(@tsparticles/engine@4.4.0) + '@tsparticles/engine': 4.4.0 + '@turf/area@7.3.5': dependencies: '@turf/helpers': 7.3.5 @@ -6188,32 +6694,8 @@ snapshots: '@types/clone@0.1.30': {} - '@types/d3-array@3.2.2': {} - - '@types/d3-color@3.1.3': {} - - '@types/d3-ease@3.0.2': {} - - '@types/d3-interpolate@3.0.4': - dependencies: - '@types/d3-color': 3.1.3 - - '@types/d3-path@3.1.1': {} - '@types/d3-random@3.0.4': {} - '@types/d3-scale@4.0.9': - dependencies: - '@types/d3-time': 3.0.4 - - '@types/d3-shape@3.1.8': - dependencies: - '@types/d3-path': 3.1.1 - - '@types/d3-time@3.0.4': {} - - '@types/d3-timer@3.0.2': {} - '@types/debug@4.1.13': dependencies: '@types/ms': 2.1.0 @@ -6232,8 +6714,6 @@ snapshots: dependencies: fast-json-stable-stringify: 2.1.0 - '@types/fingerpose@0.1.1': {} - '@types/geojson-vt@3.2.5': dependencies: '@types/geojson': 7946.0.16 @@ -6283,6 +6763,10 @@ snapshots: '@types/offscreencanvas@2019.7.3': {} + '@types/papaparse@5.5.2': + dependencies: + '@types/node': 24.13.2 + '@types/pbf@3.0.5': {} '@types/plotly.js@3.0.10': {} @@ -6322,8 +6806,6 @@ snapshots: '@types/unist@3.0.3': {} - '@types/use-sync-external-store@0.0.6': {} - '@types/warning@3.0.4': {} '@typescript-eslint/eslint-plugin@8.61.1(@typescript-eslint/parser@8.61.1(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': @@ -6419,6 +6901,10 @@ snapshots: '@ungap/structured-clone@1.3.1': {} + '@vitejs/plugin-basic-ssl@2.3.0(vite@7.3.5(@types/node@24.13.2)(jiti@2.7.0))': + dependencies: + vite: 7.3.5(@types/node@24.13.2)(jiti@2.7.0) + '@vitejs/plugin-react@5.2.0(supports-color@7.2.0)(vite@7.3.5(@types/node@24.13.2)(jiti@2.7.0))': dependencies: '@babel/core': 7.29.7(supports-color@7.2.0) @@ -6483,7 +6969,7 @@ snapshots: convert-source-map: 2.0.0 tinyrainbow: 3.1.0 - '@vladmandic/face-api@1.7.15': {} + '@vladmandic/face-api@1.7.15(patch_hash=1ec24e4d9002c522523e5c010aaad4a200d243a86622f7d9aa620936e6634c85)': {} '@webgpu/types@0.1.38': {} @@ -6562,28 +7048,80 @@ snapshots: array-bounds@1.0.1: {} + array-buffer-byte-length@1.0.2: + dependencies: + call-bound: 1.0.4 + is-array-buffer: 3.0.5 + array-find-index@1.0.2: {} array-flat-polyfill@1.0.1: {} array-ify@1.0.0: {} + array-includes@3.2.0: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-object-atoms: 1.1.2 + es-shim-unscopables: 1.1.0 + is-string: 1.1.1 + math-intrinsics: 1.1.0 + array-normalize@1.1.4: dependencies: array-bounds: 1.0.1 array-range@1.0.1: {} + array.prototype.flat@1.3.3: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-shim-unscopables: 1.1.0 + + array.prototype.flatmap@1.3.3: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-shim-unscopables: 1.1.0 + + arraybuffer.prototype.slice@1.0.4: + dependencies: + array-buffer-byte-length: 1.0.2 + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + is-array-buffer: 3.0.5 + asap@2.0.6: {} assertion-error@2.0.1: {} + ast-types-flow@0.0.8: {} + astral-regex@2.0.0: {} + async-function@1.0.0: {} + asynckit@0.4.0: {} attr-accept@2.2.5: {} + available-typed-arrays@1.0.7: + dependencies: + possible-typed-array-names: 1.1.0 + + axe-core@4.13.0: {} + + axobject-query@4.1.0: {} + bail@2.0.2: {} balanced-match@1.0.2: {} @@ -6639,6 +7177,18 @@ snapshots: es-errors: 1.3.0 function-bind: 1.1.2 + call-bind@1.0.9: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + get-intrinsic: 1.3.0 + set-function-length: 1.2.2 + + call-bound@1.0.4: + dependencies: + call-bind-apply-helpers: 1.0.2 + get-intrinsic: 1.3.0 + callsites@3.1.0: {} camelcase@5.3.1: {} @@ -6989,8 +7539,6 @@ snapshots: iconv-lite: 0.6.3 rw: 1.3.3 - d3-ease@3.0.1: {} - d3-force@1.2.1: dependencies: d3-collection: 1.0.7 @@ -7119,17 +7667,17 @@ snapshots: d3-timer@2.0.0: {} - d3-timer@3.0.1: {} - d@1.0.2: dependencies: es5-ext: 0.10.64 type: 2.7.3 + damerau-levenshtein@1.0.8: {} + danfojs@1.2.0(encoding@0.1.13)(seedrandom@3.0.5): dependencies: '@tensorflow/tfjs': 4.22.0(encoding@0.1.13)(seedrandom@3.0.5) - mathjs: 11.12.0 + mathjs: 12.4.3 papaparse: 5.5.3 plotly.js-dist-min: 2.8.0 table: 6.7.1 @@ -7143,6 +7691,24 @@ snapshots: whatwg-mimetype: 5.0.0 whatwg-url: 15.1.0 + data-view-buffer@1.0.2: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-data-view: 1.0.2 + + data-view-byte-length@1.0.2: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-data-view: 1.0.2 + + data-view-byte-offset@1.0.1: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-data-view: 1.0.2 + debug@2.6.9(supports-color@7.2.0): dependencies: ms: 2.0.0 @@ -7163,8 +7729,6 @@ snapshots: decamelize@1.2.0: {} - decimal.js-light@2.5.1: {} - decimal.js@10.6.0: {} decode-named-character-reference@1.3.0: @@ -7177,6 +7741,18 @@ snapshots: deepmerge@4.3.1: {} + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + defined@1.0.1: {} delaunator@4.0.1: {} @@ -7247,6 +7823,8 @@ snapshots: emoji-regex@8.0.0: {} + emoji-regex@9.2.2: {} + encoding@0.1.13: dependencies: iconv-lite: 0.6.3 @@ -7267,6 +7845,70 @@ snapshots: dependencies: is-arrayish: 0.2.1 + es-abstract-get@1.0.0: + dependencies: + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + is-callable: 1.2.7 + object-inspect: 1.13.4 + + es-abstract@1.24.2: + dependencies: + array-buffer-byte-length: 1.0.2 + arraybuffer.prototype.slice: 1.0.4 + available-typed-arrays: 1.0.7 + call-bind: 1.0.9 + call-bound: 1.0.4 + data-view-buffer: 1.0.2 + data-view-byte-length: 1.0.2 + data-view-byte-offset: 1.0.1 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + es-set-tostringtag: 2.1.0 + es-to-primitive: 1.3.4 + function.prototype.name: 1.2.0 + get-intrinsic: 1.3.0 + get-proto: 1.0.1 + get-symbol-description: 1.1.0 + globalthis: 1.0.4 + gopd: 1.2.0 + has-property-descriptors: 1.0.2 + has-proto: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.4 + internal-slot: 1.1.0 + is-array-buffer: 3.0.5 + is-callable: 1.2.7 + is-data-view: 1.0.2 + is-negative-zero: 2.0.3 + is-regex: 1.2.1 + is-set: 2.0.3 + is-shared-array-buffer: 1.0.4 + is-string: 1.1.1 + is-typed-array: 1.1.15 + is-weakref: 1.1.1 + math-intrinsics: 1.1.0 + object-inspect: 1.13.4 + object-keys: 1.1.1 + object.assign: 4.1.7 + own-keys: 1.0.2 + regexp.prototype.flags: 1.5.4 + safe-array-concat: 1.1.4 + safe-push-apply: 1.0.0 + safe-regex-test: 1.1.0 + set-proto: 1.0.0 + stop-iteration-iterator: 1.1.0 + string.prototype.trim: 1.2.11 + string.prototype.trimend: 1.0.10 + string.prototype.trimstart: 1.0.8 + typed-array-buffer: 1.0.3 + typed-array-byte-length: 1.0.3 + typed-array-byte-offset: 1.0.5 + typed-array-length: 1.0.8 + unbox-primitive: 1.1.0 + which-typed-array: 1.1.24 + es-define-property@1.0.1: {} es-errors@1.3.0: {} @@ -7284,6 +7926,19 @@ snapshots: has-tostringtag: 1.0.2 hasown: 2.0.4 + es-shim-unscopables@1.1.0: + dependencies: + hasown: 2.0.4 + + es-to-primitive@1.3.4: + dependencies: + es-abstract-get: 1.0.0 + es-define-property: 1.0.1 + es-errors: 1.3.0 + is-callable: 1.2.7 + is-date-object: 1.1.0 + is-symbol: 1.1.1 + es-toolkit@1.47.1: {} es5-ext@0.10.64: @@ -7362,6 +8017,25 @@ snapshots: optionalDependencies: source-map: 0.6.1 + eslint-plugin-jsx-a11y@6.10.2(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0)): + dependencies: + aria-query: 5.3.2 + array-includes: 3.2.0 + array.prototype.flatmap: 1.3.3 + ast-types-flow: 0.0.8 + axe-core: 4.13.0 + axobject-query: 4.1.0 + damerau-levenshtein: 1.0.8 + emoji-regex: 9.2.2 + eslint: 9.39.4(jiti@2.7.0)(supports-color@7.2.0) + hasown: 2.0.4 + jsx-ast-utils: 3.3.5 + language-tags: 1.0.9 + minimatch: 3.1.5 + object.fromentries: 2.0.8 + safe-regex-test: 1.1.0 + string.prototype.includes: 2.0.1 + eslint-plugin-react-hooks@7.1.1(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0): dependencies: '@babel/core': 7.29.7(supports-color@7.2.0) @@ -7471,8 +8145,6 @@ snapshots: d: 1.0.2 es5-ext: 0.10.64 - eventemitter3@5.0.4: {} - events@3.3.0: {} expect-type@1.3.0: {} @@ -7542,8 +8214,6 @@ snapshots: locate-path: 6.0.0 path-exists: 4.0.0 - fingerpose@0.1.0: {} - flat-cache@4.0.1: dependencies: flatted: 3.4.2 @@ -7563,6 +8233,10 @@ snapshots: dependencies: css-font: 1.2.0 + for-each@0.3.5: + dependencies: + is-callable: 1.2.7 + form-data@4.0.6: dependencies: asynckit: 0.4.0 @@ -7586,11 +8260,30 @@ snapshots: fs.realpath@1.0.0: {} + fsevents@2.3.2: + optional: true + fsevents@2.3.3: optional: true function-bind@1.1.2: {} + function.prototype.name@1.2.0: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + es-define-property: 1.0.1 + es-errors: 1.3.0 + functions-have-names: 1.2.3 + has-property-descriptors: 1.0.2 + hasown: 2.0.4 + is-callable: 1.2.7 + is-document.all: 1.0.0 + + functions-have-names@1.2.3: {} + + fzstd@0.1.1: {} + gauge@3.0.2: dependencies: aproba: 2.1.0 @@ -7603,6 +8296,8 @@ snapshots: strip-ansi: 6.0.1 wide-align: 1.1.5 + generator-function@2.0.1: {} + gensync@1.0.0-beta.2: {} geojson-vt@3.2.1: {} @@ -7633,6 +8328,12 @@ snapshots: get-stream@6.0.1: {} + get-symbol-description@1.1.0: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + git-raw-commits@5.0.1(conventional-commits-filter@5.0.0)(conventional-commits-parser@6.4.0): dependencies: '@conventional-changelog/git-client': 2.7.0(conventional-commits-filter@5.0.0)(conventional-commits-parser@6.4.0) @@ -7718,6 +8419,11 @@ snapshots: globals@16.5.0: {} + globalthis@1.0.4: + dependencies: + define-properties: 1.2.1 + gopd: 1.2.0 + glsl-inject-defines@1.0.3: dependencies: glsl-token-inject-block: 1.1.0 @@ -7817,7 +8523,9 @@ snapshots: optionalDependencies: uglify-js: 3.19.3 - handsign-multilingual@0.3.0: {} + handsign-multilingual@0.5.0: {} + + has-bigints@1.1.0: {} has-flag@4.0.0: {} @@ -7829,6 +8537,14 @@ snapshots: dependencies: is-browser: 2.1.0 + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + + has-proto@1.2.0: + dependencies: + dunder-proto: 1.0.1 + has-symbols@1.1.0: {} has-tostringtag@1.0.2: @@ -8044,8 +8760,17 @@ snapshots: transitivePeerDependencies: - supports-color + hyparquet-compressors@1.1.2: + dependencies: + fzstd: 0.1.1 + hysnappy: 1.1.1 + + hyparquet@1.31.2: {} + hyphenate-style-name@1.1.0: {} + hysnappy@1.1.1: {} + i18next-http-backend@3.0.6(encoding@0.1.13): dependencies: cross-fetch: 4.1.0(encoding@0.1.13) @@ -8074,10 +8799,6 @@ snapshots: immediate@3.0.6: {} - immer@10.2.0: {} - - immer@11.1.8: {} - import-fresh@3.3.1: dependencies: parent-module: 1.0.1 @@ -8109,6 +8830,12 @@ snapshots: bowser: 1.9.4 css-in-js-utils: 2.0.1 + internal-slot@1.1.0: + dependencies: + es-errors: 1.3.0 + hasown: 2.0.4 + side-channel: 1.1.1 + internmap@1.0.1: {} internmap@2.0.3: {} @@ -8126,24 +8853,76 @@ snapshots: is-any-array@3.0.0: {} + is-array-buffer@3.0.5: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + is-arrayish@0.2.1: {} + is-async-function@2.1.1: + dependencies: + async-function: 1.0.0 + call-bound: 1.0.4 + get-proto: 1.0.1 + has-tostringtag: 1.0.2 + safe-regex-test: 1.1.0 + + is-bigint@1.1.0: + dependencies: + has-bigints: 1.1.0 + + is-boolean-object@1.2.2: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + is-browser@2.1.0: {} + is-callable@1.2.7: {} + is-core-module@2.16.2: dependencies: hasown: 2.0.4 + is-data-view@1.0.2: + dependencies: + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + is-typed-array: 1.1.15 + + is-date-object@1.1.0: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + is-decimal@2.0.1: {} + is-document.all@1.0.0: + dependencies: + call-bound: 1.0.4 + is-extglob@2.1.1: {} + is-finalizationregistry@1.1.1: + dependencies: + call-bound: 1.0.4 + is-finite@1.1.0: {} is-firefox@1.0.3: {} is-fullwidth-code-point@3.0.0: {} + is-generator-function@1.1.2: + dependencies: + call-bound: 1.0.4 + generator-function: 2.0.1 + get-proto: 1.0.1 + has-tostringtag: 1.0.2 + safe-regex-test: 1.1.0 + is-glob@4.0.3: dependencies: is-extglob: 2.1.1 @@ -8154,8 +8933,17 @@ snapshots: is-lite@1.2.1: {} + is-map@2.0.3: {} + is-mobile@4.0.0: {} + is-negative-zero@2.0.3: {} + + is-number-object@1.1.1: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + is-obj@1.0.1: {} is-obj@2.0.0: {} @@ -8166,12 +8954,51 @@ snapshots: is-potential-custom-element-name@1.0.1: {} + is-regex@1.2.1: + dependencies: + call-bound: 1.0.4 + gopd: 1.2.0 + has-tostringtag: 1.0.2 + hasown: 2.0.4 + + is-set@2.0.3: {} + + is-shared-array-buffer@1.0.4: + dependencies: + call-bound: 1.0.4 + is-stream@1.1.0: {} is-string-blank@1.0.1: {} + is-string@1.1.1: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + is-svg-path@1.0.2: {} + is-symbol@1.1.1: + dependencies: + call-bound: 1.0.4 + has-symbols: 1.1.0 + safe-regex-test: 1.1.0 + + is-typed-array@1.1.15: + dependencies: + which-typed-array: 1.1.24 + + is-weakmap@2.0.2: {} + + is-weakref@1.1.1: + dependencies: + call-bound: 1.0.4 + + is-weakset@2.0.4: + dependencies: + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + isarray@0.0.1: {} isarray@1.0.0: {} @@ -8249,6 +9076,13 @@ snapshots: json5@2.2.3: {} + jsx-ast-utils@3.3.5: + dependencies: + array-includes: 3.2.0 + array.prototype.flat: 1.3.3 + object.assign: 4.1.7 + object.values: 1.2.1 + jszip-utils@0.1.0: {} jszip@3.10.1: @@ -8274,6 +9108,12 @@ snapshots: kind-of@6.0.3: {} + language-subtag-registry@0.3.23: {} + + language-tags@1.0.9: + dependencies: + language-subtag-registry: 0.3.23 + levn@0.4.1: dependencies: prelude-ls: 1.2.1 @@ -8402,7 +9242,7 @@ snapshots: math-log2@1.0.1: {} - mathjs@11.12.0: + mathjs@12.4.3: dependencies: '@babel/runtime': 7.29.7 complex.js: 2.4.3 @@ -8925,6 +9765,33 @@ snapshots: object-assign@4.1.1: {} + object-inspect@1.13.4: {} + + object-keys@1.1.1: {} + + object.assign@4.1.7: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-object-atoms: 1.1.2 + has-symbols: 1.1.0 + object-keys: 1.1.1 + + object.fromentries@2.0.8: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-object-atoms: 1.1.2 + + object.values@1.2.1: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-object-atoms: 1.1.2 + obug@2.1.3: {} once@1.3.3: @@ -8944,6 +9811,13 @@ snapshots: type-check: 0.4.0 word-wrap: 1.2.5 + own-keys@1.0.2: + dependencies: + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + object-keys: 1.1.1 + safe-push-apply: 1.0.0 + p-limit@2.3.0: dependencies: p-try: 2.2.0 @@ -9036,6 +9910,14 @@ snapshots: picomatch@4.0.4: {} + playwright-core@1.62.1: {} + + playwright@1.62.1: + dependencies: + playwright-core: 1.62.1 + optionalDependencies: + fsevents: 2.3.2 + plotly.js-dist-min@2.8.0: {} plotly.js@3.6.0(mapbox-gl@1.13.3)(supports-color@7.2.0): @@ -9093,6 +9975,8 @@ snapshots: popper.js@1.16.1: {} + possible-typed-array-names@1.1.0: {} + postcss@8.5.15: dependencies: nanoid: 3.3.12 @@ -9149,6 +10033,8 @@ snapshots: punycode@2.3.1: {} + qrcode-generator@2.0.4: {} + quickselect@2.0.0: {} quickselect@3.0.0: {} @@ -9295,15 +10181,6 @@ snapshots: prop-types: 15.8.1 react: 19.2.7 - react-redux@9.3.0(@types/react@19.2.17)(react@19.2.7)(redux@5.0.1): - dependencies: - '@types/use-sync-external-store': 0.0.6 - react: 19.2.7 - use-sync-external-store: 1.6.0(react@19.2.7) - optionalDependencies: - '@types/react': 19.2.17 - redux: 5.0.1 - react-refresh@0.18.0: {} react-router@7.18.0(react-dom@19.2.7(react@19.2.7))(react@19.2.7): @@ -9402,36 +10279,21 @@ snapshots: string_decoder: 1.3.0 util-deprecate: 1.0.2 - recharts@3.8.1(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react-is@17.0.2)(react@19.2.7)(redux@5.0.1): - dependencies: - '@reduxjs/toolkit': 2.12.0(react-redux@9.3.0(@types/react@19.2.17)(react@19.2.7)(redux@5.0.1))(react@19.2.7) - clsx: 2.1.1 - decimal.js-light: 2.5.1 - es-toolkit: 1.47.1 - eventemitter3: 5.0.4 - immer: 10.2.0 - react: 19.2.7 - react-dom: 19.2.7(react@19.2.7) - react-is: 17.0.2 - react-redux: 9.3.0(@types/react@19.2.17)(react@19.2.7)(redux@5.0.1) - reselect: 5.1.1 - tiny-invariant: 1.3.3 - use-sync-external-store: 1.6.0(react@19.2.7) - victory-vendor: 37.3.6 - transitivePeerDependencies: - - '@types/react' - - redux - redent@3.0.0: dependencies: indent-string: 4.0.0 strip-indent: 3.0.0 - redux-thunk@3.1.0(redux@5.0.1): + reflect.getprototypeof@1.0.10: dependencies: - redux: 5.0.1 - - redux@5.0.1: {} + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + get-intrinsic: 1.3.0 + get-proto: 1.0.1 + which-builtin-type: 1.2.1 refractor@5.0.0: dependencies: @@ -9442,6 +10304,15 @@ snapshots: regenerator-runtime@0.13.11: {} + regexp.prototype.flags@1.5.4: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-errors: 1.3.0 + get-proto: 1.0.1 + gopd: 1.2.0 + set-function-name: 2.0.2 + regl-error2d@2.0.12: dependencies: array-bounds: 1.0.1 @@ -9562,8 +10433,6 @@ snapshots: require-main-filename@2.0.0: {} - reselect@5.1.1: {} - resolve-from@4.0.0: {} resolve-from@5.0.0: {} @@ -9622,10 +10491,29 @@ snapshots: rw@1.3.3: {} + safe-array-concat@1.1.4: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + has-symbols: 1.1.0 + isarray: 2.0.5 + safe-buffer@5.1.2: {} safe-buffer@5.2.1: {} + safe-push-apply@1.0.0: + dependencies: + es-errors: 1.3.0 + isarray: 2.0.5 + + safe-regex-test@1.1.0: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-regex: 1.2.1 + safer-buffer@2.1.2: {} sax@1.6.0: {} @@ -9650,6 +10538,28 @@ snapshots: set-cookie-parser@2.7.2: {} + set-function-length@1.2.2: + dependencies: + define-data-property: 1.1.4 + es-errors: 1.3.0 + function-bind: 1.1.2 + get-intrinsic: 1.3.0 + gopd: 1.2.0 + has-property-descriptors: 1.0.2 + + set-function-name@2.0.2: + dependencies: + define-data-property: 1.1.4 + es-errors: 1.3.0 + functions-have-names: 1.2.3 + has-property-descriptors: 1.0.2 + + set-proto@1.0.0: + dependencies: + dunder-proto: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + setimmediate@1.0.5: {} shallow-copy@0.0.1: {} @@ -9660,6 +10570,34 @@ snapshots: shebang-regex@3.0.0: {} + side-channel-list@1.0.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.13.4 + + side-channel-map@1.0.1: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + object-inspect: 1.13.4 + + side-channel-weakmap@1.0.2: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + object-inspect: 1.13.4 + side-channel-map: 1.0.1 + + side-channel@1.1.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.13.4 + side-channel-list: 1.0.1 + side-channel-map: 1.0.1 + side-channel-weakmap: 1.0.2 + siginfo@2.0.0: {} signal-exit@3.0.7: {} @@ -9713,6 +10651,11 @@ snapshots: std-env@4.1.0: {} + stop-iteration-iterator@1.1.0: + dependencies: + es-errors: 1.3.0 + internal-slot: 1.1.0 + stream-parser@0.3.1(supports-color@7.2.0): dependencies: debug: 2.6.9(supports-color@7.2.0) @@ -9731,6 +10674,36 @@ snapshots: is-fullwidth-code-point: 3.0.0 strip-ansi: 6.0.1 + string.prototype.includes@2.0.1: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + + string.prototype.trim@1.2.11: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-data-property: 1.1.4 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-object-atoms: 1.1.2 + has-property-descriptors: 1.0.2 + safe-regex-test: 1.1.0 + + string.prototype.trimend@1.0.10: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-object-atoms: 1.1.2 + + string.prototype.trimstart@1.0.8: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-object-atoms: 1.1.2 + string_decoder@0.10.31: {} string_decoder@1.1.1: @@ -9847,8 +10820,6 @@ snapshots: tiny-emitter@2.1.0: {} - tiny-invariant@1.3.3: {} - tinybench@2.9.0: {} tinycolor2@1.6.0: {} @@ -9926,6 +10897,38 @@ snapshots: type@2.7.3: {} + typed-array-buffer@1.0.3: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-typed-array: 1.1.15 + + typed-array-byte-length@1.0.3: + dependencies: + call-bind: 1.0.9 + for-each: 0.3.5 + gopd: 1.2.0 + has-proto: 1.2.0 + is-typed-array: 1.1.15 + + typed-array-byte-offset@1.0.5: + dependencies: + available-typed-arrays: 1.0.7 + call-bind: 1.0.9 + for-each: 0.3.5 + gopd: 1.2.0 + is-typed-array: 1.1.15 + reflect.getprototypeof: 1.0.10 + + typed-array-length@1.0.8: + dependencies: + call-bind: 1.0.9 + for-each: 0.3.5 + gopd: 1.2.0 + is-typed-array: 1.1.15 + possible-typed-array-names: 1.1.0 + reflect.getprototypeof: 1.0.10 + typed-function@4.2.2: {} typedarray-pool@1.2.0: @@ -9953,6 +10956,13 @@ snapshots: uglify-js@3.19.3: optional: true + unbox-primitive@1.1.0: + dependencies: + call-bound: 1.0.4 + has-bigints: 1.1.0 + has-symbols: 1.1.0 + which-boxed-primitive: 1.1.1 + uncontrollable@7.2.1(react@19.2.7): dependencies: '@babel/runtime': 7.29.7 @@ -10414,23 +11424,6 @@ snapshots: '@types/unist': 3.0.3 vfile-message: 4.0.3 - victory-vendor@37.3.6: - dependencies: - '@types/d3-array': 3.2.2 - '@types/d3-ease': 3.0.2 - '@types/d3-interpolate': 3.0.4 - '@types/d3-scale': 4.0.9 - '@types/d3-shape': 3.1.8 - '@types/d3-time': 3.0.4 - '@types/d3-timer': 3.0.2 - d3-array: 3.2.4 - d3-ease: 3.0.1 - d3-interpolate: 3.0.1 - d3-scale: 4.0.2 - d3-shape: 3.2.0 - d3-time: 3.1.0 - d3-timer: 3.0.1 - vis-data@7.1.10(uuid@11.1.1)(vis-util@5.0.7(@egjs/hammerjs@2.0.17)(component-emitter@2.0.0)): dependencies: uuid: 11.1.1 @@ -10547,8 +11540,49 @@ snapshots: tr46: 0.0.3 webidl-conversions: 3.0.1 + which-boxed-primitive@1.1.1: + dependencies: + is-bigint: 1.1.0 + is-boolean-object: 1.2.2 + is-number-object: 1.1.1 + is-string: 1.1.1 + is-symbol: 1.1.1 + + which-builtin-type@1.2.1: + dependencies: + call-bound: 1.0.4 + function.prototype.name: 1.2.0 + has-tostringtag: 1.0.2 + is-async-function: 2.1.1 + is-date-object: 1.1.0 + is-finalizationregistry: 1.1.1 + is-generator-function: 1.1.2 + is-regex: 1.2.1 + is-weakref: 1.1.1 + isarray: 2.0.5 + which-boxed-primitive: 1.1.1 + which-collection: 1.0.2 + which-typed-array: 1.1.24 + + which-collection@1.0.2: + dependencies: + is-map: 2.0.3 + is-set: 2.0.3 + is-weakmap: 2.0.2 + is-weakset: 2.0.4 + which-module@2.0.1: {} + which-typed-array@1.1.24: + dependencies: + available-typed-arrays: 1.0.7 + call-bind: 1.0.9 + call-bound: 1.0.4 + for-each: 0.3.5 + get-proto: 1.0.1 + gopd: 1.2.0 + has-tostringtag: 1.0.2 + which@2.0.2: dependencies: isexe: 2.0.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 160225c..cdd56a2 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,10 +1,12 @@ # El proyecto usa pnpm 12 ("packageManager" en package.json; el CI toma la versión de ahí). # Scripts de build de dependencias permitidos (pnpm ≥ 11 los bloquea por defecto). # - esbuild: NECESARIO, descarga el binario nativo que usa Vite. -# - El resto son postinstall cosméticos (mensajes de financiación) o builds +# - El resto son postinstall cosméticos (mensajes de financiación o, en @tsparticles/engine, +# recomendaciones de wrappers para cada framework) o builds # nativos no necesarios para la app en navegador, por lo que se omiten. allowBuilds: '@tensorflow/tfjs-node': false + '@tsparticles/engine': false core-js: false es5-ext: false esbuild: true @@ -13,9 +15,21 @@ allowBuilds: # Necesario porque danfojs depende de xlsx servido desde el CDN de SheetJS # (https://cdn.sheetjs.com/...), que pnpm ≥ 11 bloquea por defecto (blockExoticSubdeps). blockExoticSubdeps: false +# Paquetes que se pueden instalar aunque se acaben de publicar (pnpm espera un tiempo mínimo desde su publicación): +# handsign-multilingual es nuestro (https://github.com/nonodev96/handsign-multilingual): todas sus versiones. +minimumReleaseAgeExclude: + - handsign-multilingual # danfojs 1.2 declara @tensorflow/tfjs ^3 y mathjs 9.4.4; los forzamos a las versiones del proyecto # para que solo haya una copia de cada una (ver el alias de "danfojs" en vite.config.ts). -# De mathjs, danfojs solo usa mean, median, mode, std y variance, que no cambian entre la 9 y la 11. +# De mathjs, danfojs solo usa mean, median, mode, std y variance, que no cambian entre la 9 y la 12. +# mathjs 12 ya no trae las anotaciones /* #__PURE__ */ mal colocadas de la 11, por las que Rollup avisaba al construir. overrides: 'danfojs>@tensorflow/tfjs': ^4.22.0 - 'danfojs>mathjs': ^11.12.0 + 'danfojs>mathjs': ^12.4.3 +# face-api lee los resultados de cada detección con dataSync()/arraySync() (el NMS de SSD MobileNet hacía un +# arraySync() por cada pareja de cajas). Con WebGPU cada lectura síncrona detiene la GPU y se hace copiando a +# canvas: la página de FACE-API iba muy lenta. El parche cambia su código fuente (src/) para usar data()/array(); +# la app compila face-api desde ese código (alias en vite.config.ts), no usa dist/. Las detecciones no cambian. +# Al actualizar face-api hay que rehacer el parche. +patchedDependencies: + '@vladmandic/face-api@1.7.15': patches/@vladmandic__face-api@1.7.15.patch diff --git a/public/assets/0_new.png b/public/assets/0_new.png deleted file mode 100644 index 7b7f300..0000000 Binary files a/public/assets/0_new.png and /dev/null differ diff --git a/public/assets/1_new.png b/public/assets/1_new.png deleted file mode 100644 index 60eb380..0000000 Binary files a/public/assets/1_new.png and /dev/null differ diff --git a/public/assets/2_new.png b/public/assets/2_new.png deleted file mode 100644 index a1454d9..0000000 Binary files a/public/assets/2_new.png and /dev/null differ diff --git a/public/assets/3_new.png b/public/assets/3_new.png deleted file mode 100644 index 6ca4972..0000000 Binary files a/public/assets/3_new.png and /dev/null differ diff --git a/public/assets/4_new.png b/public/assets/4_new.png deleted file mode 100644 index c6e4903..0000000 Binary files a/public/assets/4_new.png and /dev/null differ diff --git a/public/assets/5_new.png b/public/assets/5_new.png deleted file mode 100644 index 26294d1..0000000 Binary files a/public/assets/5_new.png and /dev/null differ diff --git a/public/assets/6_new.png b/public/assets/6_new.png deleted file mode 100644 index 7313be5..0000000 Binary files a/public/assets/6_new.png and /dev/null differ diff --git a/public/assets/7_new.png b/public/assets/7_new.png deleted file mode 100644 index 080c7b5..0000000 Binary files a/public/assets/7_new.png and /dev/null differ diff --git a/public/assets/8_new.png b/public/assets/8_new.png deleted file mode 100644 index 087b431..0000000 Binary files a/public/assets/8_new.png and /dev/null differ diff --git a/public/assets/9_new.png b/public/assets/9_new.png deleted file mode 100644 index da7be76..0000000 Binary files a/public/assets/9_new.png and /dev/null differ diff --git a/public/assets/beef-burger.jpg b/public/assets/beef-burger.jpg deleted file mode 100644 index abc6270..0000000 Binary files a/public/assets/beef-burger.jpg and /dev/null differ diff --git a/public/assets/bulldog.jpg b/public/assets/bulldog.jpg deleted file mode 100644 index b545357..0000000 Binary files a/public/assets/bulldog.jpg and /dev/null differ diff --git a/public/assets/butterfly.jpg b/public/assets/butterfly.jpg deleted file mode 100644 index a0435b2..0000000 Binary files a/public/assets/butterfly.jpg and /dev/null differ diff --git a/public/assets/cat.jpg b/public/assets/cat.jpg deleted file mode 100644 index 5d20089..0000000 Binary files a/public/assets/cat.jpg and /dev/null differ diff --git a/public/assets/cheetah.jpg b/public/assets/cheetah.jpg deleted file mode 100644 index 558d01a..0000000 Binary files a/public/assets/cheetah.jpg and /dev/null differ diff --git a/public/assets/cruise.jpg b/public/assets/cruise.jpg deleted file mode 100644 index d2b833c..0000000 Binary files a/public/assets/cruise.jpg and /dev/null differ diff --git a/public/assets/duck.jpg b/public/assets/duck.jpg deleted file mode 100644 index c152257..0000000 Binary files a/public/assets/duck.jpg and /dev/null differ diff --git a/public/assets/elephant.jpg b/public/assets/elephant.jpg deleted file mode 100644 index 756faa6..0000000 Binary files a/public/assets/elephant.jpg and /dev/null differ diff --git a/public/assets/footer/DaSCI.png b/public/assets/footer/DaSCI.png new file mode 100644 index 0000000..8e62c0e Binary files /dev/null and b/public/assets/footer/DaSCI.png differ diff --git a/public/assets/footer/SIMIDAT.png b/public/assets/footer/SIMIDAT.png new file mode 100644 index 0000000..7743451 Binary files /dev/null and b/public/assets/footer/SIMIDAT.png differ diff --git a/public/assets/lion.jpg b/public/assets/lion.jpg deleted file mode 100644 index 340ea06..0000000 Binary files a/public/assets/lion.jpg and /dev/null differ diff --git a/public/docs/en/00. Tabular Classification - Step 0. Upload and process dataset.md b/public/docs/en/00. Tabular Classification - Step 0. Upload and process dataset.md index 2e197b1..2a17c92 100644 --- a/public/docs/en/00. Tabular Classification - Step 0. Upload and process dataset.md +++ b/public/docs/en/00. Tabular Classification - Step 0. Upload and process dataset.md @@ -4,11 +4,11 @@ For this tutorial we will first explain the components, the function they perfor In this example we will use the [car evaluation](https://archive.ics.uci.edu/dataset/19/car+evaluation) dataset. -![00-upload-dataset.png {server}](../images/00-tabular-classification/00-0-upload-dataset.png) +![Screenshot: area to upload the CSV file with the dataset {server}](../images/00-tabular-classification/00-0-upload-dataset.png) We can see a visualisation of the original dataframe without any processing. -![00-upload-dataset.png {server}](../images/00-tabular-classification/00-process-0-original.png) +![Screenshot: table with the original, unprocessed dataset {server}](../images/00-tabular-classification/00-process-0-original.png) Below is a form that allows us to perform a simple processing by columns of each of the series of the dataframe. @@ -16,8 +16,8 @@ In this example we indicate that all its columns must be transformed to label en We also indicate that the target column to be sorted by is the "Result" column. -![00-upload-dataset.png {server}](../images/00-tabular-classification/00-process-1-form.png) +![Screenshot: form to choose how each column is transformed (label encoder) and the target column, “Result” {server}](../images/00-tabular-classification/00-process-1-form.png) Finally, the processed DataFrame is displayed. -![00-upload-dataset.png {server}](../images/00-tabular-classification/00-process-2-processed.png) \ No newline at end of file +![Screenshot: table with the processed dataset {server}](../images/00-tabular-classification/00-process-2-processed.png) \ No newline at end of file diff --git a/public/docs/en/00. Tabular Classification - Step 1. Dataset.md b/public/docs/en/00. Tabular Classification - Step 1. Dataset.md index 9368832..c7e0407 100644 --- a/public/docs/en/00. Tabular Classification - Step 1. Dataset.md +++ b/public/docs/en/00. Tabular Classification - Step 1. Dataset.md @@ -2,8 +2,8 @@ The dataset viewer is a component that allows us to see the dataframe both in its original format and the processed dataframe, it includes two submenus with the transformations that have been made, as well as the list with the label-encoder if the series is categorical. -![02-dataset-0.png {server}](../images/00-tabular-classification/01-dataset-0.png) +![Screenshot: dataset viewer showing the original dataframe {server}](../images/00-tabular-classification/01-dataset-0.png) We can see the processed dataset and how it has transformed those columns. -![02-dataset-0.png {server}](../images/00-tabular-classification/01-dataset-1.png) \ No newline at end of file +![Screenshot: dataset viewer showing the processed dataframe and its transformed columns {server}](../images/00-tabular-classification/01-dataset-1.png) \ No newline at end of file diff --git a/public/docs/en/00. Tabular Classification - Step 2. Layer Design.md b/public/docs/en/00. Tabular Classification - Step 2. Layer Design.md index 4f96266..32b7bb6 100644 --- a/public/docs/en/00. Tabular Classification - Step 2. Layer Design.md +++ b/public/docs/en/00. Tabular Classification - Step 2. Layer Design.md @@ -4,18 +4,18 @@ The layer viewer is just a visual component to represent the layers of the neura The viewer has two display modes compact mode or extended mode. -In both modes the layer, the activation function and the number of neurons are displayed. +In compact mode each layer shows its type, its number of neurons and its activation function. In extended mode each neuron is a node labelled with its layer, and the rest of the details appear when hovering over it. ## Compact mode This display mode is more recommended for low performance devices. -![02-layer-design-0.png {server}](../images/00-tabular-classification/02-layer-design-0.png) +![Screenshot: network diagram in compact mode, with each layer and its number of neurons {server}](../images/00-tabular-classification/02-layer-design-0.png) ## Extended mode In this mode you can see how each neuron is connected to all neurons in the next layer. -![02-layer-design-1.png {server}](../images/00-tabular-classification/02-layer-design-1.png) +![Screenshot: network diagram in extended mode, with each neuron connected to every neuron in the next layer {server}](../images/00-tabular-classification/02-layer-design-1.png) In the next part of the tutorial the architecture will be modified to suit the task and the dataset. \ No newline at end of file diff --git a/public/docs/en/00. Tabular Classification - Step 3. Editor Layers.md b/public/docs/en/00. Tabular Classification - Step 3. Editor Layers.md index 3c7460b..6b436fd 100644 --- a/public/docs/en/00. Tabular Classification - Step 3. Editor Layers.md +++ b/public/docs/en/00. Tabular Classification - Step 3. Editor Layers.md @@ -28,11 +28,11 @@ We will give the following configuration to the architecture: 1. Activation function: Softmax. 2. Units: 4 -![03-editor-layers-1.png {server}](../images/00-tabular-classification/03-editor-layers-0.png) +![Screenshot: layer editor with the settings of each layer (units and activation function) {server}](../images/00-tabular-classification/03-editor-layers-0.png) The layer viewer should display the following configuration: -![03-editor-layers-3-result.png {server}](../images/00-tabular-classification/03-editor-layers-3-result.png) +![Screenshot: network diagram with the resulting layer configuration {server}](../images/00-tabular-classification/03-editor-layers-3-result.png) We must remember that in a tabular classification model the last layer must have a **Softmax** activation function and as many units as classes to predict. This gives us as output of the model a numerical vector of the size of the number of classes, the sum of the vector must give 1 which corresponds to 100% prediction, each element of the vector will correspond to the percentage of predictions of that class. \ No newline at end of file diff --git a/public/docs/en/00. Tabular Classification - Step 4. Editor Hyperparameters.md b/public/docs/en/00. Tabular Classification - Step 4. Editor Hyperparameters.md index 751d48c..ac55fda 100644 --- a/public/docs/en/00. Tabular Classification - Step 4. Editor Hyperparameters.md +++ b/public/docs/en/00. Tabular Classification - Step 4. Editor Hyperparameters.md @@ -8,11 +8,11 @@ You can visit the glossary section to understand each of these parameters. In our case we leave the following configuration so that the training classify performs a very fast adjustment. -1. Learning rate: 1 +1. Learning rate: 0.01 2. Number of epochs: 30 -3. Test set size: 10 → 10% 4. +3. Test set size: 10 → 10% 4. Optimizer: Adam 5. Loss function: CategoricalCrossentropy -6. Metric function: Accuracy +6. Metric function: CategoricalAccuracy -![04-editor-hyperparameters.png {server}](../images/00-tabular-classification/04-editor-hyperparameters.png) \ No newline at end of file +![Screenshot: hyperparameter editor with the learning rate, epochs, optimizer, loss function and metric {server}](../images/00-tabular-classification/04-editor-hyperparameters.png) \ No newline at end of file diff --git a/public/docs/en/00. Tabular Classification - Step 5. Table models.md b/public/docs/en/00. Tabular Classification - Step 5. Table models.md index c4f17ed..6ae0c59 100644 --- a/public/docs/en/00. Tabular Classification - Step 5. Table models.md +++ b/public/docs/en/00. Tabular Classification - Step 5. Table models.md @@ -4,8 +4,10 @@ Once everything is set up we can start the training, Nets4Learning allows to hav Once the training has started, the tensorflow js viewer will open and show the progress. -![05-visor-training.png {server}](../images/00-tabular-classification/05-visor-training.png) +![Screenshot: TensorFlow.js visor with the training progress charts {server}](../images/00-tabular-classification/05-visor-training.png) We can see the trainings we have done and which layers and parameters we have used. -![05-table-models.png {server}](../images/00-tabular-classification/05-table-models.png) \ No newline at end of file +![Screenshot: table of trained models with their layers and parameters {server}](../images/00-tabular-classification/05-table-models.png) + +Below the table you can see the training curves and the confusion matrix of the model chosen in the selector. The **Best** label marks the model with the lowest validation loss. diff --git a/public/docs/en/00. Tabular Classification - Step 6. Predict.md b/public/docs/en/00. Tabular Classification - Step 6. Predict.md index ade20e1..f81fa89 100644 --- a/public/docs/en/00. Tabular Classification - Step 6. Predict.md +++ b/public/docs/en/00. Tabular Classification - Step 6. Predict.md @@ -16,8 +16,8 @@ Finally, but internally, a scaling is performed. You can visit the documentation section to understand the programming: [example {server}](/documentation) -![06-predict-0.png {server}](../images/00-tabular-classification/06-predict-0.png) +![Screenshot: form to enter the values of an example and classify it {server}](../images/00-tabular-classification/06-predict-0.png) Finally we can observe the prediction of the model and the percentage of each of the classification classes. -![06-predict-1.png {server}](../images/00-tabular-classification/06-predict-1.png) \ No newline at end of file +![Screenshot: prediction result with the percentage for each class {server}](../images/00-tabular-classification/06-predict-1.png) \ No newline at end of file diff --git a/public/docs/es/00. Tabular Classification - Step 0. Upload and process dataset.md b/public/docs/es/00. Tabular Classification - Step 0. Upload and process dataset.md index 538ef7e..4e1d4f1 100644 --- a/public/docs/es/00. Tabular Classification - Step 0. Upload and process dataset.md +++ b/public/docs/es/00. Tabular Classification - Step 0. Upload and process dataset.md @@ -4,11 +4,11 @@ Para este tutorial explicaremos primero los componentes, la función que realiza En este ejemplo usaremos el conjunto de datos de [car evaluation](https://archive.ics.uci.edu/dataset/19/car+evaluation). -![00-upload-dataset.png {server}](../images/00-tabular-classification/00-0-upload-dataset.png) +![Captura: zona para subir el fichero CSV con el conjunto de datos {server}](../images/00-tabular-classification/00-0-upload-dataset.png) Podemos ver una visualización del dataframe original sin ningún tratamiento. -![00-upload-dataset.png {server}](../images/00-tabular-classification/00-process-0-original.png) +![Captura: tabla con el conjunto de datos original, sin procesar {server}](../images/00-tabular-classification/00-process-0-original.png) A continuación se muestra un formulario que nos permite realizar un procesamiento sencillo por columnas de cada una de las series del dataframe. @@ -16,9 +16,9 @@ En este ejemplo indicamos que todas sus columnas deberán de ser transformadas a Además indicamos que la columna objetivo por la que se va a clasificar es la columna "Result". -![00-upload-dataset.png {server}](../images/00-tabular-classification/00-process-1-form.png) +![Captura: formulario para elegir cómo se transforma cada columna (label encoder) y la columna objetivo, «Result» {server}](../images/00-tabular-classification/00-process-1-form.png) Por último se muestra el DataFrame procesado. -![00-upload-dataset.png {server}](../images/00-tabular-classification/00-process-2-processed.png) +![Captura: tabla con el conjunto de datos ya procesado {server}](../images/00-tabular-classification/00-process-2-processed.png) diff --git a/public/docs/es/00. Tabular Classification - Step 1. Dataset.md b/public/docs/es/00. Tabular Classification - Step 1. Dataset.md index d32fade..f234100 100644 --- a/public/docs/es/00. Tabular Classification - Step 1. Dataset.md +++ b/public/docs/es/00. Tabular Classification - Step 1. Dataset.md @@ -2,8 +2,8 @@ El visualizador del conjunto de datos es un componente que nos permite ver el dataframe tanto en su formato original como el dataframe procesado, incluye dos submenus con las transformaciones que se le ha hecho, así como el listado con el label-encoder si la serie es categórica. -![02-dataset-0.png {server}](../images/00-tabular-classification/01-dataset-0.png) +![Captura: visualizador del conjunto de datos con el dataframe original {server}](../images/00-tabular-classification/01-dataset-0.png) Podemos ver el conjunto de datos procesado y como ha transformado dichas columnas. -![02-dataset-0.png {server}](../images/00-tabular-classification/01-dataset-1.png) \ No newline at end of file +![Captura: visualizador del conjunto de datos con el dataframe procesado y sus columnas transformadas {server}](../images/00-tabular-classification/01-dataset-1.png) \ No newline at end of file diff --git a/public/docs/es/00. Tabular Classification - Step 2. Layer Design.md b/public/docs/es/00. Tabular Classification - Step 2. Layer Design.md index 46f3454..11eacb9 100644 --- a/public/docs/es/00. Tabular Classification - Step 2. Layer Design.md +++ b/public/docs/es/00. Tabular Classification - Step 2. Layer Design.md @@ -4,19 +4,19 @@ El visualizador de capas es solo un componente visual para representar las capas El visualizador cuenta con dos modos de visualización modo compacto o modo extendido. -En ambos modos se muestra la capa, la función de activación y el número de neuronas. +En el modo compacto cada capa muestra su tipo, su número de neuronas y su función de activación. En el modo extendido cada neurona es un nodo con el nombre de su capa, y el resto de datos aparece al pasar el ratón por encima. ## Modo compacto Este modo de visualización es más recomendado para dispositivos con bajas prestaciones. -![02-layer-design-0.png {server}](../images/00-tabular-classification/02-layer-design-0.png) +![Captura: diagrama de la red en modo compacto, con cada capa y su número de neuronas {server}](../images/00-tabular-classification/02-layer-design-0.png) ## Modo extendido En este modo se puede apreciar como cada neurona se conecta con todas las de la siguiente capa. -![02-layer-design-1.png {server}](../images/00-tabular-classification/02-layer-design-1.png) +![Captura: diagrama de la red en modo extendido, con cada neurona conectada a todas las de la capa siguiente {server}](../images/00-tabular-classification/02-layer-design-1.png) En la siguiente parte del tutorial se modificará la arquitectura para adaptarla a la tarea y al conjunto de datos. diff --git a/public/docs/es/00. Tabular Classification - Step 3. Editor Layers.md b/public/docs/es/00. Tabular Classification - Step 3. Editor Layers.md index f0cb894..c4b8944 100644 --- a/public/docs/es/00. Tabular Classification - Step 3. Editor Layers.md +++ b/public/docs/es/00. Tabular Classification - Step 3. Editor Layers.md @@ -28,11 +28,11 @@ Le daremos la siguiente configuración a la arquitectura: 1. Función de activación: Softmax 2. Unidades: 4 -![03-editor-layers-1.png {server}](../images/00-tabular-classification/03-editor-layers-0.png) +![Captura: editor de capas con la configuración de cada capa (unidades y función de activación) {server}](../images/00-tabular-classification/03-editor-layers-0.png) El visualizador de capas debe mostrar la siguiente configuración: -![03-editor-layers-3-result.png {server}](../images/00-tabular-classification/03-editor-layers-3-result.png) +![Captura: diagrama de la red con la configuración de capas que resulta {server}](../images/00-tabular-classification/03-editor-layers-3-result.png) Debemos recordar que en un modelo de clasificación tabular la última capa debe tener una función de activación **Softmax** y tantas unidades como clases a predecir tenga. Esto nos da como salida del modelo un vector numérico del tamaño del número de clases, la sumatoria del vector debe dar 1 que corresponde al 100% de predicción, cada elemento del vector corresponderá con el porcentaje de predicciones de dicha clase. diff --git a/public/docs/es/00. Tabular Classification - Step 4. Editor Hyperparameters.md b/public/docs/es/00. Tabular Classification - Step 4. Editor Hyperparameters.md index f0dd749..564a077 100644 --- a/public/docs/es/00. Tabular Classification - Step 4. Editor Hyperparameters.md +++ b/public/docs/es/00. Tabular Classification - Step 4. Editor Hyperparameters.md @@ -8,11 +8,11 @@ Puedes visitar la sección del glosario para comprender cada uno de estos parám En nuestro caso dejamos la siguiente configuración para que el entrenamiento clasifique realice un ajuste muy rápido. -1. Learning rate: 1 +1. Learning rate: 0.01 2. Number of epochs: 30 3. Test set size: 10 → 10% 4. Optimizer: Adam 5. Loss function: CategoricalCrossentropy -6. Metric function: Accuracy +6. Metric function: CategoricalAccuracy -![04-editor-hyperparameters.png {server}](../images/00-tabular-classification/04-editor-hyperparameters.png) +![Captura: editor de hiperparámetros con la tasa de aprendizaje, las épocas, el optimizador, la función de pérdida y la métrica {server}](../images/00-tabular-classification/04-editor-hyperparameters.png) diff --git a/public/docs/es/00. Tabular Classification - Step 5. Table models.md b/public/docs/es/00. Tabular Classification - Step 5. Table models.md index f915b94..c405626 100644 --- a/public/docs/es/00. Tabular Classification - Step 5. Table models.md +++ b/public/docs/es/00. Tabular Classification - Step 5. Table models.md @@ -4,8 +4,10 @@ Una vez configurado todo podemos empezar el entrenamiento, Nets4Learning permite Una vez empezado el entrenamiento se abrirá el visor de tensorflow js que nos mostrará el progreso. -![05-visor-training.png {server}](../images/00-tabular-classification/05-visor-training.png) +![Captura: visor de TensorFlow.js con las gráficas del progreso del entrenamiento {server}](../images/00-tabular-classification/05-visor-training.png) Podemos ver los entrenamientos que hemos realizado y que capas y parámetros hemos empleado. -![05-table-models.png {server}](../images/00-tabular-classification/05-table-models.png) +![Captura: tabla con los modelos entrenados, sus capas y sus parámetros {server}](../images/00-tabular-classification/05-table-models.png) + +Debajo de la tabla se ven las curvas de entrenamiento y la matriz de confusión del modelo elegido en el selector. La etiqueta **Mejor** marca el modelo con menor pérdida de validación. diff --git a/public/docs/es/00. Tabular Classification - Step 6. Predict.md b/public/docs/es/00. Tabular Classification - Step 6. Predict.md index 1f48d3c..d834112 100644 --- a/public/docs/es/00. Tabular Classification - Step 6. Predict.md +++ b/public/docs/es/00. Tabular Classification - Step 6. Predict.md @@ -16,8 +16,8 @@ Por último, pero de forma interna se realiza un escalado. Puedes visitar la sección de la documentación para comprender la programación: [ejemplo {server}](/documentation) -![06-predict-0.png {server}](../images/00-tabular-classification/06-predict-0.png) +![Captura: formulario para escribir los valores de un ejemplo y clasificarlo {server}](../images/00-tabular-classification/06-predict-0.png) Por último podemos observar la predicción del modelo y el porcentaje de cada una de las clases de la clasificación. -![06-predict-1.png {server}](../images/00-tabular-classification/06-predict-1.png) +![Captura: resultado de la predicción con el porcentaje de cada clase {server}](../images/00-tabular-classification/06-predict-1.png) diff --git a/public/docs/images/00-tabular-classification/01-dataset-0.png b/public/docs/images/00-tabular-classification/01-dataset-0.png index 466aecc..52c4165 100644 Binary files a/public/docs/images/00-tabular-classification/01-dataset-0.png and b/public/docs/images/00-tabular-classification/01-dataset-0.png differ diff --git a/public/docs/images/00-tabular-classification/01-dataset-1.png b/public/docs/images/00-tabular-classification/01-dataset-1.png index 7bd599d..734ac14 100644 Binary files a/public/docs/images/00-tabular-classification/01-dataset-1.png and b/public/docs/images/00-tabular-classification/01-dataset-1.png differ diff --git a/public/docs/images/00-tabular-classification/02-layer-design-0.png b/public/docs/images/00-tabular-classification/02-layer-design-0.png index eb2961b..7a25abb 100644 Binary files a/public/docs/images/00-tabular-classification/02-layer-design-0.png and b/public/docs/images/00-tabular-classification/02-layer-design-0.png differ diff --git a/public/docs/images/00-tabular-classification/02-layer-design-1.png b/public/docs/images/00-tabular-classification/02-layer-design-1.png index ccc3f4d..8d9db9d 100644 Binary files a/public/docs/images/00-tabular-classification/02-layer-design-1.png and b/public/docs/images/00-tabular-classification/02-layer-design-1.png differ diff --git a/public/docs/images/00-tabular-classification/03-editor-layers-0.png b/public/docs/images/00-tabular-classification/03-editor-layers-0.png index e4d8eb7..401ad13 100644 Binary files a/public/docs/images/00-tabular-classification/03-editor-layers-0.png and b/public/docs/images/00-tabular-classification/03-editor-layers-0.png differ diff --git a/public/docs/images/00-tabular-classification/03-editor-layers-3-result.png b/public/docs/images/00-tabular-classification/03-editor-layers-3-result.png index 8418926..173f0b5 100644 Binary files a/public/docs/images/00-tabular-classification/03-editor-layers-3-result.png and b/public/docs/images/00-tabular-classification/03-editor-layers-3-result.png differ diff --git a/public/docs/images/00-tabular-classification/04-editor-hyperparameters.png b/public/docs/images/00-tabular-classification/04-editor-hyperparameters.png index 619f2b4..85bfa15 100644 Binary files a/public/docs/images/00-tabular-classification/04-editor-hyperparameters.png and b/public/docs/images/00-tabular-classification/04-editor-hyperparameters.png differ diff --git a/public/docs/images/00-tabular-classification/05-table-models.png b/public/docs/images/00-tabular-classification/05-table-models.png index 6e0dfbb..efc98eb 100644 Binary files a/public/docs/images/00-tabular-classification/05-table-models.png and b/public/docs/images/00-tabular-classification/05-table-models.png differ diff --git a/public/docs/images/00-tabular-classification/06-predict-0.png b/public/docs/images/00-tabular-classification/06-predict-0.png index 23dbdc9..7792073 100644 Binary files a/public/docs/images/00-tabular-classification/06-predict-0.png and b/public/docs/images/00-tabular-classification/06-predict-0.png differ diff --git a/public/docs/images/00-tabular-classification/06-predict-1.png b/public/docs/images/00-tabular-classification/06-predict-1.png index 998586a..8750d87 100644 Binary files a/public/docs/images/00-tabular-classification/06-predict-1.png and b/public/docs/images/00-tabular-classification/06-predict-1.png differ diff --git a/public/docs/ja/00. Tabular Classification - Step 0. Upload and process dataset.md b/public/docs/ja/00. Tabular Classification - Step 0. Upload and process dataset.md index 5e53a73..769dd67 100644 --- a/public/docs/ja/00. Tabular Classification - Step 0. Upload and process dataset.md +++ b/public/docs/ja/00. Tabular Classification - Step 0. Upload and process dataset.md @@ -4,11 +4,11 @@ この例では [car evaluation](https://archive.ics.uci.edu/dataset/19/car+evaluation) データセットを使用します。 -![00-upload-dataset.png {server}](../images/00-tabular-classification/00-0-upload-dataset.png) +![スクリーンショット:データセットの CSV ファイルをアップロードする領域 {server}](../images/00-tabular-classification/00-0-upload-dataset.png) まだ何も処理していない元のデータフレーム(「データフレーム | 元データ」)を確認できます。 -![00-upload-dataset.png {server}](../images/00-tabular-classification/00-process-0-original.png) +![スクリーンショット:処理前の元のデータセットの表 {server}](../images/00-tabular-classification/00-process-0-original.png) その下には、データフレームの各系列(列)ごとに簡単な処理を行うためのフォーム(「データフレーム | 前処理フォーム」)があります。 @@ -16,8 +16,8 @@ また、分類の基準となる「予測対象の列」として「Result」列を指定します。 -![00-upload-dataset.png {server}](../images/00-tabular-classification/00-process-1-form.png) +![スクリーンショット:各列の変換方法(ラベルエンコーダー)と目的列「Result」を選ぶフォーム {server}](../images/00-tabular-classification/00-process-1-form.png) 最後に、処理済みのデータフレーム(「データフレーム | 処理済み」)が表示されます。 -![00-upload-dataset.png {server}](../images/00-tabular-classification/00-process-2-processed.png) \ No newline at end of file +![スクリーンショット:処理後のデータセットの表 {server}](../images/00-tabular-classification/00-process-2-processed.png) \ No newline at end of file diff --git a/public/docs/ja/00. Tabular Classification - Step 1. Dataset.md b/public/docs/ja/00. Tabular Classification - Step 1. Dataset.md index 1a913b0..358fe1a 100644 --- a/public/docs/ja/00. Tabular Classification - Step 1. Dataset.md +++ b/public/docs/ja/00. Tabular Classification - Step 1. Dataset.md @@ -2,8 +2,8 @@ データセットビューア(「データセット」セクション)は、データフレームを元の形式と処理済みの形式の両方で確認できるコンポーネントです。行われた変換を示す2つのサブメニューと、系列がカテゴリ型の場合はラベルエンコーダ(label-encoder)の対応一覧も含まれています。 -![02-dataset-0.png {server}](../images/00-tabular-classification/01-dataset-0.png) +![スクリーンショット:元のデータフレームを表示したデータセットビューア {server}](../images/00-tabular-classification/01-dataset-0.png) 処理済みのデータセットと、各列がどのように変換されたかを確認できます。 -![02-dataset-0.png {server}](../images/00-tabular-classification/01-dataset-1.png) \ No newline at end of file +![スクリーンショット:処理後のデータフレームと変換された列を表示したデータセットビューア {server}](../images/00-tabular-classification/01-dataset-1.png) \ No newline at end of file diff --git a/public/docs/ja/00. Tabular Classification - Step 2. Layer Design.md b/public/docs/ja/00. Tabular Classification - Step 2. Layer Design.md index 77408b4..43eca36 100644 --- a/public/docs/ja/00. Tabular Classification - Step 2. Layer Design.md +++ b/public/docs/ja/00. Tabular Classification - Step 2. Layer Design.md @@ -4,18 +4,18 @@ ビューアには、コンパクトモードと拡張モードの2つの表示モードがあります。 -どちらのモードでも、レイヤー、活性化関数、ニューロン数が表示されます。 +コンパクトモードでは、各レイヤーの種類、ニューロン数、活性化関数が表示されます。拡張モードでは各ニューロンがレイヤー名付きのノードとして表示され、その他の情報はマウスを重ねると表示されます。 ## コンパクトモード この表示モードは、性能の低いデバイスでの使用に適しています。 -![02-layer-design-0.png {server}](../images/00-tabular-classification/02-layer-design-0.png) +![スクリーンショット:コンパクトモードのネットワーク図(各層とそのニューロン数) {server}](../images/00-tabular-classification/02-layer-design-0.png) ## 拡張モード このモードでは、各ニューロンが次のレイヤーのすべてのニューロンとどのように結合しているかを確認できます。 -![02-layer-design-1.png {server}](../images/00-tabular-classification/02-layer-design-1.png) +![スクリーンショット:拡張モードのネットワーク図(各ニューロンが次の層のすべてのニューロンにつながる) {server}](../images/00-tabular-classification/02-layer-design-1.png) チュートリアルの次のパートでは、タスクとデータセットに合わせてアーキテクチャを変更します。 \ No newline at end of file diff --git a/public/docs/ja/00. Tabular Classification - Step 3. Editor Layers.md b/public/docs/ja/00. Tabular Classification - Step 3. Editor Layers.md index 4729d99..29ebec8 100644 --- a/public/docs/ja/00. Tabular Classification - Step 3. Editor Layers.md +++ b/public/docs/ja/00. Tabular Classification - Step 3. Editor Layers.md @@ -28,11 +28,11 @@ 1. 活性化関数: Softmax 2. レイヤーニューロン: 4 -![03-editor-layers-1.png {server}](../images/00-tabular-classification/03-editor-layers-0.png) +![スクリーンショット:各層の設定(ユニット数と活性化関数)を表示した層エディター {server}](../images/00-tabular-classification/03-editor-layers-0.png) レイヤービューアには、次の構成が表示されるはずです。 -![03-editor-layers-3-result.png {server}](../images/00-tabular-classification/03-editor-layers-3-result.png) +![スクリーンショット:設定後の層構成を示すネットワーク図 {server}](../images/00-tabular-classification/03-editor-layers-3-result.png) 表形式データの分類モデルでは、最後のレイヤーの活性化関数を **Softmax** にし、ニューロン数を予測するクラスの数と同じにする必要があることを覚えておきましょう。 これにより、モデルの出力はクラス数と同じ長さの数値ベクトルになります。ベクトルの合計は 1(予測全体の 100%)になり、ベクトルの各要素はそのクラスに対する予測の割合を表します。 \ No newline at end of file diff --git a/public/docs/ja/00. Tabular Classification - Step 4. Editor Hyperparameters.md b/public/docs/ja/00. Tabular Classification - Step 4. Editor Hyperparameters.md index 487929f..32f31ee 100644 --- a/public/docs/ja/00. Tabular Classification - Step 4. Editor Hyperparameters.md +++ b/public/docs/ja/00. Tabular Classification - Step 4. Editor Hyperparameters.md @@ -8,11 +8,11 @@ 今回は、学習がすばやく調整を行えるように、次の設定にします。 -1. 学習率: 1 +1. 学習率: 0.01 2. エポック数: 30 3. テストセットサイズ: 10 → 10% 4. オプティマイザー: Adam 5. 損失関数: CategoricalCrossentropy -6. メトリクス関数: Accuracy +6. メトリクス関数: CategoricalAccuracy -![04-editor-hyperparameters.png {server}](../images/00-tabular-classification/04-editor-hyperparameters.png) \ No newline at end of file +![スクリーンショット:学習率、エポック数、最適化手法、損失関数、評価指標を設定するハイパーパラメーターエディター {server}](../images/00-tabular-classification/04-editor-hyperparameters.png) \ No newline at end of file diff --git a/public/docs/ja/00. Tabular Classification - Step 5. Table models.md b/public/docs/ja/00. Tabular Classification - Step 5. Table models.md index 1ae4fc7..8cb7c39 100644 --- a/public/docs/ja/00. Tabular Classification - Step 5. Table models.md +++ b/public/docs/ja/00. Tabular Classification - Step 5. Table models.md @@ -4,8 +4,10 @@ 学習を開始すると tensorflow js のビューアが開き、学習の進捗が表示されます。 -![05-visor-training.png {server}](../images/00-tabular-classification/05-visor-training.png) +![スクリーンショット:学習の進行状況グラフを表示した TensorFlow.js ビジュアライザー {server}](../images/00-tabular-classification/05-visor-training.png) 「生成されたモデルの一覧」では、これまでに行った学習と、それぞれで使用したレイヤーとパラメータを確認できます。 -![05-table-models.png {server}](../images/00-tabular-classification/05-table-models.png) \ No newline at end of file +![スクリーンショット:学習済みモデルとその層・パラメーターの表 {server}](../images/00-tabular-classification/05-table-models.png) + +表の下には、セレクターで選んだモデルの学習曲線と混同行列が表示されます。**最良** のラベルは検証損失が最も小さいモデルを示します。 diff --git a/public/docs/ja/00. Tabular Classification - Step 6. Predict.md b/public/docs/ja/00. Tabular Classification - Step 6. Predict.md index bbe42a8..e20c590 100644 --- a/public/docs/ja/00. Tabular Classification - Step 6. Predict.md +++ b/public/docs/ja/00. Tabular Classification - Step 6. Predict.md @@ -16,8 +16,8 @@ Nets4Learning では、生成したモデルの一覧からモデルを1つ選 プログラムの仕組みについては、ドキュメントのセクションを参照してください:[例 {server}](/documentation) -![06-predict-0.png {server}](../images/00-tabular-classification/06-predict-0.png) +![スクリーンショット:例の値を入力して分類するフォーム {server}](../images/00-tabular-classification/06-predict-0.png) 最後に、モデルの予測結果と、分類の各クラスの割合を確認できます。 -![06-predict-1.png {server}](../images/00-tabular-classification/06-predict-1.png) \ No newline at end of file +![スクリーンショット:各クラスの割合を示す予測結果 {server}](../images/00-tabular-classification/06-predict-1.png) \ No newline at end of file diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json index f43de9b..87eb968 100644 --- a/public/locales/en/translation.json +++ b/public/locales/en/translation.json @@ -1,22 +1,22 @@ { "ui": { "blur": { - "enable": "Apply blur to masked regions", - "kernelSize": "Blur kernel size (odd)", - "passes": "Blur passes" + "enable": "Blur the covered zones (instead of painting them one colour)", + "kernelSize": "Blur size (odd)", + "passes": "Times it is blurred" }, "explain": { - "title": "Explainability (SHAP)", + "title": "Model explainability", "method": "Method", "about-lrp": "LRP (Layer-wise Relevance Propagation) runs backwards through the network from the predicted class, distributing its relevance down to the input pixels. The heatmap shows which areas of the image support the model's prediction.", "about-shap": "We split the image into segments (superpixels) and measure each one's importance by masking it or keeping it visible across many different combinations, observing how the prediction changes. The heatmap colours each segment by how much it contributes to the prediction.", "perturbationSamples": "Perturbation samples:", - "gridSide": "Zones per side (the image is split into N×N segments)", - "nSamples": "nSamples (SHAP)", + "gridSide": "Zones per side", + "nSamples": "Combinations tried", "mask": "Mask (SHAP)", - "maskRange": "Mask (0..1)", + "maskRange": "Colour of the covered zones", "calculating": "Calculating...", - "explainPrediction": "Explain prediction", + "explainPrediction": "Explain the prediction", "hideExplanation": "Hide explanation", "noData": "No explanation data available.", "class": "Class {{index}}", @@ -65,8 +65,25 @@ "presence-only": "This model only answers «face» or «no face» (0 or 100 %), so the explanation shows the minimum it needs to see to find a face: the skin is usually enough.", "body-parts": "The confidence in the whole pose and in each body part is explained. The model first needs to find the person, so areas of the torso also help it locate the arms or legs.", "wrong-prediction": "Did the model get it wrong? The explanation is still useful: it shows what the model looked at to reach that answer." - } - } + }, + "waiting-for-prediction": "Make a prediction to be able to explain it.", + "waiting-for-model": "Train a model to be able to explain its predictions.", + "gridSide-help": "The image is split into N × N pieces: with more, the explanation is finer but takes longer.", + "nSamples-help": "How many times different zones are covered to measure what each one contributes (SHAP).", + "maskRange-help": "From 0 (black) to 1 (white).", + "bar-description": "SHAP value of each variable (how much it pushes the prediction up or down), from the most to the least influential: {{values}}.", + "beeswarm-description": "SHAP values of {{count}} examples for each variable. The variables, from the most to the least influential (mean absolute value): {{features}}.", + "bar-data": "SHAP value of each variable", + "beeswarm-data": "SHAP values of each variable over {{count}} examples", + "variable": "Variable", + "mean-abs": "Mean absolute value", + "min": "Minimum", + "max": "Maximum" + }, + "take-screenshot": "Take a screenshot", + "table-scroll-hint": "Scroll horizontally to see all the columns →", + "maximize": "Maximize", + "minimize": "Minimize" }, "welcome": "Welcome to Nets4Learning", "welcome-2": "To continue select one of these tasks", @@ -211,32 +228,110 @@ "dataset-web": "Original website", "dataset-reference": "Reference", "download-dataset-car": "Car evaluation data set", - "download-dataset-hepatitis-c": "Hepatitis C data set", + "download-dataset-hepatitis-c": "Hepatitis C", "download-dataset-iris": "Iris data set", - "download-dataset-titanic": "Titanic survival data set*", - "download-dataset-new-thyroid": "New thyroid data set", - "download-dataset-wine": "Wine survival data set", - "download-dataset-ecoli": "Ecoli data set", + "download-dataset-titanic": "Titanic survival", + "download-dataset-new-thyroid": "Thyroid (New Thyroid)", + "download-dataset-wine": "Wine cultivars", + "download-dataset-ecoli": "E. coli", "download": { "dataset": { "1-regression": { "salary": "Salary data set", "auto-mpg": "Fuel consumption data set", "housing-prices": "House Prices Dataset", - "breast-cancer-original": "Breast Cancer Wisconsin Dataset", - "breast-cancer-wdbc": "Breast Cancer Wisconsin Dataset (Diagnostic)", - "breast-cancer-wpbc": "Breast Cancer Wisconsin Dataset (Prognostic)", + "breast-cancer-original": "Breast cancer (Wisconsin)", + "breast-cancer-wdbc": "Breast cancer: diagnosis (WDBC)", + "breast-cancer-wpbc": "Breast cancer: prognosis (WPBC)", "student-performance-mathematics": "Mathematics student Data set", "student-performance-portuguese": "Portuguese student Data set", "wine-red": "Red wine data set", "wine-white": "White wine data set" } } + }, + "dataset-info": "Data", + "extra-title": "Other datasets", + "extra-text": "No model in the app uses them: they are for practising data preparation. “Train” loads them in the upload page, where you choose the target column and what to do with each one.", + "dataset-details": "Information", + "show-info": "View information", + "variables": { + "title": "Variables", + "name": "Variable", + "role": "Role", + "type": "Type", + "description": "Description", + "units": "Units", + "missing": "Missing values", + "roles": { + "ID": "ID", + "Feature": "Feature", + "Target": "Target", + "Other": "Other" + }, + "types": { + "Integer": "Integer", + "Continuous": "Continuous", + "Categorical": "Categorical", + "Binary": "Binary", + "Date": "Date" + }, + "note": "Role, type, description and units come from the dataset page at its source. Missing values are counted in the files you can download here.", + "images": "This dataset is made of images, so it has no variables table." + }, + "analyze-action": "Analyze", + "analyze-title": "Open “{{name}}” in the exploratory data analysis (EDA)", + "data": { + "title": "Data", + "describe": "Statistics", + "file": "File", + "error": "The CSV could not be read.", + "describe-help": "One row per numeric column: how many values it has (count), its mean, its standard deviation (std), the minimum, the quartiles and the maximum." + }, + "intro": "The Nets4Learning datasets, by task. Train with them (or cluster them), try the model that is already trained, open them in the exploratory data analysis (EDA) or download them to use in other tools.", + "models-title": "Ready to train", + "models-text": "The app's models use them: they come ready, so you pick one and train.", + "train": "Train", + "try-model": "Try the model", + "files": "Files", + "summary": { + "extra": { + "hepatitis-c": "Blood tests of donors and patients to tell hepatitis C, fibrosis and cirrhosis apart.", + "ecoli": "Where a protein is inside the E. coli bacterium: eight classes, some with very few cases.", + "new-thyroid": "Whether the thyroid works normally, too much or too little, from five lab tests.", + "wine": "Three Italian wine cultivars from 13 chemical components: easy, but the columns have very different scales.", + "titanic": "Who survived the sinking of the Titanic by class, sex, age and the family travelling with them.", + "breast-cancer-wisconsin": "Whether a breast tumour is benign or malignant from nine features of its cells (with some missing values).", + "wpbc": "Whether breast cancer comes back, from measurements of the tumour and its cells: only 198 cases.", + "wdbc": "Whether a breast tumour is benign or malignant from 30 measurements of its cell nuclei in an image." + }, + "clustering": { + "breast-cancer-wisconsin": "Nine cell traits of 699 tumours, from 1 to 10: with two groups, they almost match the benign and malignant ones.", + "wdbc": "30 measurements of the cell nuclei of 569 tumours: with two groups, k-means separates benign from malignant quite well.", + "ecoli": "Seven scores of 336 proteins and eight places in the bacterium, some with two or three cases: those small groups get lost.", + "hepatitis-c": "Blood tests of 589 people: purity comes out high only because almost all are donors, but the Rand index tells the truth: the groups do not resemble the diagnoses." + } + }, + "clustering": { + "examples-title": "Ready to cluster", + "examples-text": "They include the real classes, but k-means doesn't use them: it clusters with the other columns and compares the groups with them at the end.", + "extra-text": "Other project datasets to cluster: “Cluster” loads them as if you had uploaded them. Not all of them resemble their classes equally, and that teaches something too.", + "run": "Cluster" + }, + "time-series": { + "examples-title": "Classic time series", + "examples-text": "In a time series each row is a moment in time (a day, a month…) and the order matters: past values are used to forecast the next ones, so the rows are not shuffled. Each one has a different pattern: trend, seasons or cycles." } }, "dataframe-original": "DataFrame | Original", "dataframe-form": "DataFrame | Pre-processing data set form", "dataframe": { + "table": { + "target": "{{column}}: target column, the one to predict or classify", + "shape": "{{rows}} rows × {{columns}} columns", + "scroll-rows": "scroll inside the table to see the rest", + "column": "Column" + }, "dataframe": { "title": "DataFrame | Data set" }, @@ -272,6 +367,8 @@ "no-numeric": "There are no numeric columns to describe: all the columns are categorical." }, "query": { + "error": "The query is not valid: {{message}}", + "no-rows": "No row matches the query.", "title": "DataFrame | Query", "description": { "0": "Query the DataFrame by the result of a logical comparison or boolean mask.", @@ -279,15 +376,208 @@ "title": "Description" }, "query": "Query", - "link": "Consult more information in the following link" + "link": "Consult more information in the following link", + "column": "Column" }, "plot": { "link": "Consult more information in the following link " } }, "dataframe-processed": "DataFrame | Processed", - "dataframe-scatterplot": { - "title": "scatter plot" + "dataset-process": { + "tabs": { + "original": "1. Original data", + "form": "2. How to process it", + "processed": "3. Processed data" + }, + "original-help": "{{rows}} rows and {{columns}} columns, as they are in the file. The highlighted column is the one to be predicted.", + "classification": { + "target-title": "Which column is the class?", + "target-help": "The network will learn to tell which class each row belongs to. It is usually the last column.", + "target-badge": "Class", + "target-transform": "Each class is turned into a number for training.", + "summary_one": "{{count}} column will go into the network and “{{target}}” is predicted ({{classes}} classes), with {{scaler}} scaling.", + "summary_other": "{{count}} columns will go into the network and “{{target}}” is predicted ({{classes}} classes), with {{scaler}} scaling." + }, + "regression": { + "target-title": "Which number do you want to predict?", + "target-help": "The network will learn to compute the value of this column from the others. It has to be numeric.", + "target-badge": "Predicted", + "target-transform": "It is used as it is: it is the number being predicted.", + "summary_one": "{{count}} column will go into the network and “{{target}}” is predicted, with {{scaler}} scaling.", + "summary_other": "{{count}} columns will go into the network and “{{target}}” is predicted, with {{scaler}} scaling." + }, + "target-classes": "“{{name}}” has {{count}} classes ({{sample}}): the network will have {{count}} output neurons.", + "target-too-many": "That is {{count}} classes, too many for a classification: are you sure it is this column? If it is a continuous number, regression may fit better.", + "target-range": "“{{name}}” goes from {{min}} to {{max}}, with a mean of {{mean}}.", + "target-not-numeric": "“{{name}}” is a text column and regression predicts numbers: choose a numeric one or use tabular classification.", + "scaler-title": "Scaling the inputs", + "scaler-help": "Each column has its own scale (years, euros, centimetres). Scaling them makes them all weigh about the same and helps the network learn.", + "scalers": { + "min-max-scaler": { + "name": "Min-Max", + "help": "Takes each column to the range from 0 to 1." + }, + "standard-scaler": { + "name": "Standard", + "help": "Subtracts the mean and divides by the standard deviation: mean 0 and deviation 1. It copes better with extreme values." + } + }, + "columns-title": "Input columns", + "columns-help": "Choose which columns the network uses and how they are turned into numbers. Text columns are encoded as categories: one number for each distinct value.", + "use": "Use", + "types": { + "int32": "Integer", + "float32": "Decimal", + "string": "Text", + "boolean": "Yes/no", + "datetime": "Date" + }, + "transforms": { + "int32": "As an integer", + "float32": "As a decimal number", + "label-encoder": "As a category (one number per value)", + "drop": "Not used", + "string": "As text", + "boolean": "As yes/no", + "one-hot-encoder": "One column per value (one-hot)" + }, + "transform-of": "How “{{name}}” is converted", + "distinct_one": "{{count}} value: {{sample}}", + "distinct_other": "{{count}} distinct values, e.g. {{sample}}", + "range_one": "always {{min}}", + "range_other": "from {{min}} to {{max}} ({{count}} distinct values)", + "no-inputs": "There is no input column: turn on at least one.", + "submit": "Process the data", + "done_one": "Data ready: {{rows}} rows, {{count}} input column and “{{target}}” to predict. You can now design the network below.", + "done_other": "Data ready: {{rows}} rows, {{count}} input columns and “{{target}}” to predict. You can now design the network below.", + "view": "Which data to see", + "views": { + "scaled": "Scaled", + "encoded": "Encoded", + "scaled-help": "The input columns already scaled: exactly what the network receives.", + "encoded-help": "Each category already turned into a number, before scaling; under each column, how it was converted." + } + }, + "dataset-view": { + "file": "File", + "original": "Original", + "encoded": "Encoded", + "scaled": "Scaled (network input)", + "original-help": "The data as it is in the file: {{rows}} rows and {{columns}} columns. The highlighted column, “{{target}}”, is the one being predicted.", + "encoded-help": "Each text category is already a number and the unused columns are gone. Not scaled yet.", + "scaled-help": "The {{columns}} input columns scaled ({{scaler}}): exactly what the network receives. At the end, highlighted, what it has to predict, “{{target}}”, which is not scaled.", + "statistics": "Statistics of each column" + }, + "stored-models": { + "restored_one": "1 model you trained before with this dataset has been recovered: models are saved in this browser so they are not lost when reloading.", + "restored_other": "{{count}} models you trained before with this dataset have been recovered: models are saved in this browser so they are not lost when reloading.", + "delete-ask": "Delete the models of this dataset", + "confirm": "Are you sure? The saved models of this dataset will be deleted and removed from the table.", + "delete": "Yes, delete them", + "cancel": "Cancel" + }, + "training-diagnosis": { + "title": "How the training of model {{model}} went", + "diverged": { + "title": "The loss blew up", + "text": "From epoch {{epoch}} the loss is no longer a number (NaN): the weights grew out of control.", + "tip": "Lower the learning rate, for example to a tenth, and train again." + }, + "worse": { + "title": "The loss got worse", + "text": "The loss went up from {{first}} to {{last}}: the weights take such big steps that they overshoot.", + "tip": "Lower the learning rate and train again." + }, + "unstable": { + "title": "The loss is jumping around", + "text": "In the second half of the training, the loss goes up and down a lot from one epoch to the next (between {{min}} and {{max}}): this way you can't tell whether it's really learning.", + "tip": "Lower the learning rate. If it stays the same, increase the percentage of test data: with little of it, each epoch changes a lot." + }, + "not-learning": { + "title": "It barely learned", + "text": "The loss only went down from {{first}} to {{last}}.", + "tip": "Try raising the learning rate or the epochs, or giving the layers more neurons. Also check that the last layer has the right activation." + }, + "overfitting": { + "title": "It is memorising the data (overfitting)", + "text": "The loss on the test data was lowest at epoch {{epoch}} ({{min}}) and since then has risen to {{last}}, while the training loss kept going down.", + "tip": "Train fewer epochs (about {{epoch}}) or use a smaller network." + }, + "still-improving": { + "title": "It was still improving", + "text": "In {{epochs}} epochs the loss went down from {{first}} to {{last}}, and it was still going down at the end.", + "tip": "With more epochs it would probably learn more: try raising them." + }, + "good": { + "title": "It learned well", + "text": "The loss went down from {{first}} to {{last}}, and on the test data it ended at {{validation}}.", + "tip": "To compare, change just one thing (the neurons, the learning rate…) and train again." + } + }, + "layer-check": { + "title-error": "Check the layers: the network can't be trained like this", + "title-warning": "The layers could be better", + "error": "Error", + "warning": "Warning", + "params": { + "units": "neurons", + "kernelSize": "kernel size", + "filters": "filters", + "poolSize": "pool size", + "strides": "strides" + }, + "param": { + "text": "Layer {{layer}}: the value of “{{param}}” is not valid.", + "fix": "Set {{value}}" + }, + "hidden-softmax": { + "text": "Layer {{layer}}: softmax splits 100 % among its neurons and only makes sense in the output; in a hidden layer it slows learning down.", + "fix": "Use ReLU" + }, + "output-units": { + "text": "The last layer has {{units}} neurons but there are {{classes}} classes: it needs one neuron per class.", + "fix": "Set {{classes}}" + }, + "output-activation": { + "text": "The last layer uses {{activation}}; with {{expected}}, its outputs are the probability of each class (they add up to 1).", + "fix": "Use {{expected}}" + }, + "output-missing": { + "text": "The network has to end in a Dense layer with {{classes}} neurons (one per class) and Softmax.", + "fix": "Add it at the end" + }, + "after-flatten": { + "text": "Layer {{layer}}: after Flatten the image is already a list of numbers, and {{type}} needs the image in two dimensions.", + "fix": "Remove the layer" + }, + "flatten-again": { + "text": "Layer {{layer}}: the data is already flat, so this Flatten is not needed.", + "fix": "Remove the layer" + }, + "dense-before-flatten": { + "text": "Layer {{layer}}: a Dense layer takes a list of numbers; it needs a Flatten before it to flatten the image.", + "fix": "Add Flatten before" + }, + "too-small": { + "text": "Layer {{layer}}: at this point the image is {{height}}×{{width}} and the {{window}}×{{window}} window of {{type}} doesn't fit.", + "fix": "Remove the layer" + }, + "recurrent-after-dense": { + "text": "Layer {{layer}}: {{type}} reads a sequence value by value, but after a Dense layer there is only a list of numbers left. Recurrent layers go before the Dense ones.", + "fix": "Move the recurrent layers to the start" + }, + "all-fixed": "The layers have nothing left to review" + }, + "download-consent": { + "title": "This model downloads about {{mb}} MB", + "reason": { + "save-data": "Your browser has data saving on: it is only downloaded if you ask.", + "slow": "Your connection seems slow: the download may take a while.", + "always": "In Settings you asked to be asked before downloading a model." + }, + "accept": "Download ({{mb}} MB)", + "settings": "You can change this in Settings." }, "model-selector": { "title": "Model selector" @@ -296,7 +586,13 @@ "select-dataset": { "title": "Select the data set", "info": "Select the data set" - } + }, + "number": { + "range": "Enter a whole number between {{min}} and {{max}}.", + "at-least": "Enter a whole number of {{min}} or more.", + "in-use": "Meanwhile, {{value}} is used." + }, + "cancel": "Cancel" }, "preprocessing": { "title": "Preprocessing", @@ -310,9 +606,27 @@ "predict": "Predict", "cookies-policies": { "title": "Cookie Policy", - "text-0": "This website uses cookies to improve the user experience and analyse the use of the application. Cookies are small text files that are stored on your device when you visit our website. These cookies help us understand how users interact with our website, which pages are most visited and how we can improve the user experience.", - "text-1": "It is important to note that we do not process user data for advertising purposes. We use cookies only for analytical purposes and to improve the functionality of the website. If you continue to use our website, we understand that you agree to the use of cookies as described in our privacy policy.", - "accept": "Accept" + "banner-title": "Will you help us improve Nets4Learning?", + "accept": "Accept", + "banner": "Nets4Learning is a teaching project by the SIMIDAT research group at the University of Jaén. If you accept the Google Analytics cookies, we will learn anonymously which models, datasets and sections are used and what fails, so we can decide what to improve. They are only enabled if you accept them, and you can change your mind at any time.", + "more-info": "More information", + "reject": "Reject", + "settings": "Settings", + "close": "Close without changing anything", + "details": "What is measured and what is not", + "measured-title": "Measured", + "measured": [ + "The pages you visit and how long you spend on them.", + "Which models and datasets you use and which buttons you press.", + "Training runs (epochs, optimizer, how long they take), predictions and how long models take to load.", + "The errors that appear, the language, the theme and the TensorFlow.js backend." + ], + "never-title": "Never sent", + "never": [ + "Your files, their names or their data; your drawings or the camera image.", + "Personal data: there are no accounts or forms.", + "Anything for advertising: Google advertising signals are disabled." + ] }, "error": { "load-json-csv": "Error, the file could not be loaded", @@ -328,13 +642,22 @@ "layers-length": "You must have at least one layer with the number of neurons and their activation function", "parsing-csv": "Error, parsing data set", "file-not-valid": "Error, file not valid", - "metrics-length": "Error, the number of metrics must be between 1 and 10" + "metrics-length": "Error, the number of metrics must be between 1 and 10", + "need-model": "First you must create and train a model", + "dataset-not-processed": "The dataset is not processed", + "model-not-valid": "The model is not valid for this data", + "model-compile": "The model could not be compiled. See the console for details.", + "option-not-valid": "Option not valid", + "prediction": "The prediction could not be made", + "load-dataset": "The dataset could not be loaded." }, "warning": { "the-first-layer-need-to-be-__value__": "Warning, the first layer must be of type {{value}}", "not-more-layers": "Warning, no more layers can be added", "error-layers": "Warning, you should have between 1 and 10 layers", - "need-a-model": "Warning, you must first create and train the model." + "need-a-model": "Warning, you must first create and train the model.", + "first-layer-cant-be-removed": "The first layer cannot be removed", + "first-layer-cant-be-changed": "The first layer cannot be changed" }, "success": { "file-upload": "File upload successful" @@ -360,7 +683,8 @@ "model-train-error": "Error training the model", "prediction": "The prediction is: {{index}}", "file-upload-success": "Successfully loaded file", - "file-upload-error-incorrect-format": "The file could not be loaded, it is not the correct format" + "file-upload-error-incorrect-format": "The file could not be loaded, it is not the correct format", + "close": "Close the notice" }, "header": { "language": "Language", @@ -368,9 +692,25 @@ "glossary": "Glossary", "home": "Home", "datasets": "Data sets", - "theme": "Theme", "dataframe": "DataFrame", - "analyze": "EDA" + "analyze": "EDA", + "theme": "Theme", + "theme-light": "Light", + "theme-dark": "Dark", + "backend": "Backend", + "backend-default": "default", + "backend-unavailable": "not available", + "backend-software": "software, slow", + "backend-error": "Could not switch to {{backend}}", + "backend-error-fallback": "This browser cannot use it. TensorFlow.js keeps using {{backend}}.", + "menu": "Menu", + "tasks": "Tasks", + "lab": "2D lab", + "packages": ".n4l packages", + "packages-saved_one": "{{count}} package saved in this browser", + "packages-saved_other": "{{count}} packages saved in this browser", + "github": "GitHub (opens in a new tab)", + "main-navigation": "Main navigation" }, "footer": { "description-app": "Web platform for the design and testing of deep learning models.", @@ -381,7 +721,12 @@ "terms": "Terms and conditions", "contribute": "Contribute", "documentation": "Documentation", - "version": "Version" + "version": "Version", + "cookies": "Cookie preferences", + "links": "Links", + "institutions": "Institutions", + "settings": "Settings", + "accessibility": "Accessibility" }, "drag-and-drop": { "label-files-one": "File:", @@ -390,11 +735,23 @@ "binary": "Add the binary file", "json": "Add the JSON file", "csv": "Add the CSV file", - "csv-json": "Enter the template data file.json" + "csv-json": "Enter the template data file.json", + "dataset": "Add the data file (CSV, ARFF, JSON, JSONL or Parquet)", + "choose-file": "Choose file", + "choose-files": "Choose files", + "errors": { + "file-invalid-type": "Format not supported", + "file-too-large": "The file is too large", + "file-too-small": "The file is too small", + "too-many-files": "Only one file can be uploaded" + } }, "custom-canvas-drawer": { - "validate": "Validate", - "clear": "Clean" + "validate": "Classify", + "clear": "Clear", + "canvas": "Canvas to draw on with the mouse, a pen or your finger", + "preview": "What the network receives: the drawing at 28 × 28 pixels", + "alternative": "If you cannot draw, classify one of the examples or a test image." }, "table": { "dataset": "Dataset" @@ -407,7 +764,8 @@ "tabular-classification": "Tabular classification", "regression": "Regression", "object-detection": "Object identification", - "image-classification": "Image classifier" + "image-classification": "Image classifier", + "time-series": "Time series" }, "graphic-red": { "input": "Input", @@ -420,556 +778,6 @@ "text": "Enter separate by point and eat the values.", "items": "(parameter-1; parameter-2; parameter-3; ...; parameter-n)." } - }, - "car": { - "title": "CAR - Car classification", - "description": { - "text-1": "The dataset car evaluation allows to evaluate vehicles through the following structure", - "text-2": "For more information about this dataset, visit the ICS.UCI.edu repository.", - "details-1": { - "title": "Information", - "list": { - "1": "buying: Purchase price.", - "2": "maint: Maintenance cost.", - "3": "doors: Number of doors.", - "4": "persons: Number of places.", - "5": "lug_boot: Trunk size.", - "6": "safety: Estimated vehicle security." - } - }, - "details-2": { - "title": "Input data", - "text-1": "Characteristics of the car", - "list": { - "1": "buying: vhigh, high, med, low.", - "2": "maint: vhigh, high, med, low.", - "3": "doors: 2, 3, 4, 5more.", - "4": "persons: 2, 4, more.", - "5": "lug_boot: small, med, big.", - "6": "safety: low, med, high." - } - }, - "details-3": { - "title": "Output data", - "text-1": "Vehicle acceptance", - "list": { - "1": "unacc : Inaccessible", - "2": "acc : Accessible", - "3": "good : Good", - "4": "vgood : Very good" - } - }, - "details-4": { - "title": "References", - "list": { - "1": "Data set" - } - } - }, - "html-example": { - "text": "Enter the values corresponding to the car to be evaluated:", - "items": "(Buying; Maint; Doors; Persons; Lug_boot; Safety)", - "examples": "Examples:" - } - }, - "iris": { - "title": "IRIS - Iris classification", - "description": { - "text-1": "The Iris-Data dataset allows to detect what type of iris plant is from the altitude and length of its petal and sepalo.", - "details-1": { - "title": "Input data", - "list": { - "1": "Sepal length: continuous", - "2": "Sepal width: continuous", - "3": "Petal length: continuous", - "4": "Petal width: continuous" - } - }, - "details-2": { - "title": "Output data", - "list": { - "1": "0: Setosa", - "2": "1: Versicolor", - "3": "2: Virginica" - } - }, - "details-3": { - "title": "References", - "list": { - "1": "Data set" - } - } - }, - "html-example": { - "text": "Enter the values corresponding to the plant to be evaluated:", - "items": "(sepal length; sepalo width; petal length; petal width).", - "examples": "Examples:" - } - }, - "lymphography": { - "title": "LYMPHOGRAPHY - Lymphoma data classification", - "description": { - "text-1": "The dataset of Lymphography allows to detect that possible phases of a lymphoma and in what state it is.", - "details-input": { - "title": "Input data", - "list": { - "0": " lymphography", - "1": " Block of affection : No, Yes", - "2": " bl. OF LYMPH. C : No, Yes", - "3": " bl. OF LYMPH. S : No, Yes", - "4": " by pass : no, yes", - "5": " extravasates : No, Yes", - "6": " regeneration of : no, yes", - "7": " Early Uptake In : No, Yes", - "8": " lym.nodes dimin : 0-3", - "9": " Lym.Nodes enlar : 1-4", - "10": " Changes in Lym. : Bean, Oval, Round", - "11": " defect in node : no, Lacunar, Lac. Marginal, Lac. central", - "12": " Changes in node : No, Lacunar, Lac. Margin, Lac. central", - "13": " changes in strong", - "14": " Special Forms : No, chalices, vesicles", - "15": " Dislocation of : No, Yes", - "16": " exclusion of no : no, yes", - "17": " no. of nodes in : 0-9, 10-19, 20-29, 30-39, 40-49, 50-59, 60-69,> = 70" - } - }, - "details-output": { - "title": "Output data", - "list": { - "0": " Normal Find : Normal", - "1": " Metastases : Metastasis", - "2": " Malign Lymph : Malignant lymphoma", - "3": " fibrosis : fibrosis" - } - }, - "details-references": { - "title": "References", - "list": { - "0": "Data set" - } - } - }, - "html-example": { - "text": "Enter the corresponding values of the patient to be evaluated:", - "items": "(lymphatics, block of affere, bl. of lymph. c, bl. of lymph. s, by pass, extravasates, regeneration of, early uptake in, lym.nodes dimin, lym.nodes enlar, changes in lym., defect in node, changes in node, changes in stru, special forms, dislocation of, exclusion of no, no. of nodes in).", - "examples": "Examples:" - } - }, - "list-datasets": { - "0-option-1": "Data set - Car classification", - "0-option-2": "Data set - Iris classification", - "0-option-3": "Data set - Lymphoma classification" - }, - "list-models": { - "0-option-1": "Model - Car classification", - "0-option-2": "Model - Iris classification", - "0-option-3": "Model - Lymphomas classification" - }, - "joyride": { - "title": "Activate the tutorial", - "steps": { - "manual": { - "title": "Manual", - "content": "You can consult the manual for information" - }, - "dataset-info": { - "title": "Dataset information", - "content": "Analyze the data set" - }, - "dataset": { - "title": "Data set", - "content": "You can view the data set and extract statistics from its descriptions" - }, - "dataset-plot": { - "title": "Data set plot", - "content": "You can extract very relevant information by analyzing the data set using the different graphs, bar diagrams, pie charts, etc." - }, - "layer-visualizer": { - "title": "Neural network layer viewer", - "content": "You can view the layers, activation functions in two formats, compact mode and extended mode" - }, - "layer-editor": { - "title": "Layer editor", - "content": "You can edit the layers of the neural network, modify the units of each layer, the activation function, add new layers or delete them." - }, - "params-editor": { - "title": "Hyperparameter editor", - "content": "You can configure the hyperparameters of your neural network so that the training is personalized for the data set." - }, - "list-of-models": { - "title": "Model List", - "content": "Once the model is generated, you can upload or download the model, to test each model and perform classification." - }, - "classify-and-visualizer": { - "title": "Classify and view", - "content": "Once our model for tabular classification is loaded, you can perform the classification and view the results" - } - } - } - }, - "1-regression": { - "salary": { - "title": "Salary for years of experience", - "description": { - "text": { - "0": "The \"Salary\" data set is a collection of information that relates the number of years of work experience of an individual to their corresponding salary.", - "1": "Each entry in the data set consists of two main variables: \"Years of Experience\" and \"Salary.\" The \"Years of Experience\" variable represents the number of years an employee has worked in their specific field, while the \"Salary\" variable represents the amount of money that employee earns annually." - }, - "link": "For more information about this data set, visit the repository www.kaggy.com", - "details-1-input": { - "title": "Input", - "list": { - "0": "Years of experience - Years of experience", - "1": "Salary - Salary" - } - }, - "details-2-output": { - "title": "Output", - "list": { - "0": "Calculated regression (Salary)" - } - }, - "details-3-references": { - "title": "References", - "list": { - "0": "Data set 1", - "1": "Data set 2" - } - } - } - }, - "auto-mpg": { - "title": "Auto MPG", - "description": { - "text": { - "0": "The AUTO MPG dataset was taken from the StatLib library maintained at Carnegie Mellon University. The dataset was used at the 1983 American Statistical Association Exposition.", - "1": "The term \"Auto MPG\" refers to miles per gallon, a unit of fuel efficiency measurement commonly used in the United States. This measure indicates how many miles a vehicle can travel on one gallon of fuel. However, \"Auto MPG\" is an English term and there is no direct translation in Spanish.\n\nIn Spanish, terms such as \"consumo de combustible\" or \"rendimiento de combustible\" are often used to refer to the fuel efficiency of a car. These terms indicate how many kilometres or miles a vehicle can travel on one litre or gallon of fuel, respectively.\n\nIt is important to note that different countries use different units of measurement for fuel consumption. For example, in some places the litre per 100 kilometres travelled (L/100 km) is used to indicate fuel efficiency." - }, - "link": "For more information about this dataset, visit the ICS.UCI.edu repository.", - "details-0": { - "title": "Information", - "list": { - "0": "MPG: MPG is Miles Per Gallon. This is the amount of fuel consumed by the particular vehicle of an instance. This variable can also be used as the variable to be predicted for any car", - "1": "cylinders: This attribute describes the number of cylinders of each car. This is a discrete valued attribute", - "2": "displacement: This is another attribute of the vehicle which has a quantitative continuous value describing the engine displacement", - "3": "horsepower: This attribute tells about the horsepower of a car and is a continuous valued variable", - "4": "weight: This refers to the weight of each car which is a continuous valued quantitative variable", - "5": "acceleration: The acceleration of the car", - "6": "model year: The year the model was released is mentioned in this attribute", - "7": "origin: The origin attribute has 3 discrete values. 1 refers to cars made in USA, 2 for Europe and 3 for Asia", - "8": "car name: This is the name of the car in string" - } - }, - "details-1": { - "title": "Input data", - "list": { - "0": "MPG: continuous", - "1": "cylinders: multi-valued discrete, 4, 6, 8", - "2": "displacement: continuous", - "3": "horsepower: continuous", - "4": "weight: continuous", - "5": "acceleration: continuous", - "6": "model Year: multi-valued discrete", - "7": "origin: multi-valued discrete, 1 refers to cars made in USA, 2 for Europe and 3 for Asia", - "8": "car name: string (unique for each instance)" - } - }, - "details-2": { - "title": "Output data", - "list": { - "0": "Calculated regression (MPG/b>)" - } - }, - "details-3": { - "title": "References", - "list": { - "0": "Auto MPG" - } - } - } - }, - "housing-prices": { - "title": "The Housing prices", - "description": { - "text": { - "0": "The Boston housing data set is derived from information collected by the U.S. Census Service concerning housing in the Boston area.", - "1": "The data set is designed to address house price modeling and regression problems in different neighborhoods in Boston, Massachusetts, United States. This data set is commonly used for examples and practices in education and research." - }, - "link": "UCI data set info", - "details-input": { - "title": "Input", - "california": { - "list": { - "0": "Median House Value: Median house value for households within a block (measured in US Dollars) [$]", - "1": "Median Income: Median income for households within a block of houses (measured in tens of thousands of US Dollars) [10k$]", - "2": "Median Age: Median age of a house within a block; a lower number is a newer building [years]", - "3": "Total Rooms: Total number of rooms within a block", - "4": "Total Bedrooms: Total number of bedrooms within a block", - "5": "Population: Total number of people residing within a block", - "6": "Households: Total number of households, a group of people residing within a home unit, for a block", - "7": "Latitude: A measure of how far north a house is; a higher value is farther north [°]", - "8": "Longitude: A measure of how far west a house is; a higher value is farther west [°]", - "9": "Distance to coast: Distance to the nearest coast point [m]", - "10": "Distance to Los Angeles: Distance to the centre of Los Angeles [m]", - "11": "Distance to San Diego: Distance to the centre of San Diego [m]", - "12": "Distance to San Jose: Distance to the centre of San Jose [m]", - "13": "Distance to San Francisco: Distance to the centre of San Francisco [m]", - "14": null - } - }, - "boston": { - "list": { - "0": "CRIM per capita crime rate by town", - "1": "ZN proportion of residential land zoned for lots over 25,000 sq.ft.", - "2": "INDUS proportion of non-retail business acres per town", - "3": "CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)", - "4": "NOX nitric oxides concentration (parts per 10 million)", - "5": "RM average number of rooms per dwelling", - "6": "AGE proportion of owner-occupied units built prior to 1940", - "7": "DIS weighted distances to five Boston employment centres", - "8": "RAD index of accessibility to radial highways", - "9": "TAX full-value property-tax rate per $10,000", - "10": "PTRATIO pupil-teacher ratio by town", - "11": "B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town", - "12": "LSTAT % lower status of the population", - "13": "MEDV Median value of owner-occupied homes in $1000's" - } - } - }, - "details-output": { - "title": "Output", - "california": { - "list": { - "0": "Calculated regression" - } - }, - "boston": { - "list": { - "0": "Calculated regression" - } - } - }, - "details-references": { - "title": "References", - "california": { - "list": { - "0": "Kaggle California Housing Prices Data (5 new features!)" - } - }, - "boston": { - "list": { - "0": "UCI data set info", - "1": "Boston housing dataset controversy" - } - } - } - } - }, - "breast-cancer": { - "title": "Breast Cancer Wisconsin (Diagnostic and prognostic)", - "description": { - "text": { - "0": "It is a data set from the University of Wisconsin Hospital related to breast cancer. This data set is useful for the prediction and discrimination of a breast cancer tumor, differentiating whether it is benign or not.", - "1": "Each record represents follow-up data for a breast cancer case. These are cases treated since 1984 by Dr. Wolberg, he only includes those cases that present invasive breast cancer and without evidence of metastasis.", - "2": "The first 30 characteristics are calculated from a digitized image of a fine needle aspiration (FNAB) of the breast mass, these data describe the characteristics of the cell nuclei present in the image, some images can be found in cs wisc", - "3": "The file wdbc.csv corresponds to the diagnostic data set and wpbc.csv corresponds to the prognostic data set." - }, - "link": "UCI data set input ", - "details-1-input": { - "title": "Input", - "list": { - "0": "ID number", - "1": "Outcome (R = recur, N = nonrecur)", - "2": "Time (recurrence time if field 2 = R, disease-free time if field 2 = N)", - "3": "4-33 Ten real-valued features are computed for each cell nucleus:", - "4": "radius (mean of distances from center to points on the perimeter)", - "5": "texture (standard deviation of gray-scale values)", - "6": "perimeter", - "7": "area", - "8": "smoothness (local variation in radius lengths)", - "9": "compactness (perimeter^2 / area - 1.0)", - "10": "concavity (severity of concave portions of the contour)", - "11": "concave points (number of concave portions of the contour)", - "12": "symmetry", - "13": "fractal dimension (\"coastline approximation\" - 1)" - } - }, - "details-2-output": { - "title": "Output", - "list": { - "0": "Calculated regression (Salary)" - } - }, - "details-3-references": { - "title": "References", - "list": { - "0": "Breast Cancer Wisconsin", - "1": "Breast Cancer Wisconsin (Prognostic)", - "2": "Breast Cancer Wisconsin (Diagnostic)" - } - } - } - }, - "student-performance": { - "title": "Student Performance", - "description": { - "text": { - "0": "The data set includes data on the academic performance of students from two Portuguese schools. The data includes demographic, social characteristics, student grades, etc. Two sets of data are included, one with the performance of two different subjects: Mathematics (mat) and Portuguese language (por).", - "1": "The data set contains multivariate type data, real type attributes, 649 instances, and 12 distinct attributes.", - "2": "Important note: The target attribute G3 has a strong correlation with the attributes G2 and G1. This occurs because G3 is the grade for the last year (issued in the 3rd period), while G1 and G2 correspond to the grades for the 1st and 2nd period. It is more difficult to predict G3 without G2 and G1, but such a prediction is much more useful.", - "3": "The file student-por.csv corresponds to the data set of Portuguese student grades and student-mat.csv corresponds to the data set of mathematics student grades." - }, - "link": "UCI data set input", - "details-1-input": { - "title": "Input", - "list": { - "0": "school - student's school (binary: 'GP' - Gabriel Pereira or 'MS' - Mousinho da Silveira)", - "1": "sex - student's sex (binary: 'F' - female or 'M' - male)", - "2": "age - student's age (numeric: from 15 to 22)", - "3": "address - student's home address type (binary: 'U' - urban or 'R' - rural)", - "4": "famsize - family size (binary: 'LE3' - less or equal to 3 or 'GT3' - greater than 3)", - "5": "Pstatus - parent's cohabitation status (binary: 'T' - living together or 'A' - apart)", - "6": "Medu - mother's education (numeric: 0 - none, 1 - primary education (4th grade), 2 – 5th to 9th grade, 3 – secondary education or 4 – higher education)", - "7": "Fedu - father's education (numeric: 0 - none, 1 - primary education (4th grade), 2 – 5th to 9th grade, 3 – secondary education or 4 – higher education)", - "8": "Mjob - mother's job (nominal: 'teacher', 'health' care related, civil 'services' (e.g. administrative or police), 'at_home' or 'other')", - "9": "Fjob - father's job (nominal: 'teacher', 'health' care related, civil 'services' (e.g. administrative or police), 'at_home' or 'other')", - "10": "reason - reason to choose this school (nominal: close to 'home', school 'reputation', 'course' preference or 'other')", - "11": "guardian - student's guardian (nominal: 'mother', 'father' or 'other')", - "12": "traveltime - home to school travel time (numeric: 1 - < 15 min., 2 - 15 to 30 min., 3 - 30 min. to 1 hour, or 4 - > 1 hour)", - "13": "studytime - weekly study time (numeric: 1 - < 2 hours, 2 - 2 to 5 hours, 3 - 5 to 10 hours, or 4 - > 10 hours)", - "14": "failures - number of past class failures (numeric: n if 1 ≶=n ≶3, else 4)", - "15": "schoolsup - extra educational support (binary: yes or no)", - "16": "famsup - family educational support (binary: yes or no)", - "17": "paid - extra paid classes within the course subject (Math or Portuguese) (binary: yes or no)", - "18": "activities - extra-curricular activities (binary: yes or no)", - "19": "nursery - attended nursery school (binary: yes or no)", - "20": "higher - wants to take higher education (binary: yes or no)", - "21": "internet - Internet access at home (binary: yes or no)", - "22": "romantic - with a romantic relationship (binary: yes or no)", - "23": "famrel - quality of family relationships (numeric: from 1 - very bad to 5 - excellent)", - "24": "freetime - free time after school (numeric: from 1 - very low to 5 - very high)", - "25": "goout - going out with friends (numeric: from 1 - very low to 5 - very high)", - "26": "Dalc - workday alcohol consumption (numeric: from 1 - very low to 5 - very high)", - "27": "Walc - weekend alcohol consumption (numeric: from 1 - very low to 5 - very high)", - "28": "health - current health status (numeric: from 1 - very bad to 5 - very good)", - "29": "absences - number of school absences (numeric: from 0 to 93)" - } - }, - "details-2-output": { - "title": "Output", - "list": { - "0": "Calculated regression" - } - }, - "details-3-references": { - "title": "References", - "list": { - "0": "Student Performance" - } - } - } - }, - "wine": { - "title": "Wine Quality", - "description": { - "text": { - "0": "The two data sets are related, as they include the red wine and Portuguese white wine variants. Said data set only includes physicochemical (inputs) and sensory (outputs) variables, the data set does not include data on grape types, wine brand or wine sales price.", - "1": "The dataset contains multivariate type data, real type attributes, 4898 instances, and 12 distinct attributes.", - "2": "This data set can be used for classification or regression tasks. The classes are ordered, although the data set is unbalanced.", - "3": "The wine-qualy-red.csv file corresponds to the red wine data set and wine-qualy-white.csv corresponds to the white wine data set." - }, - "link": "For more information about this data set visit the repository archive.ics.uci.edu.", - "details-1-input": { - "title": "Input", - "list": { - "0": "Fixed Acidity: Fixed acidity refers to the concentration of non-volatile acids in wine, mainly tartaric acid. It contributes to the freshness and stability of the wine.", - "1": "Volatile Acidity: Volatile acidity refers to the concentration of volatile acids, such as acetic acid, which can give an unpleasant taste if present in excess.", - "2": "Citric Acid: Citric acid is one of the natural organic acids present in wine. It can influence the flavor and freshness of the wine.", - "3": "Residual Sugar: It is the amount of sugar that remains in the wine after fermentation. A wine can be dry (little residual sugar) or sweet (more residual sugar).", - "4": "Chlorides: The concentration of chlorides in wine can affect its flavor and aroma, and high levels can indicate problems in production.", - "5": "Free Sulfur Dioxide: Sulfur dioxide is a common preservative in wine that helps prevent oxidation and the growth of unwanted microorganisms.", - "6": "Total Sulfur Dioxide: Represents the sum of free sulfur dioxide and sulfur dioxide bound to other molecules in the wine. It is also related to the conservation of wine.", - "7": "Density: Density refers to the mass of the wine per unit of volume. It can provide information on alcohol and sugar concentration.", - "8": "pH: The pH measures the acidity or alkalinity of the wine. A low pH indicates acidity, while a high pH indicates alkalinity. It can influence flavor perception.", - "9": "Sulphates: Sulfates are additives that are sometimes used in wine production. They can influence the stability and aroma of the wine.", - "10": "Alcohol: The concentration of alcohol in wine can vary and affects both the flavor and mouthfeel.", - "11": "Quality: This is the overall quality score of the wine, generally on a scale of 0 to 10, with higher values indicating better quality wines as assessed by tasters." - } - }, - "details-2-output": { - "title": "Output", - "list": { - "0": "Calculated regression" - } - }, - "details-3-references": { - "title": "References", - "list": { - "0": "Wine quality" - } - } - } - }, - "list-datasets": { - "salary": "Data set - Salary", - "auto-mpg": "Data set - Auto MPG", - "housing-prices": "Data set - Housing Prices", - "breast-cancer": "Data set - Breast cancer", - "student-performance": "Data set - Student performance", - "wine": "Data set - Wine" - }, - "list-models": { - "salary": "Model - Salary", - "auto-mpg": "Model - Auto MPG", - "housing-prices": "Model - Housing prices", - "breast-cancer": "Model - Breast cancer", - "student-performance": "Model - Student performance", - "wine": "Model - Wine" - }, - "joyride": { - "title": "Activate the tutorial", - "steps": { - "manual": { - "title": "Manual", - "content": "You can consult the manual for information" - }, - "dataset-info": { - "title": "Dataset information", - "content": "Query data set information" - }, - "dataset": { - "title": "Data set", - "content": "You can view the data set and extract statistics from its descriptions" - }, - "pre-process-dataset": { - "title": "Pre process", - "content": "Cleaning and preparing the data set" - }, - "dataset-plot": { - "title": "Data set plot", - "content": "You can extract very relevant information by analyzing the data set using the different graphs, bar diagrams, pie charts, etc." - }, - "layer-visualizer": { - "title": "Neural network layer viewer", - "content": "You can view the layers, activation functions in two formats, compact mode and extended mode" - }, - "layer-editor": { - "title": "Layer editor", - "content": "You can edit the layers of the neural network, modify the units of each layer, the activation function, add new layers or delete them." - }, - "params-editor": { - "title": "Hyperparameter editor", - "content": "You can configure the hyperparameters of your neural network so that the training is personalized for the data set." - }, - "list-of-models": { - "title": "Model List", - "content": "Once the model is generated, you can upload or download the model, to test each model and make predictions." - }, - "predict-and-visualizer": { - "title": "Prediction and visualization", - "content": "Once our model for regression is loaded you can make predictions and visualize the results" - } - } } }, "2-object-detection": { @@ -977,11 +785,76 @@ "process-webcam": { "title": "Realtime recognition", "sub-title": "Webcam", - "button": "Webcam" + "button": "Webcam", + "device": "Camera" }, "process-image": { "title": "Image processing", "sub-title": "Upload Image" + }, + "device-info": { + "camera": "Camera in use", + "camera-off": "Turn on the webcam to see the camera details.", + "name": "Name", + "resolution": "Resolution", + "frames": "Received image", + "aspect": "Aspect ratio", + "frame-rate": "Frames per second", + "facing": "Camera", + "facing-user": "Front", + "facing-environment": "Back", + "resize-mode": "Resize mode", + "displayed": "Size on screen", + "mirrored": "Mirrored image", + "state": "State", + "state-live": "Streaming", + "state-ended": "Stopped", + "device-id": "Device ID", + "capabilities": "Camera capabilities", + "capabilities-none": "The browser does not report the camera capabilities.", + "detection": "Detection", + "model": "Model", + "predictions": "Predictions per second", + "prediction-time": "Time per prediction", + "limit": "Limit", + "limit-value": "{{fps}} per second", + "backend": "TensorFlow.js backend", + "tensors": "TensorFlow.js memory", + "devices": "Available cameras", + "devices-none": "No camera was found.", + "unnamed": "Camera {{index}}", + "in-use": "in use", + "browser": "Browser and system", + "browser-name": "Browser", + "platform": "System", + "mobile": "Mobile", + "architecture": "Architecture", + "cores": "CPU cores", + "memory": "Memory (approx.)", + "language": "Language", + "permission": "Camera permission", + "permission-granted": "Granted", + "permission-denied": "Denied", + "permission-prompt": "Not granted yet", + "webview": "WebView", + "secure": "Secure connection (HTTPS)", + "user-agent": "User agent", + "screen": "Screen and GPU", + "screen-size": "Screen", + "window": "Window", + "pixel-ratio": "Pixel density", + "orientation": "Orientation", + "gpu": "GPU", + "webgl2": "WebGL 2", + "software": "Software rendering", + "yes": "Yes", + "no": "No" + }, + "detections": { + "nothing": "Nothing is detected", + "detected": "Detected: {{list}}", + "waiting": "Waiting for the first detection…", + "announce": "Say what is detected" } }, "face-detection": { @@ -1006,6 +879,16 @@ "0": " Model entry into the tensorflow repository " } } + }, + "render": { + "face": "Face", + "face-number": "Face {{number}}", + "eye-right": "Right eye", + "eye-left": "Left eye", + "nose": "Nose", + "mouth": "Mouth", + "ear-right": "Right ear", + "ear-left": "Left ear" } }, "face-mesh": { @@ -1030,6 +913,14 @@ "0": " Model entry into the tensorflow repository " } } + }, + "render": { + "face": "Face", + "face-number": "Face {{number}}", + "points": "{{count}} points", + "eye-right": "Right eye", + "eye-left": "Left eye", + "lips": "Lips" } }, "move-net--pose-net": { @@ -1056,6 +947,23 @@ "1": "TFHub model" } } + }, + "render": { + "person": "Person", + "person-number": "Person {{number}}", + "score": "{{percent}}%", + "shoulder-left": "Left shoulder", + "shoulder-right": "Right shoulder", + "elbow-left": "Left elbow", + "elbow-right": "Right elbow", + "wrist-left": "Left wrist", + "wrist-right": "Right wrist", + "hip-left": "Left hip", + "hip-right": "Right hip", + "knee-left": "Left knee", + "knee-right": "Right knee", + "ankle-left": "Left ankle", + "ankle-right": "Right ankle" } }, "coco-ssd": { @@ -1166,7 +1074,10 @@ "hair drier": "Hair drier", "toothbrush": "Toothbrush" }, - "render-label": "{{label}} with {{score}}% confidence" + "render": { + "numbered": "{{label}} {{number}}", + "score": "{{percent}}%" + } }, "face-api": { "title": "FaceAPI - Face Expressions", @@ -1194,12 +1105,18 @@ "details-references": { "title": "References" } + }, + "render": { + "face": "Face", + "face-number": "Face {{number}}", + "age": "about {{age}} years", + "percent": "{{percent}}%" } }, "hand-sign": { "title": "Sign language with Hand sign", "description": { - "text-0": "Neural network for hand and landmark detection, used in conjunction with position descriptors to classify possible American Sign Language (ASL) or Spanish Sign Language (SSL) signs.", + "text-0": "Neural network that finds the hand and its 21 points (MediaPipe Hands) and, with them, recognises the letter of the fingerspelling alphabet: the American one (ASL), comparing the hand with 2122 real hands, or the Spanish one (SSL), with rules that describe each finger. It works with the right hand and with the left one.", "details-input": { "title": "Input data", "list": { @@ -1213,21 +1130,34 @@ "1": "Corresponding letter" } }, + "details-movement": { + "title": "Letters with movement", + "list": { + "0": "LL and RR (SSL): make the L or the R, move the hand to its own side (half a palm or more) and stop: the letter appears as soon as it stops.", + "1": "Ñ (SSL): make the N and move the hand from side to side, or turn the wrist, two or three times.", + "2": "Keep the letter while you move. A blurred image is fine: what is seen before and after the movement counts." + } + }, "details-references": { "title": "References", "list": { "0": "TFJS hand pose detection" } } + }, + "render": { + "left": "Left hand", + "right": "Right hand", + "movement": "With movement" } }, "list-models": { - "2-option-1": "Model - FaceDetector - Facial Geometry", - "2-option-2": "Model - FaceMesh - Facial Mesh", - "2-option-3": "Model - MoveNet - Joint detector", - "2-option-4": "Model - COCO SSD - Object detector", - "2-option-5": "Models - Face API - Face Manager", - "2-option-6": "Model - HandSign - Sign Detector" + "2-option-1": "FaceDetector - Facial Geometry", + "2-option-2": "FaceMesh - Facial Mesh", + "2-option-3": "MoveNet - Joint detector", + "2-option-4": "COCO SSD - Object detector", + "2-option-5": "Face API - Face Manager", + "2-option-6": "HandSign - Sign Detector" } }, "3-image-classifier": { @@ -1237,153 +1167,36 @@ "sub-title": "First the .json file and then the .bin file" }, "process-examples": { - "title": "Processing with examples" + "title": "Example images", + "help": "Click an image to classify it.", + "classify-example": "Classify example {{index}}", + "forms-help": "Each character as it is written today and in three old forms (hentaigana), with the kanji each one comes from, drawn with a font. Press any of them to classify it. With the old ones it is not always right: the network learned from strokes handwritten in books, not from printed type.", + "modern": "Today", + "old": "Before", + "classify-modern": "Classify {{char}} as written today", + "classify-old": "Classify old {{char}}, from {{origin}}", + "classify-example-label": "Classify example {{index}}: {{label}}" }, "process-draw": { "title": "Drawing" }, "process-image": { - "title": "Image processing", + "title": "Upload an image", "sub-title": "-", - "validate": "Validate" + "validate": "Classify" }, "result": "Result", "button-accept": "Accept", "modal": { "title": "Prediction" - } - }, - "mnist": { - "title": "MNIST - Number classification", - "description": { - "text-0": "The MNIST database is a large database of handwritten digits. The database is widely used for training and tests in the field of machine learning.", - "text-1": "The samples of the original NIST data sets were created \"re-mixing\".", - "text-2": "The NIST training dataset was taken from the United States Census Office. In addition, NIST's black and white images were normalized to fit into a 28 x 28 pixels and softened, which introduced gray scale levels.", - "details-input": { - "title": "Input data", - "list": { - "0": "Gray scale image and with a 28 x 28 pixels size" - } - }, - "details-output": { - "title": "Output data", - "list": { - "0": "A number between 0 and 9" - } - }, - "details-references": { - "title": "References" - } - } - }, - "kmnist": { - "title": "KMNIST - Japanese character classification", - "description": { - "text-0": "Kuzushiji-MNIST (KMNIST) is a drop-in replacement for MNIST: grayscale images of 28 x 28 pixels and 10 classes, but instead of digits it contains handwritten Japanese characters written in kuzushiji (cursive script).", - "text-1": "Kuzushiji was the usual way of writing Japanese for over a thousand years, but it stopped being taught after the writing reform of the early 20th century and today very few people can read it. The images come from classical books digitised by the National Institute of Japanese Literature and were prepared by the ROIS-DS Center for Open Data in the Humanities (CODH).", - "text-2": "Each class is a hiragana character (お, き, す, つ, な, は, ま, や, れ, を), and one character can be written in many different ways, so it is harder than MNIST.", - "details-input": { - "title": "Input data", - "list": { - "0": "Grayscale image of 28 x 28 pixels" - } - }, - "details-output": { - "title": "Output data", - "list": { - "0": "One of the 10 hiragana characters: お, き, す, つ, な, は, ま, や, れ, を" - } - }, - "details-model": { - "title": "Models", - "list": { - "0": "Pre-trained model: convolutional network trained with the 55,000 training images (and 5,000 more for validation), with {{accuracy, number(style: percent; minimumFractionDigits: 1)}} accuracy on the 10,000 test images.", - "1": "Training in the browser: a balanced subset is used, with 2,000 training images and 500 test images per character." - } - } - } - }, - "mobilenet": { - "title": "MobileNet - Image classification", - "description": { - "text-0": "MobileNet V2 is a family of neural networks for the classification of similar images and tasks.", - "text-1": "This model is able to differentiate between 1001 categories, identifying the main context of the image.", - "details-input": { - "title": "Input data", - "list": { - "0": "Image with color values between [0, 1] of 224 x 224 pixels." - } - }, - "details-output": { - "title": "Output data", - "list": { - "0": "A number of 0 to 1001 that are each of the categories of this list " - } - }, - "details-references": { - "title": "References", - "text-0": "Originally it was published by Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen:", - "list": { - "0": "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation 2018" - } - } + }, + "test-images": { + "load": "Load test images", + "loading": "Loading images…" } }, "face-mesh": { "title": "-" - }, - "list-models": { - "3-option-1": "Model - MNIST - Number Classification", - "3-option-2": "Model - MobileNet - Image Classifier", - "3-option-3": "Model - ResNet - Image classifier", - "3-option-4": "Model - KMNIST - Japanese character classification" - } - }, - "3-image-classification": { - "list-datasets": { - "mnist": "Data set - MNIST", - "kmnist": "Data set - KMNIST" - }, - "joyride": { - "title": "Activate the tutorial", - "steps": { - "manual": { - "title": "Manual", - "content": "You can consult the manual for information" - }, - "dataset-info": { - "title": "Dataset information", - "content": "Query data set information" - }, - "dataset": { - "title": "Data set", - "content": "You can view the data set and extract statistics from its descriptions" - }, - "dataset-plot": { - "title": "Data set plot", - "content": "You can extract very relevant information by analyzing the data set using the different graphs, bar diagrams, pie charts, etc." - }, - "layer-visualizer": { - "title": "Neural network layer viewer", - "content": "You can view the layers, activation functions in two formats, compact mode and extended mode" - }, - "layer-editor": { - "title": "Layer editor", - "content": "You can edit the layers of the neural network, modify the units of each layer, the activation function, add new layers or delete them." - }, - "params-editor": { - "title": "Hyperparameter editor", - "content": "You can configure the hyperparameters of your neural network so that the training is personalized for the data set." - }, - "list-of-models": { - "title": "Model List", - "content": "Once the model is generated, you can upload or download the model, to test each model and make predictions." - }, - "classify": { - "title": "Prediction and visualization", - "content": "Once our model for regression is loaded you can make predictions and visualize the results" - } - } } } }, @@ -1607,7 +1420,8 @@ "0": "Violin plots are a useful tool for visualizing and comparing data distributions.\nThey allow you to analyze the shape, dispersion, symmetry and presence of outliers in the data, and are especially useful when comparison between multiple groups or categories is required.\nTheir attractive and concise graphical representation makes them an effective tool for communicating complex information in an understandable way." } } - } + }, + "select-plot": "Chart type" }, "face-api": { "years": "Years", @@ -1621,7 +1435,23 @@ }, "pages": { "version": { - "title": "Version" + "title": "Version", + "app": "Application version", + "environment": "Environment (mode)", + "backend": "Backend in use", + "runtime": "This installation", + "changes": "Changes", + "changes-text": "Everything that changes in each version is recorded in the history of the repository.", + "commits": "Change history (commits)", + "releases": "Published versions", + "dependencies": "Dependencies", + "dependencies-help": "The libraries the application depends on, with the version requested in package.json.", + "runtime-dependencies": "Application", + "dev-dependencies": "Development", + "package": "Package", + "declared": "Requested version", + "search": "Search for a package", + "no-results": "No package matches the search." }, "index": { "tabular-classification": { @@ -1684,6 +1514,33 @@ "6": "Define metric functions." }, "2-button": "Create and train a model" + }, + "hero": { + "text": "Nets4Learning is a web platform to learn how neural networks work: pick a task, design the network, train it and test it, all in the browser with nothing to install. It is aimed at students and teachers." + }, + "clustering": { + "1-title": "Clustering", + "1-description-1": "Group the data without saying what each row is (unsupervised learning): k-means looks for k groups of rows similar to each other.", + "1-description-2": "You'll see how the groups form step by step and, in datasets with the real classes, whether the groups resemble them even though it never saw them.", + "1-button": "Choose a dataset" + }, + "time-series": { + "1-title": "Time series", + "1-description-1": "Forecast the next values of a time series (passengers each month, the temperature each day…) from the previous ones: the network learns from windows of past values.", + "1-description-2": "Try the models already trained with three classic series (airline passengers, Melbourne temperatures and sunspots): you will see how they forecast the end of the series, which they did not see while training, whether they beat the simplest forecasts (repeating the last value or the one a season ago) and what comes next.", + "1-button": "Pre-trained models", + "2-title": "Design, create and edit an architecture to forecast series", + "2-description-1": "With this tool we can create a neural network that predicts the next value of a series from the previous ones, with one of the example series or with your own.", + "2-description-2": "To design, create, train and evaluate a custom architecture, we must:", + "2-description-list": { + "1": "Define the window: how many previous values the network looks at.", + "2": "Define how much of the end of the series is set aside for testing and whether to difference it.", + "3": "Define the number of layers, their type (Dense or recurrent: SimpleRNN, LSTM and GRU) and their activation functions.", + "4": "Define the learning rate.", + "5": "Define the number of epochs and the batch size.", + "6": "Define the optimizer and the loss function." + }, + "2-button": "Create and train a model" } }, "contribute": { @@ -1692,22 +1549,93 @@ "title": "Project in GitHub" }, "license": { - "title": "License" + "title": "License", + "text": "The code is under the MIT license: you can use, copy, modify and distribute it freely, keeping the copyright notice. Third-party data sets and models keep their own licenses, which are given in the description of each one.", + "full": "Full text of the license" + }, + "intro": "Nets4Learning is free software, under the MIT license, from the SIMIDAT research group of the University of Jaén. Any help is welcome: reporting a bug, suggesting an improvement, translating, adding data sets and models or improving the code.", + "ways": { + "title": "How to contribute", + "issues": { + "title": "Report a bug or suggest an improvement", + "text": "Open an issue on GitHub telling us what happened, on which page and with which browser, or what you would like the application to have.", + "link": "Open an issue" + }, + "translate": { + "title": "Translate the application", + "text": "The texts are in public/locales, one file per language (Spanish, English and Japanese), and the manual is in public/docs. Any correction or new language helps.", + "link": "See the translations" + }, + "datasets": { + "title": "Add a data set or a model", + "text": "Each one is a class in the models folder of its task, with its key in MODEL_KEYS.ts, its menu option in DATA_MODEL.ts, its texts and its files.", + "link": "See the tasks" + }, + "code": { + "title": "Improve the code", + "text": "Fork the repository, create a branch with your changes and open a pull request. The automatic checks will review it before it is merged.", + "link": "See the pull requests" + } + }, + "setup": { + "title": "Run it on your computer", + "requirements": "You need Node.js 22 or later and pnpm 12; Corepack installs the exact version of pnpm.", + "url": "The application is then served at", + "scripts": [ + "Development server, which reloads when you save", + "Unit tests (Vitest), once", + "Browser tests (Playwright) with the Netlify build", + "Code review with ESLint", + "Type-checks and builds the SIMIDAT version" + ] + }, + "checklist": { + "title": "Before sending your changes", + "items": [ + "Write the commits with Conventional Commits (feat:, fix:, docs:…): commitlint checks them.", + "Run pnpm lint, pnpm test run and pnpm build:simidat. The GitHub checks also run pnpm test:e2e.", + "Put every new interface text in the three translation files.", + "If you add a data set or a model, cite its source and its license in its description." + ] + }, + "cite": { + "title": "Cite the work", + "text": "If you use Nets4Learning in a class, a project or a paper, please cite the article that describes the platform:", + "copy": "Copy BibTeX", + "copied": "Copied" + }, + "docs": { + "title": "Technical documentation", + "text": "Guides from the repository for anyone who wants to work on the code.", + "i18n": "Translations (i18n)", + "directory-structure": "Folder structure", + "introduction": "Tabular classification: introduction", + "add-entry": "Tabular classification: add a data set", + "create-model": "Tabular classification: create a model" } }, "menu-selection-dataset": { "0-tabular-classification": { - "csv": "Upload dataset - CSV", - "csv-text": "Upload a file with a dataset treated in .CSV format " + "csv": "Upload dataset", + "csv-text": "Upload a file with a dataset in .csv, .arff, .json, .jsonl or .parquet format" }, - "form-description-1": "Then select the dataset on you will work or load your own dataset.", + "form-description-1": "Choose the dataset you are going to train with, or upload your own.", "form-label": "Select a dataset", "form-option-_-1": "Select a dataset", "form-upload-description": "Now if you wish you can load your own architecture, otherwise click on continuing and an architecture will be loaded by example default.", "form-submit": "Continue", "1-regression": { - "csv": "Upload dataset - CSV", - "csv-text": "Upload a file with a dataset treated in .CSV format " + "csv": "Upload dataset", + "csv-text": "Upload a file with a dataset in .csv, .arff, .json, .jsonl or .parquet format" + }, + "upload-text": "Upload your own dataset (CSV, ARFF, JSON, JSONL or Parquet) and prepare it before training.", + "own-dataset": "Your own dataset", + "example-datasets": "Example datasets", + "clustering": { + "csv": "Upload a CSV" + }, + "time-series": { + "csv": "Upload a series" } }, "menu-selection-model": { @@ -1728,12 +1656,17 @@ "parameter-categorical": "Categorical parameter", "data-to-check": "Data to test", "vector-to-check": "Vector to test", - "button-check-result": "Predict" + "button-check-result": "Predict", + "type-categorical": "Categorical, {{count}} values", + "type-integer": "Whole number", + "type-decimal": "Decimal number", + "range": "{{min}} – {{max}} in the data" }, "0-tabular-classification": { "general": { "model": "Model", "description-input": "Data entry description", + "dataframe-processed-help": "The same data with each categorical value turned into a number (LabelEncoder; the mapping is under “Attributes” and “Classes”). This is how the model receives it: the last column is the class it has to predict.", "description-features": "Features edit form", "description-data": "Form data", "description-vector": "Data vector", @@ -1788,7 +1721,7 @@ "title": "Hyperparameter editor", "text-0": "The necessary general parameters can be edited for the creation of the model.
These parameters are:", "list": { - "0": "Learning rate:
Value between 0 and 100 which indicates the percentage of the weight weights.", + "0": "Learning rate:
How much the network weights change at each training step (for example, 0.01).", "1": "Number of epochs:
Number of times the network training set (the greatest number, it takes longer to train).", "2": "Test set size:
Percentage of the data set that will be used for model tests (test data). The rest of the data will be used for network training (training data).", "3": "Optimizer:
It is a function that is used to adjust the weights of the network.", @@ -1817,9 +1750,9 @@ "text-0": "If we have created the model correctly an entry will be added to the table of models generated, we are allowed to export the models generated and save them locally." }, "details-prediction": { - "title": "Prediction", + "title": "Classification", "text-0": "The final form allows us to select the main characteristics used to determine the class.", - "text-1": "By pressing the \"See result\" button, the prediction of its output class is obtained from the input characteristics of the element." + "text-1": "When you press the \"Classify\" button, the model predicts the class of the example from its input features and shows the probability of each class." } } } @@ -1863,6 +1796,12 @@ "add-layer-start": "Add a layer to the start", "add-layer-end": "Add a layer to the end", "delete-layer": "Delete layer {{index}}", + "move-up": "Move layer {{index}} up", + "move-down": "Move layer {{index}} down", + "move-group": "Order of layer {{index}}", + "moved": "Layer {{index}} moved to position {{position}}.", + "drag": "Drag to move layer {{index}}", + "drag-help": "To change the order, drag each layer by the handle on its left, or open it and use \"Move up\" and \"Move down\".", "layer-id": "Layer {{index}}", "kernel-size": "Kernel size", "kernel-size-placeholder": "Enter the kernel size of the layer.", @@ -1875,7 +1814,12 @@ "strides": "Strides", "strides-placeholder": "Enter the strides of the layer", "pool-size": "Pool size", - "pool-size-placeholder": "Enter the pool size of the layer" + "pool-size-placeholder": "Enter the pool size of the layer", + "layer-class": "Layer type", + "removed": "Layer {{index}} deleted. You can undo it with “Undo”, above the layers.", + "removed-short": "Layer {{index}} deleted.", + "restored": "Layer {{index}} restored.", + "undo": "Undo" }, "editor-feature-selector": { "title": "Feature selector", @@ -1888,7 +1832,7 @@ "title": "Hyperparameter editor", "learning-rate": "Learning rate", "learning-rate-placeholder": "Enter the learning rate", - "learning-rate-info": "A value between 0 and 100 (it is a percentage)", + "learning-rate-info": "How much the weights change at each training step. High values learn faster but may not converge; low values are more stable but slower.", "number-of-epochs": "N. epochs", "number-of-epochs-placeholder": "Number of epochs", "number-of-epochs-info": "The higher it, the more training will be executed", @@ -1908,13 +1852,18 @@ "add-metric": "Add metric function", "metric-id-__index__": "Metric {{index}}", "metric-id-select": "Select the metric function", - "metric-id-info": "It will be one of the metric functions" + "metric-id-info": "It will be one of the metric functions", + "loss-group-classification": "Classification", + "loss-group-regression": "Regression", + "batch-size": "Batch size", + "batch-size-placeholder": "Examples per batch", + "batch-size-info": "How many windows are used in each weight update: with small batches it learns with more noise; with large ones, each epoch is faster." }, "loaded": "Loaded", "load": "Load", - "waiting-for-file": "Waiting for file", - "waiting-for-process": "Waiting for data set processing", - "waiting-for-training": "Waiting for model training", + "waiting-for-file": "Upload a data file (CSV, ARFF, JSON, JSONL or Parquet) to get started.", + "waiting-for-process": "Process the dataset to continue.", + "waiting-for-training": "No trained models yet. Set up the network and train one to see it here.", "models": { "title": "Models", "history-train": "Training history", @@ -1937,8 +1886,8 @@ "download": "Download" }, "dynamic-form-dataset": { - "title": "Prediction", - "text-0-__column_name_target__": "Enter the values of each entry feature of the example to predict {{column_name_target}}", + "title": "Classification", + "text-0-__column_name_target__": "Enter the value of each input feature of the example you want to classify ({{column_name_target}}), or pick an entity of the dataset in the selector above.", "select-option": "Select an option", "input-data": "Enter the data to test", "input-vector": "Enter the vector to test", @@ -1946,7 +1895,11 @@ "test-input-data": "Form data", "test-input-vector": "Vector to test", "selector-entity": "Select the entity", - "selector-model": "Select the model" + "search-entity": "Search by number or class…", + "entity-count": "{{shown}} of {{total}}", + "no-entity": "Nothing matches the search", + "selector-model": "Select the model", + "classify-button": "Classify" }, "list-models-generated": "List generated models", "visor": { @@ -1969,7 +1922,86 @@ "confusion-matrix": "Confusion matrix", "line-chart": "Line chart" }, - "waiting-for-models": "Waiting for the creation of a model" + "waiting-for-models": "Train a model to make predictions.", + "classify": { + "waiting": "Classify an example to see the result here.", + "predicted-class": "Predicted class", + "confidence": "with a probability of {{value}}", + "chart-title": "Probability of each class", + "chart-title-output": "Network output for each class", + "chart-help": "The highlighted bar is the class the model picks: the most likely one. When the model hesitates, several bars have similar heights.", + "chart-help-output": "The last layer does not use softmax, so these values are not probabilities. The model picks the class with the highest value (highlighted bar).", + "axis-class": "Class", + "axis-probability": "Probability (%)", + "axis-output": "Output", + "select-image": "Select an image from the dataset", + "actual-class": "Actual class: {{label}}", + "chart-title-top": "The {{count}} most likely classes", + "chart-help-top": "The model tells apart many more classes; only the most likely ones are shown here, with their probability.", + "hit": "correct", + "miss": "wrong", + "test-image": "Test image", + "class": "Class" + }, + "waiting-for-prediction": "Make a prediction to see the result here.", + "training": { + "epoch": "Training… epoch {{epoch}} of {{total}}", + "preparing": "Preparing the data and the model…", + "stop": "Stop", + "stopping": "Stopping…", + "curves-title": "Training curves", + "curves-model": "Model whose curves are shown", + "curves-compare": "Compare models", + "compare-pick": "Models to compare (up to {{max}})", + "compare-pick-more": "Tick at least two models to compare them.", + "compare-same": "They have the same hyperparameters: the differences come from chance (the weights each network starts with and how the data is split).", + "compare-one": "Only {{name}} changes: the difference between their results is mostly down to that.", + "compare-some": "Several things change ({{names}}): with several changes at once you can't tell which one mattered. To see what each one does, change only one thing between trainings.", + "compare-quote": "“{{name}}”", + "compare-caption": "Hyperparameters of each model (the ones that change are highlighted) and values in the last epoch (in brackets, on the validation data).", + "compare-parameter": "Parameter", + "compare-changed": "changes", + "compare-final": "{{name}} at the end", + "epoch-axis": "Epoch", + "train": "Training", + "validation": "Validation", + "best": "Best", + "best-title": "Lowest validation loss in the last epoch", + "confusion-title": "Confusion matrix (validation)", + "confusion-accuracy": "Correct: {{accuracy}} ({{correct}} of {{total}} examples the model did not see during training).", + "confusion-real": "Actual class", + "confusion-predicted": "Predicted class", + "confusion-total": "Total", + "confusion-recall": "Recall", + "confusion-precision": "Precision", + "confusion-legend": "Each cell shows how many examples of the actual class (row) were predicted as the column's class, and what share of their row they are. Green: correct; red: errors; the stronger the colour, the more examples.", + "curve-description": "{{name}} over {{epochs}} epochs: on the training data, from {{first}} to {{last}}.", + "curve-description-validation": "On the validation data, from {{first}} to {{last}}.", + "announce-start_one": "Training started: {{count}} epoch", + "announce-start_other": "Training started: {{count}} epochs", + "announce-stopped": "Training stopped at epoch {{epoch}} of {{total}}. The model is saved with those epochs", + "announce-error": "Training could not finish", + "go-to-result": "Go to the result", + "curve-data": "{{name}} at each epoch", + "remaining": "about {{time}} left", + "last-run_one": "The last training took {{time}} ({{count}} epoch, {{perEpoch}} per epoch). With more epochs it will take longer, and you can stop it whenever you want.", + "last-run_other": "The last training took {{time}} ({{count}} epochs, {{perEpoch}} per epoch). With more epochs it will take longer, and you can stop it whenever you want." + }, + "help": { + "learning-rate": "Size of the step with which the optimizer corrects the network weights after each batch of data.", + "epochs": "An epoch is a full pass over all the training data. More epochs give more chances to learn, but also to overfit.", + "test-size": "Percentage of the data set aside to check the model with examples it has not seen during training (validation).", + "optimizer": "Algorithm that decides how to change the weights from the error. Adam usually works well without further tuning.", + "loss": "Measures how wrong the model is; training tries to make it as small as possible.", + "metric": "Measure computed during training to see how the model is doing (for example, accuracy). It is not used to correct the weights.", + "recall": "Recall: of the examples that belong to this class, the share the model gets right.", + "precision": "Precision: of the times the model predicts this class, the share that is right.", + "accuracy": "Accuracy: correct examples out of all the validation examples.", + "batch-size": "How many examples the network sees before updating its weights.", + "units": "How many neurons the layer has. With more, the network can learn more complicated relationships, but it takes longer to train and can learn the data by heart.", + "activation": "What each neuron does with the sum it receives. ReLU, sigmoid or tanh let the network learn relationships that are not straight lines; softmax, in the last layer, shares the probability among the classes." + }, + "example-from-dataset": "Example from the dataset" }, "1-regression": { "generator": { @@ -1993,7 +2025,7 @@ "0": "The necessary general parameters can be edited for the creation of the model.
These parameters are:" }, "list": { - "0": "Learning rate:
Value between 0 and 100 which indicates the percentage of the weight weights.", + "0": "Learning rate:
How much the network weights change at each training step (for example, 0.01).", "1": "Number of epochs:
Number of times the network training set (the greatest number, it takes longer to train).", "2": "Test set size:
Percentage of the data set that will be used for model tests (test data). The rest of the data will be used for network training (training data).", "3": "Optimizer:
It is a function that is used to adjust the weights of the network.", @@ -2036,7 +2068,8 @@ "multiple-regression": "Multiple linear regression" }, "dataframe": { - "title": "Processed dataframe" + "title": "Processed dataframe", + "help": "The same data with each categorical value turned into a number (LabelEncoder). Before entering the model the attributes are scaled; the {{target}} column is the value it has to predict." }, "selector-instance": { "option": "Instance selector" @@ -2061,7 +2094,14 @@ "button-submit": "Predict", "list-models-generated": "List of generated models", "list-models": "List of generated models", - "list-instances": "List of instancies" + "list-instances": "List of instancies", + "predicted-value": "Predicted {{target}}", + "actual-value": "Actual value: {{value}}", + "error": "Error: {{value}} ({{percent}})", + "input-details": "Model input step by step", + "choose-instance": "Choose an instance of the data set to fill in the form; then you can change its values.", + "no-models": "This data set has no pre-trained model. Choose another data set or train your own model in the regression playground.", + "model-selector": "Model to predict with" }, "model-selector": { "title": "Model selector", @@ -2098,7 +2138,7 @@ "title": "Hyperparameter editor", "text-0": "The necessary general parameters can be edited for the creation of the model.
These parameters are:", "list": { - "0": "Learning rate:
Value between 0 and 100 which indicates the percentage of the weight weights.", + "0": "Learning rate:
How much the network weights change at each training step (for example, 0.01).", "1": "Number of epochs:
Number of times the network training set (the greatest number, it takes longer to train).", "2": "Test set size:
Percentage of the data set that will be used for model tests (test data). The rest of the data will be used for network training (training data).", "3": "Optimizer:
It is a function that is used to adjust the weights of the network.", @@ -2133,11 +2173,450 @@ } } } + }, + "step-by-step": { + "title": "Step by step", + "intro": "This is how your network learns: an example enters on the left, goes forward through the network, its error is measured and that error goes back to correct each weight. It is the network you designed above, with random initial weights. Click a neuron to see its calculations.", + "intro-pretrained": "This is how this trained model computes its answer: an example enters on the left, goes forward through the network and is compared with the correct answer. Going backwards you will see how much each weight would change with one more training step; the model on the page does not change. Click a neuron to see its calculations.", + "too-big": "Your network has {{nodes}} neurons counting the input ones ({{detail}}). The step by step view is only drawn with fewer than {{max}}, so it can be followed: remove layers or neurons in the layer editor, for example with two hidden layers of 8.", + "too-big-pretrained": "This model has {{nodes}} neurons counting the input ones ({{detail}}). The step by step view is only drawn with fewer than {{max}}, so it can be followed. On the training page of this dataset you can see it with a smaller network.", + "not-dense": "This model is not a network of dense layers: the step by step view only draws that kind of network.", + "mismatch": "The last layer has {{units}} neurons and the network has to give {{classes}} outputs: change it in the layer editor to see it step by step.", + "example": "Choose an example", + "search": "Search an example", + "no-results": "No example matches", + "back": "Previous phase", + "next": "Next", + "play": "Play", + "pause": "Pause", + "ten": "Train with 10 examples at once", + "speed": "Speed", + "speeds": { + "slow": "Slow", + "normal": "Normal", + "fast": "Fast" + }, + "same-example": "Repeat the same example", + "reset": "Reset the weights", + "reset-pretrained": "Back to the model weights", + "legend": "Blue: positive value or weight; red: negative. The more intense or thicker, the larger. In orange, what goes backwards: the deltas of the neurons and the gradients of the weights.", + "phase-count": "Phase {{current}} of {{total}}", + "phase-title": { + "input": "The input", + "forward": "Forward: layer {{layer}}", + "loss": "The error", + "backward": "Backward: layer {{layer}}", + "update": "Update the weights" + }, + "phase": { + "input": "Example no. {{row}} comes in: its {{count}} features, already scaled as in training, are the values of the input neurons.", + "input-pretrained": "Example no. {{row}} comes in: its {{count}} features, as this model receives them, are the values of the input neurons.", + "forward": "Each neuron of layer {{layer}} multiplies each input by the weight of its connection, adds up the products and its bias (z) and applies the {{activation}} activation. The highlighted connections are the ones involved.", + "forward-softmax": "Layer {{layer}} adds up its inputs times its weights (z) and softmax turns those sums into probabilities, one per class, that add up to 1.", + "loss-classification": "The network gives a probability of {{probability}} to “{{target}}”, the correct answer. The loss, cross-entropy, is −log({{probability}}) = {{loss}}: the lower the probability of the correct class, the higher it is. Right now the network would answer “{{predicted}}”.", + "loss-regression": "The network predicts {{prediction}} and the real value is {{actual}}. In the step by step view the target is scaled between 0 and 1 ({{output}} versus {{target}}), and the loss is the squared error: ({{output}} − {{target}})² = {{loss}}.", + "loss-regression-raw": "The network predicts {{prediction}} and the real value is {{actual}}. The loss is the squared error: ({{output}} − {{target}})² = {{loss}}.", + "backward-output": "The backward pass starts. The delta of each output neuron says how much the loss would change if its sum z changed. The gradient of each weight reaching it is its delta times the input of that connection: they are the orange connections.", + "backward": "The error keeps going back to layer {{layer}}: the delta of each neuron is the sum of the deltas of the next layer times the weights joining them, multiplied by the derivative of {{activation}}. That way each weight knows how much it contributed to the error.", + "update": "Each weight moves a little against its gradient: w ← w − η × g, with η = {{rate}}, the learning rate. With this example, the loss goes from {{before}} to {{after}}. Training is repeating this with all the examples, epoch after epoch; the optimizer you choose adjusts each step in a more elaborate way." + }, + "focus": "Neuron {{index}} of layer {{layer}}", + "focus-input": "Input {{index}}", + "formula-input": "{{name}} = {{value}}", + "formula-pending": "Neuron {{index}} of layer {{layer}} has not been computed yet.", + "formula-update": "Its bias goes from {{before}} to {{after}}. The weight that changes most, the one coming from {{from}}, goes from {{weight}} to {{weightAfter}}.", + "from-neuron": "neuron {{index}} of layer {{layer}}", + "history_one": "Mean loss of {{sample}} examples from the data after each update: from {{first}} to {{last}} ({{count}} example used). If the network learns, the line goes down.", + "history_other": "Mean loss of {{sample}} examples from the data after each update: from {{first}} to {{last}} ({{count}} examples used). If the network learns, the line goes down.", + "history-empty": "When each example finishes, you will see here how the loss changes.", + "diagram": "The neural network, layer by layer", + "node-input": "Input {{name}}: {{value}}", + "node": "Neuron {{index}} of layer {{layer}}: {{value}}", + "column-input": "Input", + "column-layer": "Layer {{layer}} ({{activation}})", + "column-output": "Output ({{activation}})", + "update-rule": "w ← w − {{rate}} × gradient" + }, + "clustering": { + "intro": "k-means places k centroids, assigns each row to the closest one and moves each centroid to the centre of its rows, until no row changes group. It uses no labels: only the columns you choose.", + "upload": "Upload your data", + "rows_one": "1 row", + "rows_other": "{{count}} rows", + "features": "Columns used for clustering", + "features-help": "Only numeric ones. The more, the harder to picture, but the groups may be better.", + "label": "Column with the real classes (optional)", + "label-none": "None", + "label-help": "It is not used to cluster: only to compare at the end.", + "scale": "Scale the columns", + "scale-help": "Each column with mean 0 and deviation 1: otherwise the ones with large values (e.g. the proline of the wine) decide on their own.", + "k": "Number of groups (k)", + "k-help": "If you don't know how many there are, check the elbow after clustering.", + "run": "Cluster", + "reseed": "Try other initial centroids", + "waiting": "Choose the columns and the number of groups, and press “Cluster”.", + "groups": "Groups", + "iterations": "Iterations", + "inertia": "Inertia", + "silhouette": "Silhouette", + "silhouette-good": "High silhouette (over 0.5): the groups are well separated.", + "silhouette-fair": "Medium silhouette (between 0.25 and 0.5): there are groups, but they touch each other.", + "silhouette-weak": "Low silhouette (under 0.25): the groups are barely distinguishable; try another k or other columns.", + "scatter-title": "The groups", + "play": "Watch them form", + "pause": "Pause", + "iteration": "Iteration {{number}}", + "scatter-help": "Each point is a row; the crosses are the centroids. To draw them in 2D they are projected with PCA (the two directions in which the data varies most), but k-means uses all the chosen columns.", + "axis": "Component {{number}} ({{variance}} of the variance)", + "cluster": "Group {{number}}", + "centroids": "Centroids", + "comparison-title": "Groups versus the real classes ({{column}})", + "comparison-help": "How many rows of each class fell into each group and what share of the group they are. k-means doesn't know what each class is, so the groups have no name: the majority class of each one tells which it resembles.", + "group": "Group", + "purity": "Purity", + "ari": "Adjusted Rand index", + "elbow-title": "The elbow", + "elbow-help": "Inertia always goes down as k goes up. The “elbow”, where it stops going down a lot, is usually a good number of groups.", + "profiles-title": "What each group is like", + "size": "Rows", + "profiles-help": "The mean of each column in each group, in its units: it helps to give each group a name.", + "variable": "Variable", + "purity-help": "The share of rows that would be right if each group were named after its majority class. It always goes up as k grows: with one group per row it would be 100%.", + "ari-help": "How much the groups resemble the classes, looking at pairs of rows: do the ones together in a class end up together in a group? 1 if they are the same groups and around 0 if they match like chance. It does not go up just by having more groups.", + "ari-high": "The groups are almost the same as the classes.", + "ari-medium": "The groups resemble the classes quite well, but some class is split or mixed.", + "ari-low": "The groups barely resemble the classes.", + "ari-none": "The groups don't resemble the classes: as if they were random.", + "majority": "Majority class", + "mixed": "mixed", + "total": "Total", + "comparison-legend": "The stronger the background, the larger the share of the group from that class. “Mixed”: no class reaches two thirds of the group.", + "scatter-data": "Groups, rows and centroids", + "rows-column": "Rows" + }, + "time-series": { + "manual": { + "title": "How it works", + "windows": { + "title": "Windows", + "text": "The network does not see the whole series: it receives the last values (the window) and predicts the next one. Each position of the series is one example: with a 12-month window, the months of 1949 predict January 1950; the next twelve, February…" + }, + "split": { + "title": "Train with the past, test with the future", + "text": "The test part is the end of the series and is not shuffled: if the months were mixed, the network would see the future while training. The training windows are shuffled, because each one already carries its history." + }, + "scale": { + "title": "Scaling and differencing", + "text": "Values are scaled between 0 and 1 with the training minimum and maximum (the test part is not looked at). If the series grows, the test part may fall outside that range. Differencing makes the network learn how much each value changes from the previous one instead of the value: it removes the trend." + }, + "modes": { + "title": "One step or all at once", + "text": "One step ahead, each test value is predicted with the real values before it, like forecasting tomorrow knowing today. All at once (recursive), from the end of training each value is predicted with the ones already predicted: that is how the future is forecast, and errors add up." + }, + "baselines": { + "title": "Better than the simplest thing?", + "text": "It is compared with two forecasts without a network: the naive one (the previous value or, when forecasting all at once, the last known one) and the seasonal one (the value one season ago: 12 months, 7 days…). A network that does not beat them adds nothing." + }, + "networks": { + "title": "Dense or recurrent", + "text": "A Dense layer receives the whole window at once. Recurrent layers (SimpleRNN, LSTM and GRU) read it value by value and remember what came before: they go before the Dense layers and train more slowly. The output is one linear neuron, the predicted value." + } + }, + "upload": { + "title": "Your series", + "text": "Upload a file (CSV, ARFF, JSON, JSONL or Parquet) with one row per moment and choose the column with the values. If it has a date column, it is used to sort the rows and to date the forecasts.", + "no-numeric": "The file has no numeric column: there are no values to forecast.", + "value-column": "Column with the values", + "value-column-help": "The series that is forecast.", + "date-column": "Column with the date", + "date-column-help": "Optional: without it, the values are numbered 1, 2, 3…", + "no-date": "No date (1, 2, 3…)", + "info": "Upload your own time series: one column with its values and, if it has one, another with the date of each.", + "waiting": "Upload a file to see the series here." + }, + "data": { + "summary_one": "1 value ({{first}})", + "summary_other": "{{count}} values, from {{first}} to {{last}}", + "value-column": "forecasting {{column}}", + "dropped_one": "1 row without a number in the values column has been removed.", + "dropped_other": "{{count}} rows without a number in the values column have been removed.", + "sorted": "The rows were not in order: they have been sorted by date.", + "range_one": "{{first}} (1 value)", + "range_other": "{{first}} – {{last}} ({{count}} values)", + "split": "Training: {{train}}. Test: {{test}}" + }, + "frequency": { + "hour": "one value per hour", + "day": "one value per day", + "week": "one value per week", + "month": "one value per month", + "quarter": "one value per quarter", + "year": "one value per year" + }, + "chart": { + "test": "Test", + "description": "{{name}}: {{count}} values, from {{first}} to {{last}}.", + "train-prediction": "Network (training, one step)", + "test-one-step": "Network (test, one step)", + "test-recursive": "Network (test, all at once)", + "future": "What comes next", + "forecast-description": "Forecast of {{model}}: on the test part it is off by {{mae}} on average. Then, the next {{steps}} values." + }, + "prep": { + "title": "Preparation", + "window": "Window (previous values)", + "window-help": "How many previous values the network uses to predict the next one.", + "window-season": "To see the repeating pattern, it should cover a season ({{season}} values).", + "test-size": "Test (% at the end of the series)", + "test-size-help": "The last values: the network does not see them while training. They are not shuffled, because in a series the future is predicted with the past.", + "difference": "Predict the change (differencing)", + "difference-help": "The network learns how much each value changes from the previous one and, when predicting, it is added to the previous one. It removes the trend.", + "season": "Season (values)", + "season-help": "Every how many values the pattern repeats (12 months, 7 days…), to compare with the seasonal forecast. 0: no season.", + "too-short": "With this window and this test part there is not enough data: at least 10 windows are needed to train and 2 values to test. Try a shorter window or a smaller test part." + }, + "windows": { + "title": "What the network learns", + "text": "Each example is the {{window}} previous values and the next one, which is what it has to predict. The first ones:", + "text-difference": "Each example is the {{window}} previous changes (each value minus the previous one) and the next change, which is what it has to predict. The first ones:", + "date": "Date", + "inputs": "Previous values ({{window}})", + "inputs-difference": "Previous changes ({{window}})", + "output": "Value to predict", + "output-difference": "Change to predict", + "scaled_one": "The network receives them scaled between 0 and 1. With this preparation there is 1 example to train with.", + "scaled_other": "The network receives them scaled between 0 and 1. With this preparation there are {{count}} examples to train with." + }, + "layers": { + "class": "Layer type", + "class-help": "Dense receives the whole window; SimpleRNN, LSTM and GRU read it value by value (they go before the Dense layers)." + }, + "models": { + "yes": "Yes", + "no": "No", + "mae-one-step": "One-step error (MAE)", + "mae-recursive": "All-at-once error (MAE)", + "show": "Show", + "help": "The error is the mean absolute error on the test data, in the units of the series: how far off it is on average.", + "evaluating": "Computing the forecasts…" + }, + "forecast": { + "title": "Forecast: {{model}}", + "model": "Model", + "one-step": "One step", + "recursive": "All at once (recursive)", + "range-all": "Whole series", + "range-test": "Close-up", + "show-train": "Also show training", + "one-step-help": "Each test value is predicted with the real values before it.", + "recursive-help": "From the end of training, each value is predicted with the ones already predicted, without seeing the test part: that is how the future is forecast, and errors add up.", + "errors-title": "Errors on the test data", + "prediction": "Forecast", + "mae-title": "Mean absolute error: how far off it is on average", + "rmse-title": "Root mean squared error: penalises large errors more", + "network": "Neural network ({{model}})", + "naive-one-step": "Naive: the previous value", + "naive-recursive": "Naive: the last known value, repeated", + "seasonal-one-step": "Seasonal: the value {{season}} values ago", + "seasonal-recursive": "Seasonal: the last season, repeated", + "verdict-better": "The network is off {{percent}} less than the best simple forecast ({{baseline}}).", + "verdict-similar": "The network is off about as much as the best simple forecast ({{baseline}}): it does not add much.", + "verdict-worse": "The network is off {{percent}} more than the best simple forecast ({{baseline}}). Try another window, more epochs, differencing or recurrent layers.", + "baseline-naive": "the naive one", + "baseline-seasonal": "the seasonal one", + "train-vs-test": "On the training data it is off by {{train}} on average, and on the test data (one step), by {{test}}.", + "overfitting": "On the test data it is off by more than twice as much: it may have memorised the training data.", + "future-title": "What comes next", + "future-steps": "Values to forecast", + "future-help": "One after another, each with the ones already predicted: the further away, the less reliable." + }, + "model": { + "name": "Pre-trained model", + "train-yours": "Train your network with this series" + }, + "review": { + "tab-chart": "The series", + "tab-windows": "Prepared for the network", + "preparation": "The network receives the {{window}} previous values and predicts the next one. It was trained with the series up to {{last}}; it did not see the test part, from {{first}} to the end. Values are scaled between 0 and 1 with the training minimum ({{min}}) and maximum ({{max}}).", + "preparation-difference": "The network receives the {{window}} previous changes (each value minus the previous one) and predicts the next change. It was trained with the series up to {{last}}; it did not see the test part, from {{first}} to the end. Changes are scaled between 0 and 1 with the training minimum ({{min}}) and maximum ({{max}}).", + "predict-title": "Predict", + "test": "test", + "model-select": "Model to predict with", + "choose-instance_one": "Choose a value of the series: the form is filled with the previous one, which is what the network uses. Then you can change it.", + "choose-instance_other": "Choose a value of the series: the form is filled with the {{count}} previous ones, which is what the network uses. Then you can change them.", + "vector": "What the network receives", + "vector-help": "Each value, scaled between 0 and 1 with the training minimum and maximum.", + "vector-help-difference": "Each change (a value minus the previous one), scaled between 0 and 1 with the training minimum and maximum.", + "button-submit": "Predict", + "predicted-value": "Predicted value of {{target}} ({{date}})", + "actual-value": "Actual value: {{value}}", + "error": "Error: {{value}} ({{percent}})", + "input-details": "Model input step by step", + "step-values": { + "title": "Previous values", + "text": "as in the series" + }, + "step-changes": { + "title": "Changes", + "text": "each value minus the previous one" + }, + "step-scaled": { + "title": "Scaled", + "text": "between 0 and 1, as the network receives them" + }, + "metrics": "On the last {{testSize}} % of the series, set aside when it was trained, it is off by {{mae}} on average one step ahead; repeating the previous value, by {{naive}}.", + "metrics-seasonal": "Repeating the value one season earlier, by {{seasonal}}.", + "metrics-no-better": "It does not beat the simplest forecast: with that window, this series cannot be predicted much better." + }, + "chart-data": "{{value}}: actual and predicted at each date", + "chart-data-series": "{{value}} at each date" } }, "dataframe": { "title": "Analyze data set", - "upload-csv": "Upload data set" + "upload-csv": "Upload data set", + "intro": "Explore a data set before training a model: its size, the type and shape of each variable, missing values, how the variables relate to each other and to the target variable, and how to prepare it.", + "waiting": "Choose one of the project data sets or upload your own file (CSV, ARFF, JSON, JSONL or Parquet) to start the analysis.", + "sections": { + "data": "Data set", + "summary": "Summary", + "variables": "Variables", + "distributions": "Distributions", + "relations": "Relationships", + "table": "Data and queries", + "preprocess": "Preprocessing", + "charts": "More charts" + }, + "picker": { + "project": "Project data sets", + "project-help": "The CSV files of the Nets4Learning models and others for practice, with a description of their variables.", + "placeholder": "Choose a data set", + "upload": "Your own file", + "upload-help": "CSV (with “,” or “;”), ARFF, JSON, JSONL or Parquet. It is read in your browser: the file is not sent to any server.", + "loading": "Loading…" + }, + "info": { + "shape": "{{rows}} rows × {{columns}} columns", + "source": "Source", + "variables-sheet": "with variable sheet", + "target": "Target variable", + "target-none": "None", + "target-help": "The one to predict or classify: it is highlighted throughout the analysis and splits the charts by class.", + "problem-classification": "Classification, {{count}} classes", + "problem-regression": "Regression", + "problem-none": "No target variable" + }, + "summary": { + "rows": "Rows", + "columns": "Columns", + "columns-detail": "Numeric: {{numeric}}, categorical: {{categorical}}", + "missing": "Missing values", + "missing-detail": "{{percent}} of the cells", + "duplicates": "Duplicate rows", + "duplicates-detail": "{{percent}} of the rows", + "target-distribution": "Distribution of {{target}}", + "target-distribution-none": "Distribution of the target variable", + "no-target": "Choose a target variable to see how its values are distributed.", + "warnings": "Data warnings", + "no-warnings": "No problem found: no missing values, duplicate rows, constant columns, identifiers or imbalanced classes." + }, + "warnings": { + "missing": "{{column}} has {{count}} missing values ({{percent}}).", + "constant": "{{column}} always has the same value: it carries no information.", + "identifier": "{{column}} looks like an identifier (a code per record), not an attribute: it should not be used for training.", + "outliers": "{{column}} has {{count}} outliers ({{percent}}) according to the interquartile range rule.", + "imbalance": "The classes of {{column}} are imbalanced: “{{minority}}” has {{percent}} of the rows of the most frequent class.", + "correlation": "{{column}} and {{other}} are highly correlated (r = {{value}}): they carry almost the same information.", + "duplicates": "There are {{count}} duplicate rows." + }, + "variables": { + "title": "Profile of each variable", + "search": "Search variable", + "type": "Type", + "all": "All", + "numeric": "Numeric", + "categorical": "Categorical", + "view-cards": "Cards", + "view-table": "Table", + "kind-numeric": "Numeric", + "kind-categorical": "Categorical", + "target": "Target", + "missing": "Missing", + "distinct": "Distinct", + "mean": "Mean", + "std": "Std. dev.", + "min": "Min.", + "median": "Median", + "max": "Max.", + "top": "Most frequent values", + "more": "and {{count}} more", + "show-distribution": "See its distribution →", + "no-results": "No variable matches the search.", + "units": "Units: {{units}}", + "column": "Variable", + "histogram-of": "Histogram of {{column}}" + }, + "distributions": { + "title": "Distribution of a variable", + "variable": "Variable", + "bins": "Bins", + "bins-auto": "Automatic", + "by-class": "Split by class of {{target}}", + "histogram": "Histogram", + "frequencies": "Frequency of each value", + "boxplot": "Box plot", + "count": "Rows", + "class": "Class", + "by-class-table": "{{column}} in each class of {{target}}", + "help-histogram": "How many rows have a value in each bin. If the classes overlap little, the variable helps to tell them apart.", + "help-frequencies": "How many rows have each value (the 30 most frequent).", + "help-boxplot": "The box goes from the first to the third quartile and the middle line is the median; isolated points are outliers." + }, + "relations": { + "title": "Correlation and scatter", + "correlation": "Correlation matrix", + "correlation-help": "Pearson correlation between each pair of numeric variables: 1 is a direct linear relationship, −1 an inverse one and 0 none.", + "target-correlation": "Correlation with {{target}}", + "target-correlation-help": "The variables most correlated with the target are usually the most useful to predict it.", + "scatter": "Scatter plot", + "x": "X axis", + "y": "Y axis", + "color-help": "Each point is a row, coloured by {{target}}.", + "not-enough": "At least two numeric variables are needed." + }, + "table": { + "title": "Data table" + }, + "preprocess": { + "title": "Prepare the data for a model", + "help": "A model only takes numbers: text is encoded (label encoder) and what is not useful is dropped. The result updates with every change and can be downloaded as CSV.", + "missing": "Missing values", + "missing-keep": "Keep them", + "missing-drop-rows": "Remove rows with any", + "missing-impute": "Fill in (mean or most frequent value)", + "scaler": "Scaling of numeric attributes", + "scaler-none": "None", + "scaler-min-max": "Min-max (0 to 1)", + "scaler-standard": "Standardize (mean 0, deviation 1)", + "scaler-help": "The target variable is not scaled.", + "duplicates": "Remove duplicate rows", + "action": "Transformation", + "action-keep": "No change", + "action-label-encoder": "Encode (label encoder)", + "action-drop": "Drop", + "result": "Result", + "download": "Download CSV", + "removed-rows": "Rows removed: {{duplicates}} duplicates and {{missing}} with missing values.", + "encodings": "Encoding of the text columns", + "imputed": "Values used to fill in", + "imputed-value": "{{column}}: {{value}}" + }, + "analyzing": "Analysing the data set…", + "charts-sample": "With so many rows, these charts use a random sample of {{sample}} of the {{rows}}.", + "essentials": { + "tab": "Analysis", + "help": "The key points of the exploratory analysis of the data set: its size, missing and duplicate values, how the target variable is distributed, the warnings and which variables are related to it.", + "open": "See the full analysis (EDA)" + } }, "documentation": { "title": "Documentation" @@ -2164,7 +2643,7 @@ "title": "Step 6: Training and table of models" }, "prediction": { - "title": "Step 7: Prediction" + "title": "Step 7: Classification" } }, "app": { @@ -2252,6 +2731,33 @@ }, "glossary": { "title": "Glossary", + "intro": "The terms that appear in Nets4Learning: the tasks, the network editors, the optimizers and the activation, loss and metric functions.", + "search": "Search the glossary", + "search-placeholder": "For example: ReLU, Adam, epochs…", + "results_one": "{{count}} term", + "results_other": "{{count}} terms", + "no-results": "No term matches “{{query}}”.", + "anchor": "Link to “{{term}}”", + "plot": "Plot of {{term}}", + "plot-tabs": { + "image": "Image", + "animation": "Animation" + }, + "animation": { + "slider": "Position of x in {{name}}", + "play": "Play", + "pause": "Pause" + }, + "references-title": "References", + "confusion-legend": { + "abbreviation": "Abbreviation", + "english": "In English", + "meaning": "Meaning", + "tp": "True positives", + "tn": "True negatives", + "fp": "False positives", + "fn": "False negatives" + }, "table-head": { "name": "Name", "description": "Description", @@ -2297,6 +2803,14 @@ "sub-title-3": "Non-linear Activations (other)", "text-1": "An activation function is a mathematical function used in an artificial neural network to determine the output of a neuron or a set of neurons based on the entry received. The activation function introduces non -linearity in the neural network, allowing the network to learn more complex patterns in the input data. Common examples of activation functions are:", "table": { + "linear": { + "title": "Linear", + "description": "Returns the input unchanged (the identity). It is the activation of the output layer in regression, where the network must be able to output any number.", + "characteristics": { + "0": "It does not limit the output range.", + "1": "A network with only linear layers is equivalent to a single linear layer: it cannot learn non-linear relationships." + } + }, "softmax": { "title": "Softmax", "description": "Transforms outputs to a representation in the form of probabilities, so that the sum of all probabilities gives 1", @@ -2394,11 +2908,11 @@ "editor-layers": { "title": "Layers editor", "table": { - "activation-function": { + "units": { "title": "Layer Neurons", "description": "These are the individual units or nodes in a specific layer of the network. Each neuron receives inputs, performs computations and produces an output that is transmitted to the next layer. The number of neurons in a layer can vary and is usually a hyperparameter of the model. The choice of the number of neurons in a layer affects the model's ability to learn representations of the data." }, - "units": { + "activation-function": { "title": "Layer Activation Function", "description": "At each neuron in a layer of a neural network, an activation function is applied to introduce non-linearity into the model. The activation function determines the output of the neuron as a function of its input and associated weights." } @@ -2472,50 +2986,50 @@ "text": { "0": "In machine learning, a loss function (also called cost function) is a measure that quantifies the discrepancy between the predicted exit by a model and the real or desired output. In other words, the loss function measures how well the model conforms to training data.", "1": "The objective of a machine learning algorithm is to minimize the loss function, which means finding the model set of the model that best suits training data. Therefore, the choice of loss function is very important, since it can affect the model ability to correctly learn patterns in the data and make precise predictions in new data.", - "2": "In tensorflow.js there are different loss functions and the application of each of them depends on the type of problem we want to face. Some examples are shown below:" + "2": "These are the loss functions you can choose in Nets4Learning, grouped by the type of task where they make sense:" }, "table": { - "AbsoluteDifference": { - "references": "Absolute difference\n (Privolima, s.f.)", - "description": "Calculates the distance to the target in absolute value." + "categoricalCrossentropy": { + "description": "Measures the difference between the probabilities predicted by the model and the true class (one-hot encoded). It is the usual loss for multi-class classification with a softmax output." }, - "ComputeWeightedLoss": { - "references": "Weighted average\n (Privolima, s.f.)", - "description": "Calculate the weighted loss between two given tensors." + "binaryCrossentropy": { + "description": "Cross-entropy for two classes, or for several independent labels, with a sigmoid output." }, - "CosineDistance": { - "references": "Distance from Coseno\n (Privolima, s.f.)", - "description": "Calculate the loss by applying the cosine of the distance between two tensors." + "kullbackLeiblerDivergence": { + "description": "Measures how far the predicted probability distribution is from the true one. Used when the model output is a distribution." }, - "HingeLoss": { - "references": "Loss of hinge\n (Rennie & Srebro, 2005)", - "description": "Calculate the loss of hinge between two tensors. It applies in classification problems." + "hinge": { + "description": "Penalises predictions that do not exceed a margin with respect to the correct class. It comes from support vector machines and expects -1 and 1 labels." }, - "HuberLoss": { - "references": "(Huber loss)", - "description": "Calculate the loss caused by the estimation procedure." + "squaredHinge": { + "description": "Like the hinge loss, but squared: large errors are penalised more." }, - "LogLoss": { - "references": "Logarithmic loss\n (Shen, 2005)", - "description": " logloss or Logistic loss is a convex function that grows linearly for negative numbers and makes it recently sensitive to atypical values. Calculate the logarithmic loss between two tensors." + "categoricalHinge": { + "description": "Hinge loss for several classes: compares the score of the correct class with that of the best wrong class." }, - "MeanSquaredError": { - "references": "Middle quadratic error\n (Privolima, s.f.)", - "description": "Calculate in a geometric way the square distance to the target, this function is used in regression problems." + "meanSquaredError": { + "description": "Mean of the squared differences between the true and the predicted value. It penalises large errors heavily; it is the usual loss for regression." }, - "CategoricalCrossEntropy": { - "references": "(Privolima, s.f.)", - "description": "It measures the distance between probability distributions. It is applied in networks whose output layer is a probability." + "meanAbsoluteError": { + "description": "Mean of the absolute differences between the true and the predicted value. It is less affected by outliers than the squared error." }, - "SigmoidCrossEntropy": { - "references": "(Privolima, s.f.)", - "description": "It is a variant of the categorical function categorical categorical, in this case, it calculates the loss in a value between 0 and 1." + "meanAbsolutePercentageError": { + "description": "Mean absolute error expressed as a percentage of the true value. Useful to compare errors across different magnitudes, but true values cannot be zero." }, - "SoftmaxCrossEntropy": { - "references": "(Bendersky, 2016)", - "description": "A combination of the functions Softmax and crossenterpy calculating the loss of the network is applied." + "meanSquaredLogarithmicError": { + "description": "Mean squared error on the logarithm of the values: it measures the relative error and penalises errors on large values less." + }, + "logcosh": { + "description": "Logarithm of the hyperbolic cosine of the error: it behaves like the squared error for small errors and like the absolute error for large ones." + }, + "poisson": { + "description": "Meant for predicting counts (non-negative integers), such as the number of visits or events." + }, + "cosineProximity": { + "description": "Compares the direction of the true and the predicted vectors (the angle between them), regardless of their size." } - } + }, + "related": "Other related formulas" }, "metric-functions": { "title": "Metric functions", @@ -2556,8 +3070,48 @@ "references": "Middle quadratic error", "description": "Determine the average quadratic error between labels and predictions." } + }, + "confusion": { + "title": "Confusion matrix metrics", + "description": "They are computed from the hits and misses of each class in the confusion matrix: how many positive predictions are correct (precision), how many real positives are found (recall or sensitivity), the harmonic mean of both (F1) and how many real negatives are recognised (specificity)." } - } + }, + "time-series": { + "title": "Time series", + "text-1": "A time series is a sequence of values measured in order, one every so often: the passengers each month, the temperature each day, the sales each week. Unlike a table, order matters: each value depends on the previous ones.", + "text-2": "Forecasting a series means estimating the next values from the past ones. A neural network learns it with windows: it receives the last values and predicts the next one.", + "text-3": "To test it, the end of the series is set aside, without shuffling, and it is compared with simple forecasts, such as repeating the last value or the one a season ago.", + "group-title": "Time series", + "window": { + "title": "Window", + "text": "The previous values the network uses to predict the next one. With a window of 12 in a monthly series, the network sees the last year. If it is shorter than the season, it cannot see the repeating pattern; if it is very long, fewer examples are left to train with." + }, + "trend-seasonality": { + "title": "Trend and seasonality", + "text": "The trend is where the series goes in the long run (passengers grow year after year). Seasonality is a pattern that repeats with a fixed period (more passengers every summer). A cycle, like the sunspot cycle, repeats without a fixed period." + }, + "differencing": { + "title": "Differencing", + "text": "Replacing each value by how much it changed from the previous one. It removes the trend: the network learns changes, which look more alike in training and in testing. To get the values back, each change is added to the previous value." + }, + "one-step-recursive": { + "title": "One-step and recursive forecasts", + "text": "One step ahead, each value is predicted with the real values before it. Recursive (or all at once), each predicted value is used to predict the next: it is the only way to forecast several steps into the future, and errors add up." + }, + "baselines": { + "title": "Naive and seasonal forecasts", + "text": "The simplest forecasts, which a model is compared with: the naive one repeats the last known value and the seasonal one, the value one season ago (12 months, 7 days…). A model only adds something if it is off by less than them." + }, + "recurrent": { + "title": "Recurrent layers (SimpleRNN, LSTM and GRU)", + "text": "They read a sequence value by value and keep a state that summarises what they have seen. SimpleRNN is the simplest and forgets quickly; LSTM and GRU have gates that decide what to remember and what to forget, and learn longer dependencies." + }, + "mae-rmse": { + "title": "MAE and RMSE", + "text": "Two ways of measuring the error in the units of the series: the MAE (mean absolute error) is how far off it is on average; the RMSE (root mean squared error) penalises large errors more." + } + }, + "formula": "{{term}} formula" }, "menu": { "select-model": { @@ -2565,14 +3119,580 @@ }, "select-dataset": { "description": "Description" + }, + "open": "Open", + "info": { + "rows": "{{value}} rows", + "rows-files": "{{files}} files ({{values}} rows)", + "features": "{{value}} features", + "classes": "{{value}} classes", + "target": "target: {{value}}", + "images": "{{value}} {{size}} images", + "images-color": "{{value}} {{size}} color images", + "series": { + "hour": "{{value}} hours", + "day": "{{value}} days", + "week": "{{value}} weeks", + "month": "{{value}} months", + "quarter": "{{value}} quarters", + "year": "{{value}} years" + } } }, "terms": { - "title": "Privacy Policies and Cookies", - "privacy-title": "Privacy policies", - "privacy-text": "On our website, we only collect statistical information about visits in order to improve the performance and functionality of the site. We do not collect or store any personal information from our users. We use cookies to account for the number of visitors and improve the navigation experience. If you have any questions or doubt about our privacy policy, do not hesitate to contact us through our contact page.", - "cookies-title": "Cookies", - "cookies-text": "Our website uses Google Analytics cookies to account for the number of visitors we receive. These cookies allow us to collect anonymous statistical information about the use of our website and help us improve their performance and functionality. Google Analytics cookies do not collect personal information from users. When navigating our website, you accept the use of these cookies. If you want to get more information about how we use cookies, please consult our privacy policy." + "title": "Terms and conditions", + "updated": "Last updated: 2 October 2026.", + "summary-title": "In short", + "summary": [ + "Nets4Learning is a free educational tool: there are no accounts or sign-ups.", + "Your data stays in your browser: the models are trained and used on your computer.", + "Google Analytics cookies are only enabled if you accept them, and you can change your mind at any time." + ], + "index": "Sections", + "use": { + "title": "Use of the application", + "items": [ + "Nets4Learning is a free educational platform for learning and teaching deep learning.", + "The code is free software, under the MIT license. Third-party data sets and models keep their own licenses, given in the description of each one.", + "The results of the models are for learning: do not use them to make real decisions, for example medical or financial ones, or decisions about people.", + "The application is provided as is, without warranties: it may contain errors and change at any time." + ] + }, + "privacy": { + "title": "Your data", + "text": "All the machine learning runs in your browser with TensorFlow.js. There is no server that receives your data:", + "items": [ + "The files you upload (data sets, models and images), your drawings and the camera image are processed on your computer and are not sent anywhere.", + "The models you train with the example datasets are saved in your browser (at most 10 per dataset) so they are not lost when reloading the page. You can delete them from Settings and, to take them with you, download them.", + "We do not ask for or store personal data: there are no accounts, forms or emails." + ] + }, + "storage": { + "title": "What is saved in your browser", + "text": "To remember your preferences, the application saves in the local storage of your browser (not on our servers):", + "items": [ + "The language, theme and TensorFlow.js backend you choose.", + "The guide voice settings and which step each guide is on.", + "The models you train with the example datasets and whether you show the Step by step section.", + "Your decision about cookies, in a cookie of its own." + ], + "settings": "You can change it or delete it all from" + }, + "third-parties": { + "title": "External services", + "items": [ + "Google Analytics, only if you accept its cookies: which sections, models and datasets are used, for how long, which buttons are pressed and which errors appear.", + "Some pre-trained models (the detection ones and MobileNet) are downloaded from Google and jsDelivr servers when you open them. Like any website, those servers see the request, but not your data or your images.", + "If you choose an \"online\" voice for the guides, your browser sends the text of the guide to its speech service to read it." + ] + }, + "cookies": { + "title": "Cookies", + "text": "This is the complete list of cookies. The Google Analytics ones collect anonymous usage statistics, never for advertising, and are only created if you accept them. If you reject them later, they are deleted.", + "name": "Cookie", + "purpose": "What it is for", + "duration": "Duration", + "consent": { + "purpose": "Remember whether you accepted or rejected the Google Analytics cookies.", + "duration": "120 days" + }, + "ga": { + "purpose": "Google Analytics: tell visitors apart anonymously.", + "duration": "13 months" + }, + "ga-session": { + "purpose": "Google Analytics: keep the state of the visit.", + "duration": "13 months" + } + }, + "contact": { + "title": "Contact", + "text": "Nets4Learning is developed by the SIMIDAT research group (Intelligent Systems and Data Mining) of the University of Jaén. For any question or problem:", + "issues": "Open an issue on GitHub", + "simidat": "SIMIDAT group website" + } + }, + "not-found": { + "title": "Page not found", + "return-home": "Return to home" + }, + "settings": { + "title": "Settings", + "intro": "Everything you can adjust in the application. It is only saved in this browser.", + "appearance": { + "title": "Language and appearance", + "language": "Language", + "theme": "Theme", + "theme-system": "Same as the system", + "theme-help": "\"Same as the system\" follows the light or dark mode of your operating system.", + "summary": "Language and light or dark theme" + }, + "backend": { + "title": "TensorFlow.js backend", + "help": "Where TensorFlow.js does its computations when training and predicting. The change applies immediately; the models you already have keep working.", + "active": "in use", + "webgl": "Uses the graphics card through WebGL. It is the fastest on almost every computer.", + "webgpu": "Uses the graphics card with WebGPU, the most modern API. It can be faster, but not every browser has it.", + "wasm": "Computes on the processor with WebAssembly. Useful if the graphics card causes problems.", + "cpu": "Computes on the processor with JavaScript. It works everywhere, but it is the slowest.", + "summary": "Where TensorFlow.js computes: graphics card or processor" + }, + "downloads": { + "title": "Model downloads", + "help": "Some pretrained models (object detection, MobileNet…) download between 2 and 18 MB when you open their page. You can ask to be asked first.", + "auto": "Ask when saving data or on a slow connection", + "auto-help": "When the browser has data saving on or the connection is 2G or 3G.", + "always": "Always ask", + "always-help": "Before downloading any model over 2 MB that you haven't downloaded before.", + "never": "Don't ask", + "never-help": "Models are downloaded when you open their page.", + "now-save-data": "Right now, the browser has data saving on.", + "now-slow": "Right now, the connection seems slow.", + "now-normal": "Right now, there's no data saving and the connection doesn't seem slow (or the browser doesn't say).", + "summary": "Ask before downloading large models", + "saved": "Downloaded models are saved in this browser so they are not downloaded again: you can see how much space they take up and delete them in Data saved in this browser." + }, + "speech": { + "title": "Guide voice", + "help": "The guides of the model pages can read each step aloud with the voices of your system.", + "voice": "Read the guides aloud", + "auto": "Move on automatically after reading each step", + "voice-help": "The \"online\" voices work on a server of the browser: the text of the guide is sent there to be read.", + "no-voices": "Your system has no voices in this language: the browser will choose one.", + "rate": "Speed: {{rate}}×", + "test": "Try the voice", + "stop": "Stop", + "sample": "Hello. This is how the guide of each Nets4Learning page will sound.", + "screen-reader": "If you use a screen reader, turn this off: the screen reader already reads each step of the guide, and two voices at once cannot be understood.", + "summary": "Read the guides aloud, the voice and its speed" + }, + "tutorials": { + "title": "Guides", + "guides-help": "Each guide remembers which step you are on. Reset them so that they all start again from the beginning.", + "guides-reset": "Reset the guides", + "done": "Done", + "summary": "Start the page guides again" + }, + "learning": { + "title": "For learning", + "help": "Tools that are hidden by default so as not to overload the pages.", + "step-by-step": "Show “Step by step”: how the network learns, example by example, forwards and backwards", + "step-by-step-help": "It appears on the training pages and on the tabular classification and regression model pages, with networks of fewer than 64 neurons.", + "summary": "Step by step and other tools for learning" + }, + "privacy": { + "title": "Privacy and cookies", + "help": "Google Analytics cookies tell us anonymously which sections, models and datasets are used and what fails, without personal data or anything you upload. They are only enabled if you accept them.", + "analytics": "Allow Google Analytics cookies", + "status-accepted": "Right now: cookies accepted.", + "status-rejected": "Right now: cookies rejected.", + "status-undecided": "You have not decided yet: for now they are not used.", + "more": "More information about cookies", + "summary": "Google Analytics cookies" + }, + "data": { + "title": "Data saved in this browser", + "help": "What the application saves in this browser. It never leaves it, and you can delete it whenever you want.", + "summary": "What is saved, how much space it takes up and reset everything", + "total": "In total, this website takes up {{used}} in this browser.", + "trained": { + "title": "Trained models", + "help": "The ones you train and save: they are recovered when you go back to their page.", + "count_zero": "None", + "count_one": "1 model", + "count_other": "{{count}} models", + "delete": "Delete the trained models", + "question_one": "1 trained model will be deleted. This cannot be undone.", + "question_other": "{{count}} trained models will be deleted. This cannot be undone." + }, + "pretrained": { + "title": "Downloaded pretrained models", + "help": "Object detection, MobileNet…: saved the first time you use them so they are not downloaded again.", + "count_zero": "None", + "count_one": "1 model", + "count_other": "{{count}} models", + "delete": "Delete the downloaded pretrained models", + "delete-one": "Delete {{model}}", + "question": "They will be downloaded again the next time you use them.", + "question-one": "{{model}} will be deleted from this browser: it will be downloaded again the next time you use it.", + "mobilenet": "MobileNet - Image classification", + "other": "Other files" + }, + "offline": { + "title": "For offline use", + "help": "The pages you have already opened, so they work without internet.", + "count_zero": "Nothing", + "count_one": "1 file", + "count_other": "{{count}} files", + "delete": "Delete what is saved for offline use", + "question": "What you have opened will not work without internet until you open it again." + }, + "settings": { + "title": "Settings and progress", + "help": "Language, theme, accessibility, backend, guide voice and progress, Step by step, the download warning and your cookie decision." + }, + "delete": "Delete", + "delete-confirm": "Yes, delete", + "reset": "Reset all settings", + "reset-help": "Deletes all of the above and goes back to the default values. The page will reload.", + "confirm": "Are you sure? All the settings saved in this browser will be deleted.", + "confirm-button": "Yes, delete them", + "cancel": "Cancel" + }, + "accessibility": { + "title": "Accessibility", + "help": "To adapt the application to what you need. Saved in this browser.", + "text-size": "Text size", + "spacing": "More space between lines, letters and words", + "spacing-help": "The spacing WCAG recommends for easier reading.", + "highContrast": "High contrast", + "highContrast-help": "Black text and borders (white with the dark theme), without greys.", + "reduceMotion": "Reduce motion", + "reduceMotion-help": "No animations or smooth scrolling, also in the charts.", + "underlineLinks": "Always underline links", + "underlineLinks-help": "To tell them apart from text without relying on colour.", + "strongFocus": "Thicker focus", + "strongFocus-help": "The outline showing where you are when using the keyboard, more visible.", + "openVisor": "Open the TensorFlow.js visor when training", + "openVisor-help": "It is a library panel that cannot be used with a screen reader; the charts on the page say the same.", + "system-on": "Your system already asks for it, so it is on even if you do not tick it.", + "guide": "The voice of the guides and whether they advance on their own are changed in", + "summary": "Text size, contrast, motion and focus" + }, + "sections": "Settings sections", + "back": "All sections" + }, + "learn": { + "title": "Start here", + "intro": "Eight short steps to learn the essentials of neural networks by doing: from trying a trained network to asking it why it decides what it decides. Each step is ticked off on its own when you do it.", + "progress": "{{count}} of {{total}} steps done", + "step": "Step {{number}}", + "done": "Done", + "next": "Next", + "go": "Go to the step", + "again": "Do it again", + "mark-done": "Mark as done", + "mark-undone": "Unmark", + "reset": "Start over", + "reset-confirm": "Are you sure? All steps will be unmarked.", + "reset-yes": "Yes, start over", + "reset-no": "Cancel", + "finished": { + "title": "Route completed!", + "text": "You can now train, compare, fix and explain neural networks. Now try your own data: upload a CSV in tabular classification or regression, or explore it first in the EDA." + }, + "steps": { + "lab": { + "title": "Play with a network", + "text": "In the lab, a small network separates points on a plane and you see its boundary while it learns. Try the examples in “Try this”." + }, + "glossary": { + "title": "The key words", + "text": "Read in the glossary what a neural network, a layer, a neuron and an epoch are: they appear on every page." + }, + "pretrained": { + "title": "Try a trained network", + "text": "Draw a digit and see how a network trained on thousands of handwritten digits (MNIST) recognises it." + }, + "train": { + "title": "Train your first network", + "text": "With the Iris flowers: press “Train model” and watch the loss go down epoch by epoch. Below, you'll see in words how it went." + }, + "step-by-step": { + "title": "Watch your network learn", + "text": "With the Iris flowers, Step by step shows an example going through the network: forwards, the error and backwards, and how each weight changes. Move at least one step." + }, + "compare": { + "title": "Change one thing and compare", + "text": "Train again changing only the learning rate and turn on “Compare models” next to the curves: you'll see what changed and which one learns better." + }, + "fix-layers": { + "title": "Fix a badly built network", + "text": "In the layer editor, give the last layer a number of neurons different from the number of classes: a warning will appear. Fix it with its button and you'll see why the output has one neuron per class." + }, + "regression": { + "title": "Predict a number", + "text": "In regression the network doesn't choose a class, it gives a value: train with Auto MPG to predict a car's fuel consumption." + }, + "cnn": { + "title": "Train a network for images", + "text": "Convolutional networks look for strokes and shapes in images: train one with MNIST (it takes a bit longer than the others)." + }, + "explain": { + "title": "Ask the model why", + "text": "With the cars model (CAR), make a prediction and ask for its explanation: you'll see which attributes weighed most in the decision." + } + }, + "challenges": { + "title": "Challenges", + "intro": "Once you know how to train, put what you've learned to the test: change the layers and hyperparameters until you get there. They're ticked off on their own when you train.", + "progress": "{{count}} of {{total}} challenges completed", + "passed": "Completed", + "result": "You did it with {{value}} accuracy.", + "hint": "Hint", + "go": "Try it", + "again": "Try again", + "iris-accuracy": { + "title": "Perfect Iris", + "goal": "With Iris, get every test flower right (the ones the network doesn't see while training): 100 % accuracy.", + "hint": "Try more epochs (50) and a somewhat higher learning rate (0.05). If it doesn't work the first time, train again: each time the network starts with different weights." + }, + "iris-tiny": { + "title": "With very few neurons", + "goal": "With Iris, reach 90 % accuracy with 4 hidden neurons at most (not counting the output layer).", + "hint": "Keep a single hidden layer of 4 neurons (or two of 2) and give it more epochs: a simple problem doesn't need a big network." + }, + "iris-fast": { + "title": "In few epochs", + "goal": "With Iris, reach 90 % accuracy in 5 epochs at most.", + "hint": "With few epochs, every step has to count: raise the learning rate (0.1) and use Adam." + }, + "regression-good": { + "title": "A textbook training", + "goal": "In regression, with any dataset, get a training the diagnosis considers good: the loss goes down and settles, without overfitting.", + "hint": "Start with Salary and about 40 epochs. If the diagnosis says it was still improving, raise the epochs; if it says the loss is jumping around or blowing up, lower the learning rate." + }, + "mnist-fast": { + "title": "Digits in a hurry", + "goal": "With MNIST, get at least 93 % accuracy on the test images in 2 epochs at most.", + "hint": "In two epochs the network only sees the data twice: try raising the learning rate step by step (0.005, 0.01…) without overdoing it, or the diagnosis will tell you the loss is jumping around or blowing up." + } + }, + "toast": { + "title": "Step {{number}} of {{total}} done", + "next": "Next: {{title}} →", + "finished": "You've completed the route! →", + "close": "Close", + "challenge": "Challenge completed!", + "challenges": "See the challenges →" + }, + "home": { + "first": "First time here? Start here: eight short steps to learn by doing.", + "continue": "You've done {{count}} of {{total}} steps of Start here: pick up where you left off.", + "finished": "You've completed Start here: now try your own data." + } + }, + "regression-description": { + "title": "Linear regression", + "subtitle": "Description of the problem and the models", + "paragraphs": [ + "In data analysis, a regression problem is one where you want to predict or estimate a numeric value from some input variables. Linear regression is a mathematical model to make that prediction.", + "A linear regression model is a statistical technique that looks for a linear relationship between a response variable (or dependent variable) and one or more predictor variables (or independent variables). Its goal is to find the straight line that best fits the observed data, to then use it to predict the response variable from the predictors.", + "The model represents that relationship with the equation of a straight line: the value of the response variable is estimated as a linear combination of the predictors. Its coefficients, the regression coefficients, are computed with statistical techniques that make the difference between the observed and predicted values as small as possible.", + "Once fitted, the model can predict the response variable when the predictors are known. It also shows how much each predictor contributes to explaining the variability of the response.", + "In short, linear regression models are statistical tools to predict numeric values from predictor variables, with a linear relationship between them. They are useful in fields such as economics, science, engineering or social research." + ], + "example": "Suppose we want to predict the price of a house (the response variable, $Y$) from its size in square metres (the predictor variable, $x$). The relationship between the two can be written with this linear regression equation:", + "where": "Where:", + "terms": [ + "$Y$ is the price of the house.", + "$x$ is the size of the house.", + "$\\beta_0$ is the intercept: the value of $Y$ when $x$ is zero.", + "$\\beta_1$ is the slope of the line: how much the price changes for each extra square metre.", + "$\\epsilon$ is the error term: the variability the model does not explain." + ], + "closing": [ + "The goal of linear regression is to estimate $\\beta_0$ and $\\beta_1$ from the observed data, to get the line that best fits the points of the scatter plot.", + "With the fitted model you can predict the price of a new house from its area: just replace $x$ in the equation and compute $Y$.", + "This example is a simple case of simple linear regression: in practice, models can have many predictor variables and take into account how they combine with each other." + ] + }, + "task": { + "pretrained-title": "Pre-trained models", + "pretrained-text": "Models that have already learned: try them right away, without waiting for any training, and see why they decide what they decide.", + "pretrained-count_one": "1 model", + "pretrained-count_other": "{{count}} models", + "pretrained-button": "Choose a model", + "design-title": "Design, create and edit an architecture", + "design-text": "Choose a dataset (or upload yours), design the layers of the network, tune the training and watch it learn.", + "design-count_one": "1 dataset", + "design-count_other": "{{count}} datasets", + "design-button": "Choose a dataset", + "cluster-title": "Cluster a dataset", + "cluster-text": "You choose the columns and the number of groups, and k-means looks for them step by step; if the dataset has the real classes, they are compared at the end.", + "upload": "Upload yours", + "only-pretrained": "This task only has pre-trained models.", + "only-cluster": "Clustering uses neither a network nor pre-trained models: k-means groups the data directly." + }, + "accessibility": { + "title": "Accessibility", + "updated": "Statement prepared on 12 October 2026 and last reviewed on the same day.", + "summary-title": "In short", + "summary": [ + "We want anyone to be able to use Nets4Learning, also with a screen reader, with the keyboard only, with low vision or with large text.", + "The application is partially conformant with WCAG 2.2 level AA: almost everything conforms, except what is explained below.", + "If you find a barrier, tell us: it is the best way to fix it." + ], + "index": "Sections", + "status": { + "title": "Compliance status", + "text": "Nets4Learning is partially conformant with the Web Content Accessibility Guidelines (WCAG) 2.2, level AA, due to the exceptions in the “Non-accessible content” section.", + "standard": "WCAG 2.2 AA includes what the EN 301 549 standard requires (WCAG 2.1 AA), which is the one Spanish Royal Decree 1112/2018 applies to public sector websites." + }, + "not-accessible": { + "title": "Non-accessible content", + "text": "The following does not fully conform, and this is what can be used instead:", + "items": [ + { + "problem": "The TensorFlow.js visor that opens when training belongs to a library: it cannot be used with the keyboard and its charts have no text.", + "instead": "The same curves are on the page, with their data in a table, and in “Settings” you can choose not to open the visor." + }, + { + "problem": "The zoom buttons of the data analysis charts (Plotly) cannot be used with the keyboard.", + "instead": "The data of each chart is in its table (“View the data”)." + }, + { + "problem": "Drawing a number on the canvas needs a mouse, a pen or a finger.", + "instead": "Classify the examples and the test images on the page." + }, + { + "problem": "The camera video in object detection has no description.", + "instead": "What is detected is written below it, and a button reads it aloud. You can also upload a photo." + }, + { + "problem": "Formulas are generated with MathML for screen readers, but they have not been tested with all of them yet.", + "instead": "If one does not read well, tell us (“Report a barrier” section)." + } + ], + "out-of-scope": "Outside the scope of this statement: the third-party models and libraries the application uses and the external pages it links to.", + "instead": "Instead:" + }, + "use": { + "title": "How to use the application", + "keyboard-title": "With the keyboard", + "keyboard": [ + "Tab moves through the page in order. The first stop is “Skip to content”, which goes straight to the page without going through the menu.", + "Enter or Space activate buttons and links. The arrow keys move through tabs, dropdowns, option lists and the steps of the guide.", + "Escape closes dialogs, dropdowns, the mobile menu, the guide and the help of terms, and the focus goes back to where it was.", + "On long pages, the “On this page” index takes you to each section." + ], + "reader-title": "With a screen reader", + "reader": [ + "Each page has its title, a single main heading and its sections with headings in order.", + "Each chart has a description and a “View the data” button with a table of everything it draws.", + "What changes without moving the focus is announced: the result of a prediction, the loaded data, how a training is going, the layer warnings and changes of language or theme.", + "The guide of each page can be read with the screen reader. If you use it, turn off the guide voice in “Settings” so that both do not speak at the same time." + ], + "settings-title": "Accessibility settings", + "settings": "You can make text larger, add more space between lines and letters, use high contrast, reduce motion, underline links or make the focus thicker. They are saved in your browser.", + "settings-link": "Go to the accessibility settings" + }, + "feedback": { + "title": "Report a barrier", + "text": "If there is something you cannot use, or you think it does not conform, tell us. To fix it, it helps to know:", + "items": [ + "Which page you were on and what you wanted to do.", + "What happened.", + "Which browser and, if you use one, which screen reader or other assistive technology." + ], + "issue": "Report a barrier on GitHub (with a template)", + "simidat": "Website of the SIMIDAT group of the University of Jaén, to write to us", + "response": "We will answer as soon as possible and tell you whether there is a way to do what you needed while we fix it." + }, + "preparation": { + "title": "How it was prepared and when it is reviewed", + "items": [ + "Method: self-assessment by the development team.", + "Automated tests on every change: axe with WCAG 2.2 A and AA on every page and on the states that appear when using them (in the light and dark themes and with the accessibility settings), keyboard-only walkthroughs, pages at 320 px wide and with text at 200 %, and the accessibility rules of the linter.", + "Pending: the manual review with screen readers (NVDA, VoiceOver and TalkBack) and tests with people with different disabilities." + ], + "review": "This statement is reviewed every year and with each major version of the application." + }, + "new-tab": "(opens in a new tab)" + }, + "lab": { + "title": "Lab: a network in 2D", + "intro": "A small neural network learns to separate the orange points from the blue ones. Change the data, what goes into the network or its layers and watch the boundary change while it trains.", + "data": { + "title": "Data", + "dataset": "Dataset", + "noise": "Noise: {{value}}", + "count": "Points", + "new": "Other points" + }, + "datasets": { + "blobs": "Two clouds", + "circles": "Circles", + "xor": "XOR (quadrants)", + "spiral": "Spirals" + }, + "features": { + "title": "What goes into the network", + "help": "The coordinates of each point and, if you like, others computed from them.", + "x": "x", + "y": "y", + "x2": "x²", + "y2": "y²", + "xy": "x × y" + }, + "network": { + "title": "The network", + "help": "Hidden layers between the input and the output, each one with its neurons.", + "none": "No hidden layers: the input goes straight to the output.", + "layer": "Layer {{number}}: {{units}} neurons", + "fewer": "Remove a neuron from layer {{number}}", + "more": "Add a neuron to layer {{number}}", + "add": "Add a layer", + "remove": "Remove the last layer", + "activation": "Activation function" + }, + "training": { + "title": "How it learns", + "learning-rate": "Learning rate", + "speed": "Speed", + "speeds": { + "slow": "Slow (to watch the boundary)", + "normal": "Normal", + "fast": "As fast as possible" + }, + "batch-size": "Points per batch" + }, + "train": "Train", + "pause": "Pause", + "step": "One epoch", + "restart": "Start over", + "restarted": "The network starts over, with new random weights.", + "show-test": "Show the test points", + "canvas": "The plane with the points of {{dataset}} and, in the background, the class the network predicts in each area", + "legend": "Orange (circles) and blue (squares): the two classes. Filled, the points it learns from; white, the test points, which it does not see while training. The background is what the network predicts: the stronger, the surer.", + "not-trained": "Not trained yet: press \"Train\" or \"One epoch\".", + "summary": "Epoch {{epoch}}: it gets {{testAccuracy}} of the test points and {{trainAccuracy}} of the training points right. Loss: {{trainLoss}} on the training points and {{testLoss}} on the test points.", + "diverged": "The loss has blown up and the network no longer learns: lower the learning rate and start over.", + "loss": { + "title": "The loss", + "empty": "Here you will see the loss go down while it trains.", + "train": "training", + "test": "test", + "help": "If the test loss goes up while the training loss goes down, it is learning the points by heart (overfitting)." + }, + "experiments": { + "title": "Try this", + "xor-line": { + "title": "XOR without hidden layers", + "lesson": "Without hidden layers, the network can only draw a straight line: with XOR it does not even get half right." + }, + "xor-hidden": { + "title": "XOR with a layer of 4 neurons", + "lesson": "With a hidden layer it combines several lines and separates XOR: that is what hidden layers are for." + }, + "circles-features": { + "title": "Circles with x² and y²", + "lesson": "With x² and y² as input, the circles are separated without hidden layers: choosing well what goes into the network saves layers." + }, + "spiral": { + "title": "The spiral, the hardest one", + "lesson": "The spiral needs more neurons, more features and patience: let it train for a few hundred epochs." + }, + "learning-rate": { + "title": "A huge learning rate", + "lesson": "With a rate of 3, every step overshoots: the loss jumps up and down instead of going down. Try 0.1." + }, + "overfitting": { + "title": "Few points, lots of noise and a big network", + "lesson": "It learns the points by heart: the training loss goes down and the test loss goes up. That is overfitting." + } + }, + "next": "Once you get the idea, go on with" } }, "generator": { @@ -2590,7 +3710,10 @@ "features": "Features", "open-visor": "Open visor", "close-visor": "Close visor", - "history": "Results" + "history": "Final values (validation)", + "window": "Window", + "difference": "Differencing", + "batch-size": "Batch size" } }, "hr": { @@ -2598,9 +3721,12 @@ "editor": "Editor", "dataset": "Data set", "model": "Model", + "step-by-step": "Step by step", "generated-models": "Models generated", "predict": "Predict", "classify": "Classify", + "explainability": "Explainability", + "on-this-page": "On this page", "tasks": "Tasks", "00-tabular-classification": "Tabular Classification", "tutorial-00-tabular-classification": "Train a model for Tabular classification", @@ -2627,75 +3753,1546 @@ "ignored": "Ignore", "submit": "Process dataframe" }, - "joyride": { - "back": "Back", - "close": "Close", - "last": "Last", - "next": "Next", - "open": "Open", - "skip": "Skip" - }, "upload-dataset-info": "You must upload a dataset to perform the task.", "upload-model": "Upload model", "upload-model-info": "You must upload a model to perform the task.", - "select-attr": "Select attribute", "upload-dataset": "Upload dataset", - "00-tc": { - "car": { - "buying": "Buying price", - "maint": "Price of the maintenance", - "doors": "number of doors", - "persons": "Capacity in terms of persons to carry", - "lug_boot": "The size of luggage boot", - "safety": "Estimated safety of the car", - "result": "Result", - "unacc": "Unacceptable", - "acc": "Acceptable", - "good": "Good", - "vgood": "Very good" - }, - "iris": { - "sepal_length": "Sepal length", - "sepal_width": "Sepal width", - "petal_length": "Petal length", - "petal_width": "Petal width", - "class": "Class", - "Iris-setosa": "Iris setosa", - "Iris-versicolor": "Iris versicolor", - "Iris-virginica": "Iris virginica" - }, - "lymphography": { - "lymphatics": "lymphatics", - "block of affere": "block of affere", - "bl": { - " of lymph": { - " c": "bl. of lymph. c", - " s": "bl. of lymph. s" - } - }, - "by pass": "by pass", - "extravasates": "extravasates", - "regeneration": "regeneration of", - "early uptake in": "early uptake in", - "lym": { - "nodes dimin": "lym.nodes dimin", - "nodes enlar": "lym.nodes enlar" - }, - "changes in lym": "changes in lym.", - "defect in node": "defect in node", - "changes in node": "changes in node", - "changes in stru": "changes in stru", - "special forms": "special forms", - "dislocation of": "dislocation of", - "exclusion of": "exclusion of no", - "no": { - " of nodes in": "no. of nodes in" - }, - "Category": "Category", - "normal find": "normal find", - "metastases": "metastases", - "malign lymph": "malign lymph", - "fibrosis": "fibrosis" + "model-summary": "Model summary", + "breadcrumb": { + "label": "Breadcrumb", + "models": "Pre-trained models", + "datasets": "Train a model", + "change": "Switch to another one in the list", + "train-with-dataset": "Train with this dataset", + "try-pretrained": "Try the pre-trained model" + }, + "neural-network": { + "layer": "Layer {{index}}", + "units": "{{units}} neurons", + "kernel-size": "Kernel {{value}}", + "filters": "{{value}} filters", + "pool-size": "Pool {{value}}", + "strides": "Stride {{value}}", + "description": "Network layers, from input to output" + }, + "session": { + "export": "Export settings", + "import": "Import settings", + "imported": "Settings imported", + "error-not-json": "The file is not valid JSON", + "error-not-session": "The file is not a Nets4Learning settings file", + "error-other-task": "The settings belong to another task", + "error-link": "The link doesn't carry a valid configuration (it may have been cut off when copied)", + "share": { + "button": "Share", + "title": "Share this exercise", + "text": "Whoever opens the link will get this same network and these hyperparameters, ready to train with the same dataset. The data and the trained models are not shared.", + "link": "Link to share", + "copy": "Copy", + "copied": "Copied!", + "native": "Share with another app…", + "qr": "Or scan it with your phone", + "close": "Close" } + }, + "guide": { + "button": "Guide", + "button-title": "Step-by-step guide to this page, read aloud", + "resume": "Continue the guide (step {{current}} of {{total}})", + "restart": "Back to the start", + "step": "Step {{current}} of {{total}}", + "back": "Back", + "next": "Next", + "finish": "Finish", + "close": "Close the guide", + "voice-on": "Read aloud", + "voice-off": "Mute the voice", + "no-voice": "This browser cannot read aloud", + "repeat": "Read this step again", + "auto-on": "Move on automatically after each step", + "auto-off": "Stop moving on automatically", + "0-tabular-classification": { + "CAR": { + "intro": { + "title": "Car classification", + "content": "On this page, a neural network that has already been trained decides whether a car is acceptable from six features: the buying price, the maintenance, the doors, the seats, the luggage boot and the safety. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "model": { + "title": "The model", + "content": "This is the model card. It tells you where the data comes from, the Car Evaluation data set from the UCI repository, which features the network receives and which classes it can predict." + }, + "model-summary": { + "title": "Model summary", + "content": "This button opens the summary of the network: its layers, how many neurons each one has and how many parameters, which are the weights it adjusted during training." + }, + "dataset": { + "title": "The data set", + "content": "These are the 1728 cars the network was trained with. Each row is a car and each column is one of its features. The last column, highlighted, is the class: what the network learned to predict." + }, + "dataset-processed": { + "title": "Processed data", + "content": "A neural network only works with numbers. In this tab you will see the same cars with every category turned into a number: for example, the four possible prices become numbers from 0 to 3. This is how the model receives them." + }, + "instances": { + "title": "Examples and rows", + "content": "With this selector you fill in the whole form at once. At the top are the examples, marked with a star, one for each class; below them, every row of the data set with its real class." + }, + "fields": { + "Buying": { + "title": "Buying price", + "content": "How much it costs to buy the car: very high, high, medium or low." + }, + "Maint": { + "title": "Price of the maintenance", + "content": "What it costs to keep the car running, with its services and repairs. It also goes from very high to low." + }, + "Doors": { + "title": "Number of doors", + "content": "Two, three, four, or five or more. It is the feature with the least influence on the decision." + }, + "Persons": { + "title": "Capacity in persons", + "content": "How many people fit: two, four or more. In this data, a car with only two seats is always unacceptable." + }, + "Lug_boot": { + "title": "Size of the luggage boot", + "content": "Small, medium or big. The bigger the boot, the more acceptable the car." + }, + "Safety": { + "title": "Safety", + "content": "The estimated safety of the car: low, medium or high. It is the feature that weighs the most: with low safety, the car is always unacceptable." + } + }, + "vector": { + "title": "From words to numbers", + "content": "On the left are the values of the form and, on the right, the vector that goes into the network: the same six features turned into numbers with the encoding learned during training." + }, + "classify": { + "title": "Classify", + "content": "When you press this button, the network receives the vector, passes it through layer after layer and computes a probability for each class." + }, + "result": { + "title": "The result", + "content": "Here you will see the probability of each class, and the highest one is the prediction. If you classify an example or a row without changing it, you will also see its real class, so you can check whether the network gets it right. This model only has three outputs: unacceptable, acceptable and very good. The class good has none, so it is never predicted." + }, + "explain": { + "title": "Explainability", + "content": "After classifying, here you can see why the network decided that. SHAP shares out the decision among the features: which ones push towards the class and which ones against it. The global importance does the same with many rows, to see which feature weighs the most in general." + }, + "end": { + "title": "Your turn", + "content": "Try choosing an example, classify it, and then change the safety or the number of seats to see how the prediction changes. You can open this guide again whenever you like with the Guide button." + } + }, + "common": { + "model": { + "title": "The model", + "content": "This is the model card: where the data comes from, which features the network receives and which classes it can predict." + }, + "model-summary": { + "title": "Model summary", + "content": "This button opens the summary of the network: its layers, how many neurons each one has and how many parameters, which are the weights it adjusted during training." + }, + "dataset": { + "title": "The data set", + "content": "This is the data the network was trained with. Each row is an example and each column is a feature. The last column, highlighted, is the class: what the network learned to predict." + }, + "dataset-processed": { + "title": "Processed data", + "content": "A neural network only works with numbers. In this tab you will see the same data as the model receives it, with every category turned into a number." + }, + "dataset-analysis": { + "title": "Analysis", + "content": "This tab sums up the exploratory analysis of the data set: its size, the missing values, how many examples there are of each class, the warnings, for example whether the classes are unbalanced, and which features are related to each other. It is a good place to understand the data before classifying." + }, + "instances": { + "title": "Examples and rows", + "content": "With this selector you fill in the whole form at once. At the top are the examples, marked with a star; below them, every row of the data set with its real class." + }, + "form": { + "title": "The form", + "content": "Here you write the values of what you want to classify, one box per feature. Under each one you will see its name in the data set and which values it accepts." + }, + "vector": { + "title": "From the data to the vector", + "content": "On the left are the values of the form and, on the right, the vector that goes into the network: the same features turned into numbers with the encoding learned during training." + }, + "classify": { + "title": "Classify", + "content": "When you press this button, the network receives the vector, passes it through layer after layer and computes a probability for each class." + }, + "result": { + "title": "The result", + "content": "Here you will see the probability of each class, and the highest one is the prediction. If you classify an example or a row without changing it, you will also see its real class, so you can check whether the network gets it right." + }, + "explain": { + "title": "Explainability", + "content": "After classifying, here you can see why the network decided that. SHAP shares out the decision among the features: which ones push towards the class and which ones against it. The global importance does the same with many rows, to see which feature weighs the most in general." + }, + "step-by-step": { + "title": "Step by step", + "content": "Here you see how this model computes its answer, with its real weights: the forward pass layer by layer, the error and, going backwards, how much each weight would change with one more training step. Click a neuron to see its calculations. It is only drawn with models of fewer than 64 neurons." + }, + "end": { + "title": "Your turn", + "content": "Try choosing an example, classify it, and then change a feature to see how the prediction changes. You can open this guide again whenever you like with the Guide button." + } + }, + "IRIS": { + "intro": { + "title": "Iris flower classification", + "content": "On this page, a neural network that has already been trained recognises the species of an iris flower from four measurements: the length and width of the sepal and of the petal. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "dataset": { + "title": "The data set", + "content": "It is the famous Iris data set, which the statistician Ronald Fisher made known in 1936: 150 flowers, 50 of each species. Each row is a flower with its four measurements in centimetres, and the last column, highlighted, is its species." + }, + "fields": { + "sepal_length": { + "title": "Sepal length", + "content": "The sepal is the green leaf that protects the flower before it opens. This box is its length, in centimetres." + }, + "sepal_width": { + "title": "Sepal width", + "content": "The width of the sepal, in centimetres. It is the measurement that helps the least to tell the species apart." + }, + "petal_length": { + "title": "Petal length", + "content": "The length of the petal, in centimetres. Together with its width, it is the measurement that best separates the species: the setosa has much smaller petals than the other two." + }, + "petal_width": { + "title": "Petal width", + "content": "The width of the petal, in centimetres. In this data, a flower whose petal is less than one centimetre wide is always a setosa." + } + }, + "vector": { + "title": "From the data to the vector", + "content": "Here the four measurements are already numbers, so the vector that goes into the network is those same measurements, in the same order." + }, + "result": { + "title": "The result", + "content": "Here you will see the probability of each species: setosa, versicolor and virginica. The highest one is the prediction. The setosa is easy to recognise; the other two look more alike, and that is where the network may hesitate." + }, + "end": { + "title": "Your turn", + "content": "Choose the versicolor example, classify it and increase the length and width of the petal little by little: you will see the network start to hesitate and end up saying virginica. You can open this guide again whenever you like with the Guide button." + } + }, + "LYMPHOGRAPHY": { + "intro": { + "title": "Lymphography classification", + "content": "On this page, a neural network that has already been trained classifies the result of a lymphography, an imaging test of the lymphatic system, into four diagnoses: normal, metastases, malignant lymphoma or fibrosis. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "dataset": { + "title": "The data set", + "content": "These are 148 patients from the Institute of Oncology of the University Medical Centre in Ljubljana. Each row is a patient and each column is something observed in their lymphography. The classes are very unbalanced: there are 81 cases of metastases and 61 of malignant lymphoma, but only 4 of fibrosis and 2 normal ones." + }, + "form": { + "title": "What the lymphography shows", + "content": "The form has eighteen features. Some say whether the lymphatic vessels are normal, arched, deformed or displaced; others, whether there are blockages, bypasses or leaks of the contrast; and others describe the lymph nodes: how many there are, whether they have grown or shrunk, their shape and the defects and changes in their structure. They are medical terms: you do not need to understand them all to see how the prediction changes." + }, + "result": { + "title": "The result", + "content": "Here you will see the probability of each diagnosis, and the highest one is the prediction. With so few cases of fibrosis and normal results, the network has mostly learned to tell metastases from malignant lymphoma." + }, + "end": { + "title": "Your turn", + "content": "Choose an example of each diagnosis, classify it, and then look at the explainability to see which features weighed the most in each one. You can open this guide again whenever you like with the Guide button." + } + } + }, + "1-regression": { + "common": { + "model": { + "title": "The model", + "content": "This is the model card: where the data comes from, which variables the network receives and which one it predicts." + }, + "model-summary": { + "title": "Model summary", + "content": "This button opens the summary of the network: its layers, how many neurons each one has and how many parameters, which are the weights it adjusted during training." + }, + "dataset-select": { + "title": "Data set", + "content": "Here you choose the data set. Each one has its own trained networks." + }, + "dataset": { + "title": "The data set", + "content": "This is the data the network was trained with. Each row is an example and each column is a variable. The highlighted column is the target variable: the number the network learned to predict." + }, + "dataset-processed": { + "title": "Processed data", + "content": "In this tab you will see the same data as the model receives it, with the texts turned into numbers, and below it the statistical description of each column." + }, + "dataset-analysis": { + "title": "Analysis", + "content": "This tab sums up the exploratory analysis of the data set: its size, the missing values, how the target variable is distributed and which variables are most related to it. It is a good place to understand the data before predicting." + }, + "instances": { + "title": "Rows of the data set", + "content": "With this selector you fill in the form with any row of the data set. Next to the row number you will see its real value, to compare it with the prediction afterwards." + }, + "models": { + "title": "Models", + "content": "Here you choose one of the networks already trained for this data set." + }, + "form": { + "title": "The form", + "content": "Here you write the values of the input variables, one box per variable. Under each one you will see its type and the range of values it takes in the data." + }, + "predict": { + "title": "Predict", + "content": "When you press this button, the network receives the values already encoded and scaled, passes them through layer after layer and returns a number: its prediction." + }, + "result": { + "title": "The result", + "content": "Here you will see the predicted value. If you used a row of the data set without changing it, you will also see its real value and the error, the difference between the two. Below are the steps the data goes through before entering the network." + }, + "explain": { + "title": "Explainability", + "content": "After predicting, here you can see why the network gave that value. SHAP shares out the prediction among the variables: which ones raise it and which ones lower it compared with the average prediction. The global importance does the same with many rows, to see which variable weighs the most in general." + }, + "step-by-step": { + "title": "Step by step", + "content": "Here you see how this model computes its answer, with its real weights: the forward pass layer by layer, the error and, going backwards, how much each weight would change with one more training step. Click a neuron to see its calculations. It is only drawn with models of fewer than 64 neurons." + }, + "end": { + "title": "Your turn", + "content": "Choose a row, predict its value and then change a variable to see how the prediction changes. You can open this guide again whenever you like with the Guide button." + } + }, + "AUTO_MPG": { + "intro": { + "title": "Fuel efficiency", + "content": "On this page, a neural network that has already been trained predicts how many miles a car travels on one gallon of fuel, from six facts about the car: the cylinders, the displacement, the horsepower, the weight, the acceleration and the model year. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "dataset-select": { + "title": "Data set", + "content": "This model has a single data set, Auto MPG." + }, + "dataset": { + "title": "The data set", + "content": "These are 396 cars from 1970 to 1982, from the Auto MPG data set. The highlighted column, mpg, is the miles per gallon: the higher it is, the less the car uses. In this data it goes from 9 to 46." + }, + "fields": { + "cylinders": { + "title": "Cylinders", + "content": "The number of cylinders of the engine, from three to eight. More cylinders usually mean more consumption." + }, + "displacement": { + "title": "Displacement", + "content": "The total volume of the cylinders of the engine, in cubic inches. The bigger it is, the more fuel the car uses." + }, + "horsepower": { + "title": "Horsepower", + "content": "The power of the engine. More powerful cars usually travel fewer miles per gallon." + }, + "weight": { + "title": "Weight", + "content": "The weight of the car, in pounds. It is the variable most related to consumption: the heavier the car, the fewer miles it travels per gallon." + }, + "acceleration": { + "title": "Acceleration", + "content": "The seconds the car takes to go from 0 to 60 miles per hour. A higher number is a less sporty car, which usually uses less fuel." + }, + "model-year": { + "title": "Model year", + "content": "The year the model came out, with two digits, from 70 to 82. The newer cars in this data set use less fuel, partly because of the fuel economy laws of those years." + } + }, + "result": { + "title": "The result", + "content": "Here you will see the predicted consumption, in miles per gallon. If you used a row without changing it, you will also see the real value and the error. Below are the steps the data goes through before entering the network." + }, + "end": { + "title": "Your turn", + "content": "Choose a car, predict its consumption and then raise its weight or horsepower: you will see the network predict fewer miles per gallon. You can open this guide again whenever you like with the Guide button." + } + }, + "STUDENT_PERFORMANCE": { + "intro": { + "title": "Student performance", + "content": "On this page, a neural network that has already been trained predicts the final grade of a secondary school student, from 0 to 20, from thirty facts about their school, family and social life. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "model": { + "title": "The model", + "content": "This is the model card: where the data comes from, which variables the network receives and which one it predicts. The note about G1 and G2 that you will see in it refers to the original data: this version leaves them out on purpose, as I will explain later." + }, + "dataset-select": { + "title": "Data set", + "content": "There are two data sets: maths students and Portuguese language students, from two secondary schools in Portugal. Each one has its own trained network." + }, + "dataset": { + "title": "The data set", + "content": "Each row is a student: 395 in maths and 649 in Portuguese. The highlighted column, G3, is the final grade of the year, from 0 to 20. Two columns of the original data are missing here, G1 and G2, the grades of the first and second terms: they were removed on purpose." + }, + "form": { + "title": "The student data", + "content": "The form has thirty variables: personal ones, such as age and sex; family ones, such as the education and job of the mother and father; school ones, such as study time, past failures and absences; and social ones, such as going out with friends or alcohol consumption. Past failures are what is most related to a low final grade. The term grades are not here: the next step explains why." + }, + "grades": { + "title": "What about the grades G1 and G2?", + "content": "G1 and G2 are the grades of the first and second terms, and they are very close to the final one: their correlation with G3 goes from 0.8 to 0.92. With them, the network would hardly have to learn anything, it would be enough to copy the grade of the second term. Without them, it has to predict the final grade only from the school, family and social life of the student. It is much harder, but also much more useful: it can be done before there are any grades, to help in time those who need it. That is why the networks on this page were trained without G1 and G2." + }, + "result": { + "title": "The result", + "content": "Here you will see the predicted final grade, from 0 to 20. If you used a row without changing it, you will also see the real grade and the error. Since the network does not know the term grades, it is normal for it to be off by a few points: that is the price of being able to predict before there are any grades." + }, + "end": { + "title": "Your turn", + "content": "Choose a student, predict their grade and then change the number of past failures or the study time to see how the prediction changes. You can open this guide again whenever you like with the Guide button." + } + }, + "WINE": { + "intro": { + "title": "Wine quality", + "content": "On this page, a neural network that has already been trained predicts the quality of a Portuguese wine, the score given by wine tasters, from eleven chemical measurements. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "dataset-select": { + "title": "Data set", + "content": "There are two data sets: red wine and white wine, from the vinho verde region. Each one has its own trained network." + }, + "dataset": { + "title": "The data set", + "content": "Each row is a wine: 1599 reds and 4898 whites. The highlighted column, quality, is the tasters' score, from 0 to 10, although in this data it only goes from 3 to 9 and almost every wine has a 5 or a 6." + }, + "form": { + "title": "The wine measurements", + "content": "The form has eleven chemical measurements: fixed and volatile acidity, citric acid, residual sugar, chlorides, free and total sulphur dioxide, density, pH, sulphates and alcohol. Alcohol is the one most related to quality: wines with more alcohol usually score better. In reds, a high volatile acidity also lowers it." + }, + "result": { + "title": "The result", + "content": "Here you will see the predicted quality. It does not have to be a whole number: the network may say, for example, 5.6. If you used a row without changing it, you will also see the real score and the error." + }, + "end": { + "title": "Your turn", + "content": "Choose a wine, predict its quality and then raise the alcohol to see how the prediction changes. You can open this guide again whenever you like with the Guide button." + } + }, + "SALARY": { + "intro": { + "title": "Salaries", + "content": "On this page, an already trained neural network predicts a salary from the years of experience. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "dataset-select": { + "title": "Dataset", + "content": "There are two datasets: one with only the years of experience and another with the age, gender, education and job title. The trained network is the one for the first; with the second you can look at the data, but to predict you would have to train your own network." + }, + "dataset": { + "title": "The dataset", + "content": "The first one has 1000 people. The highlighted column, Salary, is the salary, which usually goes up with the years of experience (from less than one to almost fifty). It is example data, meant for practising regression." + }, + "form": { + "title": "The person's data", + "content": "With the first dataset, the form has a single value: the years of experience. The more years, the higher the salary the network usually predicts." + }, + "result": { + "title": "The result", + "content": "Here you see the predicted salary, in the same units as the dataset. If you used a row without changing it, you will also see the real salary and the error." + }, + "end": { + "title": "Your turn", + "content": "Choose a person, predict their salary and then change the years of experience to see how the prediction changes. You can open this guide again whenever you want with the Guide button." + } + }, + "HOUSING_PRICES": { + "intro": { + "title": "Housing prices", + "content": "On this page, an already trained neural network predicts the median price of the houses in a Boston neighbourhood from twelve facts about the neighbourhood. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "dataset-select": { + "title": "Dataset", + "content": "This model has a single dataset, Boston Housing." + }, + "dataset": { + "title": "The dataset", + "content": "Each row is one of the 506 Boston neighbourhoods of the seventies. The highlighted column, MEDV, is the median value of the houses, in thousands of dollars, from 5 to 50. This version does not have column B of the original dataset, which was removed for ethical reasons." + }, + "form": { + "title": "The neighbourhood's data", + "content": "The form has twelve values: crime (CRIM), residential (ZN) and industrial (INDUS) land, whether it borders the Charles River (CHAS), pollution (NOX), rooms per house (RM), age (AGE), distance to employment centres (DIS), access to highways (RAD), taxes (TAX), pupils per teacher (PTRATIO) and the percentage of lower-status population (LSTAT). The rooms and LSTAT are what is most related to the price." + }, + "result": { + "title": "The result", + "content": "Here you see the predicted median price, in thousands of dollars. If you used a row without changing it, you will also see the real value and the error." + }, + "end": { + "title": "Your turn", + "content": "Choose a neighbourhood, predict its price and then raise the rooms (RM) to see how the prediction changes. You can open this guide again whenever you want with the Guide button." + } + } + }, + "2-object-detection": { + "common": { + "model": { + "title": "The model", + "content": "This is the model card: what it detects, what it receives and what it returns. It is an already trained model: here it is only used, not trained." + }, + "explain-about": { + "title": "How it is explained", + "content": "This box sums up how the explainability is computed: the image is split into pieces, they are covered in many different combinations and we look at how much the result changes. That way we know which areas weighed the most." + }, + "webcam": { + "title": "Real-time recognition", + "content": "Here you see the camera image with what the model detects drawn on top, up to twenty times per second." + }, + "webcam-controls": { + "title": "The camera controls", + "content": "With the switch you turn on the webcam; the browser will ask for permission the first time. With the drop-down you choose the camera, if you have several. The photo camera button downloads a capture and the last one puts the camera in full screen." + }, + "device-info": { + "title": "Device information", + "content": "Here you have the details of your camera, your browser and your screen, and how the detection is going: how many predictions per second it makes and how long each one takes." + }, + "image": { + "title": "Recognition in images", + "content": "If you do not have a camera, drag a photo here or choose it from your computer: the model processes it and draws on top what it detects." + }, + "explain": { + "title": "Explainability", + "content": "After processing a photo, here you can compute its explanation: a heat map on the image that marks which areas weighed the most in what the model detected." + }, + "end": { + "title": "Your turn", + "content": "Turn on the webcam or upload a photo and see what the model detects. You can open this guide again whenever you like with the Guide button." + } + }, + "FACE-DETECTOR": { + "intro": { + "title": "Face detection", + "content": "On this page, the MediaPipe Face Detector model finds the faces in a photo or in the camera, up to four at a time, and marks six key points on each one: the eyes, the nose, the mouth and the ears. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "webcam": { + "title": "Real-time recognition", + "content": "When you turn on the camera you will see the key points of your face with their names on top of it, in real time. The image is shown as in a mirror." + }, + "end": { + "title": "Your turn", + "content": "Turn on the webcam, turn your head or cover part of your face and see when it stops finding it. You can open this guide again whenever you like with the Guide button." + } + }, + "FACE-MESH": { + "intro": { + "title": "Face mesh", + "content": "On this page, the MediaPipe Face Mesh model finds the faces in a photo or in the camera, up to four at a time, and places hundreds of points on each one, forming a three-dimensional mesh of its surface. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "webcam": { + "title": "Real-time recognition", + "content": "When you turn on the camera you will see the mesh of points on top of your face, following your expressions in real time. The image is shown as in a mirror." + }, + "end": { + "title": "Your turn", + "content": "Turn on the webcam, open your mouth, wink or raise your eyebrows and see how the mesh follows each expression. You can open this guide again whenever you like with the Guide button." + } + }, + "MOVE-NET--POSE-NET": { + "intro": { + "title": "Joint detector", + "content": "On this page, the MoveNet model estimates the posture of the body: up to five people at a time, with seventeen points each, such as the eyes, the ears, the shoulders, the elbows, the wrists, the hips, the knees and the ankles. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "webcam": { + "title": "Real-time recognition", + "content": "When you turn on the camera you will see the points of each person joined by lines, like a skeleton that moves with you. Step back a little so that your whole body is visible." + }, + "end": { + "title": "Your turn", + "content": "Turn on the webcam, step back until your whole body is visible and move your arms and legs. You can open this guide again whenever you like with the Guide button." + } + }, + "COCO-SSD": { + "intro": { + "title": "Object detector", + "content": "On this page, the COCO-SSD model finds objects in a photo or in the camera: it draws a box around them and says what they are and how confident it is. It recognises eighty classes from the COCO data set, such as people, animals, vehicles, food or furniture. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "webcam": { + "title": "Real-time recognition", + "content": "When you turn on the camera you will see a box around each object it recognises, with its name and the percentage of confidence." + }, + "end": { + "title": "Your turn", + "content": "Turn on the webcam and hold up a cup, a bottle, a book or your phone: see what it recognises and how confident it is. You can open this guide again whenever you like with the Guide button." + } + }, + "FACE-API": { + "intro": { + "title": "Facial expressions", + "content": "On this page, face-api, a set of several neural networks, finds the faces in a photo or in the camera and estimates for each one its approximate age and its expression: neutral, happy, sad, angry, fearful, disgusted or surprised. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "webcam": { + "title": "Real-time recognition", + "content": "When you turn on the camera you will see a box around each face with its estimated age and how much its expression looks like each emotion." + }, + "end": { + "title": "Your turn", + "content": "Turn on the webcam and try smiling, looking surprised or angry: see how the percentages of each expression change. You can open this guide again whenever you like with the Guide button." + } + }, + "HAND-SIGN": { + "intro": { + "title": "Sign language", + "content": "On this page, a neural network finds your hand and twenty-one points on its fingers and joints; then another program compares the position of the fingers with the letters of the fingerspelling alphabet: Spanish Sign Language if the application is in Spanish, and American Sign Language in the other languages. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "webcam": { + "title": "Real-time recognition", + "content": "When you turn on the camera you will see the points of your hand and the letter it recognises. Hold your hand facing the camera, well lit and fully inside the image." + }, + "end": { + "title": "Your turn", + "content": "Turn on the webcam, look at the image with the alphabet in the model card and try to form several letters with your hand. You can open this guide again whenever you like with the Guide button." + } + } + }, + "3-image-classification": { + "common": { + "model": { + "title": "The model", + "content": "This is the model card: which images it was trained with, what it receives and which classes it can recognise." + }, + "model-summary": { + "title": "Model summary", + "content": "This button opens the summary of the network: its layers, how many neurons each one has and how many parameters, which are the weights it adjusted during training." + }, + "explain-about": { + "title": "How it is explained", + "content": "This box sums up the method used to explain the predictions. LRP goes back through the network and shares out the decision down to the pixels; SHAP covers pieces of the image in many combinations and looks at how much the result changes." + }, + "examples": { + "title": "Example images", + "content": "Press any of these images to classify it: the result appears further down." + }, + "test-images": { + "title": "Test images", + "content": "With this button you load the test images, the ones the network did not see during training. Then, in this same place, you choose any of them to classify it and compare the prediction with its real class." + }, + "upload": { + "title": "Upload an image", + "content": "You can also drag an image of your own here, or choose it from your computer, and press the button to classify it." + }, + "draw": { + "title": "Draw", + "content": "Or draw here with the mouse or your finger and press the button to classify your drawing. It is reduced to 28 by 28 pixels, like the images the network was trained with." + }, + "result": { + "title": "The result", + "content": "Here you will see the image that was classified and, next to it, the probability of each class. The highest one is the prediction." + }, + "explain": { + "title": "Explainability", + "content": "After classifying, here you compute a heat map on the image that marks which pixels weighed the most in the decision of the network." + }, + "end": { + "title": "Your turn", + "content": "Classify an example, upload an image of your own and look at the explainability to see what the network paid attention to. You can open this guide again whenever you like with the Guide button." + } + }, + "IMAGE-MNIST": { + "intro": { + "title": "Digit recognition", + "content": "On this page, a convolutional neural network that has already been trained recognises handwritten numbers from 0 to 9. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "model": { + "title": "The model", + "content": "The network was trained with MNIST, a collection of 70,000 handwritten digits, 60,000 for training and 10,000 for testing, in greyscale images of 28 by 28 pixels. It is one of the most used data sets to get started with machine learning." + }, + "examples": { + "title": "Example images", + "content": "Press any of these digits to classify it: the result appears further down." + }, + "draw": { + "title": "Draw a number", + "content": "Draw a number from 0 to 9 here with the mouse or your finger and press the button to classify it. Your drawing is reduced to 28 by 28 pixels, like the MNIST ones, so draw it big and centred." + }, + "result": { + "title": "The result", + "content": "Here you will see the image the network saw and the probability of each digit. The highest one is the prediction. If you classify a test image, you will also see which digit it really was." + }, + "explain": { + "title": "Explainability with LRP", + "content": "After classifying, here you compute a heat map with LRP, which shares out the decision of the network backwards, layer by layer, down to the pixels: you will see which strokes of the drawing weighed the most." + }, + "end": { + "title": "Your turn", + "content": "Draw a number your own way, for example a seven with a cross bar or a one with a base, and see whether the network recognises it and what it paid attention to. You can open this guide again whenever you like with the Guide button." + } + }, + "IMAGE-KMNIST": { + "intro": { + "title": "Japanese characters", + "content": "On this page, a convolutional neural network that has already been trained recognises ten Japanese characters of the hiragana syllabary handwritten in kuzushiji, the cursive script used in Japan for centuries. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "model": { + "title": "The model", + "content": "The network was trained with Kuzushiji-MNIST: images of 28 by 28 pixels, like the MNIST ones, but with characters instead of digits. It is harder than MNIST, because the same character can be written in very different ways." + }, + "examples": { + "title": "Example images", + "content": "Each character appears as it is written today and in three old forms (hentaigana), with the kanji each one comes from: notice how different they are. Press any of them to classify it; the result appears further down." + }, + "draw": { + "title": "Draw a character", + "content": "Draw one of the ten characters here with the mouse or your finger and press the button to classify it. Bear in mind that the network learned the old cursive script, which does not always look like today's hiragana." + }, + "result": { + "title": "The result", + "content": "Here you will see the image the network saw and the probability of each character. The highest one is the prediction. If you classify a test image, you will also see which character it really was." + }, + "explain": { + "title": "Explainability with LRP", + "content": "After classifying, here you compute a heat map with LRP, which shares out the decision of the network backwards, layer by layer, down to the pixels: you will see which strokes weighed the most." + }, + "end": { + "title": "Your turn", + "content": "Load the test images and compare several ways of writing the same character: you will see the network get it right even with very different strokes. You can open this guide again whenever you like with the Guide button." + } + }, + "IMAGE-CIFAR10": { + "intro": { + "title": "Photo classification", + "content": "On this page, an already trained convolutional neural network recognises small color photos of ten classes: airplane, automobile, bird, cat, deer, dog, frog, horse, ship and truck. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide advance on its own." + }, + "model": { + "title": "The model", + "content": "The network was trained with CIFAR-10: 50,000 color photos of 32 by 32 pixels for training and 10,000 for testing. Each photo has three channels, red, green and blue, so the network receives almost four times as many numbers as with MNIST." + }, + "examples": { + "title": "Example images", + "content": "There is a test photo of each class, enlarged so that you can see its pixels. Click any of them to classify it: the result appears below." + }, + "upload": { + "title": "Upload an image", + "content": "Drag a photo of yours here, or choose it from your computer, and press the button to classify it. It is reduced to 32 by 32 pixels, like the ones in the dataset: it works best if the object fills almost the whole photo." + }, + "result": { + "title": "The result", + "content": "Here you see the image the network has seen, already reduced, and the probability of each class. The highest one is the prediction. If you classify a test image, you will also see its real class." + }, + "explain": { + "title": "Explainability", + "content": "After classifying, here you compute a heat map over the photo: with LRP, the decision is spread backwards, layer by layer, down to the pixels; with SHAP, parts of the photo are covered and you see how much the prediction changes. That shows which areas the network looked at." + }, + "end": { + "title": "Now you", + "content": "Load the test images and look for the classes where the network fails most: it often confuses cats with dogs and automobiles with trucks. You can open this guide again whenever you want with the Guide button." + } + }, + "IMAGE-MOBILENET": { + "intro": { + "title": "Image classification", + "content": "On this page, MobileNet, a convolutional neural network designed for mobile phones, recognises what appears in a photo among a thousand categories: animals, objects, vehicles, food and much more. I will explain what each thing is, step by step. You can move on with Next, go back, mute the voice or let the guide move on by itself." + }, + "model": { + "title": "The model", + "content": "It is MobileNet, trained with ImageNet, more than a million photos of a thousand categories. It receives colour images of 224 by 224 pixels." + }, + "examples": { + "title": "Example images", + "content": "Press any of these photos to classify it: the result appears further down." + }, + "upload": { + "title": "Upload an image", + "content": "Drag a photo of your own here, or choose it from your computer, and press the button to classify it. It works better if what you want to recognise fills almost the whole photo." + }, + "result": { + "title": "The result", + "content": "Here you will see the photo the network saw and the most likely categories, from highest to lowest. With a thousand categories, it is normal for it to hesitate between several similar ones, such as two breeds of dog." + }, + "explain": { + "title": "Explainability with SHAP", + "content": "After classifying, here you compute a heat map with SHAP: the photo is split into pieces, they are covered in many combinations and we look at how much the prediction changes. That way you see which areas of the photo weighed the most." + }, + "end": { + "title": "Your turn", + "content": "Upload a photo of something near you and see whether the network recognises it and what it paid attention to. You can open this guide again whenever you like with the Guide button." + } + } + }, + "go-to": "Go to step", + "voice": "Voice", + "voice-auto": "Automatic", + "voice-online": "online", + "train": { + "0-tabular-classification": { + "common": { + "intro": { + "title": "Train your network", + "content": "On this page you design and train your own neural network to classify a dataset, and then you test it. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "session": { + "title": "Save the configuration", + "content": "These buttons save the layers and hyperparameters you have chosen to a file, so you can load it another day to pick up where you left off, or share it. The data and the trained models are not saved." + }, + "manual": { + "title": "The manual", + "content": "If this is your first time, open the manual: it calmly explains each part of this page and what every option means." + }, + "layers-add": { + "title": "Add and remove layers", + "content": "These buttons add a layer at the beginning or at the end of the network. To remove one, or change its neurons and activation, expand it in the list." + }, + "learning-rate": { + "title": "Learning rate", + "content": "This is how much the weights are corrected at each step. With a high rate it learns quickly, but it may overshoot and never settle; with a low one it is more stable, but needs more epochs. 0.01 is a good starting point." + }, + "test-size": { + "title": "Test data", + "content": "This percentage of the data is set aside and the network does not see it while training. It is used afterwards to check how well it does with new data, which is what really matters: a network that only gets right what it has already seen has memorised, not learned." + }, + "optimizer": { + "title": "Optimizer", + "content": "This is the method that adjusts the weights based on the error. Adam usually works well out of the box; SGD is the simplest, and RMSprop, Adagrad or Adadelta adapt the step of each weight." + }, + "step-by-step": { + "title": "Step by step", + "content": "Before training for real, here you see how your network learns one example at a time: the forward pass layer by layer, the error and how it goes back to correct each weight. Move phase by phase or press play, and click a neuron to see its calculations. It is only drawn with networks of fewer than 64 neurons, so it can be followed." + }, + "models": { + "title": "Generated models", + "content": "Each training run adds a row here with its configuration and results, so you can compare them. The best one, with the lowest error on the test data, is marked. From here you can also see its history or download it." + }, + "dataset-info": { + "title": "The dataset", + "content": "This describes the dataset: where it comes from, what each column means and which classes have to be predicted. It is worth reading before designing the network." + }, + "dataset": { + "title": "The data", + "content": "This is the table you are going to train with. Each row is an example and each column a feature; the highlighted one is the class. The sections below show the statistics of each column, before and after processing it: the network only works with numbers, so each category is turned into a number." + }, + "layer-design": { + "title": "Your network", + "content": "This drawing is the network you are going to train. On the left is the input layer, with one neuron per feature; in the middle, the hidden layers, and on the right the output layer, with one neuron per class. It changes as soon as you edit the layers, and the button in the corner shows it full screen." + }, + "layers": { + "title": "The layers", + "content": "Each layer has a number of neurons and an activation function. More neurons or more layers can learn more complex relationships, but they train more slowly and may memorise the data instead of generalising. The last layer gives the answer: it needs as many neurons as there are classes and the softmax activation, which turns the output into probabilities." + }, + "epochs": { + "title": "Epochs", + "content": "An epoch is one complete pass through all the training data. With too few, the network does not get to learn; with too many, it takes longer and may memorise the data. Start with 10 and increase them if the accuracy is still improving at the end." + }, + "loss": { + "title": "Loss function", + "content": "It measures how wrong the network is on each example, and it is what the optimizer tries to reduce. To choose between several classes, categorical cross-entropy is used, which is the one selected." + }, + "metrics": { + "title": "Metric", + "content": "This is what is shown during training to tell whether it is going well, for example the accuracy: the percentage of examples it gets right. It does not change how the network learns, only what you see." + }, + "train": { + "title": "Train", + "content": "When you press Train, the network learns epoch by epoch. You will see the progress here and, in the visor, how the loss goes down and the accuracy goes up, both on the training data and on the test data. If it takes too long, you can stop it." + }, + "predict": { + "title": "Classify", + "content": "With a trained model, choose a row from the dataset or type in the values of an example, and press Classify. You will see the probability of each class. At the top you choose which model to classify with, to compare them." + }, + "explain": { + "title": "Explainability", + "content": "After classifying, SHAP shows why the network decided that: which features pushed towards the predicted class and which against it. The global importance does the same with many rows, to see which feature matters most in general." + }, + "end": { + "title": "Your turn", + "content": "Train with the starting values and look at the accuracy. Then change just one thing, for example the epochs or the neurons of a layer, train again and compare both models in the table. You can open this guide again whenever you want with the Guide button." + } + }, + "CAR": { + "intro": { + "title": "Car classification", + "content": "On this page you train a network that decides whether a car is acceptable from six features, such as the price, the maintenance or the safety, with 1728 example cars. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "layers": { + "title": "The layers", + "content": "Each layer has a number of neurons and an activation function. More neurons or more layers can learn more complex relationships, but they train more slowly and may memorise the data instead of generalising. The last layer gives the answer: it has 4 neurons, one per class (unacceptable, acceptable, good and very good), with the softmax activation, which turns them into probabilities." + } + }, + "IRIS": { + "intro": { + "title": "Iris flower classification", + "content": "On this page you train a network that recognises the species of an iris flower, among three, from four measurements of its petals and sepals, with 150 example flowers. It is a small dataset: it trains in a moment and is perfect for experimenting. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "layers": { + "title": "The layers", + "content": "Each layer has a number of neurons and an activation function. More neurons or more layers can learn more complex relationships, but they train more slowly and may memorise the data instead of generalising. The last layer gives the answer: it has 3 neurons, one per species (setosa, versicolor and virginica), with the softmax activation, which turns them into probabilities." + } + }, + "LYMPHOGRAPHY": { + "intro": { + "title": "Lymphography", + "content": "On this page you train a network that classifies lymphography examinations into four diagnoses from 18 features, with 148 example patients. Some classes have very few cases, so look at how well it does with each one. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "layers": { + "title": "The layers", + "content": "Each layer has a number of neurons and an activation function. More neurons or more layers can learn more complex relationships, but they train more slowly and, with so few patients, they easily memorise the data. The last layer gives the answer: it has 4 neurons, one per diagnosis, with the softmax activation, which turns them into probabilities." + } + }, + "UPLOAD": { + "intro": { + "title": "Your own data", + "content": "On this page you train a network with your own data: you upload it, choose which column you want to predict, design the network and train it. Your data never leaves your browser. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "dataset-info": { + "title": "Upload the data", + "content": "Drag your file here or click to choose it. CSV, TSV, ARFF, JSON, JSON Lines and Parquet are supported. Each row has to be an example, and one of the columns the class you want to predict." + }, + "process": { + "title": "Prepare the data", + "content": "Before training, the data has to be prepared: choose the column you want to predict, how to turn the text columns into numbers and how to scale the values. When you press the button, the data is ready and the network appears." + }, + "layers": { + "title": "The layers", + "content": "Each layer has a number of neurons and an activation function. More neurons or more layers can learn more complex relationships, but they train more slowly and may memorise the data. The last layer gives the answer: it needs as many neurons as classes in the column you predict, with the softmax activation, which turns them into probabilities." + } + } + }, + "1-regression": { + "common": { + "intro": { + "title": "Train your regression network", + "content": "On this page you design and train a neural network that predicts a number, such as a price or a grade, from other columns, and then you test it. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "session": { + "title": "Save the configuration", + "content": "These buttons save the layers and hyperparameters you have chosen to a file, so you can load it another day to pick up where you left off, or share it. The data and the trained models are not saved." + }, + "manual": { + "title": "The manual", + "content": "If this is your first time, open the manual: it calmly explains each part of this page and what every option means." + }, + "layers-add": { + "title": "Add and remove layers", + "content": "These buttons add a layer at the beginning or at the end of the network. To remove one, or change its neurons and activation, expand it in the list." + }, + "learning-rate": { + "title": "Learning rate", + "content": "This is how much the weights are corrected at each step. With a high rate it learns quickly, but it may overshoot and never settle; with a low one it is more stable, but needs more epochs. 0.01 is a good starting point." + }, + "test-size": { + "title": "Test data", + "content": "This percentage of the data is set aside and the network does not see it while training. It is used afterwards to check how well it does with new data, which is what really matters: a network that only gets right what it has already seen has memorised, not learned." + }, + "optimizer": { + "title": "Optimizer", + "content": "This is the method that adjusts the weights based on the error. RMSprop, the one selected, works well for regression; Adam also usually works out of the box, and SGD is the simplest." + }, + "step-by-step": { + "title": "Step by step", + "content": "Before training for real, here you see how your network learns one example at a time: the forward pass layer by layer, the error and how it goes back to correct each weight. Move phase by phase or press play, and click a neuron to see its calculations. It is only drawn with networks of fewer than 64 neurons, so it can be followed." + }, + "models": { + "title": "Generated models", + "content": "Each training run adds a row here with its configuration and results, so you can compare them. The best one, with the lowest error on the test data, is marked. From here you can also see its history or download it." + }, + "dataset-info": { + "title": "The dataset", + "content": "This describes the dataset: where it comes from, what each column means and which number has to be predicted. It is worth reading before designing the network." + }, + "dataset": { + "title": "The data", + "content": "This is the table you are going to train with, with its statistics and plots. Look at which columns change together with the one being predicted: they are the ones that will help the network most. Before training, the values are scaled so that all columns weigh about the same." + }, + "layer-design": { + "title": "Your network", + "content": "This drawing is the network you are going to train. On the left is the input layer, with one neuron per feature; in the middle, the hidden layers, and on the right a single output neuron: the number it predicts. It changes as soon as you edit the layers, and the button in the corner shows it full screen." + }, + "layers": { + "title": "The layers", + "content": "Each layer has a number of neurons and an activation function. More neurons or more layers can learn more complex relationships, but they train more slowly and may memorise the data. The last layer cannot be changed: it is a single neuron with linear activation, because the result is any number, not a probability." + }, + "epochs": { + "title": "Epochs", + "content": "An epoch is one complete pass through all the training data. With too few, the network does not get to learn; with too many, it takes longer and may memorise the data. Start with the default value and check whether the error is still going down at the end." + }, + "loss": { + "title": "Loss function", + "content": "It measures how far the prediction is from the real value, and it is what the optimizer tries to reduce. The mean squared error, the one selected, punishes large errors heavily; the mean absolute error treats them all the same." + }, + "metrics": { + "title": "Metrics", + "content": "These are shown during training to tell whether it is going well. You can add several: the mean absolute error, for example, tells how wrong it is on average, in the same units as the value you predict." + }, + "train": { + "title": "Train", + "content": "When you press Train, the network learns epoch by epoch. You will see the progress here and, in the visor, how the error goes down, both on the training data and on the test data. If it takes too long, you can stop it." + }, + "predict": { + "title": "Predict", + "content": "With a trained model, choose a row from the dataset or type in the values, and press Predict. You will see the number the network predicts and, if you choose a row without changing it, the real value to compare. At the top you choose which model to predict with." + }, + "explain": { + "title": "Explainability", + "content": "After predicting, SHAP shows why the network gave that number: which features pushed it up and which pushed it down. The global importance does the same with many rows, to see which feature matters most in general." + }, + "end": { + "title": "Your turn", + "content": "Train with the starting values and look at the error. Then change just one thing, for example the learning rate or the neurons of a layer, train again and compare both models in the table. You can open this guide again whenever you want with the Guide button." + } + }, + "SALARY": { + "intro": { + "title": "Salary by experience", + "content": "On this page you train a network that predicts the salary of a person from their work experience, with 1000 example people. With so few columns it is easy to see what the network learns. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + } + }, + "AUTO_MPG": { + "intro": { + "title": "Car fuel consumption", + "content": "On this page you train a network that predicts the fuel consumption of a car, in miles per gallon, from six features such as the cylinders, the horsepower or the weight, with 396 example cars. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + } + }, + "HOUSING_PRICES": { + "intro": { + "title": "Housing prices", + "content": "On this page you train a network that predicts the median value of the homes in a Boston neighbourhood from 12 features, such as the number of rooms or the crime rate of the area, with 506 example neighbourhoods. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + } + }, + "STUDENT_PERFORMANCE": { + "intro": { + "title": "Student grades", + "content": "On this page you train a network that predicts the final grade of a student, from 0 to 20, from 30 features such as study time, absences or the grades of the first two terms, G1 and G2. There is data from two subjects: mathematics, with 395 students, and Portuguese, with 649. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + } + }, + "WINE": { + "intro": { + "title": "Wine quality", + "content": "On this page you train a network that predicts the quality of a wine, from 0 to 10, from 11 chemical measurements such as acidity or alcohol. There are two files: 1599 red wines and 4898 white ones. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + } + }, + "UPLOAD": { + "intro": { + "title": "Your own data", + "content": "On this page you train a network with your own data: you upload it, choose which numeric column you want to predict, design the network and train it. Your data never leaves your browser. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "dataset-info": { + "title": "Upload the data", + "content": "Drag your file here or click to choose it. CSV, TSV, ARFF, JSON, JSON Lines and Parquet are supported. Each row has to be an example, and one of the columns the number you want to predict." + }, + "process": { + "title": "Prepare the data", + "content": "Before training, the data has to be prepared: choose the column you want to predict, how to turn the text columns into numbers and how to scale the values. When you press the button, the data is ready to design the network." + } + } + }, + "3-image-classification": { + "common": { + "intro": { + "title": "Train your image network", + "content": "On this page you design and train a convolutional network that recognises 28 by 28 pixel images, and then you test it by drawing. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "session": { + "title": "Save the configuration", + "content": "These buttons save the layers and hyperparameters you have chosen to a file, so you can load it another day to pick up where you left off, or share it. The data and the trained models are not saved." + }, + "manual": { + "title": "The manual", + "content": "If this is your first time, open the manual: it calmly explains each part of this page and what every option means." + }, + "layers-add": { + "title": "Add and remove layers", + "content": "This button adds a layer at the end. Expand each layer to choose its type, its filters, the filter size or its neurons, or to remove it. The first one has to be convolutional." + }, + "learning-rate": { + "title": "Learning rate", + "content": "This is how much the weights are corrected at each step. With a high rate it learns quickly, but it may overshoot and never settle; with a low one it is more stable, but needs more epochs. 0.01 is a good starting point." + }, + "test-size": { + "title": "Test data", + "content": "This percentage of the data is set aside and the network does not see it while training. It is used afterwards to check how well it does with new data, which is what really matters: a network that only gets right what it has already seen has memorised, not learned." + }, + "optimizer": { + "title": "Optimizer", + "content": "This is the method that adjusts the weights based on the error. Adam usually works well out of the box; SGD is the simplest, and RMSprop, Adagrad or Adadelta adapt the step of each weight." + }, + "models": { + "title": "Generated models", + "content": "Each training run adds a row here with its configuration and results, so you can compare them. The best one, with the lowest error on the test data, is marked. From here you can also see its history or download it." + }, + "dataset-info": { + "title": "The image set", + "content": "This describes the dataset: where the images come from, how many there are and what each of the ten classes represents." + }, + "layer-design": { + "title": "Your network", + "content": "This drawing is the network you are going to train: the image enters on the left, goes through the convolutional and pooling layers, is flattened and ends in the dense layers, with one neuron per class on the right. The button in the corner shows it full screen." + }, + "layers": { + "title": "The layers", + "content": "A network for images combines several kinds of layer. Convolutional layers look for patterns, such as edges or curves, with small filters that sweep the image; pooling layers, max pooling, shrink it keeping the most salient values; the flatten layer turns the result into a list of numbers, and the dense layers decide the class. The last one needs ten neurons, one per class, with the softmax activation. Now let's go through them one by one." + }, + "epochs": { + "title": "Epochs", + "content": "An epoch is one complete pass through all the training images. With images each epoch takes much longer than with a table, so start with a few, like the default 5, and increase them if the accuracy is still improving." + }, + "loss": { + "title": "Loss function", + "content": "It measures how wrong the network is on each image, and it is what the optimizer tries to reduce. To choose between ten classes, categorical cross-entropy is used, which is the one selected." + }, + "metrics": { + "title": "Metrics", + "content": "These are shown during training to tell whether it is going well. You can add several, such as the accuracy: the percentage of images it gets right. They do not change how the network learns, only what you see." + }, + "train": { + "title": "Train", + "content": "When you press Train, the images are downloaded first and then the network learns epoch by epoch. It takes longer than with a table: the progress and the visor tell you how the loss and accuracy are going, and you can stop it if needed." + }, + "predict": { + "title": "Test the network", + "content": "With a trained model, draw on the canvas, choose a test image from the dataset or upload your own, and the network will say what it sees, with the probability of each class. At the top you choose which model to test." + }, + "explain": { + "title": "Explainability", + "content": "After classifying, LRP colours the pixels according to how much they counted for the decision. That way you see which parts of the drawing the network looked at to decide." + }, + "end": { + "title": "Your turn", + "content": "Train with the starting network and try drawing. Then add or remove a convolutional layer, train again and compare in the table which model gets more right. You can open this guide again whenever you want with the Guide button." + }, + "layer": { + "class-name": "symbol", + "conv-first": { + "title": "Layer {{number}}: convolution", + "content": "It's the first one: it gets the image, {{inputSize}} pixels in greyscale. {{filters}} filters of {{kernel}}×{{kernel}} slide over it; each one learns to recognise a small pattern (a stroke, an edge, a curve) and leaves a map of where it finds it. That's why {{outputChannels}} maps of {{outputSize}} come out: one per filter, a bit smaller than the image because the filter doesn't go past the border. It has {{params}} weights to learn." + }, + "conv": { + "title": "Layer {{number}}: convolution", + "content": "It gets the {{inputChannels}} maps of {{inputSize}} from the previous layer and slides {{filters}} filters of {{kernel}}×{{kernel}} over them. Each filter looks at all the maps at once, so it joins simple patterns into more complex shapes, such as the parts of a {{class}}. Out come {{outputChannels}} maps of {{outputSize}}, with {{params}} weights to learn." + }, + "relu": "With ReLU, negative values become zero: only what has been found moves on.", + "activation": "Its activation is {{activation}}.", + "pool": { + "title": "Layer {{number}}: max pooling", + "content": "It shrinks each map by keeping the highest value of each {{pool}}×{{pool}} window, which moves {{strides}} at a time: the most salient part of each area. The {{inputChannels}} maps go from {{inputSize}} to {{outputSize}}. It has no weights and learns nothing, but it makes the network faster and less sensitive to the stroke moving a little." + }, + "flatten": { + "title": "Layer {{number}}: flatten", + "content": "It lines up the {{inputChannels}} maps of {{inputSize}}: a list of {{values}} numbers, because dense layers don't work with images but with lists. It doesn't learn anything either." + }, + "dense": { + "title": "Layer {{number}}: dense", + "content": "Each of its {{units}} neurons is connected to the {{inputValues}} values of the previous layer: it combines everything the filters have found, wherever it is in the image. It has {{params}} weights to learn; in a network like this, the dense layers usually have the most." + }, + "output": { + "title": "Layer {{number}}: the output", + "content": "The last layer has {{units}} neurons, one per {{class}}, connected to the {{inputValues}} previous values ({{params}} weights). With softmax, its values are the probability of each {{class}} and add up to 1: the network's answer is the highest one.", + "content-other": "The last layer has {{units}} neurons, connected to the {{inputValues}} previous values ({{params}} weights). Its activation is {{activation}}: with softmax, its values would be the probability of each {{class}}. Check the warning at the top of the editor." + }, + "broken": { + "title": "Layer {{number}}: doesn't fit", + "content": "The data doesn't reach it in the shape it needs (or a parameter is missing). Check the warning at the top of the editor: it says what's wrong and fixes it with a button." + } + } + }, + "IMAGE-MNIST": { + "intro": { + "title": "Handwritten digits", + "content": "On this page you train a convolutional network that recognises handwritten digits from 0 to 9, with the images of the MNIST dataset, and then you test it by drawing your own numbers. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "layer": { + "class-name": "digit" + } + }, + "IMAGE-KMNIST": { + "intro": { + "title": "Japanese characters", + "content": "On this page you train a convolutional network that recognises ten handwritten hiragana characters of classical Japanese, from the Kuzushiji-MNIST dataset, and then you test it by drawing them. I will walk you through each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "layer": { + "class-name": "character" + } + }, + "IMAGE-CIFAR10": { + "intro": { + "title": "Color photos", + "content": "On this page you train a convolutional network that recognises color photos of ten classes, from airplanes to trucks, with the images of the CIFAR-10 dataset, and then you test it with test photos or your own. I will explain each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "predict": { + "title": "Test the network", + "content": "With a trained model, choose a test photo from the dataset or upload one of yours and press the button: the network will say what it sees, with the probability of each class. Above you choose which model to test." + }, + "explain": { + "title": "Explainability", + "content": "After classifying, LRP colors the pixels according to how much they counted for the decision. That shows which parts of the photo the network looked at to decide." + }, + "end": { + "title": "Now you", + "content": "Train with the starting network and see in the table how often it is right: with few photos and few epochs, quite less than the pre-trained model. Then try more epochs or another convolutional layer and compare. You can open this guide again whenever you want with the Guide button." + }, + "layer": { + "class-name": "class", + "conv-first": { + "title": "Layer {{number}}: convolution", + "content": "It is the first one: it receives the photo, {{inputSize}} pixels in color, that is, {{inputChannels}} maps: red, green and blue. {{filters}} filters of {{kernel}}×{{kernel}} go over it; each one looks at the three colors at once, learns to recognise a small pattern (an edge, a patch of color, a corner) and leaves a map of where it finds it. Out come {{outputChannels}} maps of {{outputSize}}, one per filter, a bit smaller than the photo because the filter does not go past the border. It has {{params}} weights to learn." + } + } + } + }, + "5-time-series": { + "common": { + "intro": { + "title": "Train your network with a time series", + "content": "On this page you prepare a series, design a network that predicts each value from the previous ones, train it and see how it forecasts what it did not see. I explain each part in order. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "session": { + "title": "Save the configuration", + "content": "With these buttons you save the network, the hyperparameters and the preparation (the window and whether to difference) to a file, and load it another day or share it. The data and the trained models are not saved." + }, + "manual": { + "title": "How it works", + "content": "If it is your first time, open this part: it explains windows, why the test part is the end of the series, scaling, one-step and all-at-once forecasts, and what the network is compared with." + }, + "dataset-info": { + "title": "The series", + "content": "Here the series is described: where the data come from and what makes it special, such as a trend, seasons or cycles." + }, + "process": { + "title": "Upload your series", + "content": "Drop your file here and choose the column with the values and, if it has one, the date column: it is used to sort the rows and to date the forecasts." + }, + "dataset": { + "title": "The data", + "content": "The whole series, in order. The dashed line marks where the test part starts: the end of the series, which the network will not see while training." + }, + "preparation": { + "title": "The preparation", + "content": "The window is how many previous values the network looks at; it should cover a season. The test part is the percentage set aside at the end. Differencing makes it learn changes instead of values, and the season is used to compare with the seasonal forecast." + }, + "windows": { + "title": "What the network learns", + "content": "This is how the series becomes examples: each row is the previous values (the window) and the next one, which is what it has to predict. Change the window or difference and see how they change." + }, + "layers": { + "title": "The layers", + "content": "The network ends in one linear neuron, the value it predicts. Before it you can add Dense layers, which receive the whole window, or recurrent ones (SimpleRNN, LSTM, GRU), which read it value by value and go first." + }, + "layers-add": { + "title": "Adding and removing layers", + "content": "With these buttons you add a layer at the start or before the output. To remove one, or change its type, neurons or activation, open it in the list." + }, + "learning-rate": { + "title": "Learning rate", + "content": "How much the weights are corrected at each step. High, it learns fast but may not settle; low, it is more stable but needs more epochs." + }, + "epochs": { + "title": "Epochs", + "content": "How many times the network sees all the training windows. With few it has no time to learn; with too many it may memorise the training data. The model curves tell you." + }, + "batch-size": { + "title": "Batch size", + "content": "How many windows the network sees before correcting its weights. With small batches it corrects more often and with more noise; with large ones, each epoch is faster." + }, + "optimizer": { + "title": "Optimizer", + "content": "The method that adjusts the weights from the error. Adam, the one selected, usually works well out of the box." + }, + "loss": { + "title": "Loss function", + "content": "How the error is measured while training. Mean squared error penalises large errors more; mean absolute error treats all errors the same." + }, + "train": { + "title": "Train", + "content": "When you press it, the network is trained with the training windows and validated with the test ones every epoch. You can stop it whenever you want: it keeps what it has learned." + }, + "models": { + "title": "Trained models", + "content": "Each training adds a row with its preparation, its network and its error on the test part, one step ahead and all at once. The best one is marked. Below, its training curves, to compare them." + }, + "predict": { + "title": "The forecast", + "content": "Here you see what the chosen model forecasts on the test part, one step ahead or all at once, its error compared with repeating the last value or the last season, and what comes after the last value." + }, + "end": { + "title": "Let’s forecast!", + "content": "You now know the page. Try another window, differencing or an LSTM layer, and compare: what matters is that the network beats the simple forecasts on what it did not see." + } + } + } + }, + "glossary": { + "intro": { + "title": "The glossary", + "content": "Here you will find all the concepts Nets4Learning uses, explained: the tasks, the layers, the hyperparameters, the optimizers and the activation and loss functions and metrics. I will show you the most important ones and where to find them. You can move on with Next, jump to a step with the selector, mute the voice or let the guide advance on its own." + }, + "search": { + "title": "Search", + "content": "Type any term here, for example “epoch” or “ReLU”, and only the cards that mention it will remain." + }, + "index": { + "title": "The index", + "content": "The sections of the glossary, in order. Click one to go straight to it; as you scroll down, the one you are in is highlighted." + }, + "tasks": { + "title": "The tasks", + "content": "First of all: which problem each task of the application solves. Classifying rows of a table, predicting numbers with regression, classifying images and identifying objects." + }, + "units": { + "title": "Neurons", + "content": "Each layer of the network has neurons: each one multiplies its inputs by some weights, adds them up and applies an activation function. More neurons can learn more complex relationships." + }, + "activation-function": { + "title": "Activation function", + "content": "It decides what each neuron lets through. Without it, the network could only learn linear relationships, however many layers it had." + }, + "learning-rate": { + "title": "Learning rate", + "content": "How much the weights are corrected at each training step. It is perhaps the most important hyperparameter: too high and the network does not settle; too low and it learns very slowly." + }, + "epochs": { + "title": "Epochs", + "content": "How many times the network goes through all the training data. Too few are not enough to learn; too many lead to memorising the data instead of generalising." + }, + "test-size": { + "title": "Test data", + "content": "The part of the data set aside to check at the end how well the network does with data it has not seen. It is the honest measure of what it has learned." + }, + "optimizer": { + "title": "Optimizers", + "content": "The methods that adjust the weights based on the error, each with its own formula. Adam, which is almost always selected by default, combines the ideas of Momentum and RMSProp." + }, + "activation-plots": { + "title": "The plots", + "content": "Each activation function has its formula and its plot, and the animation tab shows how it transforms each value. ReLU, the most used in hidden layers, lets positive values through and cancels negative ones." + }, + "softmax": { + "title": "Softmax", + "content": "It goes in the last layer when classifying: it turns the outputs into probabilities, one per class, that add up to 1." + }, + "loss": { + "title": "Loss function", + "content": "It measures how wrong the network is, and it is what training tries to reduce. To choose between several classes, categorical cross-entropy is used." + }, + "loss-regression": { + "title": "Loss in regression", + "content": "To predict numbers, the most common is the mean squared error, which punishes large errors heavily. The mean absolute error, just below, treats them all the same." + }, + "metrics": { + "title": "Metrics", + "content": "They tell how well the network works in an easy way to understand, like accuracy: the percentage of correct answers. They do not change how it learns." + }, + "confusion-matrix": { + "title": "Confusion matrix", + "content": "A table that crosses the real class with the predicted one: that way you see not only how often the network is right, but which classes it confuses." + }, + "anchor": { + "title": "Links to each term", + "content": "Each card has its own link (#) to share it. The “More information” links in the playground bring you straight to the term you need." + }, + "end": { + "title": "Your turn", + "content": "Search for a term you do not know or scroll down to the activation functions and watch their animations. You can open this guide again whenever you want with the Guide button." + } + }, + "5-time-series": { + "common": { + "intro": { + "title": "A time series model", + "content": "On this page you try a trained network that forecasts the next values of a series from the previous ones. You will see how it forecasts the end of the series, which it did not see while training, whether it beats the simplest forecasts and what comes next." + }, + "model": { + "title": "The model", + "content": "The model card: how it forecasts the end of the series, which it did not see while training, compared with repeating the previous value or the one a season ago. Below, the description of the series." + }, + "model-summary": { + "title": "Model summary", + "content": "This button opens the summary of the network: its layers, how many neurons each one has and how many weights it adjusted while training. Below are the .n4l package, to download it, and the link to train your own network with this series." + }, + "dataset": { + "title": "The data", + "content": "The series as it is: one row per date, with the value that is predicted highlighted." + }, + "dataset-chart": { + "title": "The series", + "content": "In this tab you see it in a chart. The dashed line marks where the test part starts, which the network did not see while training." + }, + "dataset-windows": { + "title": "Prepared for the network", + "content": "Here you see how the series was prepared: how many previous values the network receives (the window), how they are scaled and the first examples it learned with." + }, + "instances": { + "title": "Values of the series", + "content": "With this selector you choose a value of the series and the form is filled with the previous ones. Those marked «test» belong to the part the network did not see." + }, + "form": { + "title": "The form", + "content": "These are the previous values, one per date: what the network uses to predict. You can change them to see how the forecast changes." + }, + "vector": { + "title": "What the network receives", + "content": "This is how they reach the network: scaled between 0 and 1 with the training minimum and maximum." + }, + "predict": { + "title": "Predict", + "content": "When you press this button, the network receives the scaled window and predicts the next value." + }, + "result": { + "title": "The result", + "content": "Here the predicted value appears. If you did not change the form, also the actual value and the error. Below, the network input step by step." + }, + "mode": { + "title": "One step or all at once", + "content": "One step ahead, each test value is predicted with the real values before it. All at once, from the end of training, each value is predicted with the ones already predicted: that is how the future is forecast, and errors add up. With «Close-up» you see only the test part." + }, + "chart": { + "title": "The forecast", + "content": "In grey, the real series; in orange, what the network predicts on the test part; and in purple, what comes next. You can also add the forecast on the training data." + }, + "errors": { + "title": "Better than the simplest thing?", + "content": "The network's average error (MAE and RMSE, in the units of the series) next to repeating the last value and repeating the last season. Below, whether the network beats them and whether it is off by much more on the test data than on the training data." + }, + "future": { + "title": "What comes next", + "content": "Choose how many values you want to forecast after the last one: they are forecast one after another, each with the ones already predicted, so the further away, the less reliable." + }, + "end": { + "title": "Done!", + "content": "You now know how to read a time series forecast. To train your own network with this series, use the «Train your network with this series» button." + } + } + } + }, + "loading-status": { + "page": "Loading the page…", + "slow": "It takes a little longer the first time: the libraries of this section are being downloaded. Your next visits will be faster.", + "model": "Loading the model…", + "model-progress": "Downloading the model: {{loaded}} of {{total}} MB", + "model-loaded": "Downloading the model: {{loaded}} MB", + "model-help": "It may take a while the first time: the model is downloaded from the internet." + }, + "report": { + "button": "Report", + "title": "Training report", + "created": "Created on {{date}}", + "print": "Print or save as PDF", + "back": "Back to training", + "network": "The network", + "hyperparameters": "Hyperparameters", + "results": "Training result", + "results-caption": "Values in the last epoch.", + "metric": "Metric", + "uploaded": "Uploaded dataset", + "empty": "There is no report yet: train a model and press “Report” in its row of the models table.", + "error-storage": "The browser doesn't allow saving the report (storage disabled or full)." + }, + "offline": { + "bar": "You're offline: you can keep using what you had already opened; the rest will be available when the connection is back." + }, + "n4l": { + "download": "Download .n4l", + "download-title": "Download this model with its data and texts in a .n4l file, to share it or open it later", + "local": { + "title": "Your .n4l packages", + "text": "Open a .n4l file (a model with its data and texts): it is saved in this browser and appears here.", + "drop": "Drag a .n4l file here or click to choose it", + "files": ".n4l file", + "version": "Version {{version}}, {{size}}", + "remove": "Remove", + "remove-title": "Remove “{{name}}” from this browser", + "imported": "“{{name}}” is ready: open it from its card.", + "error": "The file could not be opened:", + "open-title": "Open a .n4l file", + "how": "Where do they come from? On the page of each pre-trained model, “Download .n4l” gives you its package: the model, its data and its texts. After training, each model in the table is downloaded the same way, with the dataset you trained it with. You can also open one someone sends you: it only describes what it contains and how to use it, it has no code.", + "saved": "Saved in this browser", + "empty": "None yet: open a .n4l file above.", + "remove-confirm": "«{{name}}» will be removed from this browser; to use it again you will have to open its .n4l file again." + }, + "download-trained-title": "Download this model in a .n4l file, with the dataset, its preprocessing and its texts: open it later in “.n4l packages”", + "metrics": { + "title": "With data it has not seen", + "text": "With the 20% of the dataset set aside when training it, its average error is {{mae}}; always predicting the mean, the error would be {{baseline}}. R²: {{r2}} (1 would be always right; 0, the same as predicting the mean).", + "no-better": "It does not predict better than always giving the mean: with these data not much more can be known." + } + }, + "pagination": { + "label": "Table pages", + "first": "First page", + "previous": "Previous page", + "next": "Next page", + "last": "Last page", + "page": "Page {{page}}" + }, + "skip-to-content": "Skip to content", + "modal": { + "close": "Close" + }, + "model-summary-table": { + "layer": "Layer", + "output-shape": "Output shape", + "params": "Parameters", + "total": "Total parameters (weights adjusted during training)", + "trainable": "Of which trainable", + "batch-note": "“—” in the output shape is the number of examples that go in at once (the batch)." + }, + "chart-data": { + "show": "View the data", + "rows": "rows {{from}}–{{to}} of {{total}}", + "columns": { + "variable": "Variable", + "value": "Value", + "rows": "Rows", + "percent": "Percentage", + "bin": "interval centre", + "group": "Group", + "lower": "Lower fence", + "q1": "First quartile", + "median": "Median", + "q3": "Third quartile", + "upper": "Upper fence", + "mean": "Mean" + } + }, + "page-intro": { + "train": { + "text": "Here you design a neural network and train it with the chosen dataset. You can leave everything as it is and press “Train”.", + "steps": [ + "Look at the dataset: which columns it has and what has to be predicted.", + "Change the layers and the hyperparameters, if you want.", + "Press “Train” and watch how the network learns.", + "Try the model with examples and see what it pays attention to." + ] + }, + "review": { + "text": "This model is already trained: here you try it with examples and see what it pays attention to.", + "steps": [ + "Read what the model does and which data it was trained with.", + "Choose an example or type the values yourself.", + "Look at the prediction and, if you want, its explanation." + ] + }, + "detect": { + "text": "This model looks for things in an image. Turn on the camera or upload a photo, and the model will mark what it finds.", + "steps": [ + "Turn on the camera or upload a photo.", + "Look at what the model marks (it is also said in text).", + "If you want, ask for the explanation of what it found." + ] + } + }, + "model-code": { + "title": "See the code", + "summary": "The network you have designed, written in TensorFlow.js or in Keras (Python): the same one the application trains.", + "language": "Language of the code", + "copy": "Copy the code", + "copied": "Code copied", + "code": "The code in {{language}}", + "help-tfjs": "To use it in your project, install TensorFlow.js (npm install @tensorflow/tfjs) and prepare XTrain, yTrain, XTest and yTest as tensors, with the data already processed as on this page.", + "help-keras": "To use it in Python, install Keras (pip install keras tensorflow) and prepare X_train, y_train, X_test and y_test as NumPy arrays, with the data already processed as on this page.", + "data-classification": "X: the attributes of each row, already processed (scaled); y: its class in one-hot", + "data-regression": "X: the attributes of each row, already processed (scaled); y: the value to predict", + "data-image": "X: the images, with values from 0 to 1; y: their class in one-hot", + "data-series": "X: the windows with the {{window}} previous values; y: the next value of each window" + }, + "training-prediction": { + "title": "Before training, what do you think will happen?", + "optional": "(optional)", + "chosen": "Your prediction: {{prediction}}", + "help": "Choose what you expect: when it finishes, we will compare it with what really happened.", + "none": "I don't know", + "options": { + "good": "It will learn well", + "still-improving": "It will need more epochs: it will still be improving at the end", + "overfitting": "It will learn the data by heart (overfitting)", + "not-learning": "It will hardly learn", + "unstable": "It will jump up and down (unstable)", + "diverged": "The loss will blow up" + }, + "right": "You predicted: \"{{prediction}}\". You got it right!", + "wrong": "You predicted: \"{{prediction}}\". This time something else happened: you will see what and why below." } } \ No newline at end of file diff --git a/public/locales/es/translation.json b/public/locales/es/translation.json index 660e1a4..fd79d7e 100644 --- a/public/locales/es/translation.json +++ b/public/locales/es/translation.json @@ -1,22 +1,22 @@ { "ui": { "blur": { - "enable": "Aplicar blur a regiones enmascaradas", - "kernelSize": "Tamaño kernel blur (impar)", - "passes": "Veces de blur (passes)" + "enable": "Desenfocar las zonas tapadas (en vez de pintarlas de un color)", + "kernelSize": "Tamaño del desenfoque (impar)", + "passes": "Veces que se desenfoca" }, "explain": { - "title": "Explicabilidad (SHAP)", + "title": "Explicabilidad del modelo", "method": "Método", "about-lrp": "LRP (propagación de la relevancia capa a capa) recorre la red hacia atrás desde la clase predicha y reparte su relevancia hasta los píxeles de entrada. El mapa de calor muestra qué zonas de la imagen sostienen la predicción del modelo.", "about-shap": "Dividimos la imagen en segmentos (superpíxeles) y medimos la importancia de cada uno tapándolo o dejándolo visible en muchas combinaciones distintas, observando cómo cambia la predicción. El mapa de calor colorea cada segmento según cuánto aporta a la predicción.", "perturbationSamples": "Muestras de Perturbación:", - "gridSide": "Zonas por lado (la imagen se divide en N×N segmentos)", - "nSamples": "nSamples (SHAP)", + "gridSide": "Zonas por lado", + "nSamples": "Combinaciones que se prueban", "mask": "Máscara (SHAP)", - "maskRange": "Máscara (0..1)", + "maskRange": "Color de las zonas tapadas", "calculating": "Calculando...", - "explainPrediction": "Explicar Predicción", + "explainPrediction": "Explicar la predicción", "hideExplanation": "Ocultar explicación", "noData": "No hay datos de explicación disponibles.", "class": "Clase {{index}}", @@ -65,8 +65,25 @@ "presence-only": "Este modelo solo responde «hay cara» o «no hay cara» (0 o 100 %), así que la explicación muestra qué necesita ver como mínimo para encontrar una cara: suele bastar con la piel.", "body-parts": "Se explica la confianza en la pose completa y en cada parte del cuerpo. El modelo necesita encontrar primero a la persona, así que zonas del tronco también le ayudan a localizar los brazos o las piernas.", "wrong-prediction": "¿El modelo se ha equivocado? La explicación sigue siendo útil: muestra en qué se ha fijado para llegar a esa respuesta." - } - } + }, + "waiting-for-prediction": "Haz una predicción para poder explicarla.", + "waiting-for-model": "Entrena un modelo para poder explicar sus predicciones.", + "gridSide-help": "La imagen se divide en N × N trozos: con más, la explicación es más fina, pero tarda más.", + "nSamples-help": "Cuántas veces se tapan zonas distintas para medir lo que aporta cada una (SHAP).", + "maskRange-help": "De 0 (negro) a 1 (blanco).", + "bar-description": "Valor SHAP de cada variable (cuánto empuja la predicción hacia arriba o hacia abajo), de la que más influye a la que menos: {{values}}.", + "beeswarm-description": "Valores SHAP de {{count}} ejemplos para cada variable. Las variables, de la que más influye a la que menos (media del valor absoluto): {{features}}.", + "bar-data": "Valor SHAP de cada variable", + "beeswarm-data": "Valores SHAP de cada variable en {{count}} ejemplos", + "variable": "Variable", + "mean-abs": "Media del valor absoluto", + "min": "Mínimo", + "max": "Máximo" + }, + "take-screenshot": "Hacer una captura", + "table-scroll-hint": "Desliza en horizontal para ver todas las columnas →", + "maximize": "Maximizar", + "minimize": "Minimizar" }, "welcome": "Bienvenido a Nets4Learning", "welcome-2": "Para continuar selecciona una de estas disciplinas", @@ -139,7 +156,7 @@ "equations": { "title": "Fórmulas", "title-metrics": "Funciones de métricas | Ecuaciones", - "title-losses": "Funciones de perdida | Ecuaciones", + "title-losses": "Funciones de pérdida | Ecuaciones", "title-activation": "Funciones de activación | Ecuaciones", "title-optimization": "Funciones de optimización | Ecuaciones", "loss-functions": { @@ -211,32 +228,110 @@ "dataset-web": "Web original", "dataset-reference": "Referencia", "download-dataset-car": "Conjunto de datos de evaluación de coches", - "download-dataset-hepatitis-c": "Conjunto de datos de hepatitis C", + "download-dataset-hepatitis-c": "Hepatitis C", "download-dataset-iris": "Conjunto de datos de iris", - "download-dataset-titanic": "Conjunto de datos de supervivencia del titanic*", - "download-dataset-new-thyroid": "Conjunto de datos de new-thyroid", - "download-dataset-wine": "Conjunto de datos de vino", - "download-dataset-ecoli": "Conjunto de datos de ecoli", + "download-dataset-titanic": "Supervivencia en el Titanic", + "download-dataset-new-thyroid": "Tiroides (New Thyroid)", + "download-dataset-wine": "Variedades de vino", + "download-dataset-ecoli": "E. coli", "download": { "dataset": { "1-regression": { "salary": "Conjunto de datos de salarios", "auto-mpg": "Conjunto de datos consumo de combustible", "housing-prices": "Conjunto de datos precios de casas", - "breast-cancer-original": "Conjunto de datos Breast Cancer Wisconsin", - "breast-cancer-wdbc": "Conjunto de datos Breast Cancer Wisconsin (Diagnostic)", - "breast-cancer-wpbc": "Conjunto de datos Breast Cancer Wisconsin (Prognostic)", + "breast-cancer-original": "Cáncer de mama (Wisconsin)", + "breast-cancer-wdbc": "Cáncer de mama: diagnóstico (WDBC)", + "breast-cancer-wpbc": "Cáncer de mama: pronóstico (WPBC)", "student-performance-mathematics": "Conjunto de datos de estudiantes de matemáticas", "student-performance-portuguese": "Conjunto de datos de estudiantes de Portugués", "wine-red": "Conjunto de datos de vino tinto", "wine-white": "Conjunto de datos de vino blanco" } } + }, + "dataset-info": "Datos", + "extra-title": "Otros conjuntos de datos", + "extra-text": "No los usa ningún modelo de la aplicación: sirven para practicar la preparación de los datos. Con «Entrenar» se cargan en la página de subir datos, donde eliges la columna objetivo y qué hacer con cada una.", + "dataset-details": "Información", + "show-info": "Ver información", + "variables": { + "title": "Variables", + "name": "Variable", + "role": "Rol", + "type": "Tipo", + "description": "Descripción", + "units": "Unidades", + "missing": "Valores ausentes", + "roles": { + "ID": "Identificador", + "Feature": "Característica", + "Target": "Objetivo", + "Other": "Otra" + }, + "types": { + "Integer": "Entero", + "Continuous": "Continuo", + "Categorical": "Categórico", + "Binary": "Binario", + "Date": "Fecha" + }, + "note": "El rol, el tipo, la descripción (en inglés) y las unidades vienen de la ficha del conjunto de datos en su fuente. Los valores ausentes se cuentan en los ficheros que se descargan aquí.", + "images": "Este conjunto de datos está formado por imágenes, así que no tiene tabla de variables." + }, + "analyze-action": "Analizar", + "analyze-title": "Abrir «{{name}}» en el análisis exploratorio de datos (AED)", + "data": { + "title": "Datos", + "describe": "Estadísticas", + "file": "Fichero", + "error": "No se ha podido leer el CSV.", + "describe-help": "Una fila por cada columna numérica: cuántos valores tiene (count), su media (mean), su desviación típica (std), el mínimo, los cuartiles y el máximo." + }, + "intro": "Los conjuntos de datos de Nets4Learning, por tarea. Entrena con ellos (o agrúpalos), prueba el modelo que ya está entrenado, ábrelos en el análisis exploratorio de datos (AED) o descárgalos para usarlos en otras herramientas.", + "models-title": "Listos para entrenar", + "models-text": "Los usan los modelos de la aplicación: ya vienen preparados, así que eliges uno y entrenas.", + "train": "Entrenar", + "try-model": "Probar el modelo", + "files": "Ficheros", + "summary": { + "extra": { + "hepatitis-c": "Análisis de sangre de donantes y de pacientes para distinguir la hepatitis C, la fibrosis y la cirrosis.", + "ecoli": "Dónde está una proteína dentro de la bacteria E. coli: ocho clases, algunas con muy pocos casos.", + "new-thyroid": "Si el tiroides funciona con normalidad, de más o de menos, a partir de cinco análisis de laboratorio.", + "wine": "Tres variedades de vino italiano según 13 componentes químicos: es fácil, pero las columnas tienen escalas muy distintas.", + "titanic": "Quién sobrevivió al hundimiento del Titanic según su clase, su sexo, su edad y la familia que viajaba con él.", + "breast-cancer-wisconsin": "Si un tumor de mama es benigno o maligno a partir de nueve rasgos de sus células (con algunos valores ausentes).", + "wpbc": "Si un cáncer de mama vuelve a aparecer, a partir de medidas del tumor y de sus células: solo 198 casos.", + "wdbc": "Si un tumor de mama es benigno o maligno a partir de 30 medidas de los núcleos de sus células en una imagen." + }, + "clustering": { + "breast-cancer-wisconsin": "Nueve rasgos de las células de 699 tumores, del 1 al 10: con dos grupos, casi coinciden con los benignos y los malignos.", + "wdbc": "30 medidas de los núcleos de las células de 569 tumores: con dos grupos, k-means separa bastante bien los benignos de los malignos.", + "ecoli": "Siete puntuaciones de 336 proteínas y ocho lugares de la bacteria, algunos con dos o tres casos: esos grupos pequeños se pierden.", + "hepatitis-c": "Análisis de sangre de 589 personas: la pureza sale alta solo porque casi todos son donantes, pero el índice de Rand dice la verdad: los grupos no se parecen a los diagnósticos." + } + }, + "clustering": { + "examples-title": "Listos para agrupar", + "examples-text": "Traen las clases reales, pero k-means no las usa: agrupa con las demás columnas y al final compara los grupos con ellas.", + "extra-text": "Otros conjuntos del proyecto para agrupar: con «Agrupar» se cargan como si los hubieras subido. No todos se parecen igual a sus clases, y eso también enseña algo.", + "run": "Agrupar" + }, + "time-series": { + "examples-title": "Series temporales clásicas", + "examples-text": "En una serie temporal cada fila es un momento (un día, un mes…) y el orden importa: los valores pasados sirven para predecir los siguientes, así que las filas no se barajan. Cada una tiene un patrón distinto: tendencia, estaciones o ciclos." } }, "dataframe-original": "DataFrame | Original", "dataframe-form": "DataFrame | Formulario de procesamiento", "dataframe": { + "table": { + "target": "{{column}}: columna objetivo, la que se predice o clasifica", + "shape": "{{rows}} filas × {{columns}} columnas", + "scroll-rows": "desplázate dentro de la tabla para ver el resto", + "column": "Columna" + }, "dataframe": { "title": "DataFrame | Conjunto de datos" }, @@ -272,6 +367,8 @@ "no-numeric": "No hay columnas numéricas que describir: todas las columnas son categóricas." }, "query": { + "error": "La consulta no es válida: {{message}}", + "no-rows": "Ninguna fila cumple la consulta.", "title": "DataFrame | Consulta", "description": { "0": "Consulta el DataFrame por el resultado de una comparación lógica o máscara booleana.", @@ -279,15 +376,208 @@ "title": "Descripción" }, "query": "Consulta", - "link": "Consulta más información en el siguiente enlace" + "link": "Consulta más información en el siguiente enlace", + "column": "Columna" }, "plot": { "link": "Consulta más información en el siguiente enlace" } }, "dataframe-processed": "DataFrame | Procesado", - "dataframe-scatterplot": { - "title": "Gráfico de dispersión" + "dataset-process": { + "tabs": { + "original": "1. Datos originales", + "form": "2. Cómo procesarlos", + "processed": "3. Datos procesados" + }, + "original-help": "{{rows}} filas y {{columns}} columnas, tal como están en el fichero. La columna resaltada es la que se va a predecir.", + "classification": { + "target-title": "¿Qué columna es la clase?", + "target-help": "La red aprenderá a decir a qué clase pertenece cada fila. Suele ser la última columna.", + "target-badge": "Clase", + "target-transform": "Cada clase se convierte en un número para entrenar.", + "summary_one": "Entrará {{count}} columna en la red y se predice «{{target}}» ({{classes}} clases), con escalado {{scaler}}.", + "summary_other": "Entrarán {{count}} columnas en la red y se predice «{{target}}» ({{classes}} clases), con escalado {{scaler}}." + }, + "regression": { + "target-title": "¿Qué número quieres predecir?", + "target-help": "La red aprenderá a calcular el valor de esta columna a partir de las demás. Tiene que ser numérica.", + "target-badge": "Se predice", + "target-transform": "Se usa tal cual: es el número que se predice.", + "summary_one": "Entrará {{count}} columna en la red y se predice «{{target}}», con escalado {{scaler}}.", + "summary_other": "Entrarán {{count}} columnas en la red y se predice «{{target}}», con escalado {{scaler}}." + }, + "target-classes": "«{{name}}» tiene {{count}} clases ({{sample}}): la red tendrá {{count}} neuronas de salida.", + "target-too-many": "Son {{count}} clases, demasiadas para una clasificación: ¿seguro que es esta columna? Si es un número continuo, quizá encaje mejor la regresión.", + "target-range": "«{{name}}» va de {{min}} a {{max}}, con una media de {{mean}}.", + "target-not-numeric": "«{{name}}» es una columna de texto y la regresión predice números: elige una numérica o usa la clasificación tabular.", + "scaler-title": "Escalado de las entradas", + "scaler-help": "Cada columna tiene su escala (años, euros, centímetros). Escalarlas hace que todas pesen parecido y que la red aprenda mejor.", + "scalers": { + "min-max-scaler": { + "name": "Min-Max", + "help": "Lleva cada columna al intervalo de 0 a 1." + }, + "standard-scaler": { + "name": "Estándar", + "help": "Resta la media y divide entre la desviación típica: media 0 y desviación 1. Aguanta mejor los valores extremos." + } + }, + "columns-title": "Columnas de entrada", + "columns-help": "Elige qué columnas usa la red y cómo se convierten en números. Las de texto se codifican como categorías: un número por cada valor distinto.", + "use": "Usar", + "types": { + "int32": "Entero", + "float32": "Decimal", + "string": "Texto", + "boolean": "Sí/no", + "datetime": "Fecha" + }, + "transforms": { + "int32": "Como número entero", + "float32": "Como número decimal", + "label-encoder": "Como categoría (un número por valor)", + "drop": "No se usa", + "string": "Como texto", + "boolean": "Como sí/no", + "one-hot-encoder": "Una columna por valor (one-hot)" + }, + "transform-of": "Cómo se convierte «{{name}}»", + "distinct_one": "{{count}} valor: {{sample}}", + "distinct_other": "{{count}} valores distintos, p. ej. {{sample}}", + "range_one": "siempre {{min}}", + "range_other": "de {{min}} a {{max}} ({{count}} valores distintos)", + "no-inputs": "No hay ninguna columna de entrada: activa al menos una.", + "submit": "Procesar los datos", + "done_one": "Datos listos: {{rows}} filas, {{count}} columna de entrada y «{{target}}» para predecir. Ya puedes diseñar la red más abajo.", + "done_other": "Datos listos: {{rows}} filas, {{count}} columnas de entrada y «{{target}}» para predecir. Ya puedes diseñar la red más abajo.", + "view": "Qué datos ver", + "views": { + "scaled": "Escalados", + "encoded": "Codificados", + "scaled-help": "Las columnas de entrada ya escaladas: exactamente lo que recibe la red.", + "encoded-help": "Cada categoría ya convertida en un número, antes de escalar; debajo de cada columna, cómo se ha convertido." + } + }, + "dataset-view": { + "file": "Fichero", + "original": "Original", + "encoded": "Codificado", + "scaled": "Escalado (entrada de la red)", + "original-help": "Los datos tal como están en el fichero: {{rows}} filas y {{columns}} columnas. La columna resaltada, «{{target}}», es la que se predice.", + "encoded-help": "Cada categoría de texto ya es un número y no están las columnas que no se usan. Todavía sin escalar.", + "scaled-help": "Las {{columns}} columnas de entrada escaladas ({{scaler}}): exactamente lo que recibe la red. Al final, resaltado, lo que tiene que predecir, «{{target}}», que no se escala.", + "statistics": "Estadísticas de cada columna" + }, + "stored-models": { + "restored_one": "Se ha recuperado 1 modelo que entrenaste antes con este conjunto de datos: los modelos se guardan en este navegador para no perderlos al recargar.", + "restored_other": "Se han recuperado {{count}} modelos que entrenaste antes con este conjunto de datos: los modelos se guardan en este navegador para no perderlos al recargar.", + "delete-ask": "Borrar los modelos de este conjunto", + "confirm": "¿Seguro? Se borrarán los modelos guardados de este conjunto y saldrán de la tabla.", + "delete": "Sí, borrarlos", + "cancel": "Cancelar" + }, + "training-diagnosis": { + "title": "Cómo ha ido el entrenamiento del modelo {{model}}", + "diverged": { + "title": "La pérdida se ha disparado", + "text": "Desde la época {{epoch}} la pérdida ya no es un número (NaN): los pesos han crecido sin control.", + "tip": "Baja la tasa de aprendizaje, por ejemplo a la décima parte, y vuelve a entrenar." + }, + "worse": { + "title": "La pérdida ha empeorado", + "text": "La pérdida ha subido de {{first}} a {{last}}: los pesos dan saltos tan grandes que se pasan de largo.", + "tip": "Baja la tasa de aprendizaje y vuelve a entrenar." + }, + "unstable": { + "title": "La pérdida va a saltos", + "text": "En la segunda mitad del entrenamiento, la pérdida sube y baja mucho de una época a otra (entre {{min}} y {{max}}): así no se puede saber si está aprendiendo de verdad.", + "tip": "Baja la tasa de aprendizaje. Si sigue igual, aumenta el porcentaje de datos de prueba: con pocos, cada época cambia mucho." + }, + "not-learning": { + "title": "Apenas ha aprendido", + "text": "La pérdida solo ha bajado de {{first}} a {{last}}.", + "tip": "Prueba a subir la tasa de aprendizaje o las épocas, o a dar más neuronas a las capas. Revisa también que la última capa tenga la activación adecuada." + }, + "overfitting": { + "title": "Se está aprendiendo los datos de memoria (sobreajuste)", + "text": "La pérdida con los datos de prueba fue mínima en la época {{epoch}} ({{min}}) y desde entonces ha subido hasta {{last}}, mientras la de entrenamiento seguía bajando.", + "tip": "Entrena menos épocas (unas {{epoch}}) o usa una red más pequeña." + }, + "still-improving": { + "title": "Seguía mejorando", + "text": "En {{epochs}} épocas la pérdida bajó de {{first}} a {{last}}, y al final todavía bajaba.", + "tip": "Con más épocas probablemente aprendería más: prueba a subirlas." + }, + "good": { + "title": "Ha aprendido bien", + "text": "La pérdida bajó de {{first}} a {{last}}, y con los datos de prueba se quedó en {{validation}}.", + "tip": "Para comparar, cambia una sola cosa (las neuronas, la tasa de aprendizaje…) y vuelve a entrenar." + } + }, + "layer-check": { + "title-error": "Revisa las capas: así no se puede entrenar", + "title-warning": "Las capas se pueden mejorar", + "error": "Error", + "warning": "Aviso", + "params": { + "units": "neuronas", + "kernelSize": "tamaño del kernel", + "filters": "filtros", + "poolSize": "tamaño del pooling", + "strides": "paso (strides)" + }, + "param": { + "text": "Capa {{layer}}: el valor de «{{param}}» no es válido.", + "fix": "Poner {{value}}" + }, + "hidden-softmax": { + "text": "Capa {{layer}}: softmax reparte el 100 % entre sus neuronas y solo tiene sentido en la salida; en una capa oculta frena el aprendizaje.", + "fix": "Usar ReLU" + }, + "output-units": { + "text": "La última capa tiene {{units}} neuronas, pero hay {{classes}} clases: hace falta una neurona por clase.", + "fix": "Poner {{classes}}" + }, + "output-activation": { + "text": "La última capa usa {{activation}}; con {{expected}}, sus salidas son la probabilidad de cada clase (suman 1).", + "fix": "Usar {{expected}}" + }, + "output-missing": { + "text": "La red tiene que terminar en una capa Dense con {{classes}} neuronas (una por clase) y Softmax.", + "fix": "Añadirla al final" + }, + "after-flatten": { + "text": "Capa {{layer}}: después de Flatten la imagen ya es una lista de números, y {{type}} necesita la imagen en dos dimensiones.", + "fix": "Quitar la capa" + }, + "flatten-again": { + "text": "Capa {{layer}}: los datos ya están aplanados, este Flatten sobra.", + "fix": "Quitar la capa" + }, + "dense-before-flatten": { + "text": "Capa {{layer}}: una capa Dense recibe una lista de números; antes hace falta un Flatten que aplane la imagen.", + "fix": "Añadir Flatten antes" + }, + "too-small": { + "text": "Capa {{layer}}: a esas alturas la imagen mide {{height}}×{{width}} y no cabe la ventana de {{window}}×{{window}} de {{type}}.", + "fix": "Quitar la capa" + }, + "recurrent-after-dense": { + "text": "Capa {{layer}}: {{type}} lee una secuencia valor a valor, pero después de una capa Dense solo queda una lista de números. Las capas recurrentes van antes que las Dense.", + "fix": "Poner las recurrentes al principio" + }, + "all-fixed": "Las capas ya no tienen nada que revisar" + }, + "download-consent": { + "title": "Este modelo descarga unos {{mb}} MB", + "reason": { + "save-data": "Tu navegador tiene activado el ahorro de datos: se descarga solo si lo pides.", + "slow": "Tu conexión parece lenta: la descarga puede tardar un rato.", + "always": "En Ajustes has pedido que se pregunte antes de descargar un modelo." + }, + "accept": "Descargar ({{mb}} MB)", + "settings": "Puedes cambiarlo en Ajustes." }, "model-selector": { "title": "Selector de modelos" @@ -296,7 +586,13 @@ "select-dataset": { "title": "Selecciona el conjunto de datos", "info": "Selecciona el conjunto de datos" - } + }, + "number": { + "range": "Escribe un número entero entre {{min}} y {{max}}.", + "at-least": "Escribe un número entero de {{min}} o más.", + "in-use": "Mientras tanto se usa {{value}}." + }, + "cancel": "Cancelar" }, "preprocessing": { "title": "Preprocesamiento", @@ -310,9 +606,27 @@ "predict": "Predecir", "cookies-policies": { "title": "Política de cookies", - "text-0": "Este sitio web utiliza cookies para mejorar la experiencia del usuario y analizar el uso de la aplicación. Las cookies son pequeños archivos de texto que se almacenan en su dispositivo cuando visita nuestro sitio web. Estas cookies nos ayudan a entender cómo los usuarios interactúan con nuestro sitio web, qué páginas son las más visitadas y cómo podemos mejorar la experiencia del usuario.", - "text-1": "No realizamos ningún tratamiento de los datos del usuario con fines publicitarios. Utilizamos las cookies únicamente para fines analíticos y para mejorar la funcionalidad del sitio web. Si continúa utilizando nuestro sitio web, entendemos que está de acuerdo con el uso de cookies tal como se describe en nuestra política de privacidad.", - "accept": "Aceptar" + "banner-title": "¿Nos ayudas a mejorar Nets4Learning?", + "accept": "Aceptar", + "banner": "Nets4Learning es un proyecto docente del grupo SIMIDAT de la Universidad de Jaén. Si aceptas las cookies de Google Analytics, sabremos de forma anónima qué modelos, conjuntos de datos y secciones se usan y qué falla, para decidir qué mejorar. Solo se activan si las aceptas, y puedes cambiar de opinión cuando quieras.", + "more-info": "Más información", + "reject": "Rechazar", + "settings": "Configuración", + "close": "Cerrar sin cambiar nada", + "details": "Qué se mide y qué no", + "measured-title": "Se mide", + "measured": [ + "Las páginas que visitas y el tiempo que pasas en ellas.", + "Qué modelos y conjuntos de datos usas y qué botones pulsas.", + "Los entrenamientos (épocas, optimizador, cuánto tardan), las predicciones y lo que tardan en cargar los modelos.", + "Los errores que aparecen, el idioma, el tema y el backend de TensorFlow.js." + ], + "never-title": "Nunca se envía", + "never": [ + "Tus ficheros, sus nombres ni sus datos; tus dibujos ni la imagen de la cámara.", + "Datos personales: no hay cuentas ni formularios.", + "Nada para publicidad: las señales publicitarias de Google están desactivadas." + ] }, "error": { "load-json-csv": "Error, no se ha podido cargar el fichero", @@ -328,13 +642,22 @@ "layers-length": "Debes tener al menos una capa con el número de neuronas y su función de activación", "parsing-csv": "Error en la preparación del conjunto de datos", "file-not-valid": "Error, fichero no válido", - "metrics-length": "Error, el número de métricas debe estar entre 1 y 10" + "metrics-length": "Error, el número de métricas debe estar entre 1 y 10", + "need-model": "Primero debes crear y entrenar un modelo", + "dataset-not-processed": "El conjunto de datos no está procesado", + "model-not-valid": "El modelo no es válido para estos datos", + "model-compile": "No se ha podido compilar el modelo. Revisa la consola para ver los detalles.", + "option-not-valid": "Opción no válida", + "prediction": "No se ha podido hacer la predicción", + "load-dataset": "No se ha podido cargar el conjunto de datos." }, "warning": { "the-first-layer-need-to-be-__value__": "Advertencia, la primera capa debe ser de tipo {{value}}", "not-more-layers": "Advertencia, no se pueden añadir más capas", "error-layers": "Advertencia, se debe tener entre 1 y 10 capas", - "need-a-model": "Advertencia, antes debes de crear y entrenar el modelo." + "need-a-model": "Advertencia, antes debes de crear y entrenar el modelo.", + "first-layer-cant-be-removed": "La primera capa no se puede eliminar", + "first-layer-cant-be-changed": "La primera capa no se puede cambiar" }, "success": { "file-upload": "Archivo cargado correctamente" @@ -360,7 +683,8 @@ "model-train-error": "Error al entrenar el modelo", "prediction": "La predicción es: {{index}}", "file-upload-success": "Fichero cargado con éxito", - "file-upload-error-incorrect-format": "El fichero no se ha podido cargar, no es el formato correcto" + "file-upload-error-incorrect-format": "El fichero no se ha podido cargar, no es el formato correcto", + "close": "Cerrar el aviso" }, "header": { "language": "Idioma", @@ -368,9 +692,25 @@ "glossary": "Glosario", "home": "Inicio", "datasets": "Conjuntos de datos", - "theme": "Tema", "dataframe": "DataFrame", - "analyze": "AED" + "analyze": "AED", + "theme": "Tema", + "theme-light": "Claro", + "theme-dark": "Oscuro", + "backend": "Backend", + "backend-default": "por defecto", + "backend-unavailable": "no disponible", + "backend-software": "por software, lento", + "backend-error": "No se ha podido cambiar a {{backend}}", + "backend-error-fallback": "Este navegador no puede usarlo. TensorFlow.js sigue usando {{backend}}.", + "menu": "Menú", + "tasks": "Tareas", + "lab": "Laboratorio 2D", + "packages": "Paquetes .n4l", + "packages-saved_one": "{{count}} paquete guardado en este navegador", + "packages-saved_other": "{{count}} paquetes guardados en este navegador", + "github": "GitHub (se abre en otra pestaña)", + "main-navigation": "Navegación principal" }, "footer": { "description-app": "Plataforma Web para el diseño y ejecución de modelos de aprendizaje profundo.", @@ -381,7 +721,12 @@ "terms": "Términos y condiciones", "contribute": "Contribuye", "documentation": "Documentación", - "version": "Versión" + "version": "Versión", + "cookies": "Preferencias de cookies", + "links": "Enlaces", + "institutions": "Instituciones", + "settings": "Configuración", + "accessibility": "Accesibilidad" }, "drag-and-drop": { "label-files-one": "Fichero:", @@ -390,11 +735,23 @@ "binary": "Añada el fichero binario", "json": "Añada el fichero JSON", "csv": "Añada el fichero CSV", - "csv-json": "Introduce el fichero de datos plantilla.json" + "csv-json": "Introduce el fichero de datos plantilla.json", + "dataset": "Añada el fichero de datos (CSV, ARFF, JSON, JSONL o Parquet)", + "choose-file": "Elegir fichero", + "choose-files": "Elegir ficheros", + "errors": { + "file-invalid-type": "Formato no admitido", + "file-too-large": "El fichero es demasiado grande", + "file-too-small": "El fichero es demasiado pequeño", + "too-many-files": "Solo se puede subir un fichero" + } }, "custom-canvas-drawer": { - "validate": "Validar", - "clear": "Limpiar" + "validate": "Clasificar", + "clear": "Borrar", + "canvas": "Lienzo para dibujar con el ratón, un lápiz o el dedo", + "preview": "Lo que recibe la red: el dibujo en 28 × 28 píxeles", + "alternative": "Si no puedes dibujar, clasifica uno de los ejemplos o una imagen de prueba." }, "table": { "dataset": "Conjunto de datos" @@ -407,7 +764,8 @@ "tabular-classification": "Clasificación tabular", "regression": "Regresión", "object-detection": "Identificación de objetos", - "image-classification": "Clasificador de imágenes" + "image-classification": "Clasificador de imágenes", + "time-series": "Series temporales" }, "graphic-red": { "input": "Entrada", @@ -420,1117 +778,572 @@ "text": "Introduce separado por punto y coma los valores.", "items": "(parámetro-1; parámetro-2; parámetro-3; ... ;parámetro-n)." } + } + }, + "2-object-detection": { + "interface": { + "process-webcam": { + "title": "Reconocimiento en tiempo real", + "sub-title": "Webcam", + "button": "Webcam", + "device": "Cámara" + }, + "process-image": { + "title": "Procesamiento de imágenes", + "sub-title": "Subida de imágenes" + }, + "device-info": { + "camera": "Cámara en uso", + "camera-off": "Activa la webcam para ver los datos de la cámara.", + "name": "Nombre", + "resolution": "Resolución", + "frames": "Imagen recibida", + "aspect": "Proporción", + "frame-rate": "Fotogramas por segundo", + "facing": "Cámara", + "facing-user": "Frontal", + "facing-environment": "Trasera", + "resize-mode": "Ajuste de resolución", + "displayed": "Tamaño en pantalla", + "mirrored": "Imagen en espejo", + "state": "Estado", + "state-live": "Emitiendo", + "state-ended": "Detenida", + "device-id": "Id. del dispositivo", + "capabilities": "Capacidades de la cámara", + "capabilities-none": "El navegador no informa de las capacidades de la cámara.", + "detection": "Detección", + "model": "Modelo", + "predictions": "Predicciones por segundo", + "prediction-time": "Tiempo por predicción", + "limit": "Límite", + "limit-value": "{{fps}} por segundo", + "backend": "Backend de TensorFlow.js", + "tensors": "Memoria de TensorFlow.js", + "devices": "Cámaras disponibles", + "devices-none": "No se ha encontrado ninguna cámara.", + "unnamed": "Cámara {{index}}", + "in-use": "en uso", + "browser": "Navegador y sistema", + "browser-name": "Navegador", + "platform": "Sistema", + "mobile": "Móvil", + "architecture": "Arquitectura", + "cores": "Núcleos de CPU", + "memory": "Memoria (aprox.)", + "language": "Idioma", + "permission": "Permiso de la cámara", + "permission-granted": "Concedido", + "permission-denied": "Denegado", + "permission-prompt": "Sin conceder todavía", + "webview": "WebView", + "secure": "Conexión segura (HTTPS)", + "user-agent": "User agent", + "screen": "Pantalla y GPU", + "screen-size": "Pantalla", + "window": "Ventana", + "pixel-ratio": "Densidad de píxeles", + "orientation": "Orientación", + "gpu": "GPU", + "webgl2": "WebGL 2", + "software": "Renderizado por software", + "yes": "Sí", + "no": "No" + }, + "detections": { + "nothing": "No se detecta nada", + "detected": "Se detecta: {{list}}", + "waiting": "Esperando a la primera detección…", + "announce": "Decir lo que se detecta" + } }, - "car": { - "title": "CAR - Clasificación de coches", + "face-detection": { + "title": "FaceDetector - Geometría facial", "description": { - "text-1": "El conjunto de datos Car Evaluation permite evaluar vehículos a través de la siguiente estructura", - "text-2": "Para obtener más información acerca de este conjunto de datos visita el repositorio ics.uci.edu.", - "details-1": { - "title": "Información", - "list": { - "1": "buying: Precio de compra.", - "2": "maint: Costo del mantenimiento.", - "3": "doors: Número de puertas.", - "4": "persons: Número de plazas.", - "5": "lug_boot: Tamaño del maletero.", - "6": "safety: Seguridad estimada del vehículo." - } - }, - "details-2": { + "text-0": "Este modelo es capaz de reconocer a partir de una imagen o vídeo de entrada diferentes partes de la cara, como los ojos, orejas, nariz y boca.", + "details-input": { "title": "Datos de entrada", - "text-1": "Características del coche", "list": { - "1": "buying: vhigh, high, med, low.", - "2": "maint: vhigh, high, med, low.", - "3": "doors: 2, 3, 4, 5more.", - "4": "persons: 2, 4, more.", - "5": "lug_boot: small, med, big.", - "6": "safety: low, med, high." + "0": "Imagen o vídeo." } }, - "details-3": { + "details-output": { "title": "Datos de salida", - "text-1": "Aceptación del vehículo", "list": { - "1": "UNACC: Inaccesible", - "2": "ACC: Accesible", - "3": "GOOD: Bien", - "4": "VGOOD: Muy bien" + "0": "Mismo elemento de entrada con una serie de puntos que delimitan las diferentes partes de la cara." } }, - "details-4": { + "details-references": { "title": "Referencias", "list": { - "1": "Conjunto de datos" + "0": "Entrada del modelo en el repositorio de tensorflow" } } }, - "html-example": { - "text": "Introduce los valores correspondientes a el coche que se va a evaluar:", - "items": "(buying; maint; doors; persons; lug_boot; safety)", - "examples": "Ejemplos:" + "render": { + "face": "Cara", + "face-number": "Cara {{number}}", + "eye-right": "Ojo derecho", + "eye-left": "Ojo izquierdo", + "nose": "Nariz", + "mouth": "Boca", + "ear-right": "Oreja derecha", + "ear-left": "Oreja izquierda" } }, - "iris": { - "title": "IRIS - Clasificación de iris", + "face-mesh": { + "title": "FaceMesh - Malla facial", "description": { - "text-1": "El conjunto de datos de Iris-Data permite detectar que tipo de planta iris es a partir de altitud y longitud de su pétalo y sépalo.", - "details-1": { + "text-0": "Este modelo a partir de una imagen o vídeo de entrada, es capaz de reconocer diferentes puntos de la cara para finalmente hacer una malla de la misma.", + "details-input": { "title": "Datos de entrada", "list": { - "1": "Longitud del sépalo: continuo", - "2": "Anchura del sépalo: continuo", - "3": "Longitud del pétalo: continuo", - "4": "Anchura del pétalo: continuo" + "0": "Imagen o vídeo." } }, - "details-2": { + "details-output": { "title": "Datos de salida", "list": { - "1": "0: Iris Setosa", - "2": "1: Iris Versicolor", - "3": "2: Iris Virginica" + "0": "Mismo elemento de entrada con una serie de puntos que delimitan las diferentes partes de la cara." } }, - "details-3": { + "details-references": { "title": "Referencias", "list": { - "1": "Conjunto de datos" + "0": "Entrada del modelo en el repositorio de tensorflow" } } }, - "html-example": { - "text": "Introduce los valores correspondientes a la flor que se va a evaluar:", - "items": "(longitud sépalo; anchura sépalo; longitud pétalo; anchura pétalo).", - "examples": "Ejemplos:" + "render": { + "face": "Cara", + "face-number": "Cara {{number}}", + "points": "{{count}} puntos", + "eye-right": "Ojo derecho", + "eye-left": "Ojo izquierdo", + "lips": "Labios" } }, - "lymphography": { - "title": "LYMPHOGRAPHY - Clasificación por datos de linfomas", + "move-net--pose-net": { + "title": "MoveNet - Detector de articulaciones", "description": { - "text-1": "El conjunto de datos de lymphography permite detectar que posibles fases de un linfoma y en que estado se encuentra.", + "text-0": "MoveNet es un modelo de aprendizaje automático capaz de reconocer la posición del cuerpo en tiempo real. Se puede usar para estimar una sola pose o varias a la vez.", + "text-1": "En el siguiente ejemplo, para que su impacto en el rendimiento sea menor solamente detecta una pose a la vez.", "details-input": { "title": "Datos de entrada", "list": { - "0": "lymphatics: normal, arched, deformed, displaced", - "1": "block of affere: no, yes", - "2": "bl. of lymph. c: no, yes", - "3": "bl. of lymph. s: no, yes", - "4": "by pass: no, yes", - "5": "extravasates: no, yes", - "6": "regeneration of: no, yes", - "7": "early uptake in: no, yes", - "8": "lym.nodes dimin: 0-3", - "9": "lym.nodes enlar: 1-4", - "10": "changes in lym.: bean, oval, round", - "11": "defect in node: no, lacunar, lac. marginal, lac. central", - "12": "changes in node: no, lacunar, lac. margin, lac. central", - "13": "changes in stru: no, grainy, drop-like, coarse, diluted, reticular, stripped, faint,", - "14": "special forms: no, chalices, vesicles", - "15": "dislocation of: no, yes", - "16": "exclusion of no: no, yes", - "17": "no. of nodes in: 0-9, 10-19, 20-29, 30-39, 40-49, 50-59, 60-69, >=70" + "0": "Imagen o vídeo (webcam) a color." } }, "details-output": { "title": "Datos de salida", "list": { - "0": "normal find: normal", - "1": "metastases: metastasis", - "2": "malign lymph: linfoma maligno", - "3": "fibrosis: fibrosis" + "0": "Mismo elemento de entrada con una serie de puntos y líneas que delimitan diferentes partes de la cara además de hombros, codos, manos, pies, rodillas y cadera." } }, "details-references": { "title": "Referencias", "list": { - "0": "Conjunto de datos" + "0": "Entrada al repositorio de tensorflow", + "1": "Modelo de TFHub" } } }, - "html-example": { - "text": "Introduce los valores correspondientes del paciente que se va a evaluar:", - "items": "(lymphatics, block of affere, bl. of lymph. c, bl. of lymph. s, by pass, extravasates, regeneration of, early uptake in, lym.nodes dimin, lym.nodes enlar, changes in lym., defect in node, changes in node, changes in stru, special forms, dislocation of, exclusion of no, no. of nodes in).", - "examples": "Ejemplos:" + "render": { + "person": "Persona", + "person-number": "Persona {{number}}", + "score": "{{percent}} %", + "shoulder-left": "Hombro izquierdo", + "shoulder-right": "Hombro derecho", + "elbow-left": "Codo izquierdo", + "elbow-right": "Codo derecho", + "wrist-left": "Muñeca izquierda", + "wrist-right": "Muñeca derecha", + "hip-left": "Cadera izquierda", + "hip-right": "Cadera derecha", + "knee-left": "Rodilla izquierda", + "knee-right": "Rodilla derecha", + "ankle-left": "Tobillo izquierdo", + "ankle-right": "Tobillo derecho" } }, - "list-datasets": { - "0-option-1": "Conjunto de datos - Clasificación de coches", - "0-option-2": "Conjunto de datos - Clasificación de flor iris", - "0-option-3": "Conjunto de datos - Clasificación de linfomas" - }, - "list-models": { - "0-option-1": "Modelo - Clasificación de coches", - "0-option-2": "Modelo - Clasificación de flor iris", - "0-option-3": "Modelo - Clasificación de linfomas" - }, - "joyride": { - "title": "Activar el tutorial", - "steps": { - "manual": { - "title": "Manual", - "content": "Puedes consultar el manual en búsqueda de información" - }, - "dataset-info": { - "title": "Información del conjunto de datos", - "content": "Analiza el conjunto de datos" - }, - "dataset": { - "title": "Conjunto de datos", - "content": "Puedes ver el conjunto de datos y extraer estadísticas de su descripciones" - }, - "dataset-plot": { - "title": "Gráficas de los conjuntos de datos", - "content": "Puedes extraer información muy relevante analizando el conjunto de datos usando las distintas gráficas, diagrama de barras, diagramas de sectores, etc." - }, - "layer-visualizer": { - "title": "Visor de las capas de la red neuronal", - "content": "Puedes visualizar las capas, funciones de activación en dos formatos, modo compacto y modo extendido" - }, - "layer-editor": { - "title": "Editor de capas", - "content": "Puedes editar las capas de la red neuronal, modificar de las unidades de cada capa, la función de activación, añadir nuevas capas o eliminarlas." - }, - "params-editor": { - "title": "Editor de hiperparámetros", - "content": "Puedes configurar los hiperparámetros de tu red neuronal de forma que el entrenamiento sea personalizado para el conjunto de datos." - }, - "list-of-models": { - "title": "Lista de modelos", - "content": "Una vez generado el modelo puedes cargar o descargar el modelo, para probar cada modelo y realizar la clasificación." - }, - "classify-and-visualizer": { - "title": "Clasificar y visualizar", - "content": "Una vez cargado nuestro modelo para la clasificación tabular puedes realizar la clasificación y visualizar los resultados" - } - } - } - }, - "1-regression": { - "salary": { - "title": "Salario por años de experiencia", + "coco-ssd": { + "title": "COCO SSD - Detector de objetos", "description": { - "text": { - "0": "El conjunto de datos \"Salary\" es una colección de información que relaciona la cantidad de años de experiencia laboral de un individuo con su salario correspondiente.", - "1": "Cada entrada en el conjunto de datos consta de dos variables principales: \"Years of Experience\" (Años de experiencia) y \"Salary\" (Salario). La variable \"Years of Experience\" representa la cantidad de años que un empleado ha trabajado en su campo específico, mientras que la variable \"Salary\" representa la cantidad de dinero que dicho empleado gana anualmente." - }, - "link": "Para obtener más información acerca de este conjunto de datos visita el repositorio www.kaggle.com.", - "details-1-input": { + "text-0": "El modelo SSD (Single Shot MultiBox Detection) de detección de objetos pretende localizar e identificar múltiples objetos en una sola imagen.", + "text-1": "Para más información sobre la API de detección de objetos de Tensorflow, consulta este readme en tensorflow/object_detection", + "text-2": "Este modelo detecta objetos definidos en el conjunto de datos COCO, que es un conjunto de datos de detección, segmentación y subtitulado de objetos a gran escala. El modelo es capaz de detectar 80 clases de objetos", + "text-3": "Este ejemplo es una adaptación a TensorFlow.js del modelo COCO-SSD.", + "details-input": { "title": "Datos de entrada", "list": { - "0": "Years of experience - Años de experiencia", - "1": "Salary - Salario" + "0": "Imagen o vídeo (webcam) a color." } }, - "details-2-output": { + "details-output": { "title": "Datos de salida", "list": { - "0": "Regresión calculada (Salary)" + "0": "Mismo elemento de entrada con una serie de cajas que delimitan los diferentes objetos, así como las etiquetas de los mismos." } }, - "details-3-references": { + "details-references": { "title": "Referencias", "list": { - "0": "Conjunto de datos 1", - "1": "Conjunto de datos 2" + "0": "Puede encontrar más información Coco dataset" } } + }, + "classes": { + "person": "Persona", + "bicycle": "Bicicleta", + "car": "Coche", + "motorcycle": "Moto", + "airplane": "Avión", + "bus": "Autobús", + "train": "Tren", + "truck": "Camión", + "boat": "Barco", + "traffic light": "Semáforo", + "fire hydrant": "Boca de incendios", + "stop sign": "Señal de stop", + "parking meter": "Parquímetro", + "bench": "Banco", + "bird": "Pájaro", + "cat": "Gato", + "dog": "Perro", + "horse": "Caballo", + "sheep": "Oveja", + "cow": "Vaca", + "elephant": "Elefante", + "bear": "Oso", + "zebra": "Cebra", + "giraffe": "Jirafa", + "backpack": "Mochila", + "umbrella": "Paraguas", + "handbag": "Bolso", + "tie": "Corbata", + "suitcase": "Maleta", + "frisbee": "Frisbi", + "skis": "Esquís", + "snowboard": "Tabla de snowboard", + "sports ball": "Pelota", + "kite": "Cometa", + "baseball bat": "Bate de béisbol", + "baseball glove": "Guante de béisbol", + "skateboard": "Monopatín", + "surfboard": "Tabla de surf", + "tennis racket": "Raqueta de tenis", + "bottle": "Botella", + "wine glass": "Copa de vino", + "cup": "Taza", + "fork": "Tenedor", + "knife": "Cuchillo", + "spoon": "Cuchara", + "bowl": "Cuenco", + "banana": "Plátano", + "apple": "Manzana", + "sandwich": "Sándwich", + "orange": "Naranja", + "broccoli": "Brócoli", + "carrot": "Zanahoria", + "hot dog": "Perrito caliente", + "pizza": "Pizza", + "donut": "Dónut", + "cake": "Tarta", + "chair": "Silla", + "couch": "Sofá", + "potted plant": "Planta en maceta", + "bed": "Cama", + "dining table": "Mesa de comedor", + "toilet": "Inodoro", + "tv": "Televisor", + "laptop": "Portátil", + "mouse": "Ratón", + "remote": "Mando a distancia", + "keyboard": "Teclado", + "cell phone": "Teléfono móvil", + "microwave": "Microondas", + "oven": "Horno", + "toaster": "Tostadora", + "sink": "Fregadero", + "refrigerator": "Frigorífico", + "book": "Libro", + "clock": "Reloj", + "vase": "Jarrón", + "scissors": "Tijeras", + "teddy bear": "Osito de peluche", + "hair drier": "Secador de pelo", + "toothbrush": "Cepillo de dientes" + }, + "render": { + "numbered": "{{label}} {{number}}", + "score": "{{percent}} %" } }, - "auto-mpg": { - "title": "Rendimiento de combustible", + "face-api": { + "title": "FaceAPI - Expresiones en cara", "description": { - "text": { - "0": "El conjunto de datos AUTO MPG se tomó de la biblioteca StatLib que se mantiene en la Universidad Carnegie Mellon. El conjunto de datos se utilizó en la Exposición de la Asociación Estadounidense de Estadística de 1983.", - "1": "El término \"Auto MPG\" se refiere a las millas por galón, una unidad de medida de eficiencia de combustible utilizada comúnmente en los Estados Unidos. Esta medida indica cuántas millas puede recorrer un vehículo con un galón de combustible. Sin embargo, \"Auto MPG\" es un término en inglés y no hay una traducción directa en español.\n\nEn español, para referirse a la eficiencia de combustible de un automóvil, se suelen utilizar términos como \"consumo de combustible\" o \"rendimiento de combustible\". Estos términos indican cuántos kilómetros o millas puede recorrer un vehículo con un litro o galón de combustible, respectivamente.\n\nEs importante tener en cuenta que en diferentes países se utilizan unidades de medida distintas para el consumo de combustible. Por ejemplo, en algunos lugares se utiliza el litro por cada 100 kilómetros recorridos (L/100 km) para indicar la eficiencia de combustible." + "text-0": "Múltiples redes neuronales de distinto tipo agrupadas en un proyecto para la gestión de caras, permite detectar múltiples caras, detectar su edad, emociones, marcas en el rostro, extraer puntos claves como descriptores para comparar distintos tipos de caras.", + "details-input": { + "title": "Datos de entrada", + "text-0": "Imagen o vídeo (webcam) a color." }, - "link": "Para obtener más información acerca de este conjunto de datos visita el repositorio ics.uci.edu.", - "details-0": { - "title": "Información", + "details-output": { + "title": "Datos de salida", + "text-0": "Mismo elemento de entrada con una serie de cajas que delimitan las caras con el porcentaje expresividad de cada emoción, así como la edad de la persona.", "list": { - "0": "MPG: MPG son las siglas en inglés de Millas por Galón. Es la cantidad de combustible consumido por el vehículo particular de una instancia. Esta variable también se puede utilizar como la variable a predecir para cualquier coche.", - "1": "cylinders: Este atributo describe el número de cilindros de cada coche. Se trata de un atributo de valor discreto", - "2": "displacement: Este es otro atributo del vehículo que tiene un valor cuantitativo continuo que describe el desplazamiento del motor", - "3": "horsepower: Este atributo informa sobre los caballos de un coche y es una variable de valor continuo", - "4": "weight: Se refiere al peso de cada coche que es una variable cuantitativa de valor continuo", - "5": "acceleration: La aceleración del coche", - "6": "model year: El año de lanzamiento del modelo", - "7": "origin: El atributo origen tiene 3 valores discretos. 1 se refiere a coches fabricados en EE.UU., 2 para Europa y 3 para Asia", - "8": "car name: Es el nombre del coche en cadena." + "0": "Edad", + "1": "Neutral", + "2": "Feliz", + "3": "Triste", + "4": "Enojado", + "5": "Temeroso", + "6": "Disgustado", + "7": "Sorprendido", + "bounding": "Cuadro delimitador" } }, - "details-1": { + "details-references": { + "title": "Referencias" + } + }, + "render": { + "face": "Cara", + "face-number": "Cara {{number}}", + "age": "unos {{age}} años", + "percent": "{{percent}} %" + } + }, + "hand-sign": { + "title": "Lenguaje de signos con la mano", + "description": { + "text-0": "Red neuronal que encuentra la mano y sus 21 puntos (MediaPipe Hands) y, con ellos, reconoce la letra del alfabeto dactilológico: el americano (ASL), comparando la mano con 2122 manos reales, o el español (SSL), con reglas que describen cada dedo. Funciona con la mano derecha y con la izquierda.", + "details-input": { "title": "Datos de entrada", "list": { - "0": "MPG: continuo", - "1": "cylinders: discreto multivalor, 4, 6, 8", - "2": "displacement: continuo", - "3": "horsepower: continua", - "4": "weight: continuo", - "5": "acceleration: continua", - "6": "model Year: discreto de varios valores", - "7": "origin: discreto multivalor, 1 se refiere a automóviles fabricados en EE. UU., 2 para Europa y 3 para Asia", - "8": "car name: texto (única para cada instancia)" + "0": "Imagen o vídeo (webcam) a color." } }, - "details-2": { + "details-output": { "title": "Datos de salida", "list": { - "0": "Regresión calculada (MPG)" + "0": "Articulaciones de los dedos", + "1": "Letra correspondiente" } }, - "details-3": { - "title": "Referencias", + "details-movement": { + "title": "Letras con movimiento", "list": { - "0": "Auto MPG" - } - } - } - }, - "housing-prices": { - "title": "Precio de las viviendas", - "description": { - "text": { - "0": "El conjunto de datos de viviendas de Boston se deriva de la información recopilada por el Servicio del Censo de EE. UU. sobre viviendas en el área de Boston.", - "1": "El conjunto de datos está diseñado para abordar problemas de regresión y modelado de precios de viviendas en diferentes vecindarios de Boston, Massachusetts, Estados Unidos. Este conjunto de datos es comúnmente utilizado para ejemplos y prácticas en la educación y la investigación." - }, - "link": "Entrada del conjunto de datos UCI", - "details-input": { - "title": "Datos de entrada", - "california": { - "list": { - "0": "Median House Value: Valor medio de la vivienda para los hogares de un bloque (medido en dólares estadounidenses) [$].", - "1": "Median Income: Mediana de ingresos de los hogares de un bloque de casas (medida en decenas de miles de dólares estadounidenses) [10k$].", - "2": "Median Age: Edad mediana de una casa dentro de un bloque; un número más bajo corresponde a un edificio más nuevo [años].", - "3": "Total Rooms: Número total de habitaciones de un bloque", - "4": "Total Bedrooms: Número total de dormitorios en un bloque", - "5": "Population: Número total de personas que residen en un bloque", - "6": "Households: Número total de hogares, un grupo de personas que residen dentro de una unidad doméstica, para una manzana", - "7": "Latitude: Medida de la distancia al norte a la que se encuentra una vivienda; un valor más alto significa más al norte [°].", - "8": "Longitude: Medida de la distancia al oeste de una vivienda; cuanto mayor sea el valor, más al oeste [°].", - "9": "Distance to coast: Distancia al punto costero más cercano [m]", - "10": "Distance to Los Angeles: Distancia al centro de Los Ángeles [m].", - "11": "Distance to San Diego: Distancia al centro de San Diego [m]", - "12": "Distance to San Jose: Distancia al centro de San José [m]", - "13": "Distance to San Francisco: Distancia al centro de San Francisco [m Distancia al centro de San Francisco [m].", - "14": null - } - }, - "boston": { - "list": { - "0": "CRIM Tasa de criminalidad del crimen per cápita por ciudad", - "1": "Zn Proporción de tierras residenciales zonas por lotes de más de 25,000 pies cuadrados.", - "2": "INDUS Proporción de acres comerciales no reales por ciudad", - "3": "CHAS Charles River Variable Dummy (= 1 if tract bounds river; 0 en otro caso)", - "4": "NOX Concentración de óxidos nítricos (partes por 10 millones)", - "5": "RM Número promedio de habitaciones por vivienda", - "6": "AGE Proporción de unidades ocupadas por los propietarios construidas antes de 1940", - "7": "DIS Distancias ponderadas a cinco centros de empleo de Boston", - "8": "RAD Índice de accesibilidad a carreteras radiales", - "9": "TAX Impuesto a la propiedad de la propiedad de valor completo por cada $ 10,000", - "10": "PRATIO Ratio alumnos-profesor por ciudad", - "11": "B 1000 (BK - 0.63)^2 donde BK es la proporción de negros por ciudad", - "12": "LSTAT LSTAT % más bajo estado de la población", - "13": "MEDVValor mediano de las casas ocupadas por el propietario en $ 1000" - } - } - }, - "details-output": { - "title": "Datos de salida", - "california": { - "list": { - "0": "Regresión calculada" - } - }, - "boston": { - "list": { - "0": "Regresión calculada" - } + "0": "LL y RR (SSL): haz la L o la R, desplaza la mano hacia su lado (medio palmo o más) y párala: la letra sale en cuanto se para.", + "1": "Ñ (SSL): haz la N y mueve la mano de lado a lado, o gira la muñeca, dos o tres veces.", + "2": "Mantén la letra mientras te mueves. Si la imagen sale movida no pasa nada: cuenta lo que se ve antes y después del movimiento." } }, "details-references": { - "title": "Referencias", - "california": { - "list": { - "0": "Kaggle California Housing Prices Data (5 new features!)" - } - }, - "boston": { - "list": { - "0": "Entrada del conjunto de datos UCI", - "1": "Controversia sobre el conjunto de datos de vivienda de Boston" - } - } - } - } - }, - "breast-cancer": { - "title": "Cáncer de mama Wisconsin (diagnóstico y pronóstico)", - "description": { - "text": { - "0": "Es un conjunto de datos del Hospital de la Universidad de Wisconsin relacionados con el cáncer de mama. Dicho conjunto de datos es útil para la predicción y discriminación de un tumor de cancer de mama, diferenciando si es benigno o no.", - "1": "Cada registro representa los datos de seguimiento de un caso de cáncer de mama. Estos son casos atendidos desde 1984 por el Dr. Wolberg, solo incluye aquellos casos que presentan cáncer de mama invasivo y sin evidencia de metástasis.", - "2": "Las primeras 30 características se calculan a partir de una imagen digitalizada de una aspiración con aguja fina (PAAF) de la masa mamaria, dichos datos describen las características de los núcleos celulares presentes en la imagen, algunas imágenes se pueden encontrar en cs wisc.", - "3": "El fichero wdbc.csv corresponde al conjunto de datos de diagnóstico y wpbc.csv corresponde al conjunto de datos de pronóstico." - }, - "link": "Entrada del conjunto de datos UCI", - "details-1-input": { - "title": "Datos de entrada", - "list": { - "0": "Número de identificación", - "1": "Resultado (R = recurrente, N = no recurrente)", - "2": "Tiempo (tiempo de recurrencia si el campo 2 = R, tiempo libre de enfermedad si el campo 2 = N)", - "3": "4-33 Se calculan diez características de valor real para cada núcleo celular:", - "4": "radio (media de distancias desde el centro a puntos del perímetro)", - "5": "textura (desviación estándar de los valores de escala de grises)", - "6": "perímetro", - "7": "área", - "8": "suavidad (variación local en la longitud del radio)", - "9": "compacidad (perímetro^2 / área - 1,0)", - "10": "concavidad (severidad de las porciones cóncavas del contorno)", - "11": "puntos cóncavos (número de porciones cóncavas del contorno)", - "12": "simetría", - "13": "dimensión fractal (\"aproximación de la línea costera\" - 1)" - } - }, - "details-2-output": { - "title": "Datos de salida", - "list": { - "0": "Regresión calculada" - } - }, - "details-3-references": { - "title": "Referencias", - "list": { - "0": "Breast Cancer Wisconsin", - "1": "Breast Cancer Wisconsin (Prognostic)", - "2": "Breast Cancer Wisconsin (Diagnostic)" - } - } - } - }, - "student-performance": { - "title": "Rendimiento de estudiantes", - "description": { - "text": { - "0": "El conjunto de datos incluye datos del rendimiento académico de alumnos de dos centros escolares portugueses. Los datos incluyen características demográficas, sociales, calificaciones de los estudiantes, etc. Se incluyen dos conjuntos de datos uno con el desempeño de dos materias distintas: Matemáticas (mat) y lengua portuguesa (por).", - "1": "El conjunto de datos contiene datos de tipo multivariado, atributos de tipo reales, 649 instancias y 12 atributos distintos.", - "2": "Nota importante: el atributo objetivo G3 tiene una fuerte correlación con los atributos G2 y G1. Esto ocurre porque G3 es la calificación del último año (emitida en el 3er período), mientras que G1 y G2 corresponden a las calificaciones del 1er y 2do período. Es más difícil predecir G3 sin G2 y G1, pero dicha predicción es mucho más útil.", - "3": "El fichero student-por.csv corresponde al conjunto de datos de calificaciones de estudiantes de portugués y student-mat.csv corresponde al conjunto de datos de calificaciones de estudiantes de matemáticas." - }, - "link": "Entrada del conjunto de datos UCI", - "details-1-input": { - "title": "Datos de entrada", - "list": { - "0": "school - escuela del estudiante (binario: 'GP' - Gabriel Pereira o 'MS' - Mousinho da Silveira)", - "1": "sex - sexo del estudiante (binario: 'F' - femenino o 'M' - masculino)", - "2": "age - edad del estudiante (numérica: de 15 a 22)", - "3": "address: tipo de dirección particular del estudiante (binario: 'U' - urbana o 'R' - rural)", - "4": "famsize - tamaño de la familia (binario: 'LE3' - menor o igual a 3 o 'GT3' - mayor que 3)", - "5": "Pstatus - estado de convivencia de los padres (binario: 'T' - viviendo juntos o 'A' - separados)", - "6": "Medu - educación de la madre (numérica: 0 - ninguna, 1 - educación primaria (4º grado), 2 - 5º a 9º grado, 3 - educación secundaria o 4 - educación superior)", - "7": "Fedu - educación del padre (numérica: 0 - ninguna, 1 - educación primaria (4º grado), 2 - 5º a 9º grado, 3 - educación secundaria o 4 - educación superior)", - "8": "Mjob - trabajo de la madre (nominal: 'maestra', 'relacionado con la atención sanitaria', 'servicios' civiles (por ejemplo, administrativos o policiales), 'en_casa' u 'otros')", - "9": "Fjob - trabajo del padre (nominal: 'maestro', 'relacionado con la atención sanitaria', 'servicios' civiles (por ejemplo, administrativos o policiales), 'en_casa' u 'otros')", - "10": "razón: motivo para elegir esta escuela (nominal: cerca de \"casa\", \"reputación\" de la escuela, preferencia de \"curso\" u \"otro\")", - "11": "tutor - tutor del estudiante (nominal: 'madre', 'padre' u 'otro')", - "12": "tiempo de viaje: tiempo de viaje de casa a la escuela (numérico: 1 - <15 min., 2 - 15 a 30 min., 3 - 30 min. a 1 hora, o 4 - >1 hora)", - "13": "tiempo de estudio: tiempo de estudio semanal (numérico: 1 - < 2 horas, 2 - 2 a 5 horas, 3 - 5 a 10 horas o 4 - > 10 horas)", - "14": "reprobados: número de reprobados en clases anteriores (numérico: n si 1 ≶=n ≶3, en caso contrario 4)", - "15": "schoolsup - apoyo educativo adicional (binario: sí o no)", - "16": "famsup - apoyo educativo familiar (binario: sí o no)", - "17": "pagado - clases extra pagadas dentro de la materia del curso (Matemáticas o Portugués) (binario: sí o no)", - "18": "actividades - actividades extracurriculares (binario: sí o no)", - "19": "guardería: asistió a la guardería (binario: sí o no)", - "20": "superior - quiere cursar estudios superiores (binario: sí o no)", - "21": "internet - Acceso a Internet en casa (binario: sí o no)", - "22": "romántico - con una relación romántica (binario: sí o no)", - "23": "famrel - calidad de las relaciones familiares (numérica: de 1 - muy mala a 5 - excelente)", - "24": "tiempo libre: tiempo libre después de la escuela (numérico: de 1 - muy bajo a 5 - muy alto)", - "25": "goout - salir con amigos (numérico: de 1 - muy bajo a 5 - muy alto)", - "26": "Dalc - consumo de alcohol en jornada laboral (numérico: de 1 - muy bajo a 5 - muy alto)", - "27": "Walc - consumo de alcohol durante el fin de semana (numérico: de 1 - muy bajo a 5 - muy alto)", - "28": "salud: estado de salud actual (numérico: de 1: muy malo a 5: muy bueno)", - "29": "ausencias - número de ausencias escolares (numérico: de 0 a 93)" - } - }, - "details-2-output": { - "title": "Datos de salida", - "list": { - "0": "Regresión calculada" - } - }, - "details-3-references": { - "title": "Referencias", - "list": { - "0": "Student Performance" - } - } - } - }, - "wine": { - "title": "Calidad del vino", - "description": { - "text": { - "0": "Los dos conjuntos de datos están relacionados, pues incluyen las variantes de vino tinto y vino blanco portugués. Dicho conjunto de datos solo incluye variables fisicoquímicas (entradas) y sensoriales (salidas), el conjunto de datos no incluye datos de tipos de uva, marca de vino o precio de venta del vino.", - "1": "El conjunto de datos contiene datos de tipo multivariado, atributos de tipo reales, 4898 instancias y 12 atributos distintos.", - "2": "Dicho conjunto de datos puede ser usado para tareas de clasificación o de regresión. Las clases están ordenadas, aunque el conjunto de datos se encuentra desbalanceado.", - "3": "El fichero wine-quality-red.csv corresponde al conjunto de datos de vino tinto y wine-quality-white.csv corresponde al conjunto de datos de vino blanco." - }, - "link": "Para obtener más información acerca de este conjunto de datos visita el repositorio archive.ics.uci.edu.", - "details-1-input": { - "title": "Datos de entrada", - "list": { - "0": "Fixed Acidity (Acidez Fija): La acidez fija se refiere a la concentración de ácidos no volátiles en el vino, principalmente ácido tartárico. Contribuye a la frescura y estabilidad del vino.", - "1": "Volatile Acidity (Acidez Volátil): La acidez volátil se refiere a la concentración de ácidos volátiles, como el ácido acético, que pueden dar un sabor desagradable si están presentes en exceso.", - "2": "Citric Acid (Ácido Cítrico): El ácido cítrico es uno de los ácidos orgánicos naturales presentes en el vino. Puede influir en el sabor y la frescura del vino.", - "3": "Residual Sugar (Azúcar Residual): Es la cantidad de azúcar que queda en el vino después de la fermentación. Un vino puede ser seco (poco azúcar residual) o dulce (más azúcar residual).", - "4": "Chlorides (Cloruros): La concentración de cloruros en el vino puede afectar su sabor y aroma, y niveles altos pueden indicar problemas en la producción.", - "5": "Free Sulfur Dioxide (Dióxido de Azufre Libre): El dióxido de azufre es un conservante común en el vino que ayuda a prevenir la oxidación y el crecimiento de microorganismos no deseados.", - "6": "Total Sulfur Dioxide (Dióxido de Azufre Total): Representa la suma de dióxido de azufre libre y dióxido de azufre unido a otras moléculas en el vino. También se relaciona con la conservación del vino.", - "7": "Density (Densidad): La densidad se refiere a la masa del vino por unidad de volumen. Puede proporcionar información sobre la concentración de alcohol y azúcar.", - "8": "pH: El pH mide la acidez o alcalinidad del vino. Un pH bajo indica acidez, mientras que un pH alto indica alcalinidad. Puede influir en la percepción del sabor.", - "9": "Sulphates (Sulfatos): Los sulfatos son aditivos que se utilizan a veces en la producción de vino. Pueden influir en la estabilidad y el aroma del vino.", - "10": "Alcohol: La concentración de alcohol en el vino puede variar y afecta tanto el sabor como la sensación en boca.", - "11": "Quality (Calidad): Esta es la puntuación general de calidad del vino, generalmente en una escala de 0 a 10, donde valores más altos indican vinos de mejor calidad según la evaluación de los catadores." - } - }, - "details-2-output": { - "title": "Datos de salida", - "list": { - "0": "Regresión calculada" - } - }, - "details-3-references": { "title": "Referencias", "list": { - "0": "Calidad del vino" + "0": "TFJS hand pose detection" } } + }, + "render": { + "left": "Mano izquierda", + "right": "Mano derecha", + "movement": "Con movimiento" } }, - "list-datasets": { - "salary": "Conjunto de datos - Salary", - "auto-mpg": "Conjunto de datos - Auto MPG", - "housing-prices": "Conjunto de datos - Housing Prices", - "breast-cancer": "Conjunto de datos - Breast cancer", - "student-performance": "Conjunto de datos - Student performance", - "wine": "Conjunto de datos - Wine" - }, "list-models": { - "salary": "Modelo - Salary", - "auto-mpg": "Modelo - Auto MPG", - "housing-prices": "Modelo - Housing prices", - "breast-cancer": "Modelo - Breast cancer", - "student-performance": "Modelo - Student performance", - "wine": "Modelo - Wine" - }, - "joyride": { - "title": "Activar el tutorial", - "steps": { - "manual": { - "title": "Manual", - "content": "Puedes consultar el manual en búsqueda de información" - }, - "dataset-info": { - "title": "Información del conjunto de datos", - "content": "Consulta la información del conjunto de datos" - }, - "dataset": { - "title": "Conjunto de datos", - "content": "Puedes ver el conjunto de datos y extraer estadísticas de su descripciones" - }, - "pre-process-dataset": { - "title": "Pre procesamiento", - "content": "Limpieza y preparación del conjunto de datos" - }, - "dataset-plot": { - "title": "Gráficas de los conjuntos de datos", - "content": "Puedes extraer información muy relevante analizando el conjunto de datos usando las distintas gráficas, diagrama de barras, diagramas de sectores, etc." - }, - "layer-visualizer": { - "title": "Visor de las capas de la red neuronal", - "content": "Puedes visualizar las capas, funciones de activación en dos formatos, modo compacto y modo extendido" - }, - "layer-editor": { - "title": "Editor de capas", - "content": "Puedes editar las capas de la red neuronal, modificar de las unidades de cada capa, la función de activación, añadir nuevas capas o eliminarlas." - }, - "params-editor": { - "title": "Editor de hiperparámetros", - "content": "Puedes configurar los hiperparámetros de tu red neuronal de forma que el entrenamiento sea personalizado para el conjunto de datos." - }, - "list-of-models": { - "title": "Lista de modelos", - "content": "Una vez generado el modelo puedes cargar o descargar el modelo, para probar cada modelo y realizar las predicciones." - }, - "predict-and-visualizer": { - "title": "Predicción y visualización", - "content": "Una vez cargado nuestro modelo para la regresión puedes realizar predicciones y visualizar los resultados" - } - } + "2-option-1": "FaceDetector - Geometría facial", + "2-option-2": "FaceMesh - Malla facial", + "2-option-3": "MoveNet - Detector de articulaciones", + "2-option-4": "COCO SSD - Detector de objetos", + "2-option-5": "Face API - Gestor de caras", + "2-option-6": "HandSign - Detector de signos" } }, - "2-object-detection": { + "3-image-classifier": { "interface": { - "process-webcam": { - "title": "Reconocimiento en tiempo real", - "sub-title": "Webcam", - "button": "Webcam" + "0-upload": { + "title": "Carga tu propio Modelo.", + "sub-title": "Primero el archivo .json y después el fichero .bin" + }, + "process-examples": { + "title": "Imágenes de ejemplo", + "help": "Pulsa una imagen para clasificarla.", + "classify-example": "Clasificar el ejemplo {{index}}", + "forms-help": "Cada carácter como se escribe hoy y en tres formas antiguas (hentaigana), con el kanji del que viene cada una, dibujadas con una fuente. Pulsa cualquiera para clasificarlo. Con las antiguas no siempre acierta: la red aprendió con trazos escritos a mano en libros, no con letra impresa.", + "modern": "Hoy", + "old": "Antes", + "classify-modern": "Clasificar {{char}} como se escribe hoy", + "classify-old": "Clasificar {{char}} antiguo, que viene de {{origin}}", + "classify-example-label": "Clasificar el ejemplo {{index}}: {{label}}" + }, + "process-draw": { + "title": "Dibujo" }, "process-image": { - "title": "Procesamiento de images", - "sub-title": "Subida de imágenes" - } - }, - "face-detection": { - "title": "FaceDetector - Geometría facial", - "description": { - "text-0": "Este modelo es capaz de reconocer a partir de una imagen o vídeo de entrada diferentes partes de la cara, como los ojos, orejas, nariz y boca.", - "details-input": { - "title": "Datos de entrada", - "list": { - "0": "Imagen o vídeo." - } - }, - "details-output": { - "title": "Datos de salida", - "list": { - "0": "Mismo elemento de entrada con una serie de puntos que delimitan las diferentes partes de la cara." - } - }, - "details-references": { - "title": "Referencias", - "list": { - "0": "Entrada del modelo en el repositorio de tensorflow" - } - } + "title": "Sube una imagen", + "sub-title": "-", + "validate": "Clasificar" + }, + "result": "Resultado", + "button-accept": "Aceptar", + "modal": { + "title": "Predicción" + }, + "test-images": { + "load": "Cargar imágenes de test", + "loading": "Cargando imágenes…" } }, "face-mesh": { - "title": "FaceMesh - Malla facial", - "description": { - "text-0": "Este modelo a partir de una imagen o vídeo de entrada, es capaz de reconocer diferentes puntos de la cara para finalmente hacer una malla de la misma.", - "details-input": { - "title": "Datos de entrada", - "list": { - "0": "Imagen o vídeo." - } - }, - "details-output": { - "title": "Datos de salida", - "list": { - "0": "Mismo elemento de entrada con una serie de puntos que delimitan las diferentes partes de la cara." - } - }, - "details-references": { - "title": "Referencias", - "list": { - "0": "Entrada del modelo en el repositorio de tensorflow" - } - } - } + "title": "-" + } + } + }, + "dataframe-plot": { + "warning": { + "no-columns": "No hay columnas disponibles para dibujar.", + "unexpected": "No se ha podido dibujar el gráfico. Consulta la consola para más detalles." + }, + "title": "DataFrame | Gráficos", + "info": "Información", + "description": { + "title": "Descripción del tipo de gráfica" + }, + "configuration": { + "title": "Configuración", + "reset": "Reiniciar", + "select-all-columns": "Seleccionar todos las columnas", + "delete-all-columns": "Descartar todos las columnas", + "layout": { + "plot": { + "title": "Titulo del gráfico", + "x-axis": "Título eje X", + "y-axis": "Título eje Y" + }, + "title": "Disposición" }, - "move-net--pose-net": { - "title": "MoveNet - Detector de articulaciones", - "description": { - "text-0": "MoveNet es un modelo de aprendizaje automático capaz de reconocer la posición del cuerpo en tiempo real. Se puede usar para estimar una sola pose o varias a la vez.", - "text-1": "En el siguiente ejemplo, para que su impacto en el rendimiento sea menor solamente detecta una pose a la vez.", - "details-input": { - "title": "Datos de entrada", - "list": { - "0": "Imagen o vídeo (webcam) a color." - } - }, - "details-output": { - "title": "Datos de salida", - "list": { - "0": "Mismo elemento de entrada con una serie de puntos y líneas que delimitan diferentes partes de la cara además de hombros, codos, manos, pies, rodillas y cadera." - } - }, - "details-references": { - "title": "Referencias", - "list": { - "0": "Entrada al repositorio de tensorflow", - "1": "Modelo de TFHub" - } - } - } + "columns": { + "title": "Columnas del DataFrame" }, - "coco-ssd": { - "title": "COCO SSD - Detector de objetos", - "description": { - "text-0": "El modelo SSD (Single Shot MultiBox Detection) de detección de objetos pretende localizar e identificar múltiples objetos en una sola imagen.", - "text-1": "Para más información sobre la API de detección de objetos de Tensorflow, consulta este readme en tensorflow/object_detection", - "text-2": "Este modelo detecta objetos definidos en el conjunto de datos COCO, que es un conjunto de datos de detección, segmentación y subtitulado de objetos a gran escala. El modelo es capaz de detectar 80 clases de objetos", - "text-3": "Este ejemplo es una adaptación a TensorFlow.js del modelo COCO-SSD.", - "details-input": { - "title": "Datos de entrada", - "list": { - "0": "Imagen o vídeo (webcam) a color." - } - }, - "details-output": { - "title": "Datos de salida", - "list": { - "0": "Mismo elemento de entrada con una serie de cajas que delimitan los diferentes objetos, así como las etiquetas de los mismos." - } - }, - "details-references": { - "title": "Referencias", - "list": { - "0": "Puede encontrar más información Coco dataset" - } - } + "pie-charts": { + "labels": "Etiquetas" + } + }, + "buttons": { + "configuration": "Configuración", + "description": "Descripción" + }, + "bar-charts": { + "title": "Gráfico de Barras", + "description": { + "intro": { + "0": "Los gráficos de tipo barra o barras, son una representación visual que muestra la comparación de diferentes categorías o grupos mediante barras rectangulares.\nEste tipo de gráfico utiliza la longitud o altura de las barras para representar la magnitud o la cantidad de una variable específica.", + "1": "En un gráfico de tipo barra, el eje horizontal representa las categorías o grupos, mientras que el eje vertical muestra la magnitud o la frecuencia de la variable que se está analizando.\nCada categoría tiene una barra individual, y la longitud o altura de la barra es proporcional al valor o la cantidad correspondiente.\nLas barras pueden ser horizontales o verticales, dependiendo de la orientación del gráfico.", + "2": "Los gráficos de tipo barra tienen varias características y aplicaciones destacadas:" }, - "classes": { - "person": "Persona", - "bicycle": "Bicicleta", - "car": "Coche", - "motorcycle": "Moto", - "airplane": "Avión", - "bus": "Autobús", - "train": "Tren", - "truck": "Camión", - "boat": "Barco", - "traffic light": "Semáforo", - "fire hydrant": "Boca de incendios", - "stop sign": "Señal de stop", - "parking meter": "Parquímetro", - "bench": "Banco", - "bird": "Pájaro", - "cat": "Gato", - "dog": "Perro", - "horse": "Caballo", - "sheep": "Oveja", - "cow": "Vaca", - "elephant": "Elefante", - "bear": "Oso", - "zebra": "Cebra", - "giraffe": "Jirafa", - "backpack": "Mochila", - "umbrella": "Paraguas", - "handbag": "Bolso", - "tie": "Corbata", - "suitcase": "Maleta", - "frisbee": "Frisbi", - "skis": "Esquís", - "snowboard": "Tabla de snowboard", - "sports ball": "Pelota", - "kite": "Cometa", - "baseball bat": "Bate de béisbol", - "baseball glove": "Guante de béisbol", - "skateboard": "Monopatín", - "surfboard": "Tabla de surf", - "tennis racket": "Raqueta de tenis", - "bottle": "Botella", - "wine glass": "Copa de vino", - "cup": "Taza", - "fork": "Tenedor", - "knife": "Cuchillo", - "spoon": "Cuchara", - "bowl": "Cuenco", - "banana": "Plátano", - "apple": "Manzana", - "sandwich": "Sándwich", - "orange": "Naranja", - "broccoli": "Brócoli", - "carrot": "Zanahoria", - "hot dog": "Perrito caliente", - "pizza": "Pizza", - "donut": "Dónut", - "cake": "Tarta", - "chair": "Silla", - "couch": "Sofá", - "potted plant": "Planta en maceta", - "bed": "Cama", - "dining table": "Mesa de comedor", - "toilet": "Inodoro", - "tv": "Televisor", - "laptop": "Portátil", - "mouse": "Ratón", - "remote": "Mando a distancia", - "keyboard": "Teclado", - "cell phone": "Teléfono móvil", - "microwave": "Microondas", - "oven": "Horno", - "toaster": "Tostadora", - "sink": "Fregadero", - "refrigerator": "Frigorífico", - "book": "Libro", - "clock": "Reloj", - "vase": "Jarrón", - "scissors": "Tijeras", - "teddy bear": "Osito de peluche", - "hair drier": "Secador de pelo", - "toothbrush": "Cepillo de dientes" + "list": { + "0": "Comparación de categorías: Los gráficos de tipo barra son ideales para comparar visualmente diferentes categorías o grupos.\nAl observar las barras, es posible identificar rápidamente las diferencias en la magnitud o la cantidad entre las categorías.", + "1": "Representación de datos categóricos o discretos: Los gráficos de tipo barra son adecuados para representar variables categóricas o discretas.\nCada barra representa una categoría específica y la altura o longitud de la barra muestra la magnitud o la cantidad asociada a esa categoría.", + "2": "Ordenamiento de categorías: Las categorías en un gráfico de tipo barra se pueden ordenar en función de diferentes criterios, como orden alfabético, orden de magnitud o cualquier otro orden lógico.\nEsto permite resaltar patrones o tendencias específicas entre las categorías.", + "3": "Visualización de frecuencias o porcentajes: Los gráficos de tipo barra también se utilizan para representar frecuencias o porcentajes.\nEn este caso, la altura o longitud de las barras representa la proporción o el porcentaje correspondiente a cada categoría.", + "4": "Presentación efectiva: Los gráficos de tipo barra son una herramienta efectiva para presentar información de manera clara y concisa.\nSu estructura simple y su capacidad para resaltar las diferencias entre las categorías los hacen ampliamente utilizados en informes, presentaciones y documentos.", + "5": "Los gráficos de tipo barra son una forma eficaz de visualizar y comparar categorías o grupos en función de su magnitud o cantidad.\nSon ideales para representar datos categóricos o discretos y permiten una presentación efectiva de la información.\nSu simplicidad y capacidad para resaltar las diferencias los convierten en una herramienta comúnmente utilizada en el análisis de datos y la comunicación." }, - "render-label": "{{label}} con {{score}} % de confianza" - }, - "face-api": { - "title": "FaceAPI - Expresiones en cara", - "description": { - "text-0": "Múltiples redes neuronales de distinto tipo agrupadas en un proyecto para la gestión de caras, permite detectar múltiples caras, detectar su edad, emociones, marcas en el rostro, extraer puntos claves como descriptores para comparar distintos tipos de caras.", - "details-input": { - "title": "Datos de entrada", - "text-0": "Imagen o vídeo (webcam) a color." - }, - "details-output": { - "title": "Datos de salida", - "text-0": "Mismo elemento de entrada con una serie de cajas que delimitan las caras con el porcentaje expresividad de cada emoción, así como la edad de la persona.", - "list": { - "0": "Edad", - "1": "Neutral", - "2": "Feliz", - "3": "Triste", - "4": "Enojado", - "5": "Temeroso", - "6": "Disgustado", - "7": "Sorprendido", - "bounding": "Cuadro delimitador" - } - }, - "details-references": { - "title": "Referencias" - } - } - }, - "hand-sign": { - "title": "Lenguaje de signos con la mano", - "description": { - "text-0": "Red neuronal para la detección de manos y puntos de referencia, utilizada en conjunto con descriptores de posiciones para clasificar posibles signos del American Sign Language (ASL) o Spanish Sign Language (SSL)", - "details-input": { - "title": "Datos de entrada", - "list": { - "0": "Imagen o vídeo (webcam) a color." - } - }, - "details-output": { - "title": "Datos de salida", - "list": { - "0": "Articulaciones de los dedos", - "1": "Letra correspondiente" - } - }, - "details-references": { - "title": "Referencias", - "list": { - "0": "TFJS hand pose detection" - } - } + "end": { + "0": "Los gráficos de tipo barra son una forma eficaz de visualizar y comparar categorías o grupos en función de su magnitud o cantidad.\nSon ideales para representar datos categóricos o discretos y permiten una presentación efectiva de la información.\nSu simplicidad y capacidad para resaltar las diferencias los convierten en una herramienta comúnmente utilizada en el análisis de datos y la comunicación." } - }, - "list-models": { - "2-option-1": "Modelo - FaceDetector - Geometría facial", - "2-option-2": "Modelo - FaceMesh - Malla facial", - "2-option-3": "Modelo - MoveNet - Detector de articulaciones", - "2-option-4": "Modelo - COCO SSD - Detector de objetos", - "2-option-5": "Modelos - Face API - Gestor de caras", - "2-option-6": "Modelo - HandSign - Detector de signos" } }, - "3-image-classifier": { - "interface": { - "0-upload": { - "title": "Carga tu propio Modelo.", - "sub-title": "Primero el archivo .json y después el fichero .bin" + "box-plots": { + "title": "Gráfico de Bigotes", + "description": { + "intro": { + "0": "Los gráficos de tipo Box, también conocidos como diagramas de caja y bigotes o boxplots en inglés, son una representación visual utilizada para mostrar la distribución y los resúmenes estadísticos de un conjunto de datos numéricos.\nEste tipo de gráfico se basa en un rectángulo que representa el rango intercuartil (IQR, por sus siglas en inglés), donde la línea central indica la mediana y las líneas extendidas, conocidas como bigotes, representan el rango de\nvalores más allá del IQR.", + "1": "En un gráfico de tipo Box, el rectángulo se traza de manera vertical u horizontal, y está delimitado por dos líneas, una en la parte inferior y otra en la parte superior.\nLa línea en el medio del rectángulo representa la mediana, que es el valor que divide a los datos ordenados en dos partes iguales.\nLos bigotes se extienden desde los bordes del rectángulo hacia los valores extremos, con una longitud determinada por la variabilidad de los datos.", + "2": "Los gráficos de tipo Box tienen varias características y aplicaciones destacadas:" }, - "process-examples": { - "title": "Procesamiento con ejemplos" + "list": { + "0": "Resumen estadístico: Los gráficos de tipo Box proporcionan un resumen visual de los estadísticos clave de un conjunto de datos.\nAdemás de la mediana, también se pueden mostrar los cuartiles (Q1 y Q3), que dividen los datos en cuatro partes iguales, y los valores atípicos, que se muestran como puntos o asteriscos fuera de los bigotes.", + "1": "Identificación de asimetrías y valores atípicos: Al observar un gráfico de tipo Box, es posible identificar asimetrías en la distribución de los datos.\nSi los bigotes no tienen la misma longitud, puede indicar una asimetría hacia uno de los extremos.\nAdemás, los valores atípicos que se encuentran fuera de los bigotes pueden resaltarse fácilmente.", + "2": "Comparación entre grupos o categorías: Los gráficos de tipo Box también se utilizan para comparar la distribución de los datos entre diferentes grupos o categorías.\nAl superponer varios diagramas de caja en el mismo gráfico, es posible visualizar las diferencias en las medianas, los rangos intercuartiles y la presencia de valores atípicos entre los grupos.", + "3": "Detectar sesgos y distribuciones: Los gráficos de tipo Box permiten identificar visualmente si la distribución de los datos es simétrica o sesgada hacia un extremo.\nSi la línea central del rectángulo no está en el medio, puede indicar un sesgo hacia la dirección opuesta.", + "4": "Visualización de dispersiones: Además de proporcionar información sobre la posición central y la variabilidad de los datos, los gráficos de tipo Box también permiten visualizar la dispersión y la variabilidad de los datos en un solo gráfico.\nEsto puede ser útil para tener una idea rápida de la distribución y la variabilidad general de los datos." }, - "process-draw": { - "title": "Dibujo" + "end": { + "0": "Los gráficos de tipo Box son una herramienta útil para visualizar la distribución, los resúmenes estadísticos y la variabilidad de un conjunto de datos numéricos.\nPermiten identificar asimetrías, valores atípicos y comparar distribuciones entre grupos.\nSu representación visual concisa y efectiva los convierte en una herramienta comúnmente utilizada en el análisis de datos y la comunicación." + } + } + }, + "histograms": { + "title": "Gráfico de tipo Histograma", + "description": { + "intro": { + "0": "Los gráficos de tipo histograma son una representación visual utilizada para mostrar la distribución de los datos numéricos o continuos.\nEste tipo de gráfico se basa en un conjunto de barras rectangulares adyacentes, donde el ancho de cada barra representa un intervalo de valores y la altura de la barra indica la frecuencia o la cantidad de observaciones dentro de ese\nintervalo.", + "1": "En un gráfico de tipo histograma, el eje horizontal se utiliza para representar el rango de valores de la variable en estudio, dividido en intervalos o bins.\nEl eje vertical representa la frecuencia o la cantidad de observaciones en cada intervalo.\nLa altura de cada barra muestra cuántas observaciones caen dentro de ese intervalo específico.", + "2": "Los gráficos de tipo histograma tienen varias características y aplicaciones destacadas:" }, - "process-image": { - "title": "Procesamiento de imágenes", - "sub-title": "-", - "validate": "Validar" + "list": { + "0": "Visualización de distribuciones: Los histogramas permiten visualizar la forma y la distribución de los datos numéricos.\nPueden mostrar si los datos siguen una distribución simétrica, sesgada, multi modal o uniforme.", + "1": "Identificación de valores atípicos: Al observar un histograma, es posible identificar valores atípicos o extremos que se encuentren fuera del rango de la mayoría de los datos.\nEstos valores se representarán como barras aisladas o como barras que se extienden más allá del rango principal de valores.", + "2": "Análisis de tendencias y patrones: Los histogramas pueden revelar patrones y tendencias en los datos.\nPor ejemplo, una distribución sesgada hacia la izquierda o hacia la derecha indica una asimetría en los datos, mientras que una distribución normal muestra una simetría aproximada.", + "3": "Comparación de grupos o categorías: Los histogramas también pueden ser utilizados para comparar la distribución de datos entre diferentes grupos o categorías.\nAl superponer varios histogramas en el mismo gráfico, es posible visualizar las diferencias y similitudes entre los grupos.", + "4": "Estimación de densidad: Además de mostrar la frecuencia absoluta, los histogramas también pueden proporcionar una estimación visual de la densidad de probabilidad de los datos.\nAl normalizar las alturas de las barras, es posible obtener una representación relativa de la probabilidad de ocurrencia de los valores en cada intervalo." }, - "result": "Resultado", - "button-accept": "Aceptar", - "modal": { - "title": "Predicción" + "end": { + "0": "Los gráficos de tipo histograma son una herramienta útil para visualizar la distribución y los patrones de los datos numéricos.\nPermiten identificar valores atípicos, analizar tendencias y comparar distribuciones entre grupos.\nSu representación visual clara y concisa los convierte en una herramienta efectiva para comunicar información sobre la distribución de los datos de manera comprensible." } + } + }, + "line-charts": { + "warning": { + "config": "La configuración actual no es válida para un gráfico de líneas." }, - "mnist": { - "title": "MNIST - Clasificación de números", - "description": { - "text-0": "La base de datos MNIST es una gran base de datos de dígitos escritos a mano. La base de datos se usa ampliamente para capacitación y pruebas en el campo del aprendizaje automático.", - "text-1": "Fue creado \"re-mezclando\" las muestras de los conjuntos de datos originales del NIST.", - "text-2": "El conjunto de datos de capacitación del NIST se tomó de la Oficina del Censo de los Estados Unidos. Además, las imágenes en blanco y negro del NIST se normalizaron para encajar en un cuadro delimitador de 28 x 28 píxeles y se suavizaron, lo que introdujo niveles de escala de grises.", - "details-input": { - "title": "Datos de entrada", - "list": { - "0": "Imagen en escala de grises y con un tamaño de 28 x 28 píxeles" - } - }, - "details-output": { - "title": "Datos de salida", - "list": { - "0": "Un número entre 0 y 9" - } - }, - "details-references": { - "title": "Referencias" - } + "title": "Gráfico de tipo Línea", + "description": { + "intro": { + "0": "Los gráficos de tipo línea, también conocidos como gráficos de series o gráficos de tendencia, son una representación visual que muestra la relación y la evolución de los datos a lo largo del tiempo o de una variable continua.\nEstos gráficos se construyen trazando puntos de datos en un sistema de coordenadas cartesianas, donde cada punto representa una medición o un valor específico de la variable en el eje vertical en función del tiempo o de la variable\nindependiente en el eje horizontal.", + "1": "En un gráfico de tipo línea, los puntos de datos se conectan mediante líneas rectas, lo que crea una serie de puntos conectados.\nEstas líneas permiten visualizar la trayectoria y el patrón de cambio de los datos a lo largo del tiempo o de la variable independiente.\nLa pendiente de la línea puede indicar una tendencia creciente o decreciente, mientras que las variaciones en la dirección y la forma de la línea pueden revelar patrones adicionales en los datos.", + "2": "Los gráficos de tipo línea tienen varias características y aplicaciones destacadas:" + }, + "list": { + "0": "Representación de tendencias: Los gráficos de tipo línea son especialmente útiles para mostrar tendencias y cambios a lo largo del tiempo.\nPueden revelar patrones de crecimiento, declive o fluctuación en los datos a medida que se suceden en el tiempo.", + "1": "Identificación de cambios y variaciones: Al observar un gráfico de tipo línea, es posible identificar cambios abruptos o variaciones en los datos.\nEstos cambios pueden indicar eventos significativos o factores que influyen en la variable medida.", + "2": "Comparación de múltiples series: Los gráficos de tipo línea también permiten comparar múltiples series de datos en un solo gráfico.\nEsto es útil para analizar y visualizar la relación entre diferentes variables a medida que evolucionan en el tiempo.", + "3": "Análisis de estacionalidad y ciclos: Si los datos exhiben patrones estacionales o cíclicos, los gráficos de tipo línea pueden ayudar a identificar y analizar estos patrones.\nEsto puede ser útil en campos como la economía, la meteorología y el análisis de ventas, donde existen fluctuaciones recurrentes en los datos.", + "4": "Pronóstico y proyección: Los gráficos de tipo línea también se utilizan para realizar pronósticos y proyecciones basadas en los datos históricos.\nAl observar las tendencias pasadas, es posible inferir y predecir cómo se comportarán los datos en el futuro." + }, + "end": { + "0": "Los gráficos de tipo línea son una herramienta valiosa para visualizar y analizar la relación y la evolución de los datos a lo largo del tiempo o de una variable continua.\nPermiten identificar tendencias, cambios y patrones en los datos, así como realizar comparaciones y pronósticos.\nSu representación visual clara y concisa los convierte en una herramienta efectiva para comunicar información compleja de manera comprensible." } + } + }, + "pie-charts": { + "warning": { + "labels": "Selecciona en la configuración la columna de las etiquetas del gráfico de sectores." }, - "kmnist": { - "title": "KMNIST - Clasificación de caracteres japoneses", - "description": { - "text-0": "Kuzushiji-MNIST (KMNIST) es un sustituto directo de MNIST: imágenes en escala de grises de 28 x 28 píxeles y 10 clases, pero en lugar de dígitos contiene caracteres japoneses manuscritos en kuzushiji (escritura cursiva).", - "text-1": "El kuzushiji fue la forma habitual de escribir japonés durante más de mil años, pero dejó de enseñarse tras la reforma de la escritura de principios del siglo XX y hoy muy poca gente sabe leerlo. Las imágenes proceden de libros clásicos digitalizados por el Instituto Nacional de Literatura Japonesa y las preparó el ROIS-DS Center for Open Data in the Humanities (CODH).", - "text-2": "Cada clase es un carácter hiragana (お, き, す, つ, な, は, ま, や, れ, を) y un mismo carácter puede escribirse de muchas formas, por lo que es más difícil que MNIST.", - "details-input": { - "title": "Datos de entrada", - "list": { - "0": "Imagen en escala de grises de 28 x 28 píxeles" - } - }, - "details-output": { - "title": "Datos de salida", - "list": { - "0": "Uno de los 10 caracteres hiragana: お, き, す, つ, な, は, ま, や, れ, を" - } - }, - "details-model": { - "title": "Modelos", - "list": { - "0": "Modelo preentrenado: red convolucional entrenada con las 55.000 imágenes de entrenamiento (y otras 5.000 para validar), con una precisión del {{accuracy, number(style: percent; minimumFractionDigits: 1)}} en las 10.000 imágenes de test.", - "1": "Entrenamiento en el navegador: se usa un subconjunto equilibrado, con 2.000 imágenes de entrenamiento y 500 de test por carácter." - } - } + "title": "Gráfico de Sectores", + "description": { + "intro": { + "0": "Los gráficos circulares o de sectores, son una representación visual que muestra la proporción de diferentes categorías o partes en relación con el todo.\nEstos gráficos se basan en un círculo dividido en sectores, donde cada sector representa una categoría específica y su tamaño relativo refleja la proporción que esa categoría representa en el conjunto de datos.", + "1": "En un gráfico de tipo sectores, el círculo completo representa el 100% o el total de los datos.\nCada sector se muestra como una porción del círculo y se etiqueta con el nombre o la etiqueta correspondiente a la categoría que representa.\nLa medida del ángulo del sector es proporcional a la proporción que esa categoría tiene en el conjunto de datos.", + "2": "Los gráficos de tipo pie tienen varias características y aplicaciones destacadas:" + }, + "list": { + "0": "Representación de proporciones: Los gráficos de tipo pie son ideales para representar proporciones y porcentajes.\nPermiten visualizar rápidamente la contribución relativa de cada categoría en el conjunto de datos total.", + "1": "Identificación de categorías dominantes: Los tamaños relativos de los sectores en el gráfico de tipo pie ayudan a identificar fácilmente las categorías dominantes o más significativas.\nLos sectores más grandes indican las categorías que tienen una mayor proporción o contribución en relación con las demás.", + "2": "Comparación entre categorías: Si bien los gráficos de tipo pie son útiles para mostrar las proporciones de las categorías, pueden resultar limitados para realizar comparaciones precisas entre ellas.\nEsto se debe a que la percepción humana puede tener dificultades para evaluar con precisión las diferencias en los tamaños de los ángulos o sectores.\nSin embargo, la comparación relativa entre los tamaños de los sectores aún puede proporcionar información general sobre las proporciones entre categorías.", + "3": "Representación de datos categóricos: Los gráficos de tipo pie son especialmente útiles para representar datos categóricos, donde las categorías son mutuamente excluyentes y no tienen un orden inherente.\nPor ejemplo, se pueden usar para mostrar la distribución porcentual de ingresos en diferentes categorías de gastos.", + "4": "Mejora de la presentación visual: Los gráficos de tipo pie se utilizan comúnmente en presentaciones y documentos para comunicar información de manera visualmente atractiva y fácilmente comprensible.\nLa forma circular y los colores utilizados pueden captar rápidamente la atención y resaltar las relaciones proporcionales entre las categorías." + }, + "end": { + "0": "Los gráficos de tipo de sectores son una herramienta efectiva para representar proporciones y porcentajes de categorías en un conjunto de datos.\nPermiten identificar las categorías dominantes y proporcionan una presentación visual atractiva.\nSin embargo, es importante tener en cuenta sus limitaciones en términos de comparación precisa entre categorías y su enfoque en datos categóricos." } - }, - "mobilenet": { - "title": "MobileNet - Clasificación de imágenes", - "description": { - "text-0": "MobileNet V2 es una familia de arquitecturas de redes neuronales para la clasificación de imágenes y tareas similares.", - "text-1": "Este modelo es capaz de diferenciar entre 1001 categorías, identificando el contexto principal de la imagen.", - "details-input": { - "title": "Datos de entrada", - "list": { - "0": "Imagen con valores de color entre [0, 1] de 224 x 224 píxeles." - } - }, - "details-output": { - "title": "Datos de salida", - "list": { - "0": "Un número de 0 a 1001 que son cada una de las categorías de esta lista" - } - }, - "details-references": { - "title": "Referencias", - "text-0": "Originalmente, fue publicado por Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen:", - "list": { - "0": "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation 2018" - } - } - } - }, - "face-mesh": { - "title": "-" - }, - "list-models": { - "3-option-1": "Modelo - MNIST - Clasificación de números", - "3-option-2": "Modelo - MobileNet - Clasificación de imágenes", - "3-option-3": "Modelo - ResNet - Clasificación de imágenes", - "3-option-4": "Modelo - KMNIST - Clasificación de caracteres japoneses" - } - }, - "3-image-classification": { - "list-datasets": { - "mnist": "Conjunto de datos - MNIST", - "kmnist": "Conjunto de datos - KMNIST" - }, - "joyride": { - "title": "Activar el tutorial", - "steps": { - "manual": { - "title": "Manual", - "content": "Puedes consultar el manual en búsqueda de información" - }, - "dataset-info": { - "title": "Información del conjunto de datos", - "content": "Consulta la información del conjunto de datos" - }, - "dataset": { - "title": "Conjunto de datos", - "content": "Puedes ver el conjunto de datos y extraer estadísticas de su descripciones" - }, - "dataset-plot": { - "title": "Gráficas de los conjuntos de datos", - "content": "Puedes extraer información muy relevante analizando el conjunto de datos usando las distintas gráficas, diagrama de barras, diagramas de sectores, etc." - }, - "layer-visualizer": { - "title": "Visor de las capas de la red neuronal", - "content": "Puedes visualizar las capas, funciones de activación en dos formatos, modo compacto y modo extendido" - }, - "layer-editor": { - "title": "Editor de capas", - "content": "Puedes editar las capas de la red neuronal, modificar de las unidades de cada capa, la función de activación, añadir nuevas capas o eliminarlas." - }, - "params-editor": { - "title": "Editor de hiperparámetros", - "content": "Puedes configurar los hiperparámetros de tu red neuronal de forma que el entrenamiento sea personalizado para el conjunto de datos." - }, - "list-of-models": { - "title": "Lista de modelos", - "content": "Una vez generado el modelo puedes cargar o descargar el modelo, para probar cada modelo y realizar las predicciones." - }, - "classify": { - "title": "Predicción y visualización", - "content": "Una vez cargado nuestro modelo para la regresión puedes realizar predicciones y visualizar los resultados" - } - } - } - } - }, - "dataframe-plot": { - "warning": { - "no-columns": "No hay columnas disponibles para dibujar.", - "unexpected": "No se ha podido dibujar el gráfico. Consulta la consola para más detalles." - }, - "title": "DataFrame | Gráficos", - "info": "Información", - "description": { - "title": "Descripción del tipo de gráfica" - }, - "configuration": { - "title": "Configuración", - "reset": "Reiniciar", - "select-all-columns": "Seleccionar todos las columnas", - "delete-all-columns": "Descartar todos las columnas", - "layout": { - "plot": { - "title": "Titulo del gráfico", - "x-axis": "Título eje X", - "y-axis": "Título eje Y" - }, - "title": "Disposición" - }, - "columns": { - "title": "Columnas del DataFrame" - }, - "pie-charts": { - "labels": "Etiquetas" - } - }, - "buttons": { - "configuration": "Configuración", - "description": "Descripción" - }, - "bar-charts": { - "title": "Gráfico de Barras", - "description": { - "intro": { - "0": "Los gráficos de tipo barra o barras, son una representación visual que muestra la comparación de diferentes categorías o grupos mediante barras rectangulares.\nEste tipo de gráfico utiliza la longitud o altura de las barras para representar la magnitud o la cantidad de una variable específica.", - "1": "En un gráfico de tipo barra, el eje horizontal representa las categorías o grupos, mientras que el eje vertical muestra la magnitud o la frecuencia de la variable que se está analizando.\nCada categoría tiene una barra individual, y la longitud o altura de la barra es proporcional al valor o la cantidad correspondiente.\nLas barras pueden ser horizontales o verticales, dependiendo de la orientación del gráfico.", - "2": "Los gráficos de tipo barra tienen varias características y aplicaciones destacadas:" - }, - "list": { - "0": "Comparación de categorías: Los gráficos de tipo barra son ideales para comparar visualmente diferentes categorías o grupos.\nAl observar las barras, es posible identificar rápidamente las diferencias en la magnitud o la cantidad entre las categorías.", - "1": "Representación de datos categóricos o discretos: Los gráficos de tipo barra son adecuados para representar variables categóricas o discretas.\nCada barra representa una categoría específica y la altura o longitud de la barra muestra la magnitud o la cantidad asociada a esa categoría.", - "2": "Ordenamiento de categorías: Las categorías en un gráfico de tipo barra se pueden ordenar en función de diferentes criterios, como orden alfabético, orden de magnitud o cualquier otro orden lógico.\nEsto permite resaltar patrones o tendencias específicas entre las categorías.", - "3": "Visualización de frecuencias o porcentajes: Los gráficos de tipo barra también se utilizan para representar frecuencias o porcentajes.\nEn este caso, la altura o longitud de las barras representa la proporción o el porcentaje correspondiente a cada categoría.", - "4": "Presentación efectiva: Los gráficos de tipo barra son una herramienta efectiva para presentar información de manera clara y concisa.\nSu estructura simple y su capacidad para resaltar las diferencias entre las categorías los hacen ampliamente utilizados en informes, presentaciones y documentos.", - "5": "Los gráficos de tipo barra son una forma eficaz de visualizar y comparar categorías o grupos en función de su magnitud o cantidad.\nSon ideales para representar datos categóricos o discretos y permiten una presentación efectiva de la información.\nSu simplicidad y capacidad para resaltar las diferencias los convierten en una herramienta comúnmente utilizada en el análisis de datos y la comunicación." - }, - "end": { - "0": "Los gráficos de tipo barra son una forma eficaz de visualizar y comparar categorías o grupos en función de su magnitud o cantidad.\nSon ideales para representar datos categóricos o discretos y permiten una presentación efectiva de la información.\nSu simplicidad y capacidad para resaltar las diferencias los convierten en una herramienta comúnmente utilizada en el análisis de datos y la comunicación." - } - } - }, - "box-plots": { - "title": "Gráfico de Bigotes", - "description": { - "intro": { - "0": "Los gráficos de tipo Box, también conocidos como diagramas de caja y bigotes o boxplots en inglés, son una representación visual utilizada para mostrar la distribución y los resúmenes estadísticos de un conjunto de datos numéricos.\nEste tipo de gráfico se basa en un rectángulo que representa el rango intercuartil (IQR, por sus siglas en inglés), donde la línea central indica la mediana y las líneas extendidas, conocidas como bigotes, representan el rango de\nvalores más allá del IQR.", - "1": "En un gráfico de tipo Box, el rectángulo se traza de manera vertical u horizontal, y está delimitado por dos líneas, una en la parte inferior y otra en la parte superior.\nLa línea en el medio del rectángulo representa la mediana, que es el valor que divide a los datos ordenados en dos partes iguales.\nLos bigotes se extienden desde los bordes del rectángulo hacia los valores extremos, con una longitud determinada por la variabilidad de los datos.", - "2": "Los gráficos de tipo Box tienen varias características y aplicaciones destacadas:" - }, - "list": { - "0": "Resumen estadístico: Los gráficos de tipo Box proporcionan un resumen visual de los estadísticos clave de un conjunto de datos.\nAdemás de la mediana, también se pueden mostrar los cuartiles (Q1 y Q3), que dividen los datos en cuatro partes iguales, y los valores atípicos, que se muestran como puntos o asteriscos fuera de los bigotes.", - "1": "Identificación de asimetrías y valores atípicos: Al observar un gráfico de tipo Box, es posible identificar asimetrías en la distribución de los datos.\nSi los bigotes no tienen la misma longitud, puede indicar una asimetría hacia uno de los extremos.\nAdemás, los valores atípicos que se encuentran fuera de los bigotes pueden resaltarse fácilmente.", - "2": "Comparación entre grupos o categorías: Los gráficos de tipo Box también se utilizan para comparar la distribución de los datos entre diferentes grupos o categorías.\nAl superponer varios diagramas de caja en el mismo gráfico, es posible visualizar las diferencias en las medianas, los rangos intercuartiles y la presencia de valores atípicos entre los grupos.", - "3": "Detectar sesgos y distribuciones: Los gráficos de tipo Box permiten identificar visualmente si la distribución de los datos es simétrica o sesgada hacia un extremo.\nSi la línea central del rectángulo no está en el medio, puede indicar un sesgo hacia la dirección opuesta.", - "4": "Visualización de dispersiones: Además de proporcionar información sobre la posición central y la variabilidad de los datos, los gráficos de tipo Box también permiten visualizar la dispersión y la variabilidad de los datos en un solo gráfico.\nEsto puede ser útil para tener una idea rápida de la distribución y la variabilidad general de los datos." - }, - "end": { - "0": "Los gráficos de tipo Box son una herramienta útil para visualizar la distribución, los resúmenes estadísticos y la variabilidad de un conjunto de datos numéricos.\nPermiten identificar asimetrías, valores atípicos y comparar distribuciones entre grupos.\nSu representación visual concisa y efectiva los convierte en una herramienta comúnmente utilizada en el análisis de datos y la comunicación." - } - } - }, - "histograms": { - "title": "Gráfico de tipo Histograma", - "description": { - "intro": { - "0": "Los gráficos de tipo histograma son una representación visual utilizada para mostrar la distribución de los datos numéricos o continuos.\nEste tipo de gráfico se basa en un conjunto de barras rectangulares adyacentes, donde el ancho de cada barra representa un intervalo de valores y la altura de la barra indica la frecuencia o la cantidad de observaciones dentro de ese\nintervalo.", - "1": "En un gráfico de tipo histograma, el eje horizontal se utiliza para representar el rango de valores de la variable en estudio, dividido en intervalos o bins.\nEl eje vertical representa la frecuencia o la cantidad de observaciones en cada intervalo.\nLa altura de cada barra muestra cuántas observaciones caen dentro de ese intervalo específico.", - "2": "Los gráficos de tipo histograma tienen varias características y aplicaciones destacadas:" - }, - "list": { - "0": "Visualización de distribuciones: Los histogramas permiten visualizar la forma y la distribución de los datos numéricos.\nPueden mostrar si los datos siguen una distribución simétrica, sesgada, multi modal o uniforme.", - "1": "Identificación de valores atípicos: Al observar un histograma, es posible identificar valores atípicos o extremos que se encuentren fuera del rango de la mayoría de los datos.\nEstos valores se representarán como barras aisladas o como barras que se extienden más allá del rango principal de valores.", - "2": "Análisis de tendencias y patrones: Los histogramas pueden revelar patrones y tendencias en los datos.\nPor ejemplo, una distribución sesgada hacia la izquierda o hacia la derecha indica una asimetría en los datos, mientras que una distribución normal muestra una simetría aproximada.", - "3": "Comparación de grupos o categorías: Los histogramas también pueden ser utilizados para comparar la distribución de datos entre diferentes grupos o categorías.\nAl superponer varios histogramas en el mismo gráfico, es posible visualizar las diferencias y similitudes entre los grupos.", - "4": "Estimación de densidad: Además de mostrar la frecuencia absoluta, los histogramas también pueden proporcionar una estimación visual de la densidad de probabilidad de los datos.\nAl normalizar las alturas de las barras, es posible obtener una representación relativa de la probabilidad de ocurrencia de los valores en cada intervalo." - }, - "end": { - "0": "Los gráficos de tipo histograma son una herramienta útil para visualizar la distribución y los patrones de los datos numéricos.\nPermiten identificar valores atípicos, analizar tendencias y comparar distribuciones entre grupos.\nSu representación visual clara y concisa los convierte en una herramienta efectiva para comunicar información sobre la distribución de los datos de manera comprensible." - } - } - }, - "line-charts": { - "warning": { - "config": "La configuración actual no es válida para un gráfico de líneas." - }, - "title": "Gráfico de tipo Línea", - "description": { - "intro": { - "0": "Los gráficos de tipo línea, también conocidos como gráficos de series o gráficos de tendencia, son una representación visual que muestra la relación y la evolución de los datos a lo largo del tiempo o de una variable continua.\nEstos gráficos se construyen trazando puntos de datos en un sistema de coordenadas cartesianas, donde cada punto representa una medición o un valor específico de la variable en el eje vertical en función del tiempo o de la variable\nindependiente en el eje horizontal.", - "1": "En un gráfico de tipo línea, los puntos de datos se conectan mediante líneas rectas, lo que crea una serie de puntos conectados.\nEstas líneas permiten visualizar la trayectoria y el patrón de cambio de los datos a lo largo del tiempo o de la variable independiente.\nLa pendiente de la línea puede indicar una tendencia creciente o decreciente, mientras que las variaciones en la dirección y la forma de la línea pueden revelar patrones adicionales en los datos.", - "2": "Los gráficos de tipo línea tienen varias características y aplicaciones destacadas:" - }, - "list": { - "0": "Representación de tendencias: Los gráficos de tipo línea son especialmente útiles para mostrar tendencias y cambios a lo largo del tiempo.\nPueden revelar patrones de crecimiento, declive o fluctuación en los datos a medida que se suceden en el tiempo.", - "1": "Identificación de cambios y variaciones: Al observar un gráfico de tipo línea, es posible identificar cambios abruptos o variaciones en los datos.\nEstos cambios pueden indicar eventos significativos o factores que influyen en la variable medida.", - "2": "Comparación de múltiples series: Los gráficos de tipo línea también permiten comparar múltiples series de datos en un solo gráfico.\nEsto es útil para analizar y visualizar la relación entre diferentes variables a medida que evolucionan en el tiempo.", - "3": "Análisis de estacionalidad y ciclos: Si los datos exhiben patrones estacionales o cíclicos, los gráficos de tipo línea pueden ayudar a identificar y analizar estos patrones.\nEsto puede ser útil en campos como la economía, la meteorología y el análisis de ventas, donde existen fluctuaciones recurrentes en los datos.", - "4": "Pronóstico y proyección: Los gráficos de tipo línea también se utilizan para realizar pronósticos y proyecciones basadas en los datos históricos.\nAl observar las tendencias pasadas, es posible inferir y predecir cómo se comportarán los datos en el futuro." - }, - "end": { - "0": "Los gráficos de tipo línea son una herramienta valiosa para visualizar y analizar la relación y la evolución de los datos a lo largo del tiempo o de una variable continua.\nPermiten identificar tendencias, cambios y patrones en los datos, así como realizar comparaciones y pronósticos.\nSu representación visual clara y concisa los convierte en una herramienta efectiva para comunicar información compleja de manera comprensible." - } - } - }, - "pie-charts": { - "warning": { - "labels": "Selecciona en la configuración la columna de las etiquetas del gráfico de sectores." - }, - "title": "Gráfico de Sectores", - "description": { - "intro": { - "0": "Los gráficos circulares o de sectores, son una representación visual que muestra la proporción de diferentes categorías o partes en relación con el todo.\nEstos gráficos se basan en un círculo dividido en sectores, donde cada sector representa una categoría específica y su tamaño relativo refleja la proporción que esa categoría representa en el conjunto de datos.", - "1": "En un gráfico de tipo sectores, el círculo completo representa el 100% o el total de los datos.\nCada sector se muestra como una porción del círculo y se etiqueta con el nombre o la etiqueta correspondiente a la categoría que representa.\nLa medida del ángulo del sector es proporcional a la proporción que esa categoría tiene en el conjunto de datos.", - "2": "Los gráficos de tipo pie tienen varias características y aplicaciones destacadas:" - }, - "list": { - "0": "Representación de proporciones: Los gráficos de tipo pie son ideales para representar proporciones y porcentajes.\nPermiten visualizar rápidamente la contribución relativa de cada categoría en el conjunto de datos total.", - "1": "Identificación de categorías dominantes: Los tamaños relativos de los sectores en el gráfico de tipo pie ayudan a identificar fácilmente las categorías dominantes o más significativas.\nLos sectores más grandes indican las categorías que tienen una mayor proporción o contribución en relación con las demás.", - "2": "Comparación entre categorías: Si bien los gráficos de tipo pie son útiles para mostrar las proporciones de las categorías, pueden resultar limitados para realizar comparaciones precisas entre ellas.\nEsto se debe a que la percepción humana puede tener dificultades para evaluar con precisión las diferencias en los tamaños de los ángulos o sectores.\nSin embargo, la comparación relativa entre los tamaños de los sectores aún puede proporcionar información general sobre las proporciones entre categorías.", - "3": "Representación de datos categóricos: Los gráficos de tipo pie son especialmente útiles para representar datos categóricos, donde las categorías son mutuamente excluyentes y no tienen un orden inherente.\nPor ejemplo, se pueden usar para mostrar la distribución porcentual de ingresos en diferentes categorías de gastos.", - "4": "Mejora de la presentación visual: Los gráficos de tipo pie se utilizan comúnmente en presentaciones y documentos para comunicar información de manera visualmente atractiva y fácilmente comprensible.\nLa forma circular y los colores utilizados pueden captar rápidamente la atención y resaltar las relaciones proporcionales entre las categorías." - }, - "end": { - "0": "Los gráficos de tipo de sectores son una herramienta efectiva para representar proporciones y porcentajes de categorías en un conjunto de datos.\nPermiten identificar las categorías dominantes y proporcionan una presentación visual atractiva.\nSin embargo, es importante tener en cuenta sus limitaciones en términos de comparación precisa entre categorías y su enfoque en datos categóricos." - } - } - }, - "scatter-plots": { - "warning": { - "axes": "Selecciona en la configuración las columnas de los ejes X e Y." + } + }, + "scatter-plots": { + "warning": { + "axes": "Selecciona en la configuración las columnas de los ejes X e Y." }, "title": "Gráfico de tipo Dispersión", "description": { @@ -1607,7 +1420,8 @@ "0": "Los gráficos de violín son una herramienta útil para visualizar y comparar distribuciones de datos.\nPermiten analizar la forma, dispersión, simetría y presencia de valores atípicos en los datos, y son especialmente útiles cuando se requiere la comparación entre múltiples grupos o categorías.\nSu representación gráfica atractiva y concisa los convierte en una herramienta efectiva para comunicar información compleja de manera comprensible." } } - } + }, + "select-plot": "Tipo de gráfico" }, "face-api": { "years": "Años", @@ -1621,7 +1435,23 @@ }, "pages": { "version": { - "title": "Versión" + "title": "Versión", + "app": "Versión de la aplicación", + "environment": "Entorno (modo)", + "backend": "Backend en uso", + "runtime": "Esta instalación", + "changes": "Cambios", + "changes-text": "Todo lo que cambia en cada versión queda en el historial del repositorio.", + "commits": "Historial de cambios (commits)", + "releases": "Versiones publicadas", + "dependencies": "Dependencias", + "dependencies-help": "Las librerías de las que depende la aplicación, con la versión que pide package.json.", + "runtime-dependencies": "De la aplicación", + "dev-dependencies": "De desarrollo", + "package": "Paquete", + "declared": "Versión pedida", + "search": "Buscar un paquete", + "no-results": "Ningún paquete coincide con la búsqueda." }, "index": { "tabular-classification": { @@ -1661,1041 +1491,3808 @@ "title": "Para aplicar la regresión y modelar la relación entre variables, debemos seguir los siguientes pasos:" } }, - "object-detection": { - "1-title": "Identificación de objetos", - "1-description-1": "La identificación de objetos consiste en detectar y clasificar diferentes elementos en una imagen.", - "1-description-2": "Estos modelos son entrenados con multitud de imágenes diferentes que les permite aprender poco a poco qué caracteriza a cada objeto.", - "1-button": "Modelos pre-entrenados", - "2-title": "Identificación de objetos" + "object-detection": { + "1-title": "Identificación de objetos", + "1-description-1": "La identificación de objetos consiste en detectar y clasificar diferentes elementos en una imagen.", + "1-description-2": "Estos modelos son entrenados con multitud de imágenes diferentes que les permite aprender poco a poco qué caracteriza a cada objeto.", + "1-button": "Modelos pre-entrenados", + "2-title": "Identificación de objetos" + }, + "image-classification": { + "1-title": "Clasificación de imágenes", + "1-description-1": "La clasificación de imágenes de igual forma que la clasificación tabular sirve para determinar la clase a la que pertenece la imagen dependiendo de los elementos que la forman.", + "1-button": "Modelos pre-entrenados", + "2-title": "Diseñar, crear y editar una arquitectura", + "2-description-1": "A través de esta herramienta podemos crear una red neuronal para clasificar datos multi clase.", + "2-description-2": "Para diseñar, crear, entrenar y evaluar una arquitectura personalizada, debemos:", + "2-description-list": { + "1": "Definir el número de capas, sus funciones de activación.", + "2": "Definir la tasa de aprendizaje", + "3": "Definir el número de épocas.", + "4": "Definir el optimizador.", + "5": "Definir la función de perdida.", + "6": "Definir las funciones de métricas" + }, + "2-button": "Crear y entrenar un modelo" + }, + "hero": { + "text": "Nets4Learning es una plataforma web para aprender cómo funcionan las redes neuronales: eliges una tarea, diseñas la red, la entrenas y la pruebas, todo en el navegador y sin instalar nada. Está pensada para estudiantes y docentes." + }, + "clustering": { + "1-title": "Agrupamiento", + "1-description-1": "Agrupa los datos sin decir qué es cada fila (aprendizaje no supervisado): k-means busca k grupos de filas parecidas entre sí.", + "1-description-2": "Verás cómo se forman los grupos paso a paso y, en los conjuntos que traen las clases reales, si los grupos se parecen a ellas aunque no las haya visto.", + "1-button": "Elegir un conjunto de datos" + }, + "time-series": { + "1-title": "Series temporales", + "1-description-1": "Predice los siguientes valores de una serie temporal (los pasajeros de cada mes, la temperatura de cada día…) a partir de los anteriores: la red aprende con ventanas de valores pasados.", + "1-description-2": "Prueba los modelos ya entrenados con tres series clásicas (los pasajeros de avión, las temperaturas de Melbourne y las manchas solares): verás cómo predicen la parte final de la serie, que no vieron al entrenar, si mejoran las predicciones más sencillas (repetir el último valor o el de hace una estación) y lo que viene después.", + "1-button": "Modelos pre-entrenados", + "2-title": "Diseñar, crear y editar una arquitectura para predecir series", + "2-description-1": "A través de esta herramienta podemos crear una red neuronal que predice el siguiente valor de una serie a partir de los anteriores, con una de las series de ejemplo o con una propia.", + "2-description-2": "Para diseñar, crear, entrenar y evaluar una arquitectura personalizada, debemos:", + "2-description-list": { + "1": "Definir la ventana: cuántos valores anteriores mira la red.", + "2": "Definir qué parte final de la serie se aparta para probar y si se diferencia.", + "3": "Definir el número de capas, su tipo (Dense o recurrentes: SimpleRNN, LSTM y GRU) y sus funciones de activación.", + "4": "Definir la tasa de aprendizaje.", + "5": "Definir el número de épocas y el tamaño del lote.", + "6": "Definir el optimizador y la función de pérdida." + }, + "2-button": "Crear y entrenar un modelo" + } + }, + "contribute": { + "title": "Contribuye", + "github": { + "title": "Proyecto en GitHub" + }, + "license": { + "title": "Licencia", + "text": "El código tiene licencia MIT: puedes usarlo, copiarlo, modificarlo y distribuirlo libremente, manteniendo el aviso de copyright. Los conjuntos de datos y los modelos de terceros conservan sus propias licencias, que se indican en la descripción de cada uno.", + "full": "Texto completo de la licencia" + }, + "intro": "Nets4Learning es software libre, con licencia MIT, del grupo de investigación SIMIDAT de la Universidad de Jaén. Cualquier ayuda es bienvenida: avisar de un error, proponer una mejora, traducir, añadir conjuntos de datos y modelos o mejorar el código.", + "ways": { + "title": "Cómo colaborar", + "issues": { + "title": "Informa de un error o propón una mejora", + "text": "Abre una incidencia en GitHub contando qué ha pasado, en qué página y con qué navegador, o qué te gustaría que tuviera la aplicación.", + "link": "Abrir una incidencia" + }, + "translate": { + "title": "Traduce la aplicación", + "text": "Los textos están en public/locales, un fichero por idioma (español, inglés y japonés), y el manual en public/docs. Cualquier corrección o idioma nuevo ayuda.", + "link": "Ver las traducciones" + }, + "datasets": { + "title": "Añade un conjunto de datos o un modelo", + "text": "Cada uno es una clase en la carpeta models de su tarea, con su clave en MODEL_KEYS.ts, su opción del menú en DATA_MODEL.ts, sus textos y sus ficheros.", + "link": "Ver las tareas" + }, + "code": { + "title": "Mejora el código", + "text": "Haz un fork del repositorio, crea una rama con tus cambios y abre un pull request. Las pruebas automáticas lo revisarán antes de integrarlo.", + "link": "Ver los pull requests" + } + }, + "setup": { + "title": "Ponlo en marcha en tu equipo", + "requirements": "Necesitas Node.js 22 o posterior y pnpm 12; Corepack instala la versión exacta de pnpm.", + "url": "La aplicación queda en", + "scripts": [ + "Servidor de desarrollo, que se recarga al guardar", + "Tests unitarios (Vitest), una vez", + "Pruebas en el navegador (Playwright) con la versión de Netlify", + "Revisión del código con ESLint", + "Comprueba los tipos y construye la versión de SIMIDAT" + ] + }, + "checklist": { + "title": "Antes de enviar tus cambios", + "items": [ + "Escribe los commits con Conventional Commits (feat:, fix:, docs:…): commitlint los comprueba.", + "Pasa pnpm lint, pnpm test run y pnpm build:simidat. Las pruebas de GitHub también pasan pnpm test:e2e.", + "Pon cada texto nuevo de la interfaz en los tres ficheros de traducción.", + "Si añades un conjunto de datos o un modelo, cita su origen y su licencia en su descripción." + ] + }, + "cite": { + "title": "Cita el trabajo", + "text": "Si usas Nets4Learning en una clase, un trabajo o un artículo, cita el artículo que describe la plataforma:", + "copy": "Copiar BibTeX", + "copied": "Copiado" + }, + "docs": { + "title": "Documentación técnica", + "text": "Guías del repositorio para quien quiera tocar el código (en inglés).", + "i18n": "Traducciones (i18n)", + "directory-structure": "Estructura de carpetas", + "introduction": "Clasificación tabular: introducción", + "add-entry": "Clasificación tabular: añadir un conjunto de datos", + "create-model": "Clasificación tabular: crear un modelo" + } + }, + "menu-selection-dataset": { + "0-tabular-classification": { + "csv": "Subir conjunto de datos", + "csv-text": "Sube un fichero con un conjunto de datos en formato .csv, .arff, .json, .jsonl o .parquet" + }, + "form-description-1": "Elige el conjunto de datos con el que vas a entrenar o sube el tuyo.", + "form-label": "Selecciona un conjunto de datos", + "form-option-_-1": "Selecciona un conjunto de datos", + "form-upload-description": "Ahora si lo deseas puedes cargar tu propia arquitectura, en caso contrario pulsa en continuar y se cargará una arquitectura por defecto de ejemplo.", + "form-submit": "Continuar", + "1-regression": { + "csv": "Subir conjunto de datos", + "csv-text": "Sube un fichero con un conjunto de datos en formato .csv, .arff, .json, .jsonl o .parquet" + }, + "upload-text": "Sube tu propio conjunto de datos (CSV, ARFF, JSON, JSONL o Parquet) y prepáralo antes de entrenar.", + "own-dataset": "Tu propio conjunto de datos", + "example-datasets": "Conjuntos de datos de ejemplo", + "clustering": { + "csv": "Subir un CSV" + }, + "time-series": { + "csv": "Subir una serie" + } + }, + "menu-selection-model": { + "form-description-1": "Selecciona a continuación el modelo entrenado con el que se va a trabajar.", + "form-description-2": "-", + "form-label": "Selecciona un modelo pre-entrenado", + "form-option-_-1": "Selecciona un modelo pre-entrenado", + "form-submit": "Continuar" + }, + "playground": { + "form": { + "select-parameter": "Selecciona el parámetro", + "parameter": "Parámetro", + "parameter-integer": "Parámetro entero", + "parameter-decimal": "Parámetro decimal", + "parameter-float": "Parámetro flotante de precisión simple", + "parameter-double": "Parámetro flotante de precisión doble", + "parameter-categorical": "Parámetro categórico", + "data-to-check": "Datos a probar", + "vector-to-check": "Vector a probar", + "button-check-result": "Predecir", + "type-categorical": "Categórica, {{count}} valores", + "type-integer": "Número entero", + "type-decimal": "Número decimal", + "range": "{{min}} – {{max}} en los datos" + }, + "0-tabular-classification": { + "general": { + "model": "Modelo", + "description-input": "Descripción de la entrada de datos", + "dataframe-processed-help": "Los mismos datos con cada valor categórico convertido en un número (LabelEncoder; la correspondencia está en «Atributos» y «Clases»). Así es como los recibe el modelo: la última columna es la clase que tiene que predecir.", + "description-features": "Formulario de edición de las características", + "description-data": "Datos del formulario", + "description-vector": "Vector de los datos", + "explainability": "Explicabilidad del modelo", + "select-class": "Seleccionar clase", + "n-samples": "Número de muestras", + "n-samples-help": "Muestras utilizadas por KernelSHAP", + "calculating": "Calculando...", + "show-explain": "Mostrar explicación", + "hide-explain": "Ocultar explicación", + "n-instances": "Instancias a agregar", + "n-instances-help": "Instancias del conjunto de datos que se agregan para calcular la importancia global (media de |SHAP|)", + "show-global": "Mostrar importancia global", + "hide-global": "Ocultar importancia global", + "no-data": "No hay conjunto de datos disponible para calcular la importancia global", + "sort-order": "Ordenar", + "sort-desc": "De mayor a menor importancia", + "sort-asc": "De menor a mayor importancia", + "sort-none": "Orden original", + "chart-type": "Tipo de gráfico", + "chart-bar": "Barras (media |SHAP|)", + "chart-beeswarm": "Enjambre (beeswarm)", + "beeswarm-shap-value": "Valor SHAP", + "beeswarm-feature-value": "Valor de la característica", + "beeswarm-low": "Bajo", + "beeswarm-high": "Alto", + "explain-panel-title": "Explicabilidad", + "explain-panel-local-title": "Explicación local (una instancia)", + "explain-panel-local-body": "SHAP explica una predicción concreta repartiendo la diferencia entre esta predicción y la predicción media del modelo (valor base) entre las características. Cada barra indica cuánto y en qué dirección empuja una característica: positiva hacia la clase seleccionada, negativa en contra.", + "explain-panel-local-body-regression": "SHAP explica una predicción concreta repartiendo la diferencia entre el valor predicho y la predicción media del modelo (valor base) entre las características. Cada barra indica cuánto y en qué dirección empuja una característica: positiva sube el valor predicho, negativa lo baja.", + "explain-panel-global-title": "Importancia global (todas las instancias)", + "explain-panel-global-body": "La importancia global agrega muchas explicaciones locales. El gráfico de barras muestra la media de los valores absolutos (media |SHAP|): cuánto pesa cada característica en promedio. El beeswarm añade la dirección y la dispersión del efecto, coloreando cada punto según el valor de la característica. Otros métodos, como la importancia por permutación, pueden ordenar las variables de forma algo distinta, sobre todo cuando hay variables relacionadas entre sí: cada método mide la importancia a su manera." + }, + "0_upload": { + "upload": "Subir", + "upload-your-model": "Carga tu propio modelo.", + "upload-your-model-description": "Ten en cuenta que tienes que subir el archivo .json y el fichero .bin para luego cargar el modelo", + "button-upload-your-model": "Cargar modelo" + }, + "generator": { + "manual": { + "title": "Manual del generador de modelos", + "details-edit-layers": { + "title": "Editor de las capas", + "text-0": "Se pueden editar las capas de la red neuronal, puedes agregar tantas como desees pulsando el botón \"Añadir capa\" al inicio o al final.", + "list": { + "0": "Neuronas de la capa:
Cada neurona en una capa está conectada a todas las neuronas de la capa anterior y de la capa siguiente.
Cada neurona en una capa tiene un conjunto de pesos asociados que ponderan su valor de salida.
Podemos editar el número de neuronas de la capa.", + "1": "Función de activación:
La función de activación de una neurona se refiere a la función matemática que calcula su salida. Podemos editar la función de activación de las neuronas de cada capa." + } + }, + "details-hyper-parameters-editor": { + "title": "Editor de hiperparámetros", + "text-0": "Se pueden editar los parámetros generales necesarios para la creación del modelo.
Estos parámetros son:", + "list": { + "0": "Tasa de aprendizaje:
Cuánto cambian los pesos de la red en cada paso del entrenamiento (por ejemplo, 0.01).", + "1": "Número de épocas:
Cantidad de veces que se le pasa el conjunto de entrenamiento a la red (a mayor número, más tiempo tarda en entrenar).", + "2": "Tamaño del conjunto de pruebas:
Porcentaje del conjunto de datos que se utilizaran para las pruebas del modelo (datos de prueba). El resto de datos se utilizarán para el entrenamiento de la red (datos de entrenamiento).", + "3": "Optimizador:
Es una función que se utiliza para ajustar los pesos de la red.", + "4": "Función de pérdida:
Es un método de calculo de error para medir la eficiencia del modelo durante el entrenamiento.", + "5": "Función de métrica:
Es la media de evaluación que se utiliza para valorar el rendimiento de un modelo de aprendizaje automático con los datos de prueba." + } + }, + "details-hyper-parameters-info": { + "title": "Información de hiperparámetros", + "list": { + "0": "Tasa de aprendizaje:
La tasa de aprendizaje es un parámetro que determina cuánto se deben actualizar los pesos de la red neuronal en función del error calculado durante el entrenamiento.", + "1": "Número de épocas:
El número de épocas se refiere al número de veces que se presentan los datos de entrenamiento a la red neuronal durante el proceso de entrenamiento. Cada iteración implica una actualización de los pesos de la red en función del error calculado.", + "2": "Tamaño del conjunto de pruebas:
El tamaño del conjunto de pruebas se refiere a la cantidad de datos utilizados para evaluar el rendimiento de la red neuronal después del entrenamiento. Este conjunto de datos no se utiliza en el entrenamiento de la red neuronal y se utiliza para medir la capacidad de la red de generalizar a datos nuevos.", + "3": "Optimizador:
El optimizador es un algoritmo utilizado para actualizar los pesos de la red neuronal en función del error calculado durante el entrenamiento. Algunos ejemplos de optimizadores son el Descenso del Gradiente Estocástico (SGD), el Adam y el Adagrad.", + "4": "Función de pérdida:
La función de pérdida es una medida del error entre las predicciones de la red neuronal y las salidas reales. Se utiliza para optimizar la red neuronal durante el entrenamiento y existen diferentes funciones de pérdida, como la Entropía Cruzada y el Error Cuadrático Medio." + } + }, + "details-create-and-train-models": { + "title": "Crear y entrenar modelo", + "text-0": "Una vez se han rellenado todos los campos anteriores podemos crear el modelo pulsando el botón \"Crear y entrenar modelo\".", + "text-1": "Si se pulsa el botón \"Abrir Visor\" se muestran dos gráficas. La gráfica superior muestra la evolución de la función de pérdida durante el entrenamiento. La gráfica inferior muestra la evolución de la métrica de evaluación accuracy. En las gráficas el color azul representa la evolución de los valores en el conjunto de entrenamiento y el color naranja representa las medidas para el conjunto de prueba.", + "text-2": "La precisión de validación es importante para detectar el sobre ajuste (overfitting) del modelo, que se produce cuando el modelo se ajusta demasiado a los datos de entrenamiento y no generaliza bien a nuevos datos." + }, + "details-export-models": { + "title": "Exportar modelo", + "text-0": "Si hemos creado el modelo correctamente se añadirá una entrada en la tabla de modelos generados. La aplicación permite exportar los modelos generados y guardarlos localmente." + }, + "details-prediction": { + "title": "Clasificación", + "text-0": "El formulario final nos permite seleccionar las características principales que se usan para determinar la clase.", + "text-1": "Al pulsar el botón \"Clasificar\", el modelo predice la clase del ejemplo a partir de sus características de entrada y muestra la probabilidad de cada clase." + } + } + } + }, + "generator": { + "prediction": { + "class_id_name": "El identificador del target {{class_target_id}} corresponde a la clase {{name}}" + }, + "layer-design": "Diseño de capas", + "neural_network_modes": { + "title": "Modos de visualización", + "compact": "Modo compacto", + "extend": "Modo extendido" + }, + "dataset": { + "title": "Conjunto de datos", + "upload-dataset": "Subir conjunto de datos", + "attributes": { + "title": "Atributos", + "int32": "Numérico", + "float32": "Decimal", + "string": "Texto", + "label-encoder": "Label encoder", + "one-hot-encoder": "OneHot encoder", + "classes": "Clases" + }, + "details": { + "dataframe-processed": "Dataframe procesado", + "description-original": "Descripción del dataframe original", + "description-processed": "Descripción del dataframe procesado", + "data": "Información del conjunto de datos", + "info": "Información" + } + }, + "layers": { + "title": "Diseño de capas", + "page-info": "Puedes visitar la web netron.app para visualizar la topología al completo" + }, + "editor-layers": { + "title": "Editor de capas", + "add-layer-start": "Añadir capa al principio", + "add-layer-end": "Añadir capa al final", + "delete-layer": "Eliminar capa {{index}}", + "move-up": "Subir la capa {{index}}", + "move-down": "Bajar la capa {{index}}", + "move-group": "Orden de la capa {{index}}", + "moved": "Capa {{index}} movida al puesto {{position}}.", + "drag": "Arrastra para mover la capa {{index}}", + "drag-help": "Para cambiar el orden, arrastra cada capa por el asa de su izquierda, o ábrela y usa «Subir» y «Bajar».", + "layer-id": "Capa {{index}}", + "kernel-size": "Tamaño del Kernel", + "kernel-size-placeholder": "Introduce el tamaño del kernel de la capa", + "filters-size": "Tamaño del filtro", + "filters-size-placeholder": "Introduce el filtro de la capa", + "units": "Neuronas de la capa", + "units-placeholder": "Introduce el número de neuronas de la capa", + "activation-function-select": "Selecciona la función de activación", + "activation-function-info": "Será el optimizador que se usará para activar la función", + "strides": "Strides", + "strides-placeholder": "Introduce el strides de la capa", + "pool-size": "Pool size", + "pool-size-placeholder": "Introduce el pool size de la capa", + "layer-class": "Tipo de capa", + "removed": "Capa {{index}} eliminada. Puedes deshacerlo con «Deshacer», encima de las capas.", + "removed-short": "Capa {{index}} eliminada.", + "restored": "Capa {{index}} recuperada.", + "undo": "Deshacer" + }, + "editor-feature-selector": { + "title": "Selector de características", + "feature-selector-x": "Selector de características / Conjunto (X)", + "feature-selector-y": "Selector de características / Objetivo (Y)", + "add-feature": "Añadir característica", + "delete-feature": "Eliminar característica {{value}}" + }, + "general-parameters": { + "title": "Editor de hiperparámetros", + "learning-rate": "Tasa de aprendizaje", + "learning-rate-placeholder": "Introduce la tasa de aprendizaje", + "learning-rate-info": "Cuánto cambian los pesos en cada paso del entrenamiento. Con valores altos aprende más rápido pero puede no converger; con valores bajos es más estable pero más lento.", + "number-of-epochs": "N. épocas", + "number-of-epochs-placeholder": "Número de épocas", + "number-of-epochs-info": "Mientras más alto sea, mas tardará en ejecutarse el entrenamiento", + "train-rate": "Tamaño del conjunto de pruebas", + "train-rate-placeholder": "Introduce el tamaño del banco de pruebas", + "train-rate-info": "Valor entre 0 y 100 (es un porcentaje)", + "optimizer-id": "Selecciona el optimizador", + "optimizer-id-info": "Será el optimizador que se usará para corregir el error.", + "loss-id": "Selecciona la función de pérdida", + "loss-id-info": "Será la función que se usará para evaluar el error de las neuronas.", + "metrics-id": "Selecciona la métrica", + "metrics-id-info": "Será el tipo de métrica que se usará para la evaluación durante entrenamiento.", + "test-size": "Tamaño del conjunto de pruebas", + "test-size-placeholder": "Tamaño del conjunto de pruebas", + "test-size-info": "Valor entre 0 y 100 (es un porcentaje) del tamaño del conjunto de pruebas", + "delete-metric": "Eliminar función de métrica {{index}}", + "add-metric": "Añadir función de métrica", + "metric-id-__index__": "Métrica {{index}}", + "metric-id-select": "Selecciona la función de métrica", + "metric-id-info": "Será una de las funciones de métrica", + "loss-group-classification": "Clasificación", + "loss-group-regression": "Regresión", + "batch-size": "Tamaño del lote", + "batch-size-placeholder": "Ejemplos por lote", + "batch-size-info": "Cuántas ventanas se usan en cada actualización de los pesos: con lotes pequeños aprende con más ruido; con lotes grandes, cada época es más rápida." + }, + "loaded": "Cargado", + "load": "Cargar", + "waiting-for-file": "Sube un fichero de datos (CSV, ARFF, JSON, JSONL o Parquet) para empezar.", + "waiting-for-process": "Procesa el conjunto de datos para continuar.", + "waiting-for-training": "Todavía no hay modelos entrenados. Configura la red y entrena uno para verlo aquí.", + "models": { + "title": "Modelos", + "history-train": "Historial del entrenamiento", + "train": "Entrenamiento", + "button-submit": "Entrenar modelo", + "open-visor": "Abrir visor", + "close-visor": "Cerrar visor", + "export-current-model": "Exportar modelo actual" + }, + "table": { + "id": "ID", + "load": "Cargar", + "learning-rate": "Tasa de aprendizaje", + "number-of-epochs": "N. Épocas", + "train-rate": "Tamaño del conjunto de pruebas", + "layers": "Capas", + "optimizer-id": "Optimizador", + "loss-id": "Perdida", + "metric-id": "Métrica", + "download": "Descargar" + }, + "dynamic-form-dataset": { + "title": "Clasificación", + "text-0-__column_name_target__": "Introduce el valor de cada característica de entrada del ejemplo que quieres clasificar ({{column_name_target}}) o elige una entidad del conjunto de datos en el selector de arriba.", + "select-option": "Selecciona una opción", + "input-data": "Introduce los datos a probar", + "input-vector": "Introduce el vector a probar", + "test-vector": "Vector a probar", + "test-input-data": "Datos del formulario", + "test-input-vector": "Vector de los datos", + "selector-entity": "Selecciona la entidad", + "search-entity": "Buscar por número o clase…", + "entity-count": "{{shown}} de {{total}}", + "no-entity": "Ninguna coincide con la búsqueda", + "selector-model": "Selecciona el modelo", + "classify-button": "Clasificar" + }, + "list-models-generated": "Lista modelos generados", + "visor": { + "title": "Configuración del visor", + "rmse": "RMSE", + "val_rmse": "VAL RMSE", + "mae": "MAE", + "val_mae": "VAL MAE", + "history-train": "Historial del entrenamiento", + "train": "Entrenamiento", + "summary": "Resumen", + "scatterplot": { + "__feature____target__": "{{feature}} x {{target}}" + }, + "original-vs-predictions": "Datos originales / predicción", + "model": "Modelo", + "dataset": "Conjunto de datos", + "predictions": "Predicción", + "predicted": "Predicho", + "confusion-matrix": "Matriz de confusión", + "line-chart": "Gráfico de líneas" + }, + "waiting-for-models": "Entrena un modelo para poder hacer predicciones.", + "classify": { + "waiting": "Clasifica un ejemplo para ver aquí el resultado.", + "predicted-class": "Clase predicha", + "confidence": "con una probabilidad del {{value}}", + "chart-title": "Probabilidad de cada clase", + "chart-title-output": "Salida de la red para cada clase", + "chart-help": "La barra resaltada es la clase que elige el modelo: la más probable. Cuando el modelo duda, varias barras tienen alturas parecidas.", + "chart-help-output": "La última capa no usa softmax, así que estos valores no son probabilidades. El modelo elige la clase con el valor más alto (barra resaltada).", + "axis-class": "Clase", + "axis-probability": "Probabilidad (%)", + "axis-output": "Salida", + "select-image": "Selecciona una imagen del conjunto de datos", + "actual-class": "Clase real: {{label}}", + "chart-title-top": "Las {{count}} clases más probables", + "chart-help-top": "El modelo distingue muchas más clases; aquí solo se muestran las más probables, con su probabilidad.", + "hit": "acierta", + "miss": "falla", + "test-image": "Imagen de prueba", + "class": "Clase" + }, + "waiting-for-prediction": "Haz una predicción para ver aquí el resultado.", + "training": { + "epoch": "Entrenando… época {{epoch}} de {{total}}", + "preparing": "Preparando los datos y el modelo…", + "stop": "Detener", + "stopping": "Deteniendo…", + "curves-title": "Curvas de entrenamiento", + "curves-model": "Modelo cuyas curvas se muestran", + "curves-compare": "Comparar modelos", + "compare-pick": "Modelos que se comparan (hasta {{max}})", + "compare-pick-more": "Marca al menos dos modelos para compararlos.", + "compare-same": "Tienen los mismos hiperparámetros: lo que cambia entre ellos viene del azar (los pesos con los que empieza cada red y el reparto de los datos).", + "compare-one": "Solo cambia {{name}}: la diferencia entre sus resultados se debe sobre todo a eso.", + "compare-some": "Cambian varias cosas ({{names}}): con varios cambios a la vez no se sabe cuál ha influido. Para ver qué hace cada uno, cambia solo una cosa entre un entrenamiento y otro.", + "compare-quote": "«{{name}}»", + "compare-caption": "Hiperparámetros de cada modelo (resaltados, los que cambian) y valores de la última época (entre paréntesis, con los datos de validación).", + "compare-parameter": "Parámetro", + "compare-changed": "cambia", + "compare-final": "{{name}} al final", + "epoch-axis": "Época", + "train": "Entrenamiento", + "validation": "Validación", + "best": "Mejor", + "best-title": "Menor pérdida de validación en la última época", + "confusion-title": "Matriz de confusión (validación)", + "confusion-accuracy": "Aciertos: {{accuracy}} ({{correct}} de {{total}} ejemplos que el modelo no vio al entrenar).", + "confusion-real": "Clase real", + "confusion-predicted": "Clase predicha", + "confusion-total": "Total", + "confusion-recall": "Sensibilidad", + "confusion-precision": "Precisión", + "confusion-legend": "Cada celda indica cuántos ejemplos de la clase real (fila) se predijeron como la clase de la columna y qué parte de su fila son. Verde: aciertos; rojo: errores; cuanto más intenso, más ejemplos.", + "curve-description": "{{name}} en {{epochs}} épocas: con los datos de entrenamiento, de {{first}} a {{last}}.", + "curve-description-validation": "Con los de validación, de {{first}} a {{last}}.", + "announce-start_one": "Entrenamiento iniciado: {{count}} época", + "announce-start_other": "Entrenamiento iniciado: {{count}} épocas", + "announce-stopped": "Entrenamiento detenido en la época {{epoch}} de {{total}}. El modelo se guarda con esas épocas", + "announce-error": "El entrenamiento no ha podido terminar", + "go-to-result": "Ir al resultado", + "curve-data": "{{name}} en cada época", + "remaining": "quedan unos {{time}}", + "last-run_one": "El último entrenamiento tardó {{time}} ({{count}} época, {{perEpoch}} por época). Con más épocas tardará más, y se puede detener cuando quieras.", + "last-run_other": "El último entrenamiento tardó {{time}} ({{count}} épocas, {{perEpoch}} por época). Con más épocas tardará más, y se puede detener cuando quieras." + }, + "help": { + "learning-rate": "Tamaño del paso con el que el optimizador corrige los pesos de la red después de cada lote de datos.", + "epochs": "Una época es una pasada completa por todos los datos de entrenamiento. Más épocas dan más ocasiones de aprender, pero también de sobreajustar.", + "test-size": "Porcentaje de los datos que se aparta para comprobar el modelo con ejemplos que no ha visto al entrenar (validación).", + "optimizer": "Algoritmo que decide cómo cambiar los pesos a partir del error. Adam suele funcionar bien sin ajustar nada más.", + "loss": "Mide cuánto se equivoca el modelo; el entrenamiento intenta que sea lo más pequeña posible.", + "metric": "Medida que se calcula durante el entrenamiento para saber cómo va el modelo (por ejemplo, la precisión). No se usa para corregir los pesos.", + "recall": "Sensibilidad (recall): de los ejemplos que son de esta clase, la parte que el modelo acierta.", + "precision": "Precisión: de las veces que el modelo predice esta clase, la parte en que acierta.", + "accuracy": "Exactitud (accuracy): ejemplos acertados sobre el total de ejemplos de validación.", + "batch-size": "Cuántos ejemplos ve la red antes de actualizar sus pesos.", + "units": "Cuántas neuronas tiene la capa. Con más, la red puede aprender relaciones más complicadas, pero tarda más en entrenar y puede aprenderse los datos de memoria.", + "activation": "Lo que hace cada neurona con la suma que le llega. ReLU, sigmoide o tanh dejan a la red aprender relaciones que no son líneas rectas; softmax, en la última capa, reparte la probabilidad entre las clases." + }, + "example-from-dataset": "Ejemplo del conjunto de datos" + }, + "1-regression": { + "generator": { + "manual": { + "title": "Manual del generador de modelos", + "simple-regression": "Regresión simple", + "multiple-regression": "Regresión multiple", + "details-edit-layers": { + "title": "Editor de las capas", + "text": { + "0": "Se pueden editar las capas de la red neuronal, puedes agregar tantas como desees pulsando el botón \"Añadir capa\" al inicio o al final." + }, + "list": { + "0": "Neuronas de la capa:
Cada neurona en una capa está conectada a todas las neuronas de la capa anterior y de la capa siguiente.
Cada neurona en una capa tiene un conjunto de pesos asociados que ponderan su valor de salida.
Podemos editar el número de neuronas de la capa.", + "1": "Función de activación:
La función de activación de una neurona se refiere a la función matemática que calcula su salida. Podemos editar la función de activación de las neuronas de cada capa." + } + }, + "details-hyper-parameters-editor": { + "title": "Editor de hiperparámetros", + "text": { + "0": "Se pueden editar los parámetros generales necesarios para la creación del modelo.
Estos parámetros son:" + }, + "list": { + "0": "Tasa de aprendizaje:
Cuánto cambian los pesos de la red en cada paso del entrenamiento (por ejemplo, 0.01).", + "1": "Número de épocas:
Cantidad de veces que se le pasa el conjunto de entrenamiento a la red (a mayor número, más tiempo tarda en entrenar).", + "2": "Tamaño del conjunto de pruebas:
Porcentaje del conjunto de datos que se utilizaran para las pruebas del modelo (datos de prueba). El resto de datos se utilizarán para el entrenamiento de la red (datos de entrenamiento).", + "3": "Optimizador:
Es una función que se utiliza para ajustar los pesos de la red.", + "4": "Función de pérdida:
Es un método de calculo de error para medir la eficiencia del modelo durante el entrenamiento.", + "5": "Función de métrica:
Es la media de evaluación que se utiliza para valorar el rendimiento de un modelo de aprendizaje automático con los datos de prueba." + } + }, + "details-hyper-parameters-info": { + "title": "Información de hiperparámetros", + "list": { + "0": "Tasa de aprendizaje:
La tasa de aprendizaje es un parámetro que determina cuánto se deben actualizar los pesos de la red neuronal en función del error calculado durante el entrenamiento.", + "1": "Número de épocas:
El número de épocas se refiere al número de veces que se presentan los datos de entrenamiento a la red neuronal durante el proceso de entrenamiento. Cada iteración implica una actualización de los pesos de la red en función del error calculado.", + "2": "Tamaño del conjunto de pruebas:
El tamaño del conjunto de pruebas se refiere a la cantidad de datos utilizados para evaluar el rendimiento de la red neuronal después del entrenamiento. Este conjunto de datos no se utiliza en el entrenamiento de la red neuronal y se utiliza para medir la capacidad de la red de generalizar a datos nuevos.", + "3": "Optimizador:
El optimizador es un algoritmo utilizado para actualizar los pesos de la red neuronal en función del error calculado durante el entrenamiento. Algunos ejemplos de optimizadores son el Descenso del Gradiente Estocástico (SGD), el Adam y el Adagrad.", + "4": "Función de pérdida:
La función de pérdida es una medida del error entre las predicciones de la red neuronal y las salidas reales. Se utiliza para optimizar la red neuronal durante el entrenamiento y existen diferentes funciones de pérdida, como la Entropía Cruzada y el Error Cuadrático Medio." + } + }, + "details-create-and-train-models": { + "title": "Crear y entrenar modelo", + "text": { + "0": "Una vez se han rellenado todos los campos anteriores podemos crear el modelo pulsando el botón \"Crear y entrenar modelo\".", + "1": "Si se pulsa el botón \"Abrir Visor\" se muestran dos gráficas. La gráfica superior muestra la evolución de la función de pérdida durante el entrenamiento. La gráfica inferior muestra la evolución de la métrica de evaluación accuracy. En las gráficas el color azul representa la evolución de los valores en el conjunto de entrenamiento y el color naranja representa las medidas para el conjunto de prueba.", + "2": "La precisión de validación es importante para detectar el sobre ajuste (overfitting) del modelo, que se produce cuando el modelo se ajusta demasiado a los datos de entrenamiento y no generaliza bien a nuevos datos." + } + }, + "details-export-models": { + "title": "Exportar modelo", + "text": { + "0": "Si hemos creado el modelo correctamente se añadirá una entrada en la tabla de modelos generados. La aplicación permite exportar los modelos generados y guardarlos localmente." + } + }, + "details-plot-models": { + "title": "Gráfico de predicciones", + "text": { + "0": "Para verlo se usa un gráfico de dispersión: los datos originales son una nube de puntos y las predicciones del modelo, una línea. Según la arquitectura, la línea será recta (con cierta pendiente) o se curvará para ajustarse mejor a los datos. Para ello se hacen 100 predicciones x distantes, desde primer valor al último valor." + } + } + }, + "simple-regression": "Regresión simple", + "multiple-regression": "Regresión multiple" + }, + "dataframe": { + "title": "Dataframe procesado", + "help": "Los mismos datos con cada valor categórico convertido en un número (LabelEncoder). Antes de entrar en el modelo, los atributos se escalan; la columna {{target}} es el valor que tiene que predecir." + }, + "selector-instance": { + "option": "Selector de instancia" + }, + "selector-model": { + "option": "Selector de modelo" + }, + "details": { + "description-processed": { + "dataset": "Conjunto de datos procesado", + "describe": "Conjunto de datos estadísticas descriptivas" + } + }, + "predict": { + "title": "Predicción", + "instance": { + "__index__": "Instancia {{index}}" + }, + "model": { + "__index__": "Modelo {{index}}" + }, + "button-submit": "Predecir", + "list-models-generated": "Lista de modelos generados", + "list-models": "Lista de modelos generados", + "list-instances": "Lista de instancias", + "predicted-value": "Valor predicho de {{target}}", + "actual-value": "Valor real: {{value}}", + "error": "Error: {{value}} ({{percent}})", + "input-details": "Entrada del modelo paso a paso", + "choose-instance": "Elige una instancia del conjunto de datos para rellenar el formulario; después puedes cambiar sus valores.", + "no-models": "Este conjunto de datos no tiene ningún modelo preentrenado. Elige otro conjunto de datos o entrena tu propio modelo en el playground de regresión.", + "model-selector": "Modelo con el que predecir" + }, + "model-selector": { + "title": "Selector de modelos", + "option": "Selecciona un modelo" + } + }, + "3-image-classification": { + "generator": { + "manual": { + "title": "Manual del generador de modelos", + "details-edit-layers": { + "title": "Editor de las capas", + "text-0": "Se pueden editar las capas de la red neuronal, puedes agregar tantas como desees pulsando el botón \"Añadir capa\" al inicio o al final.", + "list": { + "0": "Neuronas de la capa:
Cada neurona en una capa está conectada a todas las neuronas de la capa anterior y de la capa siguiente.
Cada neurona en una capa tiene un conjunto de pesos asociados que ponderan su valor de salida.
Podemos editar el número de neuronas de la capa.", + "1": "Función de activación:
La función de activación de una neurona se refiere a la función matemática que calcula su salida. Podemos editar la función de activación de las neuronas de cada capa." + } + }, + "details-edit-layers-more-info": { + "title": "Información adicional capas", + "text-0": "Adicionalmente hay dos capas más que son comunes al resto de redes de aprendizaje automático enfocadas en la clasificación de imágenes", + "list": { + "0": "dense
Crea una capa densa (completamente conectada).", + "1": "dropout
El abandono consiste en establecer aleatoriamente una tasa de fracción de unidades de entrada a 0 en cada actualización durante el tiempo de entrenamiento, lo que ayuda a prevenir el sobreajuste.", + "2": "embedding
Asigna números enteros positivos (índices) a vectores densos de tamaño fijo. p.ej. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]", + "3": "flatten
Una capa aplanada aplana cada lote en sus entradas a 1D (haciendo la salida 2D).", + "4": "permute
Permuta las dimensiones de la entrada de acuerdo con un patrón dado.", + "5": "repeatVector
repite la entrada n veces en una nueva dimensión.", + "6": "reshape
Modifica la forma a una determinada entrada.", + "7": "spatialDropout1d
Versión 1D espacial de dropout." + } + }, + "details-hyper-parameters-editor": { + "title": "Editor de hiperparámetros", + "text-0": "Se pueden editar los parámetros generales necesarios para la creación del modelo.
Estos parámetros son:", + "list": { + "0": "Tasa de aprendizaje:
Cuánto cambian los pesos de la red en cada paso del entrenamiento (por ejemplo, 0.01).", + "1": "Número de épocas:
Cantidad de veces que se le pasa el conjunto de entrenamiento a la red (a mayor número, más tiempo tarda en entrenar).", + "2": "Tamaño del conjunto de pruebas:
Porcentaje del conjunto de datos que se utilizaran para las pruebas del modelo (datos de prueba). El resto de datos se utilizarán para el entrenamiento de la red (datos de entrenamiento).", + "3": "Optimizador:
Es una función que se utiliza para ajustar los pesos de la red.", + "4": "Función de pérdida:
Es un método de calculo de error para medir la eficiencia del modelo durante el entrenamiento.", + "5": "Función de métrica:
Es la media de evaluación que se utiliza para valorar el rendimiento de un modelo de aprendizaje automático con los datos de prueba." + } + }, + "details-hyper-parameters-info": { + "title": "Información de hiperparámetros", + "list": { + "0": "Tasa de aprendizaje:
La tasa de aprendizaje es un parámetro que determina cuánto se deben actualizar los pesos de la red neuronal en función del error calculado durante el entrenamiento.", + "1": "Número de épocas:
El número de épocas se refiere al número de veces que se presentan los datos de entrenamiento a la red neuronal durante el proceso de entrenamiento. Cada iteración implica una actualización de los pesos de la red en función del error calculado.", + "2": "Tamaño del conjunto de pruebas:
El tamaño del conjunto de pruebas se refiere a la cantidad de datos utilizados para evaluar el rendimiento de la red neuronal después del entrenamiento. Este conjunto de datos no se utiliza en el entrenamiento de la red neuronal y se utiliza para medir la capacidad de la red de generalizar a datos nuevos.", + "3": "Optimizador:
El optimizador es un algoritmo utilizado para actualizar los pesos de la red neuronal en función del error calculado durante el entrenamiento. Algunos ejemplos de optimizadores son el Descenso del Gradiente Estocástico (SGD), el Adam y el Adagrad.", + "4": "Función de pérdida:
La función de pérdida es una medida del error entre las predicciones de la red neuronal y las salidas reales. Se utiliza para optimizar la red neuronal durante el entrenamiento y existen diferentes funciones de pérdida, como la Entropía Cruzada y el Error Cuadrático Medio." + } + }, + "details-create-and-train-models": { + "title": "Crear y entrenar modelo", + "text-0": "Una vez se han rellenado todos los campos anteriores podemos crear el modelo pulsando el botón \"Crear y entrenar modelo\".", + "text-1": "Si se pulsa el botón \"Abrir Visor\" se muestran dos gráficas. La gráfica superior muestra la evolución de la función de pérdida durante el entrenamiento. La gráfica inferior muestra la evolución de la métrica de evaluación accuracy. En las gráficas el color azul representa la evolución de los valores en el conjunto de entrenamiento y el color naranja representa las medidas para el conjunto de prueba.", + "text-2": "La precisión de validación es importante para detectar el sobre ajuste (overfitting) del modelo, que se produce cuando el modelo se ajusta demasiado a los datos de entrenamiento y no generaliza bien a nuevos datos." + }, + "details-export-models": { + "title": "Exportar modelo", + "text-0": "Si hemos creado el modelo correctamente se añadirá una entrada en la tabla de modelos generados. La aplicación permite exportar los modelos generados y guardarlos localmente." + }, + "details-prediction": { + "title": "Clasificación", + "text-0": "El formulario final nos permite dibujar o subir una imagen para determinar la clase.", + "text-1": "Al pulsar el botón \"Ver resultado\", a partir de las características de entrada del elemento se obtiene la predicción de su clase de salida." + } + } + } + }, + "step-by-step": { + "title": "Paso a paso", + "intro": "Así aprende tu red: un ejemplo entra por la izquierda, recorre la red hacia delante, se mide cuánto se equivoca y ese error vuelve hacia atrás para corregir cada peso. Es la red que has diseñado arriba, con pesos iniciales al azar. Pulsa una neurona para ver sus cuentas.", + "intro-pretrained": "Así calcula este modelo ya entrenado su respuesta: un ejemplo entra por la izquierda, recorre la red hacia delante y se compara con la respuesta correcta. Hacia atrás verás cuánto cambiaría cada peso con un paso más de entrenamiento; el modelo de la página no cambia. Pulsa una neurona para ver sus cuentas.", + "too-big": "Tu red tiene {{nodes}} neuronas contando las de entrada ({{detail}}). El paso a paso solo se dibuja con menos de {{max}}, para que se pueda seguir: quita capas o neuronas en el editor de capas, por ejemplo con dos capas ocultas de 8.", + "too-big-pretrained": "Este modelo tiene {{nodes}} neuronas contando las de entrada ({{detail}}). El paso a paso solo se dibuja con menos de {{max}}, para que se pueda seguir. En la página de entrenamiento de este conjunto de datos puedes verlo con una red más pequeña.", + "not-dense": "Este modelo no es una red de capas densas: el paso a paso solo dibuja ese tipo de red.", + "mismatch": "La última capa tiene {{units}} neuronas y la red tiene que dar {{classes}} salidas: cámbiala en el editor de capas para verla paso a paso.", + "example": "Elige un ejemplo", + "search": "Buscar un ejemplo", + "no-results": "Ningún ejemplo coincide", + "back": "Fase anterior", + "next": "Siguiente", + "play": "Reproducir", + "pause": "Pausa", + "ten": "Entrenar con 10 ejemplos de golpe", + "speed": "Velocidad", + "speeds": { + "slow": "Lenta", + "normal": "Normal", + "fast": "Rápida" + }, + "same-example": "Repetir el mismo ejemplo", + "reset": "Reiniciar los pesos", + "reset-pretrained": "Volver a los pesos del modelo", + "legend": "Azul: valor o peso positivo; rojo: negativo. Cuanto más intenso o más grueso, mayor. En naranja, lo que vuelve hacia atrás: los deltas de las neuronas y los gradientes de los pesos.", + "phase-count": "Fase {{current}} de {{total}}", + "phase-title": { + "input": "La entrada", + "forward": "Hacia delante: capa {{layer}}", + "loss": "El error", + "backward": "Hacia atrás: capa {{layer}}", + "update": "Actualizar los pesos" + }, + "phase": { + "input": "Entra el ejemplo n.º {{row}}: sus {{count}} características, ya escaladas como en el entrenamiento, son los valores de las neuronas de entrada.", + "input-pretrained": "Entra el ejemplo n.º {{row}}: sus {{count}} características, tal como las recibe este modelo, son los valores de las neuronas de entrada.", + "forward": "Cada neurona de la capa {{layer}} multiplica cada entrada por el peso de su conexión, suma los productos y su sesgo (z) y aplica la activación {{activation}}. Las conexiones resaltadas son las que intervienen.", + "forward-softmax": "La capa {{layer}} suma sus entradas por sus pesos (z) y softmax convierte esas sumas en probabilidades, una por clase, que suman 1.", + "loss-classification": "La red da una probabilidad de {{probability}} a «{{target}}», la respuesta correcta. La pérdida, la entropía cruzada, es −log({{probability}}) = {{loss}}: cuanto más baja es la probabilidad de la clase correcta, mayor. Ahora mismo la red respondería «{{predicted}}».", + "loss-regression": "La red predice {{prediction}} y el valor real es {{actual}}. En el paso a paso el objetivo se escala entre 0 y 1 ({{output}} frente a {{target}}), y la pérdida es el error cuadrático: ({{output}} − {{target}})² = {{loss}}.", + "loss-regression-raw": "La red predice {{prediction}} y el valor real es {{actual}}. La pérdida es el error cuadrático: ({{output}} − {{target}})² = {{loss}}.", + "backward-output": "Empieza el paso hacia atrás. El delta de cada neurona de salida dice cuánto cambiaría la pérdida si cambiara su suma z. El gradiente de cada peso que llega a ella es su delta por la entrada de esa conexión: son las conexiones en naranja.", + "backward": "El error sigue hacia atrás hasta la capa {{layer}}: el delta de cada neurona es la suma de los deltas de la capa siguiente por los pesos que las unen, multiplicada por la derivada de {{activation}}. Así cada peso sabe cuánto ha contribuido al error.", + "update": "Cada peso se mueve un poco en contra de su gradiente: w ← w − η × g, con η = {{rate}}, la tasa de aprendizaje. Con este ejemplo, la pérdida pasa de {{before}} a {{after}}. Entrenar es repetir esto con todos los ejemplos, época tras época; el optimizador que elijas ajusta cada paso de forma más elaborada." + }, + "focus": "Neurona {{index}} de la capa {{layer}}", + "focus-input": "Entrada {{index}}", + "formula-input": "{{name}} = {{value}}", + "formula-pending": "La neurona {{index}} de la capa {{layer}} todavía no se ha calculado.", + "formula-update": "Su sesgo pasa de {{before}} a {{after}}. El peso que más cambia, el que viene de {{from}}, pasa de {{weight}} a {{weightAfter}}.", + "from-neuron": "la neurona {{index}} de la capa {{layer}}", + "history_one": "Pérdida media de {{sample}} ejemplos de los datos tras cada actualización: de {{first}} a {{last}} ({{count}} ejemplo usado). Si la red aprende, la línea baja.", + "history_other": "Pérdida media de {{sample}} ejemplos de los datos tras cada actualización: de {{first}} a {{last}} ({{count}} ejemplos usados). Si la red aprende, la línea baja.", + "history-empty": "Al terminar cada ejemplo, aquí verás cómo cambia la pérdida.", + "diagram": "La red neuronal, capa a capa", + "node-input": "Entrada {{name}}: {{value}}", + "node": "Neurona {{index}} de la capa {{layer}}: {{value}}", + "column-input": "Entrada", + "column-layer": "Capa {{layer}} ({{activation}})", + "column-output": "Salida ({{activation}})", + "update-rule": "w ← w − {{rate}} × gradiente" + }, + "clustering": { + "intro": "k-means coloca k centroides, asigna cada fila al más cercano y mueve cada centroide al centro de sus filas, hasta que nadie cambia de grupo. No usa ninguna etiqueta: solo las columnas que elijas.", + "upload": "Sube tus datos", + "rows_one": "1 fila", + "rows_other": "{{count}} filas", + "features": "Columnas con las que se agrupa", + "features-help": "Solo las numéricas. Cuantas más, más difícil de imaginar, pero los grupos pueden ser mejores.", + "label": "Columna con las clases reales (opcional)", + "label-none": "Ninguna", + "label-help": "No se usa para agrupar: solo para comparar al final.", + "scale": "Escalar las columnas", + "scale-help": "Cada columna con media 0 y desviación 1: si no, las de valores grandes (p. ej. la prolina del vino) deciden solas.", + "k": "Número de grupos (k)", + "k-help": "Si no sabes cuántos hay, mira el codo después de agrupar.", + "run": "Agrupar", + "reseed": "Probar con otros centroides iniciales", + "waiting": "Elige las columnas y el número de grupos, y pulsa «Agrupar».", + "groups": "Grupos", + "iterations": "Iteraciones", + "inertia": "Inercia", + "silhouette": "Silueta", + "silhouette-good": "Silueta alta (más de 0,5): los grupos están bien separados.", + "silhouette-fair": "Silueta media (entre 0,25 y 0,5): hay grupos, pero se tocan entre sí.", + "silhouette-weak": "Silueta baja (menos de 0,25): los grupos apenas se distinguen; prueba con otro k u otras columnas.", + "scatter-title": "Los grupos", + "play": "Ver cómo se forman", + "pause": "Pausa", + "iteration": "Iteración {{number}}", + "scatter-help": "Cada punto es una fila; las cruces, los centroides. Para dibujarlos en 2D se proyectan con PCA (las dos direcciones en las que más varían los datos), pero k-means usa todas las columnas elegidas.", + "axis": "Componente {{number}} ({{variance}} de la varianza)", + "cluster": "Grupo {{number}}", + "centroids": "Centroides", + "comparison-title": "Grupos frente a las clases reales ({{column}})", + "comparison-help": "Cuántas filas de cada clase han caído en cada grupo y qué parte del grupo son. k-means no sabe qué es cada clase, así que los grupos no tienen nombre: la clase mayoritaria de cada uno dice a cuál se parece.", + "group": "Grupo", + "purity": "Pureza", + "ari": "Índice de Rand ajustado", + "elbow-title": "El codo", + "elbow-help": "La inercia baja siempre al subir k. El «codo», donde deja de bajar mucho, suele ser un buen número de grupos.", + "profiles-title": "Cómo es cada grupo", + "size": "Filas", + "profiles-help": "La media de cada columna en cada grupo, en sus unidades: sirve para ponerle nombre a cada grupo.", + "variable": "Variable", + "purity-help": "La parte de las filas que acertaría si cada grupo se llamara como su clase mayoritaria. Sube siempre al aumentar k: con un grupo por fila sería del 100 %.", + "ari-help": "Cuánto se parecen los grupos a las clases mirando parejas de filas: ¿las que van juntas en una clase van juntas en un grupo? 1 si son los mismos grupos y alrededor de 0 si se parecen como al azar. No sube solo por tener más grupos.", + "ari-high": "Los grupos son casi las mismas clases.", + "ari-medium": "Los grupos se parecen bastante a las clases, pero alguna se reparte o se mezcla.", + "ari-low": "Los grupos se parecen poco a las clases.", + "ari-none": "Los grupos no se parecen a las clases: como si fueran al azar.", + "majority": "Clase mayoritaria", + "mixed": "mezcla", + "total": "Total", + "comparison-legend": "Cuanto más intenso el fondo, mayor parte del grupo es de esa clase. «Mezcla»: ninguna clase llega a dos tercios del grupo.", + "scatter-data": "Grupos, filas y centroides", + "rows-column": "Filas" + }, + "time-series": { + "manual": { + "title": "Cómo funciona", + "windows": { + "title": "Ventanas", + "text": "La red no ve la serie entera: recibe los últimos valores (la ventana) y predice el siguiente. Cada posición de la serie da un ejemplo: con una ventana de 12 meses, los de 1949 predicen enero de 1950; los doce siguientes, febrero…" + }, + "split": { + "title": "Entrenar con el pasado, probar con el futuro", + "text": "La parte de prueba es la última de la serie y no se baraja: si se mezclaran los meses, la red vería el futuro al entrenar. Las ventanas de entrenamiento sí se barajan, porque cada una ya lleva su historia." + }, + "scale": { + "title": "Escalar y diferenciar", + "text": "Los valores se escalan entre 0 y 1 con el mínimo y el máximo del entrenamiento (la prueba no se mira). Si la serie crece, la prueba puede salirse de ese rango. Diferenciar hace que la red aprenda cuánto cambia cada valor respecto al anterior en lugar del valor: quita la tendencia." + }, + "modes": { + "title": "A un paso o seguida", + "text": "A un paso, cada valor de prueba se predice con los reales de antes, como quien predice mañana sabiendo lo de hoy. Seguida (recursiva), desde el final del entrenamiento cada valor se predice con los ya predichos: es lo que se hace con el futuro, y los errores se acumulan." + }, + "baselines": { + "title": "¿Mejor que lo más sencillo?", + "text": "Se compara con dos predicciones sin red: la ingenua (el valor anterior o, si se predice seguido, el último conocido) y la estacional (el valor de hace una estación: 12 meses, 7 días…). Una red que no las mejora no aporta nada." + }, + "networks": { + "title": "Dense o recurrentes", + "text": "Una capa Dense recibe la ventana entera de una vez. Las recurrentes (SimpleRNN, LSTM y GRU) la leen valor a valor y recuerdan lo anterior: van antes que las Dense y entrenan más despacio. La salida es una neurona lineal, el valor que se predice." + } + }, + "upload": { + "title": "Tu serie", + "text": "Sube un fichero (CSV, ARFF, JSON, JSONL o Parquet) con una fila por momento y elige la columna con los valores. Si tiene una columna de fechas, se usa para ordenar las filas y para poner fecha a lo que se predice.", + "no-numeric": "El fichero no tiene ninguna columna numérica: no hay valores que predecir.", + "value-column": "Columna con los valores", + "value-column-help": "La serie que se predice.", + "date-column": "Columna con la fecha", + "date-column-help": "Opcional: sin ella, los valores se numeran 1, 2, 3…", + "no-date": "Sin fecha (1, 2, 3…)", + "info": "Sube tu propia serie temporal: una columna con sus valores y, si la tiene, otra con la fecha de cada uno.", + "waiting": "Sube un fichero para ver aquí la serie." + }, + "data": { + "summary_one": "1 valor ({{first}})", + "summary_other": "{{count}} valores, de {{first}} a {{last}}", + "value-column": "se predice {{column}}", + "dropped_one": "Se ha quitado 1 fila sin un número en la columna de los valores.", + "dropped_other": "Se han quitado {{count}} filas sin un número en la columna de los valores.", + "sorted": "Las filas no estaban en orden: se han ordenado por fecha.", + "range_one": "{{first}} (1 valor)", + "range_other": "{{first}} – {{last}} ({{count}} valores)", + "split": "Entrenamiento: {{train}}. Prueba: {{test}}" + }, + "frequency": { + "hour": "un valor por hora", + "day": "un valor al día", + "week": "un valor por semana", + "month": "un valor al mes", + "quarter": "un valor por trimestre", + "year": "un valor al año" + }, + "chart": { + "test": "Prueba", + "description": "{{name}}: {{count}} valores, de {{first}} a {{last}}.", + "train-prediction": "Red (entrenamiento, a un paso)", + "test-one-step": "Red (prueba, a un paso)", + "test-recursive": "Red (prueba, seguida)", + "future": "Lo que viene después", + "forecast-description": "Predicción del {{model}}: en la prueba se equivoca {{mae}} de media. Después, los {{steps}} valores siguientes." + }, + "prep": { + "title": "Preparación", + "window": "Ventana (valores anteriores)", + "window-help": "Con cuántos valores anteriores predice la red el siguiente.", + "window-season": "Para ver el patrón que se repite, conviene que abarque una estación ({{season}} valores).", + "test-size": "Prueba (% final de la serie)", + "test-size-help": "Los últimos valores: la red no los ve al entrenar. No se barajan, porque en una serie el futuro se predice con el pasado.", + "difference": "Predecir el cambio (diferenciar)", + "difference-help": "La red aprende cuánto cambia cada valor respecto al anterior y, al predecir, se suma al anterior. Quita la tendencia.", + "season": "Estación (valores)", + "season-help": "Cada cuántos valores se repite el patrón (12 meses, 7 días…), para compararse con la predicción estacional. 0: sin estación.", + "too-short": "Con esta ventana y esta parte de prueba no quedan datos suficientes: hacen falta al menos 10 ventanas para entrenar y 2 valores para probar. Prueba con una ventana más corta o con menos prueba." + }, + "windows": { + "title": "Lo que aprende la red", + "text": "Cada ejemplo son los {{window}} valores anteriores y el siguiente, que es lo que tiene que predecir. Los primeros:", + "text-difference": "Cada ejemplo son los {{window}} cambios anteriores (cada valor menos el anterior) y el siguiente cambio, que es lo que tiene que predecir. Los primeros:", + "date": "Fecha", + "inputs": "Valores anteriores ({{window}})", + "inputs-difference": "Cambios anteriores ({{window}})", + "output": "Valor que predice", + "output-difference": "Cambio que predice", + "scaled_one": "La red los recibe escalados entre 0 y 1. Con esta preparación hay 1 ejemplo para entrenar.", + "scaled_other": "La red los recibe escalados entre 0 y 1. Con esta preparación hay {{count}} ejemplos para entrenar." + }, + "layers": { + "class": "Tipo de capa", + "class-help": "Dense recibe la ventana entera; SimpleRNN, LSTM y GRU la leen valor a valor (van antes que las Dense)." + }, + "models": { + "yes": "Sí", + "no": "No", + "mae-one-step": "Error a un paso (MAE)", + "mae-recursive": "Error seguida (MAE)", + "show": "Ver", + "help": "El error es el error absoluto medio con los datos de prueba, en las unidades de la serie: cuánto se equivoca de media.", + "evaluating": "Calculando las predicciones…" + }, + "forecast": { + "title": "Predicción: {{model}}", + "model": "Modelo", + "one-step": "A un paso", + "recursive": "Seguida (recursiva)", + "range-all": "Toda la serie", + "range-test": "De cerca", + "show-train": "Ver también el entrenamiento", + "one-step-help": "Cada valor de prueba se predice con los valores reales anteriores.", + "recursive-help": "Desde el final del entrenamiento, cada valor se predice con los ya predichos, sin ver la prueba: así se predice el futuro, y los errores se acumulan.", + "errors-title": "Errores con los datos de prueba", + "prediction": "Predicción", + "mae-title": "Error absoluto medio: cuánto se equivoca de media", + "rmse-title": "Raíz del error cuadrático medio: castiga más los errores grandes", + "network": "Red neuronal ({{model}})", + "naive-one-step": "Ingenua: el valor anterior", + "naive-recursive": "Ingenua: el último conocido, repetido", + "seasonal-one-step": "Estacional: el de hace {{season}} valores", + "seasonal-recursive": "Estacional: la última estación, repetida", + "verdict-better": "La red se equivoca un {{percent}} menos que la mejor predicción sencilla ({{baseline}}).", + "verdict-similar": "La red se equivoca más o menos lo mismo que la mejor predicción sencilla ({{baseline}}): no aporta mucho.", + "verdict-worse": "La red se equivoca un {{percent}} más que la mejor predicción sencilla ({{baseline}}). Prueba con otra ventana, más épocas, diferenciar o capas recurrentes.", + "baseline-naive": "la ingenua", + "baseline-seasonal": "la estacional", + "train-vs-test": "Con los datos de entrenamiento se equivoca {{train}} de media y con los de prueba (a un paso), {{test}}.", + "overfitting": "Con los de prueba se equivoca más del doble: puede que se haya aprendido el entrenamiento de memoria.", + "future-title": "Lo que viene después", + "future-steps": "Valores que predecir", + "future-help": "Seguidos, cada uno con los ya predichos: cuanto más lejos, menos fiables." + }, + "model": { + "name": "Modelo ya entrenado", + "train-yours": "Entrenar tu red con esta serie" + }, + "review": { + "tab-chart": "La serie", + "tab-windows": "Preparada para la red", + "preparation": "La red recibe los {{window}} valores anteriores y predice el siguiente. Se entrenó con la serie hasta {{last}}; la prueba, de {{first}} al final, no la vio. Los valores se escalan entre 0 y 1 con el mínimo ({{min}}) y el máximo ({{max}}) del entrenamiento.", + "preparation-difference": "La red recibe los {{window}} cambios anteriores (cada valor menos el anterior) y predice el siguiente cambio. Se entrenó con la serie hasta {{last}}; la prueba, de {{first}} al final, no la vio. Los cambios se escalan entre 0 y 1 con el mínimo ({{min}}) y el máximo ({{max}}) del entrenamiento.", + "predict-title": "Predecir", + "test": "prueba", + "model-select": "Modelo con el que predecir", + "choose-instance_one": "Elige un valor de la serie: el formulario se rellena con el anterior, que es lo que usa la red. Después puedes cambiarlo.", + "choose-instance_other": "Elige un valor de la serie: el formulario se rellena con los {{count}} anteriores, que es lo que usa la red. Después puedes cambiarlos.", + "vector": "Lo que recibe la red", + "vector-help": "Cada valor, escalado entre 0 y 1 con el mínimo y el máximo del entrenamiento.", + "vector-help-difference": "Cada cambio (un valor menos el anterior), escalado entre 0 y 1 con el mínimo y el máximo del entrenamiento.", + "button-submit": "Predecir", + "predicted-value": "Valor predicho de {{target}} ({{date}})", + "actual-value": "Valor real: {{value}}", + "error": "Error: {{value}} ({{percent}})", + "input-details": "Entrada del modelo paso a paso", + "step-values": { + "title": "Valores anteriores", + "text": "como en la serie" + }, + "step-changes": { + "title": "Cambios", + "text": "cada valor menos el anterior" + }, + "step-scaled": { + "title": "Escalados", + "text": "entre 0 y 1, como los recibe la red" + }, + "metrics": "Con el último {{testSize}} % de la serie, que se apartó al entrenarlo, se equivoca de media en {{mae}} a un paso; repitiendo el valor anterior, en {{naive}}.", + "metrics-seasonal": "Repitiendo el de hace una estación, en {{seasonal}}.", + "metrics-no-better": "No mejora la predicción más sencilla: con esa ventana, esta serie no se predice mucho mejor." + }, + "chart-data": "{{value}}: real y predicho en cada fecha", + "chart-data-series": "{{value}} en cada fecha" + } + }, + "dataframe": { + "title": "Analizar conjunto de datos", + "upload-csv": "Subir conjunto de datos", + "intro": "Explora un conjunto de datos antes de entrenar un modelo: su tamaño, el tipo y la forma de cada variable, los valores ausentes, cómo se relacionan las variables entre sí y con la variable objetivo, y cómo prepararlo.", + "waiting": "Elige uno de los conjuntos de datos del proyecto o sube tu propio fichero (CSV, ARFF, JSON, JSONL o Parquet) para empezar el análisis.", + "sections": { + "data": "Conjunto de datos", + "summary": "Resumen", + "variables": "Variables", + "distributions": "Distribuciones", + "relations": "Relaciones", + "table": "Datos y consultas", + "preprocess": "Preprocesado", + "charts": "Más gráficos" + }, + "picker": { + "project": "Conjuntos de datos del proyecto", + "project-help": "Los CSV de los modelos de Nets4Learning y otros para practicar, con la descripción de sus variables.", + "placeholder": "Elige un conjunto de datos", + "upload": "Tu propio fichero", + "upload-help": "CSV (con «,» o «;»), ARFF, JSON, JSONL o Parquet. Se lee en tu navegador: el fichero no se envía a ningún servidor.", + "loading": "Cargando…" + }, + "info": { + "shape": "{{rows}} filas × {{columns}} columnas", + "source": "Fuente", + "variables-sheet": "con ficha de variables", + "target": "Variable objetivo", + "target-none": "Ninguna", + "target-help": "La que se quiere predecir o clasificar: se resalta en todo el análisis y separa los gráficos por clases.", + "problem-classification": "Clasificación, {{count}} clases", + "problem-regression": "Regresión", + "problem-none": "Sin variable objetivo" + }, + "summary": { + "rows": "Filas", + "columns": "Columnas", + "columns-detail": "Numéricas: {{numeric}}, categóricas: {{categorical}}", + "missing": "Valores ausentes", + "missing-detail": "{{percent}} de las celdas", + "duplicates": "Filas repetidas", + "duplicates-detail": "{{percent}} de las filas", + "target-distribution": "Distribución de {{target}}", + "target-distribution-none": "Distribución de la variable objetivo", + "no-target": "Elige una variable objetivo para ver cómo se reparten sus valores.", + "warnings": "Avisos sobre los datos", + "no-warnings": "No se ha encontrado ningún problema: sin valores ausentes, filas repetidas, columnas constantes, identificadores ni clases desequilibradas." + }, + "warnings": { + "missing": "{{column}} tiene {{count}} valores ausentes ({{percent}}).", + "constant": "{{column}} tiene siempre el mismo valor: no aporta información.", + "identifier": "{{column}} parece un identificador (un código por registro), no un atributo: conviene no usarla para entrenar.", + "outliers": "{{column}} tiene {{count}} valores atípicos ({{percent}}) según la regla del rango intercuartílico.", + "imbalance": "Las clases de {{column}} están desequilibradas: «{{minority}}» tiene el {{percent}} de las filas de la clase más frecuente.", + "correlation": "{{column}} y {{other}} están muy correlacionadas (r = {{value}}): aportan casi la misma información.", + "duplicates": "Hay {{count}} filas repetidas." + }, + "variables": { + "title": "Perfil de cada variable", + "search": "Buscar variable", + "type": "Tipo", + "all": "Todas", + "numeric": "Numéricas", + "categorical": "Categóricas", + "view-cards": "Fichas", + "view-table": "Tabla", + "kind-numeric": "Numérica", + "kind-categorical": "Categórica", + "target": "Objetivo", + "missing": "Ausentes", + "distinct": "Distintos", + "mean": "Media", + "std": "Desv. típica", + "min": "Mín.", + "median": "Mediana", + "max": "Máx.", + "top": "Valores más frecuentes", + "more": "y {{count}} más", + "show-distribution": "Ver su distribución →", + "no-results": "Ninguna variable coincide con la búsqueda.", + "units": "Unidades: {{units}}", + "column": "Variable", + "histogram-of": "Histograma de {{column}}" + }, + "distributions": { + "title": "Distribución de una variable", + "variable": "Variable", + "bins": "Intervalos", + "bins-auto": "Automático", + "by-class": "Separar por clase de {{target}}", + "histogram": "Histograma", + "frequencies": "Frecuencia de cada valor", + "boxplot": "Diagrama de caja", + "count": "Filas", + "class": "Clase", + "by-class-table": "{{column}} en cada clase de {{target}}", + "help-histogram": "Cuántas filas tienen un valor en cada intervalo. Si las clases se solapan poco, la variable ayuda a distinguirlas.", + "help-frequencies": "Cuántas filas tienen cada valor (los 30 más frecuentes).", + "help-boxplot": "La caja va del primer al tercer cuartil y la línea central es la mediana; los puntos sueltos son valores atípicos." + }, + "relations": { + "title": "Correlación y dispersión", + "correlation": "Matriz de correlación", + "correlation-help": "Correlación de Pearson entre cada par de variables numéricas: 1 es una relación lineal directa, −1 inversa y 0 ninguna.", + "target-correlation": "Correlación con {{target}}", + "target-correlation-help": "Las variables más correlacionadas con el objetivo suelen ser las más útiles para predecirlo.", + "scatter": "Diagrama de dispersión", + "x": "Eje X", + "y": "Eje Y", + "color-help": "Cada punto es una fila, coloreada por {{target}}.", + "not-enough": "Hacen falta al menos dos variables numéricas." + }, + "table": { + "title": "Tabla de datos" + }, + "preprocess": { + "title": "Preparar los datos para un modelo", + "help": "Un modelo solo recibe números: el texto se codifica (label encoder) y lo que no sirve se descarta. El resultado se actualiza con cada cambio y se puede descargar como CSV.", + "missing": "Valores ausentes", + "missing-keep": "Dejarlos", + "missing-drop-rows": "Quitar las filas con alguno", + "missing-impute": "Rellenar (media o valor más frecuente)", + "scaler": "Escalado de los atributos numéricos", + "scaler-none": "Ninguno", + "scaler-min-max": "Min-max (de 0 a 1)", + "scaler-standard": "Estandarizar (media 0, desviación 1)", + "scaler-help": "La variable objetivo no se escala.", + "duplicates": "Quitar las filas repetidas", + "action": "Transformación", + "action-keep": "Sin cambios", + "action-label-encoder": "Codificar (label encoder)", + "action-drop": "Descartar", + "result": "Resultado", + "download": "Descargar CSV", + "removed-rows": "Filas quitadas: {{duplicates}} repetidas y {{missing}} con valores ausentes.", + "encodings": "Codificación de las columnas de texto", + "imputed": "Valores con los que se rellenó", + "imputed-value": "{{column}}: {{value}}" + }, + "analyzing": "Analizando el conjunto de datos…", + "charts-sample": "Con tantas filas, estos gráficos usan una muestra aleatoria de {{sample}} de las {{rows}}.", + "essentials": { + "tab": "Análisis", + "help": "Lo más importante del análisis exploratorio del conjunto: su tamaño, los valores ausentes y repetidos, cómo se reparte la variable objetivo, los avisos y qué variables se relacionan con ella.", + "open": "Ver el análisis completo (AED)" + } + }, + "documentation": { + "title": "Documentación" + }, + "manual": { + "title": "Manual", + "00-tabular-classification": { + "upload-and-process": { + "title": "Paso 1: Subir y procesar el conjunto de datos" + }, + "dataset": { + "title": "Paso 2: Analizar el conjunto de datos" + }, + "layer-design": { + "title": "Paso 3: Visualizar el diseño de capas de la red neuronal." + }, + "editor-layers": { + "title": "Paso 4: Editar las capas de la red neuronal" + }, + "editor-hyperparameters": { + "title": "Paso 5: Editar los hiperparámetros del entrenamiento" + }, + "table-models": { + "title": "Paso 6: Entrenamiento y tabla de modelos" + }, + "prediction": { + "title": "Paso 7: Clasificación" + } + }, + "app": { + "title": "Objetivos de la herramienta", + "description-1": "Esta aplicación muestra algunas de las tareas más importantes que pueden realizar las redes neuronales artificiales, como son: clasificación tabular, clasificación de imágenes e Identificación de objetos. Las redes son técnicas de inteligencia artificial pertenecientes al campo del aprendizaje automático, en el cual se desarrollan modelos que se entrenan (o aprenden) a partir de conjuntos de datos.", + "description-2": "Algunos de los motivos por los que trabajar con redes neuronales son los siguientes:", + "list": { + "0": { + "title": "Aplicaciones prácticas", + "description": "Las redes neuronales se utilizan en una amplia variedad de aplicaciones, desde reconocimiento de voz y visión por computadora hasta análisis de datos y predicción de resultados. Aprender sobre redes neuronales puede ayudar a los profesionales a desarrollar habilidades que pueden aplicarse en campos como la medicina, la ingeniería, la ciencia de datos, el marketing y muchos otros." + }, + "1": { + "title": "Solución de problemas complejos", + "description": "Las redes neuronales son útiles para resolver problemas complejos que tienen múltiples variables y relaciones no lineales. Al aprender redes neuronales, los profesionales pueden desarrollar soluciones más efectivas para estos tipos de problemas y mejorar la precisión y la eficiencia de sus análisis." + }, + "2": { + "title": "Innovación tecnológica", + "description": "Las redes neuronales son una tecnología innovadora que sigue evolucionando y mejorando. Aprender sobre redes neuronales puede ayudar a los profesionales a mantenerse actualizados en las últimas tendencias y desarrollos en el campo del aprendizaje automático y la inteligencia artificial." + } + }, + "description-3": "Las redes neuronales son una forma de aprendizaje automático que imita la forma en que funciona el cerebro humano. Estas redes están diseñadas para aprender y mejorar continuamente a partir de datos y experiencias pasadas, permitiendo a las máquinas realizar tareas complejas que antes eran imposibles o muy difíciles para los sistemas programados tradicionales.", + "description-4": "En resumen, aprender redes neuronales es importante porque puede ayudar a los profesionales a desarrollar habilidades que son valiosas en una amplia variedad de campos, resolver problemas complejos de manera más efectiva y mantenerse actualizados en la tecnología y la innovación." + }, + "0-tabular-classification": { + "title": "Clasificación tabular", + "1-title": "Modelos pre-entrenados", + "1-description-1": "Debemos acceder a la sección de modelos pre-entrenados y seleccionar uno de los disponibles.", + "1-description-2": "La herramienta cuenta con una lista de ejemplos representativos que permiten alterar el formulario de características.", + "1-description-3": "Al acceder a la sección de la herramienta en los modelos podremos editar las características de los elementos a predecir. La herramienta cuenta con formulario dinámico que permite cambiar los tipos de datos de entrada de la red neuronal.", + "2-title": "Entrenar modelos", + "2-description-1": "La herramienta cuenta con un visor de datos que permite mostrar las clases y los atributos del conjunto de datos. Así como un gestor para crear, diseñar, entrenar y exportar un modelo de datos.", + "2-description-2": "A la izquierda contamos con un editor de las distintas capas que tiene la red neuronal. Se debe dejar que la ultima capa de la red tenga el mismo número de neuronas que clases a predecir.", + "2-description-3": "Number of epochs:
The number of iterations refers to the number of times the training data is presented to the neural network during the training process. Each iteration implies an update of the weights of the network as a function of the calculated error.", + "2-description-4": "Debemos pulsar el botón de \"Crear y entrenar modelo\" para que se inicie el proceso de entrenamiento de la red neuronal. Si toda la configuración y selección de las funciones es correcta entonces se añadirá en la tabla de abajo una entrada con el modelos entrenado.", + "2-description-5": "Una vez entrenado un modelo a partir de los datos podremos realizar predicciones, para ello se incluye un formulario dinámico con las características del conjunto de datos. La precisión del modelo en la predicción podrá ser mayor o menor en función del entrenamiento y las opciones seleccionadas." + }, + "1-regression": { + "title": "Regresión", + "1-title": "Modelos pre-entrenados", + "1-description": { + "0": "Debemos acceder a la sección de modelos pre-entrenados y seleccionar uno de los disponibles.", + "1": null, + "2": null + }, + "2-title": "Entrenar modelos", + "2-description": { + "0": "La sección cuenta con la posibilidad subir tus conjuntos de datos, conjuntos de datos preparados, descripciones, herramientas de visualización gráficas y de estadísticas.", + "1": "Cuenta con un generador de modelos de regresión. Gestiona capas de la red neuronal, hiperparámetros, funciones de optimización, funciones de perdida y de métricas. así como el selector de características.", + "2": "Debemos pulsar el botón de \"Crear y entrenar modelo\" para que se inicie el proceso de entrenamiento de la red neuronal. Si toda la configuración y selección de las funciones es correcta entonces se añadirá en la la lista una entrada con el modelos entrenado.", + "3": "Para la predicción se usa el gráfico de dispersión creando una linea" + }, + "2-link": "Consulta más información en el siguiente enlace" + }, + "2-object-identification": { + "title": "Identificación de objetos", + "1-title": "Modelos pre-entrenados", + "1-description-1": "Dentro de la identificación de objetos contamos con cuatro modelos, para usar esta herramienta es tan sencillo como activar la opción de usar webcam o subir una imagen.", + "1-description-2": "En esta sección la herramienta ofrece cuatro modelos de identificación de objetos, dichos modelos han sido optimizados para ser funcionales en dispositivos móviles. Estos modelos son:", + "1-description-3": "En caso de usar la webcam como entrada se generará un filtro de forma que se pueda ver en tiempo real sobre el video los puntos que se están detectando. En caso de usar la opción de subir imágenes podemos adjuntar un fichero en formato png o jpg. Como resultado se mostrará la imagen original, el filtro generado y la imagen con el filtro aplicado.", + "1-list": { + "0": "Identificación de la geometría facial.", + "1": "Identificación de una malla facial completa.", + "2": "Identificación de las articulaciones.", + "3": "Identificación de objetos." + } + }, + "3-image-classification": { + "title": "Clasificación de imágenes", + "1-title": "Modelos pre-entrenados", + "1-description-1": "En la sección de la clasificación de imágenes podemos seleccionar entre dos ejemplos muy representativos de las redes neuronales. Estos son el modelo entrenado con el conjunto de imágenes MNIST y un modelo de clasificación de imágenes genérico. Concretamente:", + "1-list": { + "0": "MNIST, Clasificación de imágenes que detecta números.", + "1": "MobileNet, clasificación de imágenes pertenecientes a 1001 categorías." + }, + "1-description-2": "En el modelo de MNIST se permite seleccionar entre una lista de imágenes que contienen un número, dibujar en un canvas el número a predecir o subir una imagen de un número.", + "1-description-3": "En el modelo de MobileNet se han incluido una lista de imágenes de ejemplo que pueden ser seleccionadas o podemos subir una imagen que la red neuronal clasificará.", + "1-description-4": "Para ambos modelos el sistema mostrará la predicción con el porcentaje de precisión calculado." + }, + "layer-editor": { + "title": "Editor de capas" + }, + "hyperparameters-editor": { + "title": "Editor de hiperparámetros" + } + }, + "glossary": { + "title": "Glosario", + "intro": "Los términos que aparecen en Nets4Learning: las tareas, los editores de la red, los optimizadores y las funciones de activación, de pérdida y de métrica.", + "search": "Buscar en el glosario", + "search-placeholder": "Por ejemplo: ReLU, Adam, épocas…", + "results_one": "{{count}} término", + "results_other": "{{count}} términos", + "no-results": "Ningún término coincide con «{{query}}».", + "anchor": "Enlace a «{{term}}»", + "plot": "Gráfica de {{term}}", + "plot-tabs": { + "image": "Imagen", + "animation": "Animación" + }, + "animation": { + "slider": "Recorrido de x en {{name}}", + "play": "Reproducir", + "pause": "Pausa" + }, + "references-title": "Referencias", + "confusion-legend": { + "abbreviation": "Abreviatura", + "english": "En inglés", + "meaning": "Significado", + "tp": "Verdaderos positivos", + "tn": "Verdaderos negativos", + "fp": "Falsos positivos", + "fn": "Falsos negativos" + }, + "table-head": { + "name": "Nombre", + "description": "Descripción", + "references": "Referencias", + "characteristics": "Características", + "function": "Función" + }, + "tabular-classification": { + "title": "Clasificación tabular", + "text-1": "La clasificación tabular es un tipo de aprendizaje supervisado en el que se utiliza un conjunto de datos etiquetados para entrenar un modelo de aprendizaje automático, de forma que el modelo pueda predecir la clase de nuevos ejemplos de datos no utilizados en el entrenamiento. En la clasificación tabular, los datos de entrada y salida se representan en forma de una tabla con filas y columnas, donde cada fila representa una instancia o ejemplo de los datos, y cada columna representa una característica o atributo de los datos.", + "text-2": "Por ejemplo, si se quiere predecir si un cliente de un banco es solvente o no, las características o atributos que se pueden utilizar son: ingresos, deudas, historial crediticio, edad, etc. En la clasificación tabular, cada instancia o ejemplo del conjunto de datos tendrá valores para cada una de estas características y una etiqueta (clase) que indica si el cliente es solvente o no.", + "text-3": "Una vez que se tiene un conjunto de datos etiquetados, se utiliza un algoritmo de aprendizaje automático para entrenar un modelo que pueda predecir la etiqueta de nuevos conjuntos de datos. Este modelo puede ser utilizado para realizar predicciones precisas y rápidas sobre nuevas instancias de datos.", + "text-4": "La clasificación tabular es una técnica muy útil para resolver problemas de clasificación en una amplia variedad de campos, como la medicina, el comercio electrónico, la banca, la seguridad y muchos otros." + }, + "regression": { + "title": "Regresión", + "text": { + "0": "La regresión es un método de análisis estadístico utilizado en el aprendizaje automático para modelar la relación lineal entre una variable independiente y una variable dependiente, buscando encontrar la mejor línea recta que ajuste los datos y permita hacer predicciones.", + "1": "En la regresión, los datos se representan generalmente como puntos dispersos en un plano cartesiano, donde la variable independiente se coloca en el eje X y la variable dependiente en el eje Y. El objetivo es encontrar la ecuación de una línea recta (y = mx + b) que minimice la distancia entre esta línea y los puntos de datos. Una vez que se ha obtenido esta ecuación, se puede utilizar para hacer predicciones sobre valores futuros de la variable dependiente en función de los valores de la variable independiente.", + "2": "Por ejemplo, si estamos analizando la relación entre la cantidad de publicidad en un sitio web y las ventas de un producto, la cantidad de publicidad sería la variable independiente, y las ventas del producto serían la variable dependiente. La regresión nos ayudaría a determinar si existe una relación lineal entre la inversión en publicidad y las ventas, y si es así, nos permitiría predecir las ventas futuras en función del gasto en publicidad.", + "3": "La regresión es una herramienta poderosa en el análisis de datos y se utiliza en una variedad de campos, incluyendo la economía, la ciencia social, la investigación médica y muchas otras disciplinas para comprender y predecir relaciones entre variables." + } + }, + "object-identification": { + "title": "Identificación de objetos", + "text-1": "La identificación de objetos en redes neuronales es una técnica utilizada en el campo del aprendizaje automático y la visión por computador para detectar y reconocer objetos en imágenes o videos. Es una tarea importante en el análisis de imágenes y es utilizada en aplicaciones como el reconocimiento de rostros, el seguimiento de objetos en tiempo real, la clasificación de objetos en imágenes médicas y la detección de objetos en vehículos autónomos.", + "text-2": "Las redes neuronales utilizadas para la identificación de objetos son modelos de aprendizaje profundo que se entrenan en conjuntos de datos etiquetados. El proceso de entrenamiento implica proporcionar a la red neuronas una gran cantidad de imágenes etiquetadas, y ajustar los pesos de las conexiones entre las neuronas para que la red pueda identificar objetos en nuevas imágenes con alta precisión.", + "text-3": "Una vez que la red neuronal ha sido entrenada, se utiliza para identificar objetos en nuevas imágenes. La red examina la imagen y, mediante el procesamiento de múltiples capas, extrae características importantes que se utilizan para identificar los objetos de interés. Luego, la red utiliza estas características para asignar una etiqueta a cada objeto detectado en la imagen.", + "text-4": "En resumen, la identificación de objetos en redes neuronales es una técnica importante en la visión por computador y el aprendizaje automático que se utiliza para detectar y reconocer objetos en imágenes y videos. Se basa en el uso de redes neuronales profundas entrenadas en conjuntos de datos etiquetados para identificar y clasificar objetos en nuevas imágenes con alta precisión." + }, + "image-classification": { + "title": "Clasificación de imágenes", + "text-1": "La clasificación de imágenes es una técnica utilizada en las redes neuronales para clasificar imágenes en diferentes categorías o etiquetas. El objetivo de un clasificador de imágenes es tomar una imagen de entrada y predecir a qué clase pertenece, basándose en un conjunto de categorías o etiquetas predefinidas.", + "text-2": "En el aprendizaje profundo, los clasificadores de imágenes se basan en las redes neuronales convolucionales (CNN, por sus siglas en inglés), que son una arquitectura especializada para procesar imágenes. Estas redes neuronales tienen múltiples capas y operaciones de convolución que les permiten extraer características importantes de las imágenes, como bordes, formas y texturas.", + "text-3": "Para entrenar un clasificador de imágenes, se utiliza un conjunto de datos etiquetados que contiene imágenes y sus respectivas etiquetas de clase. Luego, se entrena la red neuronal utilizando este conjunto de datos para que aprenda a identificar patrones en las imágenes y asociarlos con las etiquetas de clase correspondientes.", + "text-4": "Una vez que la red neuronal ha sido entrenada, se puede utilizar para clasificar nuevas imágenes en diferentes categorías. El clasificador de imágenes examina la imagen de entrada y la procesa a través de la red neuronal para extraer características importantes y predecir a qué clase pertenece la imagen.", + "text-5": "En resumen, la clasificación de imágenes en las redes neuronales es una técnica que utiliza las redes neuronales convolucionales para clasificar imágenes en diferentes categorías o etiquetas. Se basa en el uso de un conjunto de datos etiquetados para entrenar la red neuronal y en la extracción de características importantes de las imágenes para predecir a qué clase pertenece una nueva imagen de entrada." + }, + "activation-functions": { + "title": "Funciones de activación", + "sub-title-1": "Capas lineales", + "sub-title-2": "Activaciones no lineales (suma ponderada, no linealidad)", + "sub-title-3": "Activaciones no lineales (otras)", + "text-1": "Una función de activación es una función matemática utilizada en una red neuronal artificial para determinar la salida de una neurona o de un conjunto de neuronas en función de la entrada recibida. La función de activación introduce no linealidad en la red neuronal, lo que permite a la red aprender patrones más complejos en los datos de entrada. Ejemplos comunes de funciones de activación son:", + "table": { + "linear": { + "title": "Linear", + "description": "Devuelve la entrada sin cambios (la identidad). Es la activación de la capa de salida en regresión, donde la red tiene que poder dar cualquier número.", + "characteristics": { + "0": "No limita el rango de la salida.", + "1": "Una red solo con capas lineales equivale a una única capa lineal: no puede aprender relaciones no lineales." + } + }, + "softmax": { + "title": "Softmax", + "description": "Transforma las salidas a una representación en forma de probabilidades, de forma que la suma de todas las probabilidades da 1", + "characteristics": { + "0": "Acotada entre 0 y 1", + "1": "Buena en capas finales", + "2": "Utilizada para normalizar tipo multi clase" + } + }, + "sigmoid": { + "title": "Sigmoid", + "description": "La función sigmoide transforma los valores de entrada en un rango entre 0 y 1. Es comúnmente utilizada en redes neuronales para problemas de clasificación binaria.", + "characteristics": { + "0": "Resultados con el rango [0, 1].", + "1": "Útil en la capa de salida de clasificadores binarios.", + "2": "Puede sufrir el problema de desvanecimiento del gradiente en redes profundas." + } + }, + "hard-sigmoid": { + "title": "Hard Sigmoid", + "description": "Hard Sigmoid es una versión simplificada de la función sigmoide utilizada para la eficiencia computacional.", + "characteristics": { + "0": "Es más rápida de calcular que la sigmoide.", + "1": "Menos suave en la transición entre 0 y 1." + } + }, + "relu": { + "title": "ReLU (Rectified Linear Unit)", + "description": "La función ReLU es simple y efectiva al devolver cero para valores negativos y mantener los valores positivos sin cambios.", + "characteristics": { + "0": "Eficiente en términos de cómputo.", + "1": "Mitiga el problema de desvanecimiento del gradiente.", + "2": "Puede activar neuronas esparsamente." + } + }, + "relu6": { + "title": "ReLU6", + "description": "Similar a ReLU, pero con una limitación superior de 6 para los valores positivos, lo que puede ayudar a evitar la explosión de gradientes.", + "characteristics": { + "0": "Mitiga el problema de desvanecimiento del gradiente.", + "1": "Útil en redes con gradientes inestables." + } + }, + "leaky-relu": { + "title": "LeakyReLU", + "description": "Leaky ReLU es una variante de ReLU que permite que una fracción pequeña de los valores negativos pase a través de la función.", + "characteristics": { + "0": "Mitiga el problema de muerte de neuronas en comparación con ReLU.", + "1": "Ayuda a mantener la información en los gradientes negativos." + } + }, + "elu": { + "title": "ELU (Exponential Linear Unit)", + "description": "ELU es una función que se asemeja a ReLU en los valores positivos, pero también tiene un gradiente definido para valores negativos.", + "characteristics": { + "0": "Reduce el problema de desvanecimiento del gradiente.", + "1": "Ayuda a mantener activas más neuronas." + } + }, + "tanh": { + "title": "Tanh (Tangente hiperbólica)", + "description": "La función tangente hiperbólica transforma los valores de entrada en un rango [-1, 1].", + "characteristics": { + "0": "Resultados en el rango [-1, 1].", + "1": "Útil en problemas de clasificación binaria.", + "2": "Sufre de desvanecimiento del gradiente en redes profundas." + } + }, + "soft-plus": { + "title": "SoftPlus", + "description": "SoftPlus es una función suave que se utiliza a menudo como una alternativa suave a ReLU.", + "characteristics": { + "0": "Suave y derivable en todas partes.", + "1": "Puede ser útil en redes generativas y de regresión." + } + }, + "mish": { + "title": "Mish", + "description": "Mish es una función de activación relativamente nueva que combina características de otras funciones como la tangente hiperbólica y la función sigmoide.", + "characteristics": { + "0": "Suavidad y derivabilidad en todo su rango.", + "1": "Proporciona un mejor rendimiento en algunas aplicaciones." + } + }, + "selu": { + "title": "SELU (Scaled Exponential Linear Unit)", + "description": "SELU es una función que se beneficia de una normalización específica y puede ayudar a mantener la estabilidad de la red.", + "characteristics": { + "0": "Autocalibración: propaga estadísticas estables a través de las capas.", + "1": "Puede ser útil en redes con arquitectura autoencoder." + } + } + } + }, + "editor-layers": { + "title": "Glosario del editor de capas", + "table": { + "units": { + "title": "Neuronas de Capa (Layer Neurons)", + "description": "Son las unidades individuales o nodos en una capa específica de la red. Cada neurona recibe entradas, realiza cálculos y produce una salida que se transmite a la siguiente capa. La cantidad de neuronas en una capa puede variar y suele ser un hiperparámetro del modelo. La elección del número de neuronas en una capa afecta la capacidad del modelo para aprender representaciones de los datos." + }, + "activation-function": { + "title": "Función de Activación de Capa (Layer Activation Function)", + "description": "En cada neurona de una capa de una red neuronal, se aplica una función de activación para introducir no linealidad en el modelo. La función de activación determina la salida de la neurona en función de su entrada y los pesos asociados." + } + } + }, + "editor-hyperparameters": { + "title": "Glosario del editor de hiperparámetros", + "table": { + "learning-rate": { + "title": "Tasa de Aprendizaje (Learning Rate)", + "description": "La tasa de aprendizaje es un hiperparámetro crucial en algoritmos de aprendizaje automático y redes neuronales. Determina cuánto deben actualizarse los pesos del modelo en cada iteración durante el proceso de entrenamiento. Una tasa de aprendizaje alta puede llevar a la convergencia rápida, pero puede resultar en inestabilidad, mientras que una tasa baja puede llevar a la convergencia lenta o quedarse atrapada en mínimos locales." + }, + "number-or-epochs": { + "title": "Número de Épocas (Number of Epochs)", + "description": "Las épocas se refieren al número de veces que todo el conjunto de datos de entrenamiento se ha pasado a través del modelo durante el proceso de entrenamiento. Un mayor número de épocas generalmente permite que el modelo se ajuste mejor a los datos, pero también puede conducir al sobre ajuste si se excede un cierto límite." + }, + "test-size": { + "title": "Tamaño del Conjunto de Pruebas (Test Size)", + "description": "Es la cantidad de datos que se reserva para evaluar el rendimiento del modelo después de su entrenamiento. El conjunto de pruebas se utiliza para medir la precisión y el rendimiento general del modelo en datos no vistos." + }, + "optimizer": { + "title": "Optimizador (Optimizer)", + "description": "El optimizador es un algoritmo que ajusta los parámetros de un modelo de aprendizaje automático durante el entrenamiento. Su objetivo es minimizar la función de pérdida al actualizar los pesos del modelo de manera eficiente. Ejemplos de optimizadores comunes incluyen el Descenso del Gradiente Estocástico (SGD), el Adam y el RMSprop." + }, + "loss-function": { + "title": "Función de Pérdida (Loss Function)", + "description": "La función de pérdida es una medida que cuantifica qué tan bien se está desempeñando el modelo en sus predicciones. Ayuda a calcular la diferencia entre las predicciones del modelo y los valores reales del conjunto de datos. El objetivo del entrenamiento es minimizar esta función, ya que un valor bajo de pérdida indica que el modelo se ajusta mejor a los datos." + }, + "metric-function": { + "title": "Función de Métrica (Metric Function)", + "description": "A diferencia de la función de pérdida, que se utiliza para optimizar el modelo durante el entrenamiento, las funciones de métrica se utilizan para evaluar el rendimiento del modelo después del entrenamiento. Estas métricas proporcionan información sobre la precisión, la recuperación, la precisión, el F1-score, etc., y ayudan a comprender cómo se desempeña el modelo en tareas específicas." + } + } + }, + "optimization-functions": { + "title": "Funciones de optimización", + "text-1": "Una función de optimización es una técnica matemática utilizada para minimizar o maximizar una función objetivo. En el contexto del aprendizaje automático, las funciones objetivo suelen ser funciones de error que miden la discrepancia entre la salida de la red neuronal y los valores de salida deseados para un conjunto de datos de entrenamiento dado.", + "text-2": "La función de optimización ajusta los parámetros de la red neuronal para minimizar la función objetivo y, por lo tanto, mejorar su capacidad para hacer predicciones precisas en nuevos datos de entrada. Ejemplos comunes de funciones de optimización son el descenso del gradiente estocástico y el algoritmo de Adam.", + "table": { + "sgd": { + "references": "Descenso del gradiente estocástico \n (Instituto Tecnológico Autónomo de México, 2017)", + "description": "El descenso del gradiente es un algoritmo que estima dónde una función genera sus valores más bajos. En el caso de que el modelo de aprendizaje automático sea de gran escala este cálculo puede ser muy costoso.\n Debido a esto surge el descenso del gradiente estocástico que usa una constante y por consiguiente el número de gradientes a calcular es fijo." + }, + "momentum": { + "references": "-", + "description": "Es una variación de la función anterior. Define un valor que acelera el descenso del gradiente si el signo del gradiente es el mismo durante diferentes épocas." + }, + "adagrad": { + "references": "(Velasco, 2020)", + "description": "Introduce una variación en el concepto de tasa de entrenamiento. Esta función escala y adapta este valor para cada peso respecto del gradiente acumulado en cada iteración." + }, + "adadelta": { + "references": "(Velasco, 2020)", + "description": "Es una variación de AdaGrad en la que se restringe el cálculo de la tasa de entrenamiento de cada peso a una ventana de tamaño fijo de los últimos n gradientes en vez de hacerlo con el gradiente acumulado de cada iteración." + }, + "rmsprop": { + "references": "Propagación de raíz cuadrática media \n (Root Mean Square Propagation) \n (Velasco, 2020)", + "description": "Este algoritmo mantiene un factor de entrenamiento diferente para cada dimensión, pero el escalado del factor del entrenamiento se realiza dividiéndolo por la media del declive exponencial del cuadrado de los gradientes." + }, + "adam": { + "references": "Estimación adaptativa del mo \n (Adaptive moment estimation) \n (Velasco, 2020)", + "description": "Es una combinación de AdaGrad y RMSProp. Se mantiene un factor de entrenamiento por parámetro y se calcula RMSProp, además cada factor de entrenamiento se ve afectado por el momentum del gradiente." + }, + "adamax": { + "description": "Combina técnicas de momentum y adaptación del aprendizaje para acelerar la convergencia durante el entrenamiento de redes neuronales. Ajusta automáticamente la tasa de aprendizaje y utiliza un escalado de gradiente para evitar problemas de divergencia." + } + } + }, + "loss-functions": { + "title": "Funciones de pérdida", + "text": { + "0": "En aprendizaje automático, una función de pérdida (también llamada función de costo) es una medida que cuantifica la discrepancia entre la salida predicha por un modelo y la salida real o deseada. En otras palabras, la función de pérdida mide qué tan bien el modelo se ajusta a los datos de entrenamiento.", + "1": "El objetivo de un algoritmo de aprendizaje automático es minimizar la función de pérdida, lo que significa encontrar el conjunto de parámetros del modelo que mejor se ajuste a los datos de entrenamiento. Por lo tanto, la elección de la función de pérdida es muy importante, ya que puede afectar la capacidad del modelo para aprender correctamente los patrones en los datos y hacer predicciones precisas en nuevos datos.", + "2": "Estas son las funciones de pérdida que puedes elegir en Nets4Learning, agrupadas por el tipo de tarea en el que tienen sentido:" + }, + "table": { + "categoricalCrossentropy": { + "description": "Mide la diferencia entre las probabilidades que predice el modelo y la clase real (codificada en one-hot). Es la pérdida habitual en clasificación con varias clases y salida softmax." + }, + "binaryCrossentropy": { + "description": "Entropía cruzada para dos clases, o para varias etiquetas independientes entre sí, con salida sigmoide." + }, + "kullbackLeiblerDivergence": { + "description": "Mide cuánto se aleja la distribución de probabilidades predicha de la real. Se usa cuando la salida del modelo es una distribución." + }, + "hinge": { + "description": "Penaliza las predicciones que no superan un margen respecto a la clase correcta. Viene de las máquinas de vectores soporte y espera etiquetas -1 y 1." + }, + "squaredHinge": { + "description": "Como la pérdida hinge, pero elevada al cuadrado: castiga más los errores grandes." + }, + "categoricalHinge": { + "description": "Pérdida hinge para varias clases: compara la puntuación de la clase correcta con la de la mejor clase incorrecta." + }, + "meanSquaredError": { + "description": "Media de los cuadrados de las diferencias entre el valor real y el predicho. Castiga mucho los errores grandes; es la pérdida habitual en regresión." + }, + "meanAbsoluteError": { + "description": "Media del valor absoluto de las diferencias entre el valor real y el predicho. Le afectan menos los valores atípicos que al error cuadrático." + }, + "meanAbsolutePercentageError": { + "description": "Error absoluto medio expresado como porcentaje del valor real. Sirve para comparar errores entre magnitudes distintas, pero no admite valores reales iguales a cero." + }, + "meanSquaredLogarithmicError": { + "description": "Error cuadrático medio sobre el logaritmo de los valores: mide el error relativo y castiga menos los errores en valores grandes." + }, + "logcosh": { + "description": "Logaritmo del coseno hiperbólico del error: se comporta como el error cuadrático con errores pequeños y como el absoluto con errores grandes." + }, + "poisson": { + "description": "Pensada para predecir conteos (valores enteros no negativos), como el número de visitas o de sucesos." + }, + "cosineProximity": { + "description": "Compara la dirección del vector real y la del predicho (el ángulo entre ellos), sin tener en cuenta su tamaño." + } + }, + "related": "Otras fórmulas relacionadas" + }, + "metric-functions": { + "title": "Funciones de métrica", + "text-1": "Se utilizan para evaluar el rendimiento del modelo de la red neuronal en un conjunto de datos de prueba. La función de métrica toma las predicciones realizadas por el modelo y las compara con los valores reales de los datos de prueba para determinar la precisión del modelo.", + "text-2": "Existen diferentes tipos de funciones de métrica que se pueden utilizar en una red neuronal, dependiendo del tipo de problema que se esté abordando. Por ejemplo, para un problema de clasificación binaria, se podría utilizar la precisión (accuracy) como métrica, mientras que para un problema de regresión se podría utilizar el error cuadrático medio (mean squared error).", + "text-3": "En resumen, una función de métrica es una herramienta importante para evaluar la capacidad de una red neuronal para realizar predicciones precisas en un conjunto de datos de prueba y para ayudar a ajustar los parámetros del modelo para mejorar su rendimiento.", + "text-4": "Nosotros usamos principalmente la función accuracy. En la clasificación multietiqueta, esta función calcula la precisión del subconjunto: el conjunto de etiquetas previsto para una muestra debe coincidir exactamente con el conjunto de etiquetas correspondiente en y", + "table": { + "BinaryAccuracy": { + "references": "Precisión binaria
(Acervolima, s.f.)", + "description": "Calcula la frecuencia con la que las predicciones coinciden con las etiquetas binarias." + }, + "BinaryCrossentropy": { + "references": "Entropía cruzada binaria
(Saxena, 2021)", + "description": "Es el promedio negativo del logaritmo de las probabilidades predichas que se han corregido." + }, + "CategoricalAccuracy": { + "references": "Exactitud categórica", + "description": "Calcula la frecuencia con la que las predicciones coinciden con las etiquetas one-hot." + }, + "CategoricalCrossentropy": { + "references": "Entropía cruzada categórica", + "description": "Calcula la métrica de entropía cruzada entre las etiquetas y las predicciones." + }, + "CosineProximity": { + "references": "Proximidad del coseno", + "description": "Calcula entre las etiquetas y las predicciones el coseno de la proximidad. Normalmente se obtienen valores negativos." + }, + "MeanAbsoluteError": { + "references": "Error absoluto medio", + "description": "En estadística, es una medida de la diferencia entre dos variables continuas, aplicada a los modelos de aprendizaje automático estas variables son las etiquetas y las predicciones." + }, + "MeanAbsolutePercentageError": { + "references": "Porcentaje de error absoluto medio", + "description": "De igual forma que MeanAbsoluteError calcula la diferencia entre las etiquetas y las predicciones, pero en este caso con un porcentaje." + }, + "MeanSquaredError": { + "references": "Error cuadrático medio", + "description": "Determina el error cuadrático medio entre las etiquetas y las predicciones." + } + }, + "confusion": { + "title": "Métricas de la matriz de confusión", + "description": "Se calculan a partir de los aciertos y fallos de cada clase en la matriz de confusión: cuántas predicciones positivas son correctas (precisión), cuántos positivos reales se detectan (exhaustividad o sensibilidad), la media armónica de ambas (F1) y cuántos negativos reales se reconocen (especificidad)." + } + }, + "time-series": { + "title": "Series temporales", + "text-1": "Una serie temporal es una sucesión de valores medidos en orden, uno cada cierto tiempo: los pasajeros de cada mes, la temperatura de cada día, las ventas de cada semana. A diferencia de una tabla, el orden importa: cada valor depende de los anteriores.", + "text-2": "Predecir una serie es estimar los valores siguientes a partir de los pasados. Una red neuronal lo aprende con ventanas: recibe los últimos valores y predice el siguiente.", + "text-3": "Para probarla se aparta el final de la serie, sin barajar, y se compara con predicciones sencillas, como repetir el último valor o el de hace una estación.", + "group-title": "Series temporales", + "window": { + "title": "Ventana", + "text": "Los valores anteriores con los que la red predice el siguiente. Con una ventana de 12 en una serie mensual, la red ve el último año. Si es más corta que la estación, no ve el patrón que se repite; si es muy larga, quedan menos ejemplos para entrenar." + }, + "trend-seasonality": { + "title": "Tendencia y estacionalidad", + "text": "La tendencia es hacia dónde va la serie a largo plazo (los pasajeros crecen año tras año). La estacionalidad es un patrón que se repite con un periodo fijo (más pasajeros cada verano). Un ciclo, como el de las manchas solares, se repite sin un periodo fijo." + }, + "differencing": { + "title": "Diferenciar", + "text": "Cambiar cada valor por lo que ha cambiado respecto al anterior. Quita la tendencia: la red aprende cambios, que se parecen más en el entrenamiento y en la prueba. Para volver a los valores, se suma cada cambio al valor anterior." + }, + "one-step-recursive": { + "title": "Predicción a un paso y recursiva", + "text": "A un paso, cada valor se predice con los valores reales de antes. Recursiva (o seguida), cada valor predicho se usa para predecir el siguiente: es la única forma de predecir varios pasos del futuro, y los errores se acumulan." + }, + "baselines": { + "title": "Predicción ingenua y estacional", + "text": "Las predicciones más sencillas, con las que se compara un modelo: la ingenua repite el último valor conocido y la estacional, el de hace una estación (12 meses, 7 días…). Un modelo solo aporta algo si se equivoca menos que ellas." + }, + "recurrent": { + "title": "Capas recurrentes (SimpleRNN, LSTM y GRU)", + "text": "Leen una secuencia valor a valor y guardan un estado que resume lo que han visto. SimpleRNN es la más sencilla y olvida pronto; LSTM y GRU tienen puertas que deciden qué recordar y qué olvidar, y aprenden dependencias más largas." + }, + "mae-rmse": { + "title": "MAE y RMSE", + "text": "Dos formas de medir el error en las unidades de la serie: el MAE (error absoluto medio) es cuánto se equivoca de media; el RMSE (raíz del error cuadrático medio) castiga más los errores grandes." + } + }, + "formula": "Fórmula de {{term}}" + }, + "menu": { + "select-model": { + "description": "Descripción" }, - "image-classification": { - "1-title": "Clasificación de imágenes", - "1-description-1": "La clasificación de imágenes de igual forma que la clasificación tabular sirve para determinar la clase a la que pertenece la imagen dependiendo de los elementos que la forman.", - "1-button": "Modelos pre-entrenados", - "2-title": "Diseñar, crear y editar una arquitectura", - "2-description-1": "A través de esta herramienta podemos crear una red neuronal para clasificar datos multi clase.", - "2-description-2": "Para diseñar, crear, entrenar y evaluar una arquitectura personalizada, debemos:", - "2-description-list": { - "1": "Definir el número de capas, sus funciones de activación.", - "2": "Definir la tasa de aprendizaje", - "3": "Definir el número de épocas.", - "4": "Definir el optimizador.", - "5": "Definir la función de perdida.", - "6": "Definir las funciones de métricas" - }, - "2-button": "Crear y entrenar un modelo" + "select-dataset": { + "description": "Descripción" + }, + "open": "Abrir", + "info": { + "rows": "{{value}} filas", + "rows-files": "{{files}} ficheros ({{values}} filas)", + "features": "{{value}} características", + "classes": "{{value}} clases", + "target": "objetivo: {{value}}", + "images": "{{value}} imágenes de {{size}}", + "images-color": "{{value}} imágenes de {{size}} en color", + "series": { + "hour": "{{value}} horas", + "day": "{{value}} días", + "week": "{{value}} semanas", + "month": "{{value}} meses", + "quarter": "{{value}} trimestres", + "year": "{{value}} años" + } } }, - "contribute": { - "title": "Contribuye", - "github": { - "title": "Proyecto en GitHub" + "terms": { + "title": "Términos y condiciones", + "updated": "Última actualización: 2 de octubre de 2026.", + "summary-title": "En resumen", + "summary": [ + "Nets4Learning es una herramienta educativa gratuita: no hay cuentas ni registros.", + "Tus datos se quedan en tu navegador: los modelos se entrenan y se usan en tu equipo.", + "Las cookies de Google Analytics solo se activan si las aceptas, y puedes cambiar de opinión cuando quieras." + ], + "index": "Apartados", + "use": { + "title": "Uso de la aplicación", + "items": [ + "Nets4Learning es una plataforma educativa y gratuita para aprender y enseñar aprendizaje profundo.", + "El código es libre, con licencia MIT. Los conjuntos de datos y los modelos de terceros conservan sus propias licencias, indicadas en la descripción de cada uno.", + "Los resultados de los modelos sirven para aprender: no los uses para tomar decisiones reales, por ejemplo médicas, económicas o sobre personas.", + "La aplicación se ofrece tal cual, sin garantías: puede tener errores y cambiar en cualquier momento." + ] }, - "license": { - "title": "Licencia" + "privacy": { + "title": "Tus datos", + "text": "Todo el aprendizaje automático se ejecuta en tu navegador con TensorFlow.js. No hay ningún servidor que reciba tus datos:", + "items": [ + "Los ficheros que subes (conjuntos de datos, modelos e imágenes), tus dibujos y la imagen de la cámara se procesan en tu equipo y no se envían a ningún sitio.", + "Los modelos que entrenas con los conjuntos de ejemplo se guardan en tu navegador (como mucho 10 por conjunto) para no perderlos al recargar la página. Los puedes borrar desde Configuración y, para llevártelos, descargarlos.", + "No pedimos ni guardamos datos personales: no hay cuentas, formularios ni correos." + ] + }, + "storage": { + "title": "Lo que se guarda en tu navegador", + "text": "Para recordar tus preferencias, la aplicación guarda en el almacenamiento local de tu navegador (no en nuestros servidores):", + "items": [ + "El idioma, el tema y el backend de TensorFlow.js que elijas.", + "Los ajustes de la voz de las guías y por qué paso va cada guía.", + "Los modelos que entrenas con los conjuntos de ejemplo y si muestras la sección Paso a paso.", + "Tu decisión sobre las cookies, en una cookie propia." + ], + "settings": "Puedes cambiarlo o borrarlo todo desde" + }, + "third-parties": { + "title": "Servicios externos", + "items": [ + "Google Analytics, solo si aceptas sus cookies: qué secciones, modelos y conjuntos de datos se usan, cuánto tiempo, qué botones se pulsan y qué errores aparecen.", + "Algunos modelos preentrenados (los de detección y MobileNet) se descargan al abrirlos desde servidores de Google y de jsDelivr. Como cualquier web, esos servidores ven la petición, pero no tus datos ni tus imágenes.", + "Si eliges una voz «en línea» para las guías, tu navegador envía el texto de la guía a su servicio de voz para leerlo." + ] + }, + "cookies": { + "title": "Cookies", + "text": "Esta es la lista completa de cookies. Las de Google Analytics recogen estadísticas anónimas de uso, nunca con fines publicitarios, y solo se crean si las aceptas. Si las rechazas después, se borran.", + "name": "Cookie", + "purpose": "Para qué sirve", + "duration": "Duración", + "consent": { + "purpose": "Recordar si has aceptado o rechazado las cookies de Google Analytics.", + "duration": "120 días" + }, + "ga": { + "purpose": "Google Analytics: distinguir visitantes de forma anónima.", + "duration": "13 meses" + }, + "ga-session": { + "purpose": "Google Analytics: mantener el estado de la visita.", + "duration": "13 meses" + } + }, + "contact": { + "title": "Contacto", + "text": "Nets4Learning lo desarrolla el grupo de investigación SIMIDAT (Sistemas Inteligentes y Minería de Datos) de la Universidad de Jaén. Para cualquier duda o problema:", + "issues": "Abre una incidencia en GitHub", + "simidat": "Web del grupo SIMIDAT" } }, - "menu-selection-dataset": { - "0-tabular-classification": { - "csv": "Subir conjunto de datos - CSV", - "csv-text": "Sube un fichero con un conjunto de datos tratado en formato .csv" + "not-found": { + "title": "Página no encontrada", + "return-home": "Volver al inicio" + }, + "settings": { + "title": "Configuración", + "intro": "Todo lo que puedes ajustar de la aplicación. Se guarda solo en este navegador.", + "appearance": { + "title": "Idioma y apariencia", + "language": "Idioma", + "theme": "Tema", + "theme-system": "Como el sistema", + "theme-help": "«Como el sistema» sigue el modo claro u oscuro de tu sistema operativo.", + "summary": "Idioma y tema claro u oscuro" }, - "form-description-1": "Selecciona a continuación el conjunto de datos sobre se va a trabajar o carga tu propio conjunto de datos.", - "form-label": "Selecciona un conjunto de datos", - "form-option-_-1": "Selecciona un conjunto de datos", - "form-upload-description": "Ahora si lo deseas puedes cargar tu propia arquitectura, en caso contrario pulsa en continuar y se cargará una arquitectura por defecto de ejemplo.", - "form-submit": "Continuar", - "1-regression": { - "csv": "Subir conjunto de datos - CSV", - "csv-text": "Sube un fichero con un conjunto de datos tratado en formato .csv" + "backend": { + "title": "Backend de TensorFlow.js", + "help": "Dónde hace los cálculos TensorFlow.js al entrenar y predecir. El cambio se aplica al momento; los modelos que ya tengas siguen valiendo.", + "active": "en uso", + "webgl": "Usa la tarjeta gráfica a través de WebGL. Es el más rápido en casi todos los equipos.", + "webgpu": "Usa la tarjeta gráfica con WebGPU, la API más moderna. Puede ser más rápido, pero no todos los navegadores lo tienen.", + "wasm": "Calcula en el procesador con WebAssembly. Útil si la tarjeta gráfica da problemas.", + "cpu": "Calcula en el procesador con JavaScript. Funciona en todas partes, pero es el más lento.", + "summary": "Dónde calcula TensorFlow.js: tarjeta gráfica o procesador" + }, + "downloads": { + "title": "Descarga de modelos", + "help": "Algunos modelos preentrenados (detección de objetos, MobileNet…) descargan entre 2 y 18 MB al abrir su página. Puedes pedir que se pregunte antes.", + "auto": "Preguntar si ahorro datos o la conexión es lenta", + "auto-help": "Cuando el navegador tiene activado el ahorro de datos o la conexión es 2G o 3G.", + "always": "Preguntar siempre", + "always-help": "Antes de descargar cualquier modelo de más de 2 MB que no hayas descargado antes.", + "never": "No preguntar", + "never-help": "Los modelos se descargan al abrir su página.", + "now-save-data": "Ahora mismo, el navegador tiene activado el ahorro de datos.", + "now-slow": "Ahora mismo, la conexión parece lenta.", + "now-normal": "Ahora mismo, ni hay ahorro de datos ni la conexión parece lenta (o el navegador no lo dice).", + "summary": "Preguntar antes de descargar modelos grandes", + "saved": "Los modelos descargados se guardan en este navegador para no volver a descargarlos: puedes ver cuánto ocupan y borrarlos en Datos guardados en este navegador." + }, + "speech": { + "title": "Voz de las guías", + "help": "Las guías de las páginas de los modelos pueden leer cada paso en voz alta con las voces de tu sistema.", + "voice": "Leer las guías en voz alta", + "auto": "Avanzar solo al terminar de leer cada paso", + "voice-help": "Las voces «en línea» funcionan en un servidor del navegador: el texto de la guía se envía allí para leerlo.", + "no-voices": "Tu sistema no tiene voces en este idioma: se usará la que elija el navegador.", + "rate": "Velocidad: {{rate}}×", + "test": "Probar la voz", + "stop": "Parar", + "sample": "Hola. Así sonará la guía de cada página de Nets4Learning.", + "screen-reader": "Si usas un lector de pantalla, desactívalo: el lector ya lee cada paso de la guía y las dos voces a la vez no se entienden.", + "summary": "Leer las guías en voz alta, la voz y su velocidad" + }, + "tutorials": { + "title": "Guías", + "guides-help": "Cada guía recuerda por qué paso vas. Reinícialas para que todas vuelvan a empezar desde el principio.", + "guides-reset": "Reiniciar las guías", + "done": "Hecho", + "summary": "Volver a empezar las guías de las páginas" + }, + "learning": { + "title": "Para aprender", + "help": "Herramientas que no se ven por defecto para no recargar las páginas.", + "step-by-step": "Mostrar «Paso a paso»: cómo aprende la red, ejemplo a ejemplo, hacia delante y hacia atrás", + "step-by-step-help": "Aparece en las páginas de entrenamiento y en las de los modelos de clasificación tabular y regresión, con redes de menos de 64 neuronas.", + "summary": "Paso a paso y otras herramientas para aprender" + }, + "privacy": { + "title": "Privacidad y cookies", + "help": "Las cookies de Google Analytics nos dicen de forma anónima qué secciones, modelos y conjuntos de datos se usan y qué falla, sin datos personales ni lo que subes. Solo se activan si las aceptas.", + "analytics": "Permitir las cookies de Google Analytics", + "status-accepted": "Ahora mismo: cookies aceptadas.", + "status-rejected": "Ahora mismo: cookies rechazadas.", + "status-undecided": "Todavía no has decidido: de momento no se usan.", + "more": "Más información sobre las cookies", + "summary": "Cookies de Google Analytics" + }, + "data": { + "title": "Datos guardados en este navegador", + "help": "Lo que la aplicación guarda en este navegador. No sale de él y puedes borrarlo cuando quieras.", + "summary": "Lo que se guarda, cuánto ocupa y restablecer todo", + "total": "En total, esta web ocupa {{used}} en este navegador.", + "trained": { + "title": "Modelos entrenados", + "help": "Los que entrenas y guardas: se recuperan al volver a su página.", + "count_zero": "Ninguno", + "count_one": "1 modelo", + "count_other": "{{count}} modelos", + "delete": "Borrar los modelos entrenados", + "question_one": "Se borrará 1 modelo entrenado. No se puede deshacer.", + "question_other": "Se borrarán {{count}} modelos entrenados. No se puede deshacer." + }, + "pretrained": { + "title": "Modelos preentrenados descargados", + "help": "Los de detección de objetos, MobileNet…: se guardan la primera vez que los usas para no volver a descargarlos.", + "count_zero": "Ninguno", + "count_one": "1 modelo", + "count_other": "{{count}} modelos", + "delete": "Borrar los modelos preentrenados descargados", + "delete-one": "Borrar {{model}}", + "question": "Se volverán a descargar la próxima vez que los uses.", + "question-one": "Se borrará {{model}} de este navegador: se volverá a descargar la próxima vez que lo uses.", + "mobilenet": "MobileNet - Clasificación de imágenes", + "other": "Otros ficheros" + }, + "offline": { + "title": "Para usar sin conexión", + "help": "Las páginas que ya has abierto, para que funcionen sin internet.", + "count_zero": "Nada", + "count_one": "1 fichero", + "count_other": "{{count}} ficheros", + "delete": "Borrar lo guardado para usar sin conexión", + "question": "Lo que has abierto no funcionará sin internet hasta que lo vuelvas a abrir." + }, + "settings": { + "title": "Ajustes y progreso", + "help": "Idioma, tema, accesibilidad, backend, voz y progreso de las guías, Paso a paso, el aviso de descargas y tu decisión sobre las cookies." + }, + "delete": "Borrar", + "delete-confirm": "Sí, borrar", + "reset": "Restablecer todos los ajustes", + "reset-help": "Borra todo lo anterior y vuelve a los valores por defecto. La página se recargará.", + "confirm": "¿Seguro? Se borrarán todos los ajustes guardados en este navegador.", + "confirm-button": "Sí, borrarlos", + "cancel": "Cancelar" + }, + "accessibility": { + "title": "Accesibilidad", + "help": "Para adaptar la aplicación a lo que necesitas. Se guarda en este navegador.", + "text-size": "Tamaño del texto", + "spacing": "Más espacio entre líneas, letras y palabras", + "spacing-help": "El espaciado que recomienda WCAG para leer con más facilidad.", + "highContrast": "Alto contraste", + "highContrast-help": "Texto y bordes en negro (o en blanco con el tema oscuro), sin grises.", + "reduceMotion": "Reducir el movimiento", + "reduceMotion-help": "Sin animaciones ni desplazamientos suaves, también en las gráficas.", + "underlineLinks": "Subrayar siempre los enlaces", + "underlineLinks-help": "Para distinguirlos del texto sin depender del color.", + "strongFocus": "Foco más grueso", + "strongFocus-help": "El borde que marca dónde estás al usar el teclado, más visible.", + "openVisor": "Abrir el visor de TensorFlow.js al entrenar", + "openVisor-help": "Es un panel de una librería que no se puede usar con lector de pantalla; las curvas de la página dicen lo mismo.", + "system-on": "Tu sistema ya lo pide, así que está activo aunque no lo marques.", + "guide": "La voz de las guías y que avancen solas se cambian en", + "summary": "Tamaño del texto, contraste, movimiento y foco" + }, + "sections": "Apartados de la configuración", + "back": "Todos los apartados" + }, + "learn": { + "title": "Empieza aquí", + "intro": "Ocho pasos cortos para aprender lo esencial de las redes neuronales haciendo: de probar una red ya entrenada a preguntarle por qué decide lo que decide. Cada paso se marca solo al hacerlo.", + "progress": "{{count}} de {{total}} pasos hechos", + "step": "Paso {{number}}", + "done": "Hecho", + "next": "Siguiente", + "go": "Ir al paso", + "again": "Volver a hacerlo", + "mark-done": "Marcar como hecho", + "mark-undone": "Desmarcar", + "reset": "Empezar de cero", + "reset-confirm": "¿Seguro? Se desmarcarán todos los pasos.", + "reset-yes": "Sí, empezar de cero", + "reset-no": "Cancelar", + "finished": { + "title": "¡Recorrido completado!", + "text": "Ya sabes entrenar, comparar, arreglar y explicar redes neuronales. Ahora prueba con tus propios datos: sube un CSV en clasificación tabular o en regresión, o analízalo antes en el AED." + }, + "steps": { + "lab": { + "title": "Juega con una red", + "text": "En el laboratorio, una red pequeña separa puntos en un plano y ves su frontera mientras aprende. Prueba los ejemplos de «Prueba esto»." + }, + "glossary": { + "title": "Las palabras clave", + "text": "Lee en el glosario qué son una red neuronal, una capa, una neurona y una época: salen en todas las páginas." + }, + "pretrained": { + "title": "Prueba una red ya entrenada", + "text": "Dibuja un número y mira cómo lo reconoce una red entrenada con miles de dígitos escritos a mano (MNIST)." + }, + "train": { + "title": "Entrena tu primera red", + "text": "Con las flores Iris: pulsa «Entrenar modelo» y mira cómo baja la pérdida época a época. Debajo verás en palabras cómo ha ido." + }, + "step-by-step": { + "title": "Mira cómo aprende tu red", + "text": "Con las flores Iris, Paso a paso enseña un ejemplo recorriendo la red: hacia delante, el error y hacia atrás, y cómo cambia cada peso. Avanza al menos un paso." + }, + "compare": { + "title": "Cambia una cosa y compara", + "text": "Vuelve a entrenar cambiando solo la tasa de aprendizaje y activa «Comparar modelos» junto a las curvas: verás qué ha cambiado y cuál aprende mejor." + }, + "fix-layers": { + "title": "Arregla una red mal montada", + "text": "En el editor de capas, pon en la última capa un número de neuronas distinto del de clases: aparecerá un aviso. Arréglalo con su botón y entenderás por qué la salida tiene una neurona por clase." + }, + "regression": { + "title": "Predice un número", + "text": "En regresión la red no elige una clase, sino que da un valor: entrena con Auto MPG para predecir el consumo de un coche." + }, + "cnn": { + "title": "Entrena una red para imágenes", + "text": "Las redes convolucionales buscan trazos y formas en las imágenes: entrena una con MNIST (tarda algo más que las otras)." + }, + "explain": { + "title": "Pregunta al modelo por qué", + "text": "Con el modelo de los coches (CAR), haz una predicción y pide su explicación: verás qué atributos han pesado más en la decisión." + } + }, + "challenges": { + "title": "Retos", + "intro": "Cuando ya sepas entrenar, pon a prueba lo aprendido: cambia las capas y los hiperparámetros hasta conseguirlo. Se marcan solos al entrenar.", + "progress": "{{count}} de {{total}} retos superados", + "passed": "Superado", + "result": "Lo has conseguido con un {{value}} de aciertos.", + "hint": "Pista", + "go": "Intentarlo", + "again": "Volver a intentarlo", + "iris-accuracy": { + "title": "Iris perfecto", + "goal": "Con Iris, acierta todas las flores de prueba (las que la red no ve al entrenar): un 100 % de aciertos.", + "hint": "Prueba con más épocas (50) y una tasa de aprendizaje algo mayor (0,05). Si no sale a la primera, vuelve a entrenar: cada vez la red empieza con otros pesos." + }, + "iris-tiny": { + "title": "Con muy pocas neuronas", + "goal": "Con Iris, llega al 90 % de aciertos con 4 neuronas ocultas como mucho (sin contar la capa de salida).", + "hint": "Deja una sola capa oculta de 4 neuronas (o dos de 2) y dale más épocas: un problema sencillo no necesita una red grande." + }, + "iris-fast": { + "title": "En pocas épocas", + "goal": "Con Iris, llega al 90 % de aciertos en 5 épocas como mucho.", + "hint": "Con pocas épocas, cada paso tiene que contar: sube la tasa de aprendizaje (0,1) y usa Adam." + }, + "regression-good": { + "title": "Un entrenamiento de manual", + "goal": "En regresión, con cualquier conjunto de datos, consigue un entrenamiento que el diagnóstico dé por bueno: la pérdida baja y se estabiliza, sin sobreajuste.", + "hint": "Empieza con Salary y unas 40 épocas. Si el diagnóstico dice que seguía mejorando, sube las épocas; si dice que la pérdida va a saltos o se dispara, baja la tasa de aprendizaje." + }, + "mnist-fast": { + "title": "Dígitos a toda prisa", + "goal": "Con MNIST, consigue al menos un 93 % de aciertos con las imágenes de prueba en 2 épocas como mucho.", + "hint": "En dos épocas la red ve los datos solo dos veces: prueba a subir la tasa de aprendizaje poco a poco (0,005, 0,01…) sin pasarte, o el diagnóstico te dirá que la pérdida va a saltos o se dispara." + } + }, + "toast": { + "title": "Paso {{number}} de {{total}} hecho", + "next": "Siguiente: {{title}} →", + "finished": "¡Has completado el recorrido! →", + "close": "Cerrar", + "challenge": "¡Reto superado!", + "challenges": "Ver los retos →" + }, + "home": { + "first": "¿Es tu primera vez? Empieza aquí: ocho pasos cortos para aprender haciendo.", + "continue": "Llevas {{count}} de {{total}} pasos de Empieza aquí: sigue por donde ibas.", + "finished": "Has completado Empieza aquí: ya puedes probar con tus propios datos." } }, - "menu-selection-model": { - "form-description-1": "Selecciona a continuación el modelo entrenado con el que se va a trabajar.", - "form-description-2": "-", - "form-label": "Selecciona un modelo pre-entrenado", - "form-option-_-1": "Selecciona un modelo pre-entrenado", - "form-submit": "Continuar" + "regression-description": { + "title": "Regresión lineal", + "subtitle": "Descripción del problema y los modelos", + "paragraphs": [ + "En el análisis de datos, un problema de regresión es aquel en el que se quiere predecir o estimar un valor numérico a partir de unas variables de entrada. La regresión lineal es un modelo matemático para hacer esa predicción.", + "Un modelo de regresión lineal es una técnica estadística que busca una relación lineal entre una variable de respuesta (o dependiente) y una o más variables predictoras (o independientes). Su objetivo es encontrar la recta que mejor se ajusta a los datos observados, para usarla después para predecir la variable de respuesta a partir de las predictoras.", + "El modelo representa esa relación con la ecuación de una recta: el valor de la variable de respuesta se estima como una combinación lineal de las predictoras. Sus coeficientes, los coeficientes de regresión, se calculan con técnicas estadísticas que buscan que la diferencia entre los valores observados y los predichos sea la menor posible.", + "Una vez ajustado, el modelo sirve para predecir la variable de respuesta cuando se conocen las predictoras. También permite ver cuánto contribuye cada variable predictora a explicar la variabilidad de la respuesta.", + "En resumen, los modelos de regresión lineal son herramientas estadísticas para predecir valores numéricos a partir de variables predictoras, con una relación lineal entre ellas. Son útiles en campos como la economía, la ciencia, la ingeniería o la investigación social." + ], + "example": "Supongamos que queremos predecir el precio de una casa (la variable de respuesta, $Y$) a partir de su tamaño en metros cuadrados (la variable predictora, $x$). La relación entre las dos se puede expresar con esta ecuación de regresión lineal:", + "where": "Donde:", + "terms": [ + "$Y$ es el precio de la casa.", + "$x$ es el tamaño de la casa.", + "$\\beta_0$ es el intercepto: el valor de $Y$ cuando $x$ vale cero.", + "$\\beta_1$ es la pendiente de la recta: cuánto cambia el precio de la casa por cada metro cuadrado más.", + "$\\epsilon$ es el término de error: la variabilidad que el modelo no explica." + ], + "closing": [ + "El objetivo de la regresión lineal es estimar $\\beta_0$ y $\\beta_1$ a partir de los datos observados, para obtener la recta que mejor se ajusta a los puntos del gráfico de dispersión.", + "Con el modelo ajustado se puede predecir el precio de una casa nueva a partir de su superficie: basta con sustituir $x$ en la ecuación y calcular $Y$.", + "Este ejemplo es un caso sencillo de regresión lineal simple: en la práctica, los modelos pueden tener muchas variables predictoras y tener en cuenta cómo se combinan entre ellas." + ] }, - "playground": { - "form": { - "select-parameter": "Selecciona el parámetro", - "parameter": "Parámetro", - "parameter-integer": "Parámetro entero", - "parameter-decimal": "Parámetro decimal", - "parameter-float": "Parámetro flotante de precisión simple", - "parameter-double": "Parámetro flotante de precisión doble", - "parameter-categorical": "Parámetro categórico", - "data-to-check": "Datos a probar", - "vector-to-check": "Vector a probar", - "button-check-result": "Predecir" + "task": { + "pretrained-title": "Modelos ya entrenados", + "pretrained-text": "Modelos que ya han aprendido: pruébalos al momento, sin esperar a ningún entrenamiento, y mira por qué deciden lo que deciden.", + "pretrained-count_one": "1 modelo", + "pretrained-count_other": "{{count}} modelos", + "pretrained-button": "Elegir un modelo", + "design-title": "Diseñar, crear y editar una arquitectura", + "design-text": "Elige un conjunto de datos (o sube el tuyo), diseña las capas de la red, ajusta el entrenamiento y mira cómo aprende.", + "design-count_one": "1 conjunto de datos", + "design-count_other": "{{count}} conjuntos de datos", + "design-button": "Elegir un conjunto de datos", + "cluster-title": "Agrupar un conjunto de datos", + "cluster-text": "Eliges las columnas y el número de grupos, y k-means los busca paso a paso; si el conjunto trae las clases reales, al final se comparan.", + "upload": "Subir el tuyo", + "only-pretrained": "En esta tarea solo hay modelos ya entrenados.", + "only-cluster": "El agrupamiento no usa una red ni modelos ya entrenados: k-means agrupa los datos directamente." + }, + "accessibility": { + "title": "Accesibilidad", + "updated": "Declaración preparada el 12 de octubre de 2026 y revisada por última vez ese mismo día.", + "summary-title": "En resumen", + "summary": [ + "Queremos que cualquier persona pueda usar Nets4Learning, también con lector de pantalla, solo con el teclado, con baja visión o con el texto grande.", + "La aplicación es parcialmente conforme con las WCAG 2.2 de nivel AA: casi todo cumple, salvo lo que se explica abajo.", + "Si encuentras una barrera, cuéntanoslo: es la mejor forma de arreglarla." + ], + "index": "Apartados", + "status": { + "title": "Situación de cumplimiento", + "text": "Nets4Learning es parcialmente conforme con las Pautas de Accesibilidad para el Contenido Web (WCAG) 2.2, nivel AA, debido a las excepciones del apartado «Contenido no accesible».", + "standard": "Las WCAG 2.2 AA incluyen lo que pide la norma UNE-EN 301 549 (WCAG 2.1 AA), que es la que aplica el Real Decreto 1112/2018 a las webs del sector público." }, - "0-tabular-classification": { - "general": { - "model": "Modelo", - "description-input": "Descripción de la entrada de datos", - "description-features": "Formulario de edición de las características", - "description-data": "Datos del formulario", - "description-vector": "Vector de los datos", - "explainability": "Explicabilidad del modelo", - "select-class": "Seleccionar clase", - "n-samples": "Número de muestras", - "n-samples-help": "Muestras utilizadas por KernelSHAP", - "calculating": "Calculando...", - "show-explain": "Mostrar explicación", - "hide-explain": "Ocultar explicación", - "n-instances": "Instancias a agregar", - "n-instances-help": "Instancias del conjunto de datos que se agregan para calcular la importancia global (media de |SHAP|)", - "show-global": "Mostrar importancia global", - "hide-global": "Ocultar importancia global", - "no-data": "No hay conjunto de datos disponible para calcular la importancia global", - "sort-order": "Ordenar", - "sort-desc": "De mayor a menor importancia", - "sort-asc": "De menor a mayor importancia", - "sort-none": "Orden original", - "chart-type": "Tipo de gráfico", - "chart-bar": "Barras (media |SHAP|)", - "chart-beeswarm": "Enjambre (beeswarm)", - "beeswarm-shap-value": "Valor SHAP", - "beeswarm-feature-value": "Valor de la característica", - "beeswarm-low": "Bajo", - "beeswarm-high": "Alto", - "explain-panel-title": "Explicabilidad", - "explain-panel-local-title": "Explicación local (una instancia)", - "explain-panel-local-body": "SHAP explica una predicción concreta repartiendo la diferencia entre esta predicción y la predicción media del modelo (valor base) entre las características. Cada barra indica cuánto y en qué dirección empuja una característica: positiva hacia la clase seleccionada, negativa en contra.", - "explain-panel-local-body-regression": "SHAP explica una predicción concreta repartiendo la diferencia entre el valor predicho y la predicción media del modelo (valor base) entre las características. Cada barra indica cuánto y en qué dirección empuja una característica: positiva sube el valor predicho, negativa lo baja.", - "explain-panel-global-title": "Importancia global (todas las instancias)", - "explain-panel-global-body": "La importancia global agrega muchas explicaciones locales. El gráfico de barras muestra la media de los valores absolutos (media |SHAP|): cuánto pesa cada característica en promedio. El beeswarm añade la dirección y la dispersión del efecto, coloreando cada punto según el valor de la característica. Otros métodos, como la importancia por permutación, pueden ordenar las variables de forma algo distinta, sobre todo cuando hay variables relacionadas entre sí: cada método mide la importancia a su manera." + "not-accessible": { + "title": "Contenido no accesible", + "text": "Lo siguiente no cumple del todo, y esto es lo que se puede usar en su lugar:", + "items": [ + { + "problem": "El visor de TensorFlow.js que se abre al entrenar es de una librería: no se maneja con el teclado y sus gráficas no tienen texto.", + "instead": "Las mismas curvas están en la página, con sus datos en una tabla, y en «Configuración» se puede elegir que el visor no se abra." + }, + { + "problem": "Los botones de zoom de los gráficos del análisis de datos (Plotly) no se manejan con el teclado.", + "instead": "Los datos de cada gráfico están en su tabla («Ver los datos»)." + }, + { + "problem": "Dibujar un número en el lienzo necesita un ratón, un lápiz o el dedo.", + "instead": "Clasificar los ejemplos y las imágenes de prueba de la página." + }, + { + "problem": "El vídeo de la cámara en la detección de objetos no tiene descripción.", + "instead": "Lo detectado se dice en texto debajo, y un botón lo lee en voz alta. También se puede subir una foto." + }, + { + "problem": "Las fórmulas se generan con MathML para los lectores de pantalla, pero todavía no se han probado con todos.", + "instead": "Si alguna no se lee bien, cuéntanoslo (apartado «Comunicar una barrera»)." + } + ], + "out-of-scope": "Fuera del alcance de esta declaración: los modelos y las librerías de terceros que usa la aplicación y las páginas externas a las que enlaza.", + "instead": "En su lugar:" + }, + "use": { + "title": "Cómo usar la aplicación", + "keyboard-title": "Con el teclado", + "keyboard": [ + "El Tab recorre la página en orden. Lo primero es «Saltar al contenido», que lleva directamente a la página sin pasar por el menú.", + "Intro o Espacio activan botones y enlaces. Las flechas mueven por las pestañas, los desplegables, las listas de opciones y los pasos de la guía.", + "Escape cierra los diálogos, los desplegables, el menú del móvil, la guía y la ayuda de los términos, y el foco vuelve a donde estaba.", + "En las páginas largas, el índice «En esta página» lleva a cada apartado." + ], + "reader-title": "Con un lector de pantalla", + "reader": [ + "Cada página tiene su título, un solo encabezado principal y sus apartados con encabezados en orden.", + "Cada gráfica tiene una descripción y un botón «Ver los datos» con una tabla de todo lo que dibuja.", + "Lo que cambia sin mover el foco se anuncia: el resultado de una predicción, los datos cargados, cómo va un entrenamiento, los avisos de las capas y los cambios de idioma o de tema.", + "La guía de cada página se puede leer con el lector. Si la usas, desactiva la voz de la guía en «Configuración» para que no hablen los dos a la vez." + ], + "settings-title": "Ajustes de accesibilidad", + "settings": "Puedes agrandar el texto, separar más las líneas y las letras, usar alto contraste, reducir el movimiento, subrayar los enlaces o hacer más grueso el foco. Se guardan en tu navegador.", + "settings-link": "Ir a los ajustes de accesibilidad" + }, + "feedback": { + "title": "Comunicar una barrera", + "text": "Si algo no puedes usar, o crees que no cumple, cuéntanoslo. Para poder arreglarlo, ayuda saber:", + "items": [ + "En qué página estabas y qué querías hacer.", + "Qué ha pasado.", + "Qué navegador y, si usas alguno, qué lector de pantalla u otra ayuda técnica." + ], + "issue": "Comunicar una barrera en GitHub (con una plantilla)", + "simidat": "Web del grupo SIMIDAT de la Universidad de Jaén, para escribirnos", + "response": "Responderemos lo antes posible y te diremos si hay una forma de hacer lo que necesitabas mientras lo arreglamos." + }, + "preparation": { + "title": "Cómo se ha preparado y cuándo se revisa", + "items": [ + "Método: autoevaluación del equipo de desarrollo.", + "Pruebas automáticas en cada cambio: axe con WCAG 2.2 A y AA en todas las páginas y en los estados que aparecen al usarlas (en los temas claro y oscuro y con los ajustes de accesibilidad), recorridos solo con el teclado, páginas a 320 px de ancho y con el texto al 200 %, y las reglas de accesibilidad del linter.", + "Pendiente: la revisión manual con lectores de pantalla (NVDA, VoiceOver y TalkBack) y las pruebas con personas con distintas discapacidades." + ], + "review": "Esta declaración se revisa cada año y con cada versión mayor de la aplicación." + }, + "new-tab": "(se abre en otra pestaña)" + }, + "lab": { + "title": "Laboratorio: una red en 2D", + "intro": "Una red neuronal pequeña aprende a separar los puntos naranjas de los azules. Cambia los datos, lo que entra en la red o sus capas y mira cómo cambia la frontera mientras entrena.", + "data": { + "title": "Datos", + "dataset": "Conjunto", + "noise": "Ruido: {{value}}", + "count": "Puntos", + "new": "Otros puntos" + }, + "datasets": { + "blobs": "Dos nubes", + "circles": "Círculos", + "xor": "XOR (cuadrantes)", + "spiral": "Espirales" + }, + "features": { + "title": "Lo que entra en la red", + "help": "Las coordenadas de cada punto y, si quieres, otras calculadas con ellas.", + "x": "x", + "y": "y", + "x2": "x²", + "y2": "y²", + "xy": "x × y" + }, + "network": { + "title": "La red", + "help": "Capas ocultas entre la entrada y la salida, cada una con sus neuronas.", + "none": "Sin capas ocultas: la entrada va directa a la salida.", + "layer": "Capa {{number}}: {{units}} neuronas", + "fewer": "Quitar una neurona a la capa {{number}}", + "more": "Añadir una neurona a la capa {{number}}", + "add": "Añadir una capa", + "remove": "Quitar la última capa", + "activation": "Función de activación" + }, + "training": { + "title": "Cómo aprende", + "learning-rate": "Tasa de aprendizaje", + "speed": "Velocidad", + "speeds": { + "slow": "Despacio (para ver la frontera)", + "normal": "Normal", + "fast": "Lo más rápido posible" }, - "0_upload": { - "upload": "Subir", - "upload-your-model": "Carga tu propio modelo.", - "upload-your-model-description": "Ten en cuenta que tienes que subir el archivo .json y el fichero .bin para luego cargar el modelo", - "button-upload-your-model": "Cargar modelo" + "batch-size": "Puntos por lote" + }, + "train": "Entrenar", + "pause": "Pausar", + "step": "Una época", + "restart": "Empezar de cero", + "restarted": "La red empieza de cero, con pesos nuevos al azar.", + "show-test": "Ver los de prueba", + "canvas": "El plano con los puntos de {{dataset}} y, de fondo, la clase que predice la red en cada zona", + "legend": "Naranja (círculos) y azul (cuadrados): las dos clases. Rellenos, los puntos con los que aprende; blancos, los de prueba, que no ve al entrenar. El fondo es lo que predice la red: cuanto más intenso, más segura.", + "not-trained": "Aún sin entrenar: pulsa «Entrenar» o «Una época».", + "summary": "Época {{epoch}}: acierta el {{testAccuracy}} de los puntos de prueba y el {{trainAccuracy}} de los de entrenamiento. Pérdida: {{trainLoss}} con los de entrenamiento y {{testLoss}} con los de prueba.", + "diverged": "La pérdida se ha disparado y la red ya no aprende: baja la tasa de aprendizaje y empieza de cero.", + "loss": { + "title": "La pérdida", + "empty": "Aquí verás cómo baja la pérdida al entrenar.", + "train": "entrenamiento", + "test": "prueba", + "help": "Si la de prueba sube mientras la de entrenamiento baja, se está aprendiendo los puntos de memoria (sobreajuste)." + }, + "experiments": { + "title": "Prueba esto", + "xor-line": { + "title": "XOR sin capas ocultas", + "lesson": "Sin capas ocultas, la red solo puede trazar una línea recta: con el XOR no llega ni a la mitad de aciertos." }, - "generator": { - "manual": { - "title": "Manual del generador de modelos", - "details-edit-layers": { - "title": "Editor de las capas", - "text-0": "Se pueden editar las capas de la red neuronal, puedes agregar tantas como desees pulsando el botón \"Añadir capa\" al inicio o al final.", - "list": { - "0": "Neuronas de la capa:
Cada neurona en una capa está conectada a todas las neuronas de la capa anterior y de la capa siguiente.
Cada neurona en una capa tiene un conjunto de pesos asociados que ponderan su valor de salida.
Podemos editar el número de neuronas de la capa.", - "1": "Función de activación:
La función de activación de una neurona se refiere a la función matemática que calcula su salida. Podemos editar la función de activación de las neuronas de cada capa." - } - }, - "details-hyper-parameters-editor": { - "title": "Editor de hiperparámetros", - "text-0": "Se pueden editar los parámetros generales necesarios para la creación del modelo.
Estos parámetros son:", - "list": { - "0": "Tasa de aprendizaje:
Valor entre 0 y 100 el cual indica el porcentaje de cambio de los pesos de la red.", - "1": "Número de épocas:
Cantidad de veces que se le pasa el conjunto de entrenamiento a la red (a mayor número, más tiempo tarda en entrenar).", - "2": "Tamaño del conjunto de pruebas:
Porcentaje del conjunto de datos que se utilizaran para las pruebas del modelo (datos de prueba). El resto de datos se utilizarán para el entrenamiento de la red (datos de entrenamiento).", - "3": "Optimizador:
Es una función que se utiliza para ajustar los pesos de la red.", - "4": "Función de pérdida:
Es un método de calculo de error para medir la eficiencia del modelo durante el entrenamiento.", - "5": "Función de métrica:
Es la media de evaluación que se utiliza para valorar el rendimiento de un modelo de aprendizaje automático con los datos de prueba." - } - }, - "details-hyper-parameters-info": { - "title": "Información de hiperparámetros", - "list": { - "0": "Tasa de aprendizaje:
La tasa de aprendizaje es un parámetro que determina cuánto se deben actualizar los pesos de la red neuronal en función del error calculado durante el entrenamiento.", - "1": "Número de épocas:
El número de épocas se refiere al número de veces que se presentan los datos de entrenamiento a la red neuronal durante el proceso de entrenamiento. Cada iteración implica una actualización de los pesos de la red en función del error calculado.", - "2": "Tamaño del conjunto de pruebas:
El tamaño del conjunto de pruebas se refiere a la cantidad de datos utilizados para evaluar el rendimiento de la red neuronal después del entrenamiento. Este conjunto de datos no se utiliza en el entrenamiento de la red neuronal y se utiliza para medir la capacidad de la red de generalizar a datos nuevos.", - "3": "Optimizador:
El optimizador es un algoritmo utilizado para actualizar los pesos de la red neuronal en función del error calculado durante el entrenamiento. Algunos ejemplos de optimizadores son el Descenso del Gradiente Estocástico (SGD), el Adam y el Adagrad.", - "4": "Función de pérdida:
La función de pérdida es una medida del error entre las predicciones de la red neuronal y las salidas reales. Se utiliza para optimizar la red neuronal durante el entrenamiento y existen diferentes funciones de pérdida, como la Entropía Cruzada y el Error Cuadrático Medio." - } - }, - "details-create-and-train-models": { - "title": "Crear y entrenar modelo", - "text-0": "Una vez se han rellenado todos los campos anteriores podemos crear el modelo pulsando el botón \"Crear y entrenar modelo\".", - "text-1": "Si se pulsa el botón \"Abrir Visor\" se muestran dos gráficas. La gráfica superior muestra la evolución de la función de pérdida durante el entrenamiento. La gráfica inferior muestra la evolución de la métrica de evaluación accuracy. En las gráficas el color azul representa la evolución de los valores en el conjunto de entrenamiento y el color naranja representa las medidas para el conjunto de prueba.", - "text-2": "La precisión de validación es importante para detectar el sobre ajuste (overfitting) del modelo, que se produce cuando el modelo se ajusta demasiado a los datos de entrenamiento y no generaliza bien a nuevos datos." - }, - "details-export-models": { - "title": "Exportar modelo", - "text-0": "Si hemos creado el modelo correctamente se añadirá una entrada en la tabla de modelos generados. La aplicación permite exportar los modelos generados y guardarlos localmente." - }, - "details-prediction": { - "title": "Predicción", - "text-0": "El formulario final nos permite seleccionar las características principales que se usan para determinar la clase.", - "text-1": "Al pulsar el botón \"Ver resultado\", a partir de las características de entrada del elemento se obtiene la predicción de su clase de salida." - } + "xor-hidden": { + "title": "XOR con una capa de 4 neuronas", + "lesson": "Con una capa oculta combina varias rectas y ya separa el XOR: para eso sirven las capas ocultas." + }, + "circles-features": { + "title": "Círculos con x² e y²", + "lesson": "Con x² e y² como entrada, los círculos se separan sin capas ocultas: elegir bien lo que entra en la red ahorra capas." + }, + "spiral": { + "title": "La espiral, la más difícil", + "lesson": "La espiral necesita más neuronas, más características y paciencia: deja que entrene unos cientos de épocas." + }, + "learning-rate": { + "title": "Una tasa de aprendizaje enorme", + "lesson": "Con una tasa de 3, cada paso se pasa de largo: la pérdida va a saltos en vez de bajar. Prueba con 0,1." + }, + "overfitting": { + "title": "Pocos puntos, mucho ruido y una red grande", + "lesson": "Se aprende los puntos de memoria: la pérdida de entrenamiento baja y la de prueba sube. Es el sobreajuste." + } + }, + "next": "Cuando tengas la idea, sigue con" + } + }, + "generator": { + "table-models": { + "list-models-generated": "Lista modelos generados", + "learning-rate": "Tasa de aprendizaje", + "test-size": "Tamaño del conjunto de pruebas", + "n-of-epochs": "N. épocas", + "n-epochs": "N. épocas", + "id-optimizer": "Optimizador", + "id-loss": "Pérdida", + "id-metrics": "Métrica", + "layers": "Capas", + "download": "Descargar", + "features": "Características", + "open-visor": "Abrir visor", + "close-visor": "Cerrar visor", + "history": "Valores finales (validación)", + "window": "Ventana", + "difference": "Diferenciar", + "batch-size": "Tamaño del lote" + } + }, + "hr": { + "information": "Información", + "editor": "Editor", + "dataset": "Conjunto de datos", + "model": "Modelo", + "step-by-step": "Paso a paso", + "generated-models": "Modelos generados", + "predict": "Predecir", + "classify": "Clasificar", + "explainability": "Explicabilidad", + "on-this-page": "En esta página", + "tasks": "Tareas", + "00-tabular-classification": "Clasificación Tabular", + "tutorial-00-tabular-classification": "Entrenar un modelo para clasificación tabular", + "01-regression": "Regresión", + "02-object-detection": "Detección de objetos", + "03-image-classification": "Clasificación de imágenes", + "optimization-function": "Funciones de optimización", + "activation-functions": "Funciones de activación", + "loss-functions": "Funciones de pérdida", + "metric-function": "Funciones de métrica", + "layers": "Capas", + "process-dataset": "Procesamiento del conjunto de datos", + "project": "Proyecto", + "add-model-dataset": "Añadir modelo al proyecto", + "dataframe": "DataFrame" + }, + "form-dataframe": { + "int32": "Entero", + "float32": "Flotante", + "string": "Texto", + "label-encoder": "Label encoder", + "one-hot-encoder": "OneHot encoder", + "drop": "Descartar", + "ignored": "Ignorar", + "submit": "Procesar dataframe" + }, + "upload-dataset-info": "Debes subir un conjunto de datos para realizar la tarea.", + "upload-model": "Subir modelo", + "upload-model-info": "Debes subir un modelo para realizar la tarea.", + "upload-dataset": "Subir conjunto de datos", + "model-summary": "Resumen del modelo", + "breadcrumb": { + "label": "Ruta de navegación", + "models": "Modelos pre-entrenados", + "datasets": "Entrenar un modelo", + "change": "Cambiar a otro de la lista", + "train-with-dataset": "Entrenar con este conjunto de datos", + "try-pretrained": "Probar el modelo pre-entrenado" + }, + "neural-network": { + "layer": "Capa {{index}}", + "units": "{{units}} neuronas", + "kernel-size": "Kernel {{value}}", + "filters": "{{value}} filtros", + "pool-size": "Pool {{value}}", + "strides": "Paso {{value}}", + "description": "Capas de la red, de la entrada a la salida" + }, + "session": { + "export": "Exportar configuración", + "import": "Importar configuración", + "imported": "Configuración importada", + "error-not-json": "El fichero no es un JSON válido", + "error-not-session": "El fichero no es una configuración de Nets4Learning", + "error-other-task": "La configuración es de otra tarea", + "error-link": "El enlace no trae una configuración válida (puede que se haya cortado al copiarlo)", + "share": { + "button": "Compartir", + "title": "Compartir este ejercicio", + "text": "Quien abra el enlace tendrá esta misma red y estos hiperparámetros, listos para entrenar con el mismo conjunto de datos. Los datos y los modelos entrenados no se comparten.", + "link": "Enlace para compartir", + "copy": "Copiar", + "copied": "¡Copiado!", + "native": "Compartir con otra aplicación…", + "qr": "O escanéalo con el móvil", + "close": "Cerrar" + } + }, + "guide": { + "button": "Guía", + "button-title": "Guía paso a paso de esta página, leída en voz alta", + "resume": "Continuar la guía (paso {{current}} de {{total}})", + "restart": "Volver al principio", + "step": "Paso {{current}} de {{total}}", + "back": "Atrás", + "next": "Siguiente", + "finish": "Terminar", + "close": "Cerrar la guía", + "voice-on": "Leer en voz alta", + "voice-off": "Silenciar la voz", + "no-voice": "Este navegador no puede leer en voz alta", + "repeat": "Volver a leer este paso", + "auto-on": "Avanzar solo al terminar cada paso", + "auto-off": "Dejar de avanzar solo", + "0-tabular-classification": { + "CAR": { + "intro": { + "title": "Clasificación de coches", + "content": "En esta página, una red neuronal ya entrenada decide si un coche es aceptable a partir de seis características: el precio de compra, el mantenimiento, las puertas, las plazas, el maletero y la seguridad. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "model": { + "title": "El modelo", + "content": "Esta es la ficha del modelo. Cuenta de dónde salen los datos, el conjunto Car Evaluation del repositorio de la UCI, qué características recibe la red y qué clases puede predecir." + }, + "model-summary": { + "title": "Resumen del modelo", + "content": "Este botón abre el resumen de la red: sus capas, cuántas neuronas tiene cada una y cuántos parámetros, que son los pesos que ajustó durante el entrenamiento." + }, + "dataset": { + "title": "El conjunto de datos", + "content": "Estos son los 1728 coches con los que se entrenó la red. Cada fila es un coche y cada columna, una de sus características. La última columna, resaltada, es la clase: lo que la red aprendió a predecir." + }, + "dataset-processed": { + "title": "Datos procesados", + "content": "Una red neuronal solo trabaja con números. En esta pestaña verás los mismos coches con cada categoría convertida en un número: por ejemplo, los cuatro precios posibles pasan a ser números del 0 al 3. Así es como los recibe el modelo." + }, + "instances": { + "title": "Ejemplos y filas", + "content": "Con este selector rellenas el formulario de golpe. Arriba están los ejemplos, marcados con una estrella, uno de cada clase; debajo, todas las filas del conjunto de datos con su clase real." + }, + "fields": { + "Buying": { + "title": "Precio de compra", + "content": "Cuánto cuesta comprar el coche: muy alto, alto, medio o bajo." + }, + "Maint": { + "title": "Precio del mantenimiento", + "content": "Lo que cuesta mantener el coche, con sus revisiones y reparaciones. También va de muy alto a bajo." + }, + "Doors": { + "title": "Número de puertas", + "content": "Dos, tres, cuatro, o cinco o más. Es la característica que menos influye en la decisión." + }, + "Persons": { + "title": "Capacidad de personas", + "content": "Cuántas personas caben: dos, cuatro o más. En estos datos, un coche de solo dos plazas siempre es inaceptable." + }, + "Lug_boot": { + "title": "Tamaño del maletero", + "content": "Pequeño, mediano o grande. Cuanto más grande es el maletero, más aceptable es el coche." + }, + "Safety": { + "title": "Seguridad", + "content": "La seguridad estimada del coche: baja, media o alta. Es la característica que más pesa: con seguridad baja, el coche siempre es inaceptable." } + }, + "vector": { + "title": "De palabras a números", + "content": "A la izquierda están los valores del formulario y, a la derecha, el vector que entra en la red: las mismas seis características convertidas en números con la codificación aprendida al entrenar." + }, + "classify": { + "title": "Clasificar", + "content": "Al pulsar este botón, la red recibe el vector, lo pasa capa a capa y calcula una probabilidad para cada clase." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece la probabilidad de cada clase, y la más alta es la predicción. Si clasificas un ejemplo o una fila sin cambiarla, también verás su clase real, para comprobar si la red acierta. Este modelo solo tiene tres salidas: inaceptable, aceptable y muy bueno. La clase bueno no tiene ninguna, así que nunca la predice." + }, + "explain": { + "title": "Explicabilidad", + "content": "Después de clasificar, aquí ves por qué la red ha decidido eso. SHAP reparte la decisión entre las características: cuáles empujan hacia la clase y cuáles en contra. La importancia global hace lo mismo con muchas filas, para ver qué característica pesa más en general." + }, + "end": { + "title": "Ahora tú", + "content": "Prueba a elegir un ejemplo, clasifícalo y cambia después la seguridad o el número de plazas para ver cómo cambia la predicción. Puedes volver a abrir esta guía cuando quieras con el botón Guía." } }, - "generator": { - "prediction": { - "class_id_name": "El identificador del target {{class_target_id}} corresponde a la clase {{name}}" + "common": { + "model": { + "title": "El modelo", + "content": "Esta es la ficha del modelo: de dónde salen los datos, qué características recibe la red y qué clases puede predecir." }, - "layer-design": "Diseño de capas", - "neural_network_modes": { - "title": "Modos de visualización", - "compact": "Modo compacto", - "extend": "Modo extendido" + "model-summary": { + "title": "Resumen del modelo", + "content": "Este botón abre el resumen de la red: sus capas, cuántas neuronas tiene cada una y cuántos parámetros, que son los pesos que ajustó durante el entrenamiento." }, "dataset": { - "title": "Conjunto de datos", - "upload-dataset": "Subir conjunto de datos", - "attributes": { - "title": "Atributos", - "int32": "Numérico", - "float32": "Decimal", - "string": "Texto", - "label-encoder": "Label encoder", - "one-hot-encoder": "OneHot encoder", - "classes": "Clases" - }, - "details": { - "dataframe-processed": "Dataframe procesado", - "description-original": "Descripción del dataframe original", - "description-processed": "Descripción del dataframe procesado", - "data": "Información del conjunto de datos", - "info": "Información" - } + "title": "El conjunto de datos", + "content": "Estos son los datos con los que se entrenó la red. Cada fila es un ejemplo y cada columna, una característica. La última columna, resaltada, es la clase: lo que la red aprendió a predecir." }, - "layers": { - "title": "Diseño de capas", - "page-info": "Puedes visitar la web netron.app para visualizar la topología al completo" + "dataset-processed": { + "title": "Datos procesados", + "content": "Una red neuronal solo trabaja con números. En esta pestaña verás los mismos datos tal y como los recibe el modelo, con cada categoría convertida en un número." }, - "editor-layers": { - "title": "Editor de capas", - "add-layer-start": "Añadir capa al principio", - "add-layer-end": "Añadir capa al final", - "delete-layer": "Eliminar capa {{index}}", - "layer-id": "Capa {{index}}", - "kernel-size": "Tamaño del Kernel", - "kernel-size-placeholder": "Introduce el tamaño del kernel de la capa", - "filters-size": "Tamaño del filtro", - "filters-size-placeholder": "Introduce el filtro de la capa", - "units": "Neuronas de la capa", - "units-placeholder": "Introduce el número de neuronas de la capa", - "activation-function-select": "Selecciona la función de activación", - "activation-function-info": "Será el optimizador que se usará para activar la función", - "strides": "Strides", - "strides-placeholder": "Introduce el strides de la capa", - "pool-size": "Pool size", - "pool-size-placeholder": "Introduce el pool size de la capa" + "dataset-analysis": { + "title": "Análisis", + "content": "Esta pestaña resume el análisis exploratorio del conjunto: su tamaño, los valores ausentes, cuántos ejemplos hay de cada clase, los avisos, por ejemplo si las clases están desequilibradas, y qué características se relacionan entre sí. Es un buen sitio para entender los datos antes de clasificar." }, - "editor-feature-selector": { - "title": "Selector de características", - "feature-selector-x": "Selector de características / Conjunto (X)", - "feature-selector-y": "Selector de características / Objetivo (Y)", - "add-feature": "Añadir característica", - "delete-feature": "Eliminar característica {{value}}" + "instances": { + "title": "Ejemplos y filas", + "content": "Con este selector rellenas el formulario de golpe. Arriba están los ejemplos, marcados con una estrella; debajo, todas las filas del conjunto de datos con su clase real." }, - "general-parameters": { - "title": "Editor de hiperparámetros", - "learning-rate": "Tasa de aprendizaje", - "learning-rate-placeholder": "Introduce la tasa de aprendizaje", - "learning-rate-info": "Valor entre 0 y 100 (es un porcentaje)", - "number-of-epochs": "N. épocas", - "number-of-epochs-placeholder": "Número de épocas", - "number-of-epochs-info": "Mientras más alto sea, mas tardará en ejecutarse el entrenamiento", - "train-rate": "Tamaño del conjunto de pruebas", - "train-rate-placeholder": "Introduce el tamaño del banco de pruebas", - "train-rate-info": "Valor entre 0 y 100 (es un porcentaje)", - "optimizer-id": "Selecciona el optimizador", - "optimizer-id-info": "Será el optimizador que se usará para corregir el error.", - "loss-id": "Selecciona la función de pérdida", - "loss-id-info": "Será la función que se usará para evaluar el error de las neuronas.", - "metrics-id": "Selecciona la métrica", - "metrics-id-info": "Será el tipo de métrica que se usará para la evaluación durante entrenamiento.", - "test-size": "Tamaño del conjunto de pruebas", - "test-size-placeholder": "Tamaño del conjunto de pruebas", - "test-size-info": "Valor entre 0 y 100 (es un porcentaje) del tamaño del conjunto de pruebas", - "delete-metric": "Eliminar función de métrica {{index}}", - "add-metric": "Añadir función de métrica", - "metric-id-__index__": "Métrica {{index}}", - "metric-id-select": "Selecciona la función de métrica", - "metric-id-info": "Será una de las funciones de métrica" + "form": { + "title": "El formulario", + "content": "Aquí escribes los valores de lo que quieres clasificar, una casilla por característica. Debajo de cada una verás su nombre en el conjunto de datos y qué valores admite." }, - "loaded": "Cargado", - "load": "Cargar", - "waiting-for-file": "Esperando archivo", - "waiting-for-process": "Esperando el procesamiento del conjunto de datos", - "waiting-for-training": "Esperando el entrenamiento del modelo", - "models": { - "title": "Modelos", - "history-train": "Historial del entrenamiento", - "train": "Entrenamiento", - "button-submit": "Entrenar modelo", - "open-visor": "Abrir visor", - "close-visor": "Cerrar visor", - "export-current-model": "Exportar modelo actual" + "vector": { + "title": "De los datos al vector", + "content": "A la izquierda están los valores del formulario y, a la derecha, el vector que entra en la red: las mismas características convertidas en números con la codificación aprendida al entrenar." }, - "table": { - "id": "ID", - "load": "Cargar", - "learning-rate": "Tasa de aprendizaje", - "number-of-epochs": "N. Épocas", - "train-rate": "Tamaño del conjunto de pruebas", - "layers": "Capas", - "optimizer-id": "Optimizador", - "loss-id": "Perdida", - "metric-id": "Métrica", - "download": "Descargar" + "classify": { + "title": "Clasificar", + "content": "Al pulsar este botón, la red recibe el vector, lo pasa capa a capa y calcula una probabilidad para cada clase." }, - "dynamic-form-dataset": { - "title": "Predicción", - "text-0-__column_name_target__": "Introduce los valores de cada característica de entrada del ejemplo a predecir {{column_name_target}}", - "select-option": "Selecciona una opción", - "input-data": "Introduce los datos a probar", - "input-vector": "Introduce el vector a probar", - "test-vector": "Vector a probar", - "test-input-data": "Datos del formulario", - "test-input-vector": "Vector de los datos", - "selector-entity": "Selecciona la entidad", - "selector-model": "Selecciona el modelo" + "result": { + "title": "El resultado", + "content": "Aquí aparece la probabilidad de cada clase, y la más alta es la predicción. Si clasificas un ejemplo o una fila sin cambiarla, también verás su clase real, para comprobar si la red acierta." }, - "list-models-generated": "Lista modelos generados", - "visor": { - "title": "Configuración del visor", - "rmse": "RMSE", - "val_rmse": "VAL RMSE", - "mae": "MAE", - "val_mae": "VAL MAE", - "history-train": "Historial del entrenamiento", - "train": "Entrenamiento", - "summary": "Resumen", - "scatterplot": { - "__feature____target__": "{{feature}} x {{target}}" - }, - "original-vs-predictions": "Datos originales / predicción", - "model": "Modelo", - "dataset": "Conjunto de datos", - "predictions": "Predicción", - "predicted": "Predicho", - "confusion-matrix": "Matriz de confusión", - "line-chart": "Gráfico de líneas" + "explain": { + "title": "Explicabilidad", + "content": "Después de clasificar, aquí ves por qué la red ha decidido eso. SHAP reparte la decisión entre las características: cuáles empujan hacia la clase y cuáles en contra. La importancia global hace lo mismo con muchas filas, para ver qué característica pesa más en general." }, - "waiting-for-models": "Esperando a la creación de un modelo" + "step-by-step": { + "title": "Paso a paso", + "content": "Aquí ves cómo calcula este modelo su respuesta, con sus pesos de verdad: el paso hacia delante capa a capa, el error y, hacia atrás, cuánto cambiaría cada peso con un paso más de entrenamiento. Pulsa una neurona para ver sus cuentas. Solo se dibuja con modelos de menos de 64 neuronas." + }, + "end": { + "title": "Ahora tú", + "content": "Prueba a elegir un ejemplo, clasifícalo y cambia después alguna característica para ver cómo cambia la predicción. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } }, - "1-regression": { - "generator": { - "manual": { - "title": "Manual del generador de modelos", - "simple-regression": "Regresión simple", - "multiple-regression": "Regresión multiple", - "details-edit-layers": { - "title": "Editor de las capas", - "text": { - "0": "Se pueden editar las capas de la red neuronal, puedes agregar tantas como desees pulsando el botón \"Añadir capa\" al inicio o al final." - }, - "list": { - "0": "Neuronas de la capa:
Cada neurona en una capa está conectada a todas las neuronas de la capa anterior y de la capa siguiente.
Cada neurona en una capa tiene un conjunto de pesos asociados que ponderan su valor de salida.
Podemos editar el número de neuronas de la capa.", - "1": "Función de activación:
La función de activación de una neurona se refiere a la función matemática que calcula su salida. Podemos editar la función de activación de las neuronas de cada capa." - } - }, - "details-hyper-parameters-editor": { - "title": "Editor de hiperparámetros", - "text": { - "0": "Se pueden editar los parámetros generales necesarios para la creación del modelo.
Estos parámetros son:" - }, - "list": { - "0": "Tasa de aprendizaje:
Valor entre 0 y 100 el cual indica el porcentaje de cambio de los pesos de la red.", - "1": "Número de épocas:
Cantidad de veces que se le pasa el conjunto de entrenamiento a la red (a mayor número, más tiempo tarda en entrenar).", - "2": "Tamaño del conjunto de pruebas:
Porcentaje del conjunto de datos que se utilizaran para las pruebas del modelo (datos de prueba). El resto de datos se utilizarán para el entrenamiento de la red (datos de entrenamiento).", - "3": "Optimizador:
Es una función que se utiliza para ajustar los pesos de la red.", - "4": "Función de pérdida:
Es un método de calculo de error para medir la eficiencia del modelo durante el entrenamiento.", - "5": "Función de métrica:
Es la media de evaluación que se utiliza para valorar el rendimiento de un modelo de aprendizaje automático con los datos de prueba." - } - }, - "details-hyper-parameters-info": { - "title": "Información de hiperparámetros", - "list": { - "0": "Tasa de aprendizaje:
La tasa de aprendizaje es un parámetro que determina cuánto se deben actualizar los pesos de la red neuronal en función del error calculado durante el entrenamiento.", - "1": "Número de épocas:
El número de épocas se refiere al número de veces que se presentan los datos de entrenamiento a la red neuronal durante el proceso de entrenamiento. Cada iteración implica una actualización de los pesos de la red en función del error calculado.", - "2": "Tamaño del conjunto de pruebas:
El tamaño del conjunto de pruebas se refiere a la cantidad de datos utilizados para evaluar el rendimiento de la red neuronal después del entrenamiento. Este conjunto de datos no se utiliza en el entrenamiento de la red neuronal y se utiliza para medir la capacidad de la red de generalizar a datos nuevos.", - "3": "Optimizador:
El optimizador es un algoritmo utilizado para actualizar los pesos de la red neuronal en función del error calculado durante el entrenamiento. Algunos ejemplos de optimizadores son el Descenso del Gradiente Estocástico (SGD), el Adam y el Adagrad.", - "4": "Función de pérdida:
La función de pérdida es una medida del error entre las predicciones de la red neuronal y las salidas reales. Se utiliza para optimizar la red neuronal durante el entrenamiento y existen diferentes funciones de pérdida, como la Entropía Cruzada y el Error Cuadrático Medio." - } - }, - "details-create-and-train-models": { - "title": "Crear y entrenar modelo", - "text": { - "0": "Una vez se han rellenado todos los campos anteriores podemos crear el modelo pulsando el botón \"Crear y entrenar modelo\".", - "1": "Si se pulsa el botón \"Abrir Visor\" se muestran dos gráficas. La gráfica superior muestra la evolución de la función de pérdida durante el entrenamiento. La gráfica inferior muestra la evolución de la métrica de evaluación accuracy. En las gráficas el color azul representa la evolución de los valores en el conjunto de entrenamiento y el color naranja representa las medidas para el conjunto de prueba.", - "2": "La precisión de validación es importante para detectar el sobre ajuste (overfitting) del modelo, que se produce cuando el modelo se ajusta demasiado a los datos de entrenamiento y no generaliza bien a nuevos datos." - } - }, - "details-export-models": { - "title": "Exportar modelo", - "text": { - "0": "Si hemos creado el modelo correctamente se añadirá una entrada en la tabla de modelos generados. La aplicación permite exportar los modelos generados y guardarlos localmente." - } - }, - "details-plot-models": { - "title": "Gráfico de predicciones", - "text": { - "0": "Podemos usar un gráfico disperso para dicha tarea, de forma que representemos los datos originales en una nube de puntos y usamos una línea para trazar las predicciones del modelo, en función de la arquitectura que usemos nos dará una línea recta con cierta pendiente o una línea que se ajustará y curvará más a los datos. Para ello se hacen 100 predicciones x distantes, desde primer valor al último valor." - } - } + "IRIS": { + "intro": { + "title": "Clasificación de flores iris", + "content": "En esta página, una red neuronal ya entrenada reconoce la especie de una flor iris a partir de cuatro medidas: el largo y el ancho del sépalo y del pétalo. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "dataset": { + "title": "El conjunto de datos", + "content": "Es el famoso conjunto Iris, que el estadístico Ronald Fisher dio a conocer en 1936: 150 flores, 50 de cada especie. Cada fila es una flor con sus cuatro medidas en centímetros y la última columna, resaltada, es su especie." + }, + "fields": { + "sepal_length": { + "title": "Longitud del sépalo", + "content": "El sépalo es la hoja verde que protege la flor antes de abrirse. Esta casilla es su largo, en centímetros." }, - "simple-regression": "Regresión simple", - "multiple-regression": "Regresión multiple" + "sepal_width": { + "title": "Anchura del sépalo", + "content": "El ancho del sépalo, en centímetros. Es la medida que menos ayuda a distinguir las especies." + }, + "petal_length": { + "title": "Longitud del pétalo", + "content": "El largo del pétalo, en centímetros. Junto con su anchura, es la medida que mejor separa las especies: la setosa tiene los pétalos mucho más pequeños que las otras dos." + }, + "petal_width": { + "title": "Anchura del pétalo", + "content": "El ancho del pétalo, en centímetros. En estos datos, una flor con el pétalo de menos de un centímetro de ancho siempre es una setosa." + } + }, + "vector": { + "title": "De los datos al vector", + "content": "Aquí las cuatro medidas ya son números, así que el vector que entra en la red son esas mismas medidas, en el mismo orden." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece la probabilidad de cada especie: setosa, versicolor y virginica. La más alta es la predicción. La setosa es fácil de reconocer; las otras dos se parecen más y es donde la red puede dudar." + }, + "end": { + "title": "Ahora tú", + "content": "Elige el ejemplo de versicolor, clasifícalo y ve aumentando poco a poco el largo y el ancho del pétalo: verás cómo la red empieza a dudar y acaba diciendo virginica. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } + }, + "LYMPHOGRAPHY": { + "intro": { + "title": "Clasificación de linfografías", + "content": "En esta página, una red neuronal ya entrenada clasifica el resultado de una linfografía, una prueba de imagen del sistema linfático, en cuatro diagnósticos: normal, metástasis, linfoma maligno o fibrosis. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "dataset": { + "title": "El conjunto de datos", + "content": "Son 148 pacientes del Instituto de Oncología del Centro Médico Universitario de Liubliana. Cada fila es un paciente y cada columna, algo que se observó en su linfografía. Las clases están muy desequilibradas: hay 81 casos de metástasis y 61 de linfoma maligno, pero solo 4 de fibrosis y 2 normales." + }, + "form": { + "title": "Lo que se ve en la linfografía", + "content": "El formulario tiene dieciocho características. Unas dicen si los vasos linfáticos son normales, arqueados, deformados o desplazados; otras, si hay bloqueos, derivaciones o salida del contraste; y otras describen los ganglios: cuántos hay, si han aumentado o disminuido, su forma y los defectos y cambios de su estructura. Son términos médicos: no hace falta entenderlos todos para ver cómo cambia la predicción." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece la probabilidad de cada diagnóstico, y la más alta es la predicción. Con tan pocos casos de fibrosis y de resultados normales, la red ha aprendido sobre todo a distinguir entre metástasis y linfoma maligno." + }, + "end": { + "title": "Ahora tú", + "content": "Elige un ejemplo de cada diagnóstico, clasifícalo y mira después en la explicabilidad qué características han pesado más en cada uno. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } + } + }, + "1-regression": { + "common": { + "model": { + "title": "El modelo", + "content": "Esta es la ficha del modelo: de dónde salen los datos, qué variables recibe la red y cuál predice." + }, + "model-summary": { + "title": "Resumen del modelo", + "content": "Este botón abre el resumen de la red: sus capas, cuántas neuronas tiene cada una y cuántos parámetros, que son los pesos que ajustó durante el entrenamiento." }, - "dataframe": { - "title": "Dataframe procesado" + "dataset-select": { + "title": "Conjunto de datos", + "content": "Aquí eliges el conjunto de datos. Cada uno tiene sus propias redes entrenadas." }, - "selector-instance": { - "option": "Selector de instancia" + "dataset": { + "title": "El conjunto de datos", + "content": "Estos son los datos con los que se entrenó la red. Cada fila es un ejemplo y cada columna, una variable. La columna resaltada es la variable objetivo: el número que la red aprendió a predecir." }, - "selector-model": { - "option": "Selector de modelo" + "dataset-processed": { + "title": "Datos procesados", + "content": "En esta pestaña verás los mismos datos tal y como los recibe el modelo, con los textos convertidos en números, y debajo la descripción estadística de cada columna." }, - "details": { - "description-processed": { - "dataset": "Conjunto de datos procesado", - "describe": "Conjunto de datos estadísticas descriptivas" - } + "dataset-analysis": { + "title": "Análisis", + "content": "Esta pestaña resume el análisis exploratorio del conjunto: su tamaño, los valores ausentes, cómo se reparte la variable objetivo y qué variables se relacionan más con ella. Es un buen sitio para entender los datos antes de predecir." + }, + "instances": { + "title": "Filas del conjunto", + "content": "Con este selector rellenas el formulario con cualquier fila del conjunto de datos. Junto al número de fila verás su valor real, para compararlo después con la predicción." + }, + "models": { + "title": "Modelos", + "content": "Aquí eliges una de las redes ya entrenadas para este conjunto de datos." + }, + "form": { + "title": "El formulario", + "content": "Aquí escribes los valores de las variables de entrada, una casilla por variable. Debajo de cada una verás su tipo y el rango de valores que toma en los datos." }, "predict": { - "title": "Predicción", - "instance": { - "__index__": "Instancia {{index}}" + "title": "Predecir", + "content": "Al pulsar este botón, la red recibe los valores ya codificados y escalados, los pasa capa a capa y devuelve un número: su predicción." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece el valor predicho. Si usaste una fila del conjunto sin cambiarla, también verás su valor real y el error, la diferencia entre los dos. Debajo están los pasos por los que pasan los datos antes de entrar en la red." + }, + "explain": { + "title": "Explicabilidad", + "content": "Después de predecir, aquí ves por qué la red ha dado ese valor. SHAP reparte la predicción entre las variables: cuáles la suben y cuáles la bajan respecto a la predicción media. La importancia global hace lo mismo con muchas filas, para ver qué variable pesa más en general." + }, + "step-by-step": { + "title": "Paso a paso", + "content": "Aquí ves cómo calcula este modelo su respuesta, con sus pesos de verdad: el paso hacia delante capa a capa, el error y, hacia atrás, cuánto cambiaría cada peso con un paso más de entrenamiento. Pulsa una neurona para ver sus cuentas. Solo se dibuja con modelos de menos de 64 neuronas." + }, + "end": { + "title": "Ahora tú", + "content": "Elige una fila, predice su valor y cambia después alguna variable para ver cómo cambia la predicción. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } + }, + "AUTO_MPG": { + "intro": { + "title": "Rendimiento de combustible", + "content": "En esta página, una red neuronal ya entrenada predice cuántas millas recorre un coche con un galón de combustible, a partir de seis datos del coche: los cilindros, la cilindrada, la potencia, el peso, la aceleración y el año del modelo. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "dataset-select": { + "title": "Conjunto de datos", + "content": "Este modelo tiene un único conjunto de datos, Auto MPG." + }, + "dataset": { + "title": "El conjunto de datos", + "content": "Son 396 coches de 1970 a 1982, del conjunto Auto MPG. La columna resaltada, mpg, son las millas por galón: cuanto más alta, menos gasta el coche. En estos datos van de 9 a 46." + }, + "fields": { + "cylinders": { + "title": "Cilindros", + "content": "El número de cilindros del motor, de tres a ocho. Más cilindros suelen significar más consumo." }, - "model": { - "__index__": "Modelo {{index}}" + "displacement": { + "title": "Cilindrada", + "content": "El volumen total de los cilindros del motor, en pulgadas cúbicas. Cuanto mayor es, más combustible gasta el coche." }, - "button-submit": "Predecir", - "list-models-generated": "Lista de modelos generados", - "list-models": "Lista de modelos generados", - "list-instances": "Lista de instancias" + "horsepower": { + "title": "Potencia", + "content": "Los caballos de potencia del motor. Los coches más potentes suelen recorrer menos millas por galón." + }, + "weight": { + "title": "Peso", + "content": "El peso del coche, en libras. Es la variable más relacionada con el consumo: cuanto más pesa, menos millas recorre por galón." + }, + "acceleration": { + "title": "Aceleración", + "content": "Los segundos que tarda el coche en pasar de 0 a 60 millas por hora. Un número más alto es un coche menos brusco, que suele gastar menos." + }, + "model-year": { + "title": "Año del modelo", + "content": "El año en que salió el modelo, con dos cifras, de 70 a 82. Los coches más modernos de este conjunto gastan menos, en parte por las leyes de ahorro de combustible de aquellos años." + } }, - "model-selector": { - "title": "Selector de modelos", - "option": "Selecciona un modelo" + "result": { + "title": "El resultado", + "content": "Aquí aparece el consumo predicho, en millas por galón. Si usaste una fila sin cambiarla, también verás el valor real y el error. Debajo están los pasos por los que pasan los datos antes de entrar en la red." + }, + "end": { + "title": "Ahora tú", + "content": "Elige un coche, predice su consumo y súbele después el peso o la potencia: verás que la red predice menos millas por galón. Puedes volver a abrir esta guía cuando quieras con el botón Guía." } }, - "3-image-classification": { - "generator": { - "manual": { - "title": "Manual del generador de modelos", - "details-edit-layers": { - "title": "Editor de las capas", - "text-0": "Se pueden editar las capas de la red neuronal, puedes agregar tantas como desees pulsando el botón \"Añadir capa\" al inicio o al final.", - "list": { - "0": "Neuronas de la capa:
Cada neurona en una capa está conectada a todas las neuronas de la capa anterior y de la capa siguiente.
Cada neurona en una capa tiene un conjunto de pesos asociados que ponderan su valor de salida.
Podemos editar el número de neuronas de la capa.", - "1": "Función de activación:
La función de activación de una neurona se refiere a la función matemática que calcula su salida. Podemos editar la función de activación de las neuronas de cada capa." - } - }, - "details-edit-layers-more-info": { - "title": "Información adicional capas", - "text-0": "Adicionalmente hay dos capas más que son comunes al resto de redes de aprendizaje automático enfocadas en la clasificación de imágenes", - "list": { - "0": "dense
Crea una capa densa (completamente conectada).", - "1": "dropout
El abandono consiste en establecer aleatoriamente una tasa de fracción de unidades de entrada a 0 en cada actualización durante el tiempo de entrenamiento, lo que ayuda a prevenir el sobreajuste.", - "2": "embedding
Asigna números enteros positivos (índices) a vectores densos de tamaño fijo. p.ej. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]", - "3": "flatten
Una capa aplanada aplana cada lote en sus entradas a 1D (haciendo la salida 2D).", - "4": "permute
Permuta las dimensiones de la entrada de acuerdo con un patrón dado.", - "5": "repeatVector
repite la entrada n veces en una nueva dimensión.", - "6": "reshape
Modifica la forma a una determinada entrada.", - "7": "spatialDropout1d
Versión 1D espacial de dropout." - } - }, - "details-hyper-parameters-editor": { - "title": "Editor de hiperparámetros", - "text-0": "Se pueden editar los parámetros generales necesarios para la creación del modelo.
Estos parámetros son:", - "list": { - "0": "Tasa de aprendizaje:
Valor entre 0 y 100 el cual indica el porcentaje de cambio de los pesos de la red.", - "1": "Número de épocas:
Cantidad de veces que se le pasa el conjunto de entrenamiento a la red (a mayor número, más tiempo tarda en entrenar).", - "2": "Tamaño del conjunto de pruebas:
Porcentaje del conjunto de datos que se utilizaran para las pruebas del modelo (datos de prueba). El resto de datos se utilizarán para el entrenamiento de la red (datos de entrenamiento).", - "3": "Optimizador:
Es una función que se utiliza para ajustar los pesos de la red.", - "4": "Función de pérdida:
Es un método de calculo de error para medir la eficiencia del modelo durante el entrenamiento.", - "5": "Función de métrica:
Es la media de evaluación que se utiliza para valorar el rendimiento de un modelo de aprendizaje automático con los datos de prueba." - } - }, - "details-hyper-parameters-info": { - "title": "Información de hiperparámetros", - "list": { - "0": "Tasa de aprendizaje:
La tasa de aprendizaje es un parámetro que determina cuánto se deben actualizar los pesos de la red neuronal en función del error calculado durante el entrenamiento.", - "1": "Número de épocas:
El número de épocas se refiere al número de veces que se presentan los datos de entrenamiento a la red neuronal durante el proceso de entrenamiento. Cada iteración implica una actualización de los pesos de la red en función del error calculado.", - "2": "Tamaño del conjunto de pruebas:
El tamaño del conjunto de pruebas se refiere a la cantidad de datos utilizados para evaluar el rendimiento de la red neuronal después del entrenamiento. Este conjunto de datos no se utiliza en el entrenamiento de la red neuronal y se utiliza para medir la capacidad de la red de generalizar a datos nuevos.", - "3": "Optimizador:
El optimizador es un algoritmo utilizado para actualizar los pesos de la red neuronal en función del error calculado durante el entrenamiento. Algunos ejemplos de optimizadores son el Descenso del Gradiente Estocástico (SGD), el Adam y el Adagrad.", - "4": "Función de pérdida:
La función de pérdida es una medida del error entre las predicciones de la red neuronal y las salidas reales. Se utiliza para optimizar la red neuronal durante el entrenamiento y existen diferentes funciones de pérdida, como la Entropía Cruzada y el Error Cuadrático Medio." - } - }, - "details-create-and-train-models": { - "title": "Crear y entrenar modelo", - "text-0": "Una vez se han rellenado todos los campos anteriores podemos crear el modelo pulsando el botón \"Crear y entrenar modelo\".", - "text-1": "Si se pulsa el botón \"Abrir Visor\" se muestran dos gráficas. La gráfica superior muestra la evolución de la función de pérdida durante el entrenamiento. La gráfica inferior muestra la evolución de la métrica de evaluación accuracy. En las gráficas el color azul representa la evolución de los valores en el conjunto de entrenamiento y el color naranja representa las medidas para el conjunto de prueba.", - "text-2": "La precisión de validación es importante para detectar el sobre ajuste (overfitting) del modelo, que se produce cuando el modelo se ajusta demasiado a los datos de entrenamiento y no generaliza bien a nuevos datos." - }, - "details-export-models": { - "title": "Exportar modelo", - "text-0": "Si hemos creado el modelo correctamente se añadirá una entrada en la tabla de modelos generados. La aplicación permite exportar los modelos generados y guardarlos localmente." - }, - "details-prediction": { - "title": "Clasificación", - "text-0": "El formulario final nos permite dibujar o subir una imagen para determinar la clase.", - "text-1": "Al pulsar el botón \"Ver resultado\", a partir de las características de entrada del elemento se obtiene la predicción de su clase de salida." - } - } + "STUDENT_PERFORMANCE": { + "intro": { + "title": "Rendimiento de estudiantes", + "content": "En esta página, una red neuronal ya entrenada predice la nota final de un estudiante de secundaria, de 0 a 20, a partir de treinta datos sobre su vida escolar, familiar y social. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "model": { + "title": "El modelo", + "content": "Esta es la ficha del modelo: de dónde salen los datos, qué variables recibe la red y cuál predice. La nota sobre G1 y G2 que verás en ella habla de los datos originales: esta versión las deja fuera a propósito, como te explico más adelante." + }, + "dataset-select": { + "title": "Conjunto de datos", + "content": "Hay dos conjuntos: estudiantes de matemáticas y estudiantes de portugués, de dos institutos de Portugal. Cada uno tiene su propia red entrenada." + }, + "dataset": { + "title": "El conjunto de datos", + "content": "Cada fila es un estudiante: 395 en matemáticas y 649 en portugués. La columna resaltada, G3, es la nota final del curso, de 0 a 20. A los datos originales les faltan aquí dos columnas, G1 y G2, las notas del primer y del segundo trimestre: se quitaron a propósito." + }, + "form": { + "title": "Los datos del estudiante", + "content": "El formulario tiene treinta variables: personales, como la edad y el sexo; familiares, como los estudios y el trabajo de la madre y del padre; escolares, como el tiempo de estudio, los suspensos anteriores y las faltas; y sociales, como las salidas con amigos o el consumo de alcohol. Los suspensos anteriores son lo que más se relaciona con una nota final baja. Las notas de los trimestres no están: en el siguiente paso te explico por qué." + }, + "grades": { + "title": "¿Y las notas G1 y G2?", + "content": "G1 y G2 son las notas del primer y del segundo trimestre, y se parecen muchísimo a la final: su correlación con G3 va de 0,8 a 0,92. Con ellas, la red apenas tendría que aprender nada, le bastaría con copiar la nota del segundo trimestre. Sin ellas, tiene que predecir la nota final solo con la vida escolar, familiar y social del estudiante. Es mucho más difícil, pero también mucho más útil: se puede hacer antes de que haya ninguna nota, para ayudar a tiempo a quien lo necesite. Por eso las redes de esta página se entrenaron sin G1 ni G2." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece la nota final predicha, de 0 a 20. Si usaste una fila sin cambiarla, también verás la nota real y el error. Como la red no conoce las notas de los trimestres, es normal que se equivoque en varios puntos: es el precio de poder predecir antes de que haya notas." + }, + "end": { + "title": "Ahora tú", + "content": "Elige un estudiante, predice su nota y cambia después el número de suspensos anteriores o el tiempo de estudio para ver cómo cambia la predicción. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } + }, + "WINE": { + "intro": { + "title": "Calidad del vino", + "content": "En esta página, una red neuronal ya entrenada predice la calidad de un vino portugués, la nota que le dieron los catadores, a partir de once medidas químicas. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "dataset-select": { + "title": "Conjunto de datos", + "content": "Hay dos conjuntos: vino tinto y vino blanco, de la denominación vinho verde. Cada uno tiene su propia red entrenada." + }, + "dataset": { + "title": "El conjunto de datos", + "content": "Cada fila es un vino: 1599 tintos y 4898 blancos. La columna resaltada, quality, es la nota de los catadores, de 0 a 10, aunque en estos datos solo va de 3 a 9 y casi todos los vinos tienen un 5 o un 6." + }, + "form": { + "title": "Las medidas del vino", + "content": "El formulario tiene once medidas químicas: la acidez fija y la volátil, el ácido cítrico, el azúcar residual, los cloruros, el dióxido de azufre libre y el total, la densidad, el pH, los sulfatos y el alcohol. El alcohol es la que más se relaciona con la calidad: los vinos con más grados suelen tener mejor nota. En los tintos, además, una acidez volátil alta la baja." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece la calidad predicha. No tiene por qué ser un número entero: la red puede decir, por ejemplo, 5,6. Si usaste una fila sin cambiarla, también verás la nota real y el error." + }, + "end": { + "title": "Ahora tú", + "content": "Elige un vino, predice su calidad y súbele después el alcohol para ver cómo cambia la predicción. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } + }, + "SALARY": { + "intro": { + "title": "Salarios", + "content": "En esta página, una red neuronal ya entrenada predice un salario a partir de los años de experiencia. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "dataset-select": { + "title": "Conjunto de datos", + "content": "Hay dos conjuntos: uno solo con los años de experiencia y otro con la edad, el sexo, los estudios y el puesto. La red ya entrenada es la del primero; con el segundo puedes ver los datos, pero para predecir tendrías que entrenar tu propia red." + }, + "dataset": { + "title": "El conjunto de datos", + "content": "En el primero hay 1000 personas. La columna resaltada, Salary, es el salario, que suele subir con los años de experiencia (de menos de uno a casi cincuenta). Son datos de ejemplo, pensados para practicar la regresión." + }, + "form": { + "title": "Los datos de la persona", + "content": "Con el primer conjunto, el formulario tiene un solo dato: los años de experiencia. Cuantos más años, más salario suele predecir la red." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece el salario predicho, en las mismas unidades que el conjunto. Si usaste una fila sin cambiarla, también verás el salario real y el error." + }, + "end": { + "title": "Ahora tú", + "content": "Elige una persona, predice su salario y cambia después los años de experiencia para ver cómo cambia la predicción. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } + }, + "HOUSING_PRICES": { + "intro": { + "title": "Precio de las viviendas", + "content": "En esta página, una red neuronal ya entrenada predice el precio medio de las viviendas de un barrio de Boston a partir de doce datos del barrio. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "dataset-select": { + "title": "Conjunto de datos", + "content": "Este modelo tiene un único conjunto de datos, Boston Housing." + }, + "dataset": { + "title": "El conjunto de datos", + "content": "Cada fila es uno de los 506 barrios de Boston de los años setenta. La columna resaltada, MEDV, es el valor medio de las viviendas, en miles de dólares, de 5 a 50. Esta versión no tiene la columna B del conjunto original, que se quitó por motivos éticos." + }, + "form": { + "title": "Los datos del barrio", + "content": "El formulario tiene doce datos: la criminalidad (CRIM), el suelo residencial (ZN) e industrial (INDUS), si linda con el río Charles (CHAS), la contaminación (NOX), las habitaciones por vivienda (RM), la antigüedad (AGE), la distancia a los centros de empleo (DIS), el acceso a las autopistas (RAD), los impuestos (TAX), los alumnos por profesor (PTRATIO) y el porcentaje de población con menos recursos (LSTAT). Las habitaciones y LSTAT son lo que más se relaciona con el precio." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece el precio medio predicho, en miles de dólares. Si usaste una fila sin cambiarla, también verás el valor real y el error." + }, + "end": { + "title": "Ahora tú", + "content": "Elige un barrio, predice su precio y súbele después las habitaciones (RM) para ver cómo cambia la predicción. Puedes volver a abrir esta guía cuando quieras con el botón Guía." } } }, - "dataframe": { - "title": "Analizar conjunto de datos", - "upload-csv": "Subir conjunto de datos" - }, - "documentation": { - "title": "Documentación" - }, - "manual": { - "title": "Manual", - "00-tabular-classification": { - "upload-and-process": { - "title": "Paso 1: Subir y procesar el conjunto de datos" + "2-object-detection": { + "common": { + "model": { + "title": "El modelo", + "content": "Esta es la ficha del modelo: qué detecta, qué recibe y qué devuelve. Es un modelo ya entrenado: aquí solo se usa, no se entrena." }, - "dataset": { - "title": "Paso 2: Analizar el conjunto de datos" + "explain-about": { + "title": "Cómo se explica", + "content": "Este recuadro resume cómo se calcula la explicabilidad: la imagen se divide en trozos, se tapan en muchas combinaciones distintas y se mira cuánto cambia el resultado. Así se sabe qué zonas han pesado más." }, - "layer-design": { - "title": "Paso 3: Visualizar el diseño de capas de la red neuronal." + "webcam": { + "title": "Reconocimiento en tiempo real", + "content": "Aquí se ve la imagen de la cámara con lo que detecta el modelo dibujado encima, hasta veinte veces por segundo." }, - "editor-layers": { - "title": "Paso 4: Editar las capas de la red neuronal" + "webcam-controls": { + "title": "Los controles de la cámara", + "content": "Con el interruptor enciendes la webcam; el navegador te pedirá permiso la primera vez. Con el desplegable eliges la cámara, si tienes varias. El botón de la cámara de fotos descarga una captura y el último pone la cámara a pantalla completa." }, - "editor-hyperparameters": { - "title": "Paso 5: Editar los hiperparámetros del entrenamiento" + "device-info": { + "title": "Información del dispositivo", + "content": "Aquí tienes los datos de tu cámara, de tu navegador y de tu pantalla, y cómo va la detección: cuántas predicciones por segundo hace y cuánto tarda cada una." }, - "table-models": { - "title": "Paso 6: Entrenamiento y tabla de modelos" + "image": { + "title": "Reconocimiento en imágenes", + "content": "Si no tienes cámara, arrastra aquí una foto o elígela de tu equipo: el modelo la procesa y dibuja encima lo que detecta." }, - "prediction": { - "title": "Paso 7: Predicción" + "explain": { + "title": "Explicabilidad", + "content": "Después de procesar una foto, aquí puedes calcular su explicación: un mapa de calor sobre la imagen que marca qué zonas han pesado más en lo que ha detectado el modelo." + }, + "end": { + "title": "Ahora tú", + "content": "Enciende la webcam o sube una foto y mira qué detecta el modelo. Puedes volver a abrir esta guía cuando quieras con el botón Guía." } }, - "app": { - "title": "Objetivos de la herramienta", - "description-1": "Esta aplicación muestra algunas de las tareas más importantes que pueden realizar las redes neuronales artificiales, como son: clasificación tabular, clasificación de imágenes e Identificación de objetos. Las redes son técnicas de inteligencia artificial pertenecientes al campo del aprendizaje automático, en el cual se desarrollan modelos que se entrenan (o aprenden) a partir de conjuntos de datos.", - "description-2": "Algunos de los motivos por los que trabajar con redes neuronales son los siguientes:", - "list": { - "0": { - "title": "Aplicaciones prácticas", - "description": "Las redes neuronales se utilizan en una amplia variedad de aplicaciones, desde reconocimiento de voz y visión por computadora hasta análisis de datos y predicción de resultados. Aprender sobre redes neuronales puede ayudar a los profesionales a desarrollar habilidades que pueden aplicarse en campos como la medicina, la ingeniería, la ciencia de datos, el marketing y muchos otros." - }, - "1": { - "title": "Solución de problemas complejos", - "description": "Las redes neuronales son útiles para resolver problemas complejos que tienen múltiples variables y relaciones no lineales. Al aprender redes neuronales, los profesionales pueden desarrollar soluciones más efectivas para estos tipos de problemas y mejorar la precisión y la eficiencia de sus análisis." - }, - "2": { - "title": "Innovación tecnológica", - "description": "Las redes neuronales son una tecnología innovadora que sigue evolucionando y mejorando. Aprender sobre redes neuronales puede ayudar a los profesionales a mantenerse actualizados en las últimas tendencias y desarrollos en el campo del aprendizaje automático y la inteligencia artificial." - } + "FACE-DETECTOR": { + "intro": { + "title": "Detección de caras", + "content": "En esta página, el modelo Face Detector de MediaPipe encuentra las caras de una foto o de la cámara, hasta cuatro a la vez, y marca en cada una seis puntos clave: los ojos, la nariz, la boca y las orejas. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." }, - "description-3": "Las redes neuronales son una forma de aprendizaje automático que imita la forma en que funciona el cerebro humano. Estas redes están diseñadas para aprender y mejorar continuamente a partir de datos y experiencias pasadas, permitiendo a las máquinas realizar tareas complejas que antes eran imposibles o muy difíciles para los sistemas programados tradicionales.", - "description-4": "En resumen, aprender redes neuronales es importante porque puede ayudar a los profesionales a desarrollar habilidades que son valiosas en una amplia variedad de campos, resolver problemas complejos de manera más efectiva y mantenerse actualizados en la tecnología y la innovación." + "webcam": { + "title": "Reconocimiento en tiempo real", + "content": "Al encender la cámara verás encima de tu cara sus puntos clave con su nombre, en tiempo real. La imagen se muestra como en un espejo." + }, + "end": { + "title": "Ahora tú", + "content": "Enciende la webcam, gira la cabeza o tápate parte de la cara y mira cuándo deja de encontrarla. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } }, - "0-tabular-classification": { - "title": "Clasificación tabular", - "1-title": "Modelos pre-entrenados", - "1-description-1": "Debemos acceder a la sección de modelos pre-entrenados y seleccionar uno de los disponibles.", - "1-description-2": "La herramienta cuenta con una lista de ejemplos representativos que permiten alterar el formulario de características.", - "1-description-3": "Al acceder a la sección de la herramienta en los modelos podremos editar las características de los elementos a predecir. La herramienta cuenta con formulario dinámico que permite cambiar los tipos de datos de entrada de la red neuronal.", - "2-title": "Entrenar modelos", - "2-description-1": "La herramienta cuenta con un visor de datos que permite mostrar las clases y los atributos del conjunto de datos. Así como un gestor para crear, diseñar, entrenar y exportar un modelo de datos.", - "2-description-2": "A la izquierda contamos con un editor de las distintas capas que tiene la red neuronal. Se debe dejar que la ultima capa de la red tenga el mismo número de neuronas que clases a predecir.", - "2-description-3": "Number of epochs:
The number of iterations refers to the number of times the training data is presented to the neural network during the training process. Each iteration implies an update of the weights of the network as a function of the calculated error.", - "2-description-4": "Debemos pulsar el botón de \"Crear y entrenar modelo\" para que se inicie el proceso de entrenamiento de la red neuronal. Si toda la configuración y selección de las funciones es correcta entonces se añadirá en la tabla de abajo una entrada con el modelos entrenado.", - "2-description-5": "Una vez entrenado un modelo a partir de los datos podremos realizar predicciones, para ello se incluye un formulario dinámico con las características del conjunto de datos. La precisión del modelo en la predicción podrá ser mayor o menor en función del entrenamiento y las opciones seleccionadas." + "FACE-MESH": { + "intro": { + "title": "Malla facial", + "content": "En esta página, el modelo Face Mesh de MediaPipe encuentra las caras de una foto o de la cámara, hasta cuatro a la vez, y coloca sobre cada una cientos de puntos que forman una malla en tres dimensiones de su superficie. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "webcam": { + "title": "Reconocimiento en tiempo real", + "content": "Al encender la cámara verás la malla de puntos encima de tu cara, siguiendo tus gestos en tiempo real. La imagen se muestra como en un espejo." + }, + "end": { + "title": "Ahora tú", + "content": "Enciende la webcam, abre la boca, guiña un ojo o levanta las cejas y mira cómo la malla sigue cada gesto. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } }, - "1-regression": { - "title": "Regresión", - "1-title": "Modelos pre-entrenados", - "1-description": { - "0": "Debemos acceder a la sección de modelos pre-entrenados y seleccionar uno de los disponibles.", - "1": null, - "2": null + "MOVE-NET--POSE-NET": { + "intro": { + "title": "Detector de articulaciones", + "content": "En esta página, el modelo MoveNet estima la postura del cuerpo: hasta cinco personas a la vez, con diecisiete puntos cada una, como los ojos, las orejas, los hombros, los codos, las muñecas, las caderas, las rodillas y los tobillos. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." }, - "2-title": "Entrenar modelos", - "2-description": { - "0": "La sección cuenta con la posibilidad subir tus conjuntos de datos, conjuntos de datos preparados, descripciones, herramientas de visualización gráficas y de estadísticas.", - "1": "Cuenta con un generador de modelos de regresión. Gestiona capas de la red neuronal, hiperparámetros, funciones de optimización, funciones de perdida y de métricas. así como el selector de características.", - "2": "Debemos pulsar el botón de \"Crear y entrenar modelo\" para que se inicie el proceso de entrenamiento de la red neuronal. Si toda la configuración y selección de las funciones es correcta entonces se añadirá en la la lista una entrada con el modelos entrenado.", - "3": "Para la predicción se usa el gráfico de dispersión creando una linea" + "webcam": { + "title": "Reconocimiento en tiempo real", + "content": "Al encender la cámara verás encima de cada persona sus puntos unidos por líneas, como un esqueleto que se mueve contigo. Aléjate un poco para que se vea el cuerpo entero." }, - "2-link": "Consulta más información en el siguiente enlace" + "end": { + "title": "Ahora tú", + "content": "Enciende la webcam, aléjate hasta que se vea todo tu cuerpo y mueve los brazos y las piernas. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } }, - "2-object-identification": { - "title": "Identificación de objetos", - "1-title": "Modelos pre-entrenados", - "1-description-1": "Dentro de la identificación de objetos contamos con cuatro modelos, para usar esta herramienta es tan sencillo como activar la opción de usar webcam o subir una imagen.", - "1-description-2": "En esta sección la herramienta ofrece cuatro modelos de identificación de objetos, dichos modelos han sido optimizados para ser funcionales en dispositivos móviles. Estos modelos son:", - "1-description-3": "En caso de usar la webcam como entrada se generará un filtro de forma que se pueda ver en tiempo real sobre el video los puntos que se están detectando. En caso de usar la opción de subir imágenes podemos adjuntar un fichero en formato png o jpg. Como resultado se mostrará la imagen original, el filtro generado y la imagen con el filtro aplicado.", - "1-list": { - "0": "Identificación de la geometría facial.", - "1": "Identificación de una malla facial completa.", - "2": "Identificación de las articulaciones.", - "3": "Identificación de objetos." + "COCO-SSD": { + "intro": { + "title": "Detector de objetos", + "content": "En esta página, el modelo COCO-SSD encuentra objetos en una foto o en la cámara: los rodea con un recuadro y dice qué son y con qué confianza. Reconoce ochenta clases del conjunto COCO, como personas, animales, vehículos, comida o muebles. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "webcam": { + "title": "Reconocimiento en tiempo real", + "content": "Al encender la cámara verás un recuadro alrededor de cada objeto que reconoce, con su nombre y el porcentaje de confianza." + }, + "end": { + "title": "Ahora tú", + "content": "Enciende la webcam y pon delante una taza, una botella, un libro o tu móvil: mira qué reconoce y con cuánta confianza. Puedes volver a abrir esta guía cuando quieras con el botón Guía." } }, - "3-image-classification": { - "title": "Clasificación de imágenes", - "1-title": "Modelos pre-entrenados", - "1-description-1": "En la sección de la clasificación de imágenes podemos seleccionar entre dos ejemplos muy representativos de las redes neuronales. Estos son el modelo entrenado con el conjunto de imágenes MNIST y un modelo de clasificación de imágenes genérico. Concretamente:", - "1-list": { - "0": "MNIST, Clasificación de imágenes que detecta números.", - "1": "MobileNet, clasificación de imágenes pertenecientes a 1001 categorías." + "FACE-API": { + "intro": { + "title": "Expresiones en la cara", + "content": "En esta página, face-api, un conjunto de varias redes neuronales, encuentra las caras de una foto o de la cámara y estima para cada una su edad aproximada y su expresión: neutral, feliz, triste, enfadada, asustada, asqueada o sorprendida. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." }, - "1-description-2": "En el modelo de MNIST se permite seleccionar entre una lista de imágenes que contienen un número, dibujar en un canvas el número a predecir o subir una imagen de un número.", - "1-description-3": "En el modelo de MobileNet se han incluido una lista de imágenes de ejemplo que pueden ser seleccionadas o podemos subir una imagen que la red neuronal clasificará.", - "1-description-4": "Para ambos modelos el sistema mostrará la predicción con el porcentaje de precisión calculado." - }, - "layer-editor": { - "title": "Editor de capas" + "webcam": { + "title": "Reconocimiento en tiempo real", + "content": "Al encender la cámara verás un recuadro alrededor de cada cara con su edad estimada y cuánto se parece su gesto a cada expresión." + }, + "end": { + "title": "Ahora tú", + "content": "Enciende la webcam y prueba a sonreír, a poner cara de sorpresa o de enfado: mira cómo cambian los porcentajes de cada expresión. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } }, - "hyperparameters-editor": { - "title": "Editor de hiperparámetros" + "HAND-SIGN": { + "intro": { + "title": "Lengua de signos", + "content": "En esta página, una red neuronal encuentra tu mano y veintiún puntos de sus dedos y articulaciones; después, otro programa compara la posición de los dedos con las letras del alfabeto dactilológico: el de la lengua de signos española si la aplicación está en español, y el de la americana en los demás idiomas. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "webcam": { + "title": "Reconocimiento en tiempo real", + "content": "Al encender la cámara verás los puntos de tu mano y la letra que reconoce. Pon la mano de frente, bien iluminada y sin que se salga de la imagen." + }, + "end": { + "title": "Ahora tú", + "content": "Enciende la webcam, mira en la ficha del modelo la imagen con el alfabeto e intenta formar varias letras con la mano. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } } }, - "glossary": { - "title": "Glosario", - "table-head": { - "name": "Nombre", - "description": "Descripción", - "references": "Referencias", - "characteristics": "Características", - "function": "Función" + "3-image-classification": { + "common": { + "model": { + "title": "El modelo", + "content": "Esta es la ficha del modelo: con qué imágenes se entrenó, qué recibe y qué clases puede reconocer." + }, + "model-summary": { + "title": "Resumen del modelo", + "content": "Este botón abre el resumen de la red: sus capas, cuántas neuronas tiene cada una y cuántos parámetros, que son los pesos que ajustó durante el entrenamiento." + }, + "explain-about": { + "title": "Cómo se explica", + "content": "Este recuadro resume el método con el que se explican las predicciones. LRP recorre la red hacia atrás y reparte la decisión hasta los píxeles; SHAP tapa trozos de la imagen en muchas combinaciones y mira cuánto cambia el resultado." + }, + "examples": { + "title": "Imágenes de ejemplo", + "content": "Pulsa cualquiera de estas imágenes para clasificarla: el resultado aparece más abajo." + }, + "test-images": { + "title": "Imágenes de test", + "content": "Con este botón cargas las imágenes de test, las que la red no vio al entrenar. Después, en este mismo sitio, eliges cualquiera para clasificarla y comparar la predicción con su clase real." + }, + "upload": { + "title": "Subir una imagen", + "content": "También puedes arrastrar aquí una imagen tuya, o elegirla de tu equipo, y pulsar el botón para clasificarla." + }, + "draw": { + "title": "Dibujar", + "content": "O dibuja aquí con el ratón o con el dedo y pulsa el botón para clasificar tu dibujo. Se reduce a 28 por 28 píxeles, como las imágenes con las que se entrenó la red." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece la imagen que se ha clasificado y, al lado, la probabilidad de cada clase. La más alta es la predicción." + }, + "explain": { + "title": "Explicabilidad", + "content": "Después de clasificar, aquí calculas un mapa de calor sobre la imagen que marca qué píxeles han pesado más en la decisión de la red." + }, + "end": { + "title": "Ahora tú", + "content": "Clasifica un ejemplo, sube una imagen tuya y mira en la explicabilidad en qué se ha fijado la red. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } }, - "tabular-classification": { - "title": "Clasificación tabular", - "text-1": "La clasificación tabular es un tipo de aprendizaje supervisado en el que se utiliza un conjunto de datos etiquetados para entrenar un modelo de aprendizaje automático, de forma que el modelo pueda predecir la clase de nuevos ejemplos de datos no utilizados en el entrenamiento. En la clasificación tabular, los datos de entrada y salida se representan en forma de una tabla con filas y columnas, donde cada fila representa una instancia o ejemplo de los datos, y cada columna representa una característica o atributo de los datos.", - "text-2": "Por ejemplo, si se quiere predecir si un cliente de un banco es solvente o no, las características o atributos que se pueden utilizar son: ingresos, deudas, historial crediticio, edad, etc. En la clasificación tabular, cada instancia o ejemplo del conjunto de datos tendrá valores para cada una de estas características y una etiqueta (clase) que indica si el cliente es solvente o no.", - "text-3": "Una vez que se tiene un conjunto de datos etiquetados, se utiliza un algoritmo de aprendizaje automático para entrenar un modelo que pueda predecir la etiqueta de nuevos conjuntos de datos. Este modelo puede ser utilizado para realizar predicciones precisas y rápidas sobre nuevas instancias de datos.", - "text-4": "La clasificación tabular es una técnica muy útil para resolver problemas de clasificación en una amplia variedad de campos, como la medicina, el comercio electrónico, la banca, la seguridad y muchos otros." + "IMAGE-MNIST": { + "intro": { + "title": "Reconocimiento de dígitos", + "content": "En esta página, una red neuronal convolucional ya entrenada reconoce números del 0 al 9 escritos a mano. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "model": { + "title": "El modelo", + "content": "La red se entrenó con MNIST, una colección de 70.000 dígitos escritos a mano, 60.000 para entrenar y 10.000 para probar, en imágenes de 28 por 28 píxeles en escala de grises. Es uno de los conjuntos de datos más usados para empezar con el aprendizaje automático." + }, + "examples": { + "title": "Imágenes de ejemplo", + "content": "Pulsa cualquiera de estos dígitos para clasificarlo: el resultado aparece más abajo." + }, + "draw": { + "title": "Dibujar un número", + "content": "Dibuja aquí un número del 0 al 9 con el ratón o con el dedo y pulsa el botón para clasificarlo. Tu dibujo se reduce a 28 por 28 píxeles, como los de MNIST, así que dibújalo grande y centrado." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece la imagen que ha visto la red y la probabilidad de cada dígito. La más alta es la predicción. Si clasificas una imagen de test, también verás cuál era el dígito real." + }, + "explain": { + "title": "Explicabilidad con LRP", + "content": "Después de clasificar, aquí calculas un mapa de calor con LRP, que reparte la decisión de la red hacia atrás, capa a capa, hasta los píxeles: verás qué trazos del dibujo han pesado más." + }, + "end": { + "title": "Ahora tú", + "content": "Dibuja un número a tu manera, por ejemplo un siete con raya o un uno con base, y mira si la red lo reconoce y en qué se ha fijado. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } }, - "regression": { - "title": "Regresión", - "text": { - "0": "La regresión es un método de análisis estadístico utilizado en el aprendizaje automático para modelar la relación lineal entre una variable independiente y una variable dependiente, buscando encontrar la mejor línea recta que ajuste los datos y permita hacer predicciones.", - "1": "En la regresión, los datos se representan generalmente como puntos dispersos en un plano cartesiano, donde la variable independiente se coloca en el eje X y la variable dependiente en el eje Y. El objetivo es encontrar la ecuación de una línea recta (y = mx + b) que minimice la distancia entre esta línea y los puntos de datos. Una vez que se ha obtenido esta ecuación, se puede utilizar para hacer predicciones sobre valores futuros de la variable dependiente en función de los valores de la variable independiente.", - "2": "Por ejemplo, si estamos analizando la relación entre la cantidad de publicidad en un sitio web y las ventas de un producto, la cantidad de publicidad sería la variable independiente, y las ventas del producto serían la variable dependiente. La regresión nos ayudaría a determinar si existe una relación lineal entre la inversión en publicidad y las ventas, y si es así, nos permitiría predecir las ventas futuras en función del gasto en publicidad.", - "3": "La regresión es una herramienta poderosa en el análisis de datos y se utiliza en una variedad de campos, incluyendo la economía, la ciencia social, la investigación médica y muchas otras disciplinas para comprender y predecir relaciones entre variables." + "IMAGE-KMNIST": { + "intro": { + "title": "Caracteres japoneses", + "content": "En esta página, una red neuronal convolucional ya entrenada reconoce diez caracteres japoneses del silabario hiragana escritos a mano en kuzushiji, la escritura cursiva que se usó en Japón durante siglos. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "model": { + "title": "El modelo", + "content": "La red se entrenó con Kuzushiji-MNIST: imágenes de 28 por 28 píxeles, como las de MNIST, pero con caracteres en lugar de dígitos. Es más difícil que MNIST, porque un mismo carácter se puede escribir de formas muy distintas." + }, + "examples": { + "title": "Imágenes de ejemplo", + "content": "Cada carácter aparece como se escribe hoy y en tres formas antiguas (hentaigana), con el kanji del que viene cada una: fíjate en lo distintas que son. Pulsa cualquiera para clasificarlo; el resultado aparece más abajo." + }, + "draw": { + "title": "Dibujar un carácter", + "content": "Dibuja aquí uno de los diez caracteres con el ratón o con el dedo y pulsa el botón para clasificarlo. Ten en cuenta que la red aprendió la escritura cursiva antigua, que no siempre se parece al hiragana de hoy." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece la imagen que ha visto la red y la probabilidad de cada carácter. La más alta es la predicción. Si clasificas una imagen de test, también verás cuál era el carácter real." + }, + "explain": { + "title": "Explicabilidad con LRP", + "content": "Después de clasificar, aquí calculas un mapa de calor con LRP, que reparte la decisión de la red hacia atrás, capa a capa, hasta los píxeles: verás qué trazos han pesado más." + }, + "end": { + "title": "Ahora tú", + "content": "Carga las imágenes de test y compara varias formas de escribir un mismo carácter: verás que la red acierta incluso con trazos muy diferentes. Puedes volver a abrir esta guía cuando quieras con el botón Guía." } }, - "object-identification": { - "title": "Identificación de objetos", - "text-1": "La identificación de objetos en redes neuronales es una técnica utilizada en el campo del aprendizaje automático y la visión por computador para detectar y reconocer objetos en imágenes o videos. Es una tarea importante en el análisis de imágenes y es utilizada en aplicaciones como el reconocimiento de rostros, el seguimiento de objetos en tiempo real, la clasificación de objetos en imágenes médicas y la detección de objetos en vehículos autónomos.", - "text-2": "Las redes neuronales utilizadas para la identificación de objetos son modelos de aprendizaje profundo que se entrenan en conjuntos de datos etiquetados. El proceso de entrenamiento implica proporcionar a la red neuronas una gran cantidad de imágenes etiquetadas, y ajustar los pesos de las conexiones entre las neuronas para que la red pueda identificar objetos en nuevas imágenes con alta precisión.", - "text-3": "Una vez que la red neuronal ha sido entrenada, se utiliza para identificar objetos en nuevas imágenes. La red examina la imagen y, mediante el procesamiento de múltiples capas, extrae características importantes que se utilizan para identificar los objetos de interés. Luego, la red utiliza estas características para asignar una etiqueta a cada objeto detectado en la imagen.", - "text-4": "En resumen, la identificación de objetos en redes neuronales es una técnica importante en la visión por computador y el aprendizaje automático que se utiliza para detectar y reconocer objetos en imágenes y videos. Se basa en el uso de redes neuronales profundas entrenadas en conjuntos de datos etiquetados para identificar y clasificar objetos en nuevas imágenes con alta precisión." + "IMAGE-CIFAR10": { + "intro": { + "title": "Clasificación de fotos", + "content": "En esta página, una red neuronal convolucional ya entrenada reconoce fotos pequeñas en color de diez clases: avión, automóvil, pájaro, gato, ciervo, perro, rana, caballo, barco y camión. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "model": { + "title": "El modelo", + "content": "La red se entrenó con CIFAR-10: 50.000 fotos en color de 32 por 32 píxeles para entrenar y 10.000 para probar. Cada foto tiene tres canales, rojo, verde y azul, así que la red recibe casi cuatro veces más números que con MNIST." + }, + "examples": { + "title": "Imágenes de ejemplo", + "content": "Hay una foto de prueba de cada clase, ampliada para que se vean sus píxeles. Pulsa cualquiera para clasificarla: el resultado aparece más abajo." + }, + "upload": { + "title": "Subir una imagen", + "content": "Arrastra aquí una foto tuya, o elígela de tu equipo, y pulsa el botón para clasificarla. Se reduce a 32 por 32 píxeles, como las del conjunto: funciona mejor si el objeto ocupa casi toda la foto." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece la imagen que ha visto la red, ya reducida, y la probabilidad de cada clase. La más alta es la predicción. Si clasificas una imagen de test, también verás cuál era su clase real." + }, + "explain": { + "title": "Explicabilidad", + "content": "Después de clasificar, aquí calculas un mapa de calor sobre la foto: con LRP, la decisión se reparte hacia atrás, capa a capa, hasta los píxeles; con SHAP, se tapan trozos de la foto y se mira cuánto cambia la predicción. Así ves en qué zonas se ha fijado la red." + }, + "end": { + "title": "Ahora tú", + "content": "Carga las imágenes de test y busca en qué clases se equivoca más la red: suele confundir gatos con perros y automóviles con camiones. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } }, - "image-classification": { - "title": "Clasificación de imágenes", - "text-1": "La clasificación de imágenes es una técnica utilizada en las redes neuronales para clasificar imágenes en diferentes categorías o etiquetas. El objetivo de un clasificador de imágenes es tomar una imagen de entrada y predecir a qué clase pertenece, basándose en un conjunto de categorías o etiquetas predefinidas.", - "text-2": "En el aprendizaje profundo, los clasificadores de imágenes se basan en las redes neuronales convolucionales (CNN, por sus siglas en inglés), que son una arquitectura especializada para procesar imágenes. Estas redes neuronales tienen múltiples capas y operaciones de convolución que les permiten extraer características importantes de las imágenes, como bordes, formas y texturas.", - "text-3": "Para entrenar un clasificador de imágenes, se utiliza un conjunto de datos etiquetados que contiene imágenes y sus respectivas etiquetas de clase. Luego, se entrena la red neuronal utilizando este conjunto de datos para que aprenda a identificar patrones en las imágenes y asociarlos con las etiquetas de clase correspondientes.", - "text-4": "Una vez que la red neuronal ha sido entrenada, se puede utilizar para clasificar nuevas imágenes en diferentes categorías. El clasificador de imágenes examina la imagen de entrada y la procesa a través de la red neuronal para extraer características importantes y predecir a qué clase pertenece la imagen.", - "text-5": "En resumen, la clasificación de imágenes en las redes neuronales es una técnica que utiliza las redes neuronales convolucionales para clasificar imágenes en diferentes categorías o etiquetas. Se basa en el uso de un conjunto de datos etiquetados para entrenar la red neuronal y en la extracción de características importantes de las imágenes para predecir a qué clase pertenece una nueva imagen de entrada." + "IMAGE-MOBILENET": { + "intro": { + "title": "Clasificación de imágenes", + "content": "En esta página, MobileNet, una red neuronal convolucional pensada para móviles, reconoce lo que aparece en una foto entre mil categorías: animales, objetos, vehículos, comida y mucho más. Te explico paso a paso qué es cada cosa. Puedes avanzar con Siguiente, volver atrás, silenciar la voz o dejar que la guía avance sola." + }, + "model": { + "title": "El modelo", + "content": "Es MobileNet, entrenada con ImageNet, más de un millón de fotos de mil categorías. Recibe imágenes en color de 224 por 224 píxeles." + }, + "examples": { + "title": "Imágenes de ejemplo", + "content": "Pulsa cualquiera de estas fotos para clasificarla: el resultado aparece más abajo." + }, + "upload": { + "title": "Subir una imagen", + "content": "Arrastra aquí una foto tuya, o elígela de tu equipo, y pulsa el botón para clasificarla. Funciona mejor si lo que quieres reconocer ocupa casi toda la foto." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece la foto que ha visto la red y las categorías más probables, de mayor a menor. Con mil categorías, es normal que dude entre varias parecidas, como dos razas de perro." + }, + "explain": { + "title": "Explicabilidad con SHAP", + "content": "Después de clasificar, aquí calculas un mapa de calor con SHAP: la foto se divide en trozos, se tapan en muchas combinaciones y se mira cuánto cambia la predicción. Así ves qué zonas de la foto han pesado más." + }, + "end": { + "title": "Ahora tú", + "content": "Sube una foto de algo que tengas cerca y mira si la red lo reconoce y en qué se ha fijado. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } + } + }, + "go-to": "Ir al paso", + "voice": "Voz", + "voice-auto": "Automática", + "voice-online": "en línea", + "train": { + "0-tabular-classification": { + "common": { + "intro": { + "title": "Entrena tu red", + "content": "En esta página diseñas y entrenas tu propia red neuronal para clasificar un conjunto de datos, y después la pruebas. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." + }, + "session": { + "title": "Guardar la configuración", + "content": "Con estos botones guardas en un fichero las capas y los hiperparámetros que hayas elegido, y lo cargas otro día para seguir donde lo dejaste o para compartirlo. No se guardan los datos ni los modelos entrenados." + }, + "manual": { + "title": "El manual", + "content": "Si es tu primera vez, despliega el manual: explica con calma cada parte de esta página y qué significa cada opción." + }, + "layers-add": { + "title": "Añadir y quitar capas", + "content": "Con estos botones añades una capa al principio o al final de la red. Para quitar una, o cambiar sus neuronas y su activación, despliégala en la lista." + }, + "learning-rate": { + "title": "Tasa de aprendizaje", + "content": "Es cuánto se corrigen los pesos en cada paso. Con una tasa alta aprende deprisa, pero puede pasarse de largo y no estabilizarse; con una baja es más estable, pero necesita más épocas. 0,01 es un buen punto de partida." + }, + "test-size": { + "title": "Datos de prueba", + "content": "Este porcentaje de los datos se aparta y la red no lo ve al entrenar. Sirve para comprobar después cómo acierta con datos nuevos, que es lo que de verdad importa: una red que solo acierta con lo que ya ha visto ha memorizado, no aprendido." + }, + "optimizer": { + "title": "Optimizador", + "content": "Es el método que ajusta los pesos a partir del error. Adam suele funcionar bien sin tocar nada; SGD es el más sencillo, y RMSprop, Adagrad o Adadelta adaptan el paso de cada peso." + }, + "step-by-step": { + "title": "Paso a paso", + "content": "Antes de entrenar de verdad, aquí ves cómo aprende tu red con un ejemplo cada vez: el paso hacia delante capa a capa, el error y cómo vuelve hacia atrás para corregir cada peso. Avanza fase a fase o pulsa reproducir, y pulsa una neurona para ver sus cuentas. Solo se dibuja con redes de menos de 64 neuronas, para que se pueda seguir." + }, + "models": { + "title": "Modelos generados", + "content": "Cada entrenamiento añade aquí una fila con su configuración y sus resultados, para compararlos. El mejor, el de menor error con los datos de prueba, lleva una marca. Desde aquí también puedes ver su historial o descargarlo." + }, + "dataset-info": { + "title": "El conjunto de datos", + "content": "Aquí se describe el conjunto de datos: de dónde sale, qué significa cada columna y qué clases hay que predecir. Conviene leerlo antes de diseñar la red." + }, + "dataset": { + "title": "Los datos", + "content": "Esta es la tabla con la que vas a entrenar. Cada fila es un ejemplo y cada columna una característica; la resaltada es la clase. En los apartados de debajo tienes las estadísticas de cada columna, antes y después de procesarla: la red solo trabaja con números, así que cada categoría se convierte en un número." + }, + "layer-design": { + "title": "Tu red", + "content": "Este dibujo es la red que vas a entrenar. A la izquierda está la capa de entrada, con una neurona por característica; en medio, las capas ocultas, y a la derecha la de salida, con una neurona por clase. Cambia en cuanto editas las capas, y con el botón de la esquina la ves a pantalla completa." + }, + "layers": { + "title": "Las capas", + "content": "Cada capa tiene un número de neuronas y una función de activación. Más neuronas o más capas permiten aprender relaciones más complejas, pero entrenan más despacio y pueden memorizar los datos en lugar de generalizar. La última capa da la respuesta: necesita tantas neuronas como clases y la activación softmax, que convierte la salida en probabilidades." + }, + "epochs": { + "title": "Épocas", + "content": "Una época es una pasada completa por todos los datos de entrenamiento. Con pocas, la red no llega a aprender; con demasiadas, tarda más y puede memorizar los datos. Empieza con 10 y súbelas si la precisión sigue mejorando al final." + }, + "loss": { + "title": "Función de pérdida", + "content": "Mide cuánto se equivoca la red en cada ejemplo, y es lo que el optimizador intenta reducir. Para elegir entre varias clases se usa la entropía cruzada categórica, que es la que viene elegida." + }, + "metrics": { + "title": "Métrica", + "content": "Es lo que se enseña durante el entrenamiento para saber si va bien, por ejemplo la precisión: el porcentaje de ejemplos que acierta. No cambia cómo aprende la red, solo lo que ves." + }, + "train": { + "title": "Entrenar", + "content": "Al pulsar Entrenar, la red aprende época a época. Verás el progreso aquí y, en el visor, cómo baja la pérdida y sube la precisión, tanto con los datos de entrenamiento como con los de prueba. Si tarda demasiado, puedes pararlo." + }, + "predict": { + "title": "Clasificar", + "content": "Con un modelo entrenado, elige una fila del conjunto de datos o escribe los valores de un ejemplo, y pulsa Clasificar. Verás la probabilidad de cada clase. Arriba eliges con qué modelo clasificar, para comparar unos con otros." + }, + "explain": { + "title": "Explicabilidad", + "content": "Después de clasificar, SHAP muestra por qué la red ha decidido eso: qué características han empujado hacia la clase predicha y cuáles en contra. La importancia global hace lo mismo con muchas filas, para ver qué característica pesa más en general." + }, + "end": { + "title": "Ahora tú", + "content": "Entrena con los valores de partida y mira la precisión. Después cambia una sola cosa, por ejemplo las épocas o las neuronas de una capa, vuelve a entrenar y compara los dos modelos en la tabla. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + } + }, + "CAR": { + "intro": { + "title": "Clasificación de coches", + "content": "En esta página entrenas una red que decide si un coche es aceptable a partir de seis características, como el precio, el mantenimiento o la seguridad, con 1728 coches de ejemplo. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." + }, + "layers": { + "title": "Las capas", + "content": "Cada capa tiene un número de neuronas y una función de activación. Más neuronas o más capas permiten aprender relaciones más complejas, pero entrenan más despacio y pueden memorizar los datos en lugar de generalizar. La última capa da la respuesta: tiene 4 neuronas, una por clase (inaceptable, aceptable, bueno y muy bueno), con la activación softmax, que las convierte en probabilidades." + } + }, + "IRIS": { + "intro": { + "title": "Clasificación de flores iris", + "content": "En esta página entrenas una red que reconoce la especie de una flor iris, entre tres, a partir de cuatro medidas de sus pétalos y sépalos, con 150 flores de ejemplo. Es un conjunto pequeño: entrena en un momento y es perfecto para experimentar. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." + }, + "layers": { + "title": "Las capas", + "content": "Cada capa tiene un número de neuronas y una función de activación. Más neuronas o más capas permiten aprender relaciones más complejas, pero entrenan más despacio y pueden memorizar los datos en lugar de generalizar. La última capa da la respuesta: tiene 3 neuronas, una por especie (setosa, versicolor y virginica), con la activación softmax, que las convierte en probabilidades." + } + }, + "LYMPHOGRAPHY": { + "intro": { + "title": "Linfografía", + "content": "En esta página entrenas una red que clasifica exploraciones de linfografía en cuatro diagnósticos a partir de 18 características, con 148 pacientes de ejemplo. Hay muy pocos casos de algunas clases, así que fíjate en cómo acierta con cada una. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." + }, + "layers": { + "title": "Las capas", + "content": "Cada capa tiene un número de neuronas y una función de activación. Más neuronas o más capas permiten aprender relaciones más complejas, pero entrenan más despacio y, con tan pocos pacientes, es fácil que memoricen los datos. La última capa da la respuesta: tiene 4 neuronas, una por diagnóstico, con la activación softmax, que las convierte en probabilidades." + } + }, + "UPLOAD": { + "intro": { + "title": "Tus propios datos", + "content": "En esta página entrenas una red con tus propios datos: los subes, eliges qué columna quieres predecir, diseñas la red y la entrenas. Tus datos no salen de tu navegador. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." + }, + "dataset-info": { + "title": "Subir los datos", + "content": "Arrastra aquí tu fichero o pulsa para elegirlo. Admite CSV, TSV, ARFF, JSON, JSON Lines y Parquet. Cada fila tiene que ser un ejemplo, y una de las columnas, la clase que quieres predecir." + }, + "process": { + "title": "Preparar los datos", + "content": "Antes de entrenar hay que preparar los datos: elige la columna que quieres predecir, cómo convertir en números las columnas de texto y cómo escalar los valores. Al pulsar el botón, los datos quedan listos y aparece la red." + }, + "layers": { + "title": "Las capas", + "content": "Cada capa tiene un número de neuronas y una función de activación. Más neuronas o más capas permiten aprender relaciones más complejas, pero entrenan más despacio y pueden memorizar los datos. La última capa da la respuesta: necesita tantas neuronas como clases tenga la columna que predices, con la activación softmax, que las convierte en probabilidades." + } + } }, - "activation-functions": { - "title": "Funciones de activación", - "sub-title-1": "Capas lineales", - "sub-title-2": "Activaciones no lineales (suma ponderada, no linealidad)", - "sub-title-3": "Activaciones no lineales (otras)", - "text-1": "Una función de activación es una función matemática utilizada en una red neuronal artificial para determinar la salida de una neurona o de un conjunto de neuronas en función de la entrada recibida. La función de activación introduce no linealidad en la red neuronal, lo que permite a la red aprender patrones más complejos en los datos de entrada. Ejemplos comunes de funciones de activación son:", - "table": { - "softmax": { - "title": "Softmax", - "description": "Transforma las salidas a una representación en forma de probabilidades, de forma que la suma de todas las probabilidades da 1", - "characteristics": { - "0": "Acotada entre 0 y 1", - "1": "Buena en capas finales", - "2": "Utilizada para normalizar tipo multi clase" - } + "1-regression": { + "common": { + "intro": { + "title": "Entrena tu red de regresión", + "content": "En esta página diseñas y entrenas una red neuronal que predice un número, como un precio o una nota, a partir de otras columnas, y después la pruebas. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." }, - "sigmoid": { - "title": "Sigmoid", - "description": "La función sigmoide transforma los valores de entrada en un rango entre 0 y 1. Es comúnmente utilizada en redes neuronales para problemas de clasificación binaria.", - "characteristics": { - "0": "Resultados con el rango [0, 1].", - "1": "Útil en la capa de salida de clasificadores binarios.", - "2": "Puede sufrir el problema de desvanecimiento del gradiente en redes profundas." - } + "session": { + "title": "Guardar la configuración", + "content": "Con estos botones guardas en un fichero las capas y los hiperparámetros que hayas elegido, y lo cargas otro día para seguir donde lo dejaste o para compartirlo. No se guardan los datos ni los modelos entrenados." }, - "hard-sigmoid": { - "title": "Hard Sigmoid", - "description": "Hard Sigmoid es una versión simplificada de la función sigmoide utilizada para la eficiencia computacional.", - "characteristics": { - "0": "Es más rápida de calcular que la sigmoide.", - "1": "Menos suave en la transición entre 0 y 1." - } + "manual": { + "title": "El manual", + "content": "Si es tu primera vez, despliega el manual: explica con calma cada parte de esta página y qué significa cada opción." }, - "relu": { - "title": "ReLU (Rectified Linear Unit)", - "description": "La función ReLU es simple y efectiva al devolver cero para valores negativos y mantener los valores positivos sin cambios.", - "characteristics": { - "0": "Eficiente en términos de cómputo.", - "1": "Mitiga el problema de desvanecimiento del gradiente.", - "2": "Puede activar neuronas esparsamente." - } + "layers-add": { + "title": "Añadir y quitar capas", + "content": "Con estos botones añades una capa al principio o al final de la red. Para quitar una, o cambiar sus neuronas y su activación, despliégala en la lista." }, - "relu6": { - "title": "ReLU6", - "description": "Similar a ReLU, pero con una limitación superior de 6 para los valores positivos, lo que puede ayudar a evitar la explosión de gradientes.", - "characteristics": { - "0": "Mitiga el problema de desvanecimiento del gradiente.", - "1": "Útil en redes con gradientes inestables." - } + "learning-rate": { + "title": "Tasa de aprendizaje", + "content": "Es cuánto se corrigen los pesos en cada paso. Con una tasa alta aprende deprisa, pero puede pasarse de largo y no estabilizarse; con una baja es más estable, pero necesita más épocas. 0,01 es un buen punto de partida." }, - "leaky-relu": { - "title": "LeakyReLU", - "description": "Leaky ReLU es una variante de ReLU que permite que una fracción pequeña de los valores negativos pase a través de la función.", - "characteristics": { - "0": "Mitiga el problema de muerte de neuronas en comparación con ReLU.", - "1": "Ayuda a mantener la información en los gradientes negativos." - } + "test-size": { + "title": "Datos de prueba", + "content": "Este porcentaje de los datos se aparta y la red no lo ve al entrenar. Sirve para comprobar después cómo acierta con datos nuevos, que es lo que de verdad importa: una red que solo acierta con lo que ya ha visto ha memorizado, no aprendido." }, - "elu": { - "title": "ELU (Exponential Linear Unit)", - "description": "ELU es una función que se asemeja a ReLU en los valores positivos, pero también tiene un gradiente definido para valores negativos.", - "characteristics": { - "0": "Reduce el problema de desvanecimiento del gradiente.", - "1": "Ayuda a mantener activas más neuronas." - } + "optimizer": { + "title": "Optimizador", + "content": "Es el método que ajusta los pesos a partir del error. RMSprop, el que viene elegido, va bien en regresión; Adam también suele funcionar sin tocar nada, y SGD es el más sencillo." }, - "tanh": { - "title": "Tanh (Tangente hiperbólica)", - "description": "La función tangente hiperbólica transforma los valores de entrada en un rango [-1, 1].", - "characteristics": { - "0": "Resultados en el rango [-1, 1].", - "1": "Útil en problemas de clasificación binaria.", - "2": "Sufre de desvanecimiento del gradiente en redes profundas." - } + "step-by-step": { + "title": "Paso a paso", + "content": "Antes de entrenar de verdad, aquí ves cómo aprende tu red con un ejemplo cada vez: el paso hacia delante capa a capa, el error y cómo vuelve hacia atrás para corregir cada peso. Avanza fase a fase o pulsa reproducir, y pulsa una neurona para ver sus cuentas. Solo se dibuja con redes de menos de 64 neuronas, para que se pueda seguir." }, - "soft-plus": { - "title": "SoftPlus", - "description": "SoftPlus es una función suave que se utiliza a menudo como una alternativa suave a ReLU.", - "characteristics": { - "0": "Suave y derivable en todas partes.", - "1": "Puede ser útil en redes generativas y de regresión." - } + "models": { + "title": "Modelos generados", + "content": "Cada entrenamiento añade aquí una fila con su configuración y sus resultados, para compararlos. El mejor, el de menor error con los datos de prueba, lleva una marca. Desde aquí también puedes ver su historial o descargarlo." }, - "mish": { - "title": "Mish", - "description": "Mish es una función de activación relativamente nueva que combina características de otras funciones como la tangente hiperbólica y la función sigmoide.", - "characteristics": { - "0": "Suavidad y derivabilidad en todo su rango.", - "1": "Proporciona un mejor rendimiento en algunas aplicaciones." - } + "dataset-info": { + "title": "El conjunto de datos", + "content": "Aquí se describe el conjunto de datos: de dónde sale, qué significa cada columna y cuál es el número que hay que predecir. Conviene leerlo antes de diseñar la red." }, - "selu": { - "title": "SELU (Scaled Exponential Linear Unit)", - "description": "SELU es una función que se beneficia de una normalización específica y puede ayudar a mantener la estabilidad de la red.", - "characteristics": { - "0": "Autocalibración: propaga estadísticas estables a través de las capas.", - "1": "Puede ser útil en redes con arquitectura autoencoder." - } + "dataset": { + "title": "Los datos", + "content": "Esta es la tabla con la que vas a entrenar, con sus estadísticas y gráficos. Fíjate en qué columnas cambian a la vez que la que se predice: son las que más ayudarán a la red. Antes de entrenar, los valores se escalan para que todas las columnas pesen parecido." + }, + "layer-design": { + "title": "Tu red", + "content": "Este dibujo es la red que vas a entrenar. A la izquierda está la capa de entrada, con una neurona por característica; en medio, las capas ocultas, y a la derecha una sola neurona de salida: el número que predice. Cambia en cuanto editas las capas, y con el botón de la esquina la ves a pantalla completa." + }, + "layers": { + "title": "Las capas", + "content": "Cada capa tiene un número de neuronas y una función de activación. Más neuronas o más capas permiten aprender relaciones más complejas, pero entrenan más despacio y pueden memorizar los datos. La última capa no se puede cambiar: es una sola neurona con activación lineal, porque el resultado es un número cualquiera, no una probabilidad." + }, + "epochs": { + "title": "Épocas", + "content": "Una época es una pasada completa por todos los datos de entrenamiento. Con pocas, la red no llega a aprender; con demasiadas, tarda más y puede memorizar los datos. Empieza con las que vienen y fíjate en si el error sigue bajando al final." + }, + "loss": { + "title": "Función de pérdida", + "content": "Mide cuánto se aleja la predicción del valor real, y es lo que el optimizador intenta reducir. El error cuadrático medio, el que viene elegido, castiga mucho los errores grandes; el error absoluto medio los trata a todos por igual." + }, + "metrics": { + "title": "Métricas", + "content": "Son lo que se enseña durante el entrenamiento para saber si va bien. Puedes añadir varias: el error absoluto medio, por ejemplo, dice cuánto se equivoca de media, en las mismas unidades que el dato que predices." + }, + "train": { + "title": "Entrenar", + "content": "Al pulsar Entrenar, la red aprende época a época. Verás el progreso aquí y, en el visor, cómo baja el error, tanto con los datos de entrenamiento como con los de prueba. Si tarda demasiado, puedes pararlo." + }, + "predict": { + "title": "Predecir", + "content": "Con un modelo entrenado, elige una fila del conjunto de datos o escribe los valores, y pulsa Predecir. Verás el número que predice la red y, si eliges una fila sin cambiarla, el valor real para comparar. Arriba eliges con qué modelo predecir." + }, + "explain": { + "title": "Explicabilidad", + "content": "Después de predecir, SHAP muestra por qué la red ha dado ese número: qué características lo han subido y cuáles lo han bajado. La importancia global hace lo mismo con muchas filas, para ver qué característica pesa más en general." + }, + "end": { + "title": "Ahora tú", + "content": "Entrena con los valores de partida y mira el error. Después cambia una sola cosa, por ejemplo la tasa de aprendizaje o las neuronas de una capa, vuelve a entrenar y compara los dos modelos en la tabla. Puedes volver a abrir esta guía cuando quieras con el botón Guía." } - } - }, - "editor-layers": { - "title": "Glosario del editor de capas", - "table": { - "activation-function": { - "title": "Neuronas de Capa (Layer Neurons)", - "description": "Son las unidades individuales o nodos en una capa específica de la red. Cada neurona recibe entradas, realiza cálculos y produce una salida que se transmite a la siguiente capa. La cantidad de neuronas en una capa puede variar y suele ser un hiperparámetro del modelo. La elección del número de neuronas en una capa afecta la capacidad del modelo para aprender representaciones de los datos." + }, + "SALARY": { + "intro": { + "title": "Salario según la experiencia", + "content": "En esta página entrenas una red que predice el salario de una persona a partir de su experiencia laboral, con 1000 personas de ejemplo. Con tan pocas columnas es fácil ver qué aprende la red. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." + } + }, + "AUTO_MPG": { + "intro": { + "title": "Consumo de coches", + "content": "En esta página entrenas una red que predice el consumo de un coche, en millas por galón, a partir de seis características como los cilindros, la potencia o el peso, con 396 coches de ejemplo. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." + } + }, + "HOUSING_PRICES": { + "intro": { + "title": "Precio de la vivienda", + "content": "En esta página entrenas una red que predice el valor medio de las viviendas de un barrio de Boston a partir de 12 características, como el número de habitaciones o la criminalidad de la zona, con 506 barrios de ejemplo. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." + } + }, + "STUDENT_PERFORMANCE": { + "intro": { + "title": "Notas de estudiantes", + "content": "En esta página entrenas una red que predice la nota final de un estudiante, de 0 a 20, a partir de 30 características como las horas de estudio, las faltas o las notas de los dos primeros trimestres, G1 y G2. Hay datos de dos asignaturas: matemáticas, con 395 estudiantes, y portugués, con 649. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." + } + }, + "WINE": { + "intro": { + "title": "Calidad del vino", + "content": "En esta página entrenas una red que predice la calidad de un vino, de 0 a 10, a partir de 11 medidas químicas como la acidez o el alcohol. Hay dos ficheros: 1599 vinos tintos y 4898 blancos. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." + } + }, + "UPLOAD": { + "intro": { + "title": "Tus propios datos", + "content": "En esta página entrenas una red con tus propios datos: los subes, eliges qué columna numérica quieres predecir, diseñas la red y la entrenas. Tus datos no salen de tu navegador. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." }, - "units": { - "title": "Función de Activación de Capa (Layer Activation Function)", - "description": "En cada neurona de una capa de una red neuronal, se aplica una función de activación para introducir no linealidad en el modelo. La función de activación determina la salida de la neurona en función de su entrada y los pesos asociados." + "dataset-info": { + "title": "Subir los datos", + "content": "Arrastra aquí tu fichero o pulsa para elegirlo. Admite CSV, TSV, ARFF, JSON, JSON Lines y Parquet. Cada fila tiene que ser un ejemplo, y una de las columnas, el número que quieres predecir." + }, + "process": { + "title": "Preparar los datos", + "content": "Antes de entrenar hay que preparar los datos: elige la columna que quieres predecir, cómo convertir en números las columnas de texto y cómo escalar los valores. Al pulsar el botón, los datos quedan listos para diseñar la red." } } }, - "editor-hyperparameters": { - "title": "Glosario del editor de hiperparámetros", - "table": { - "learning-rate": { - "title": "Tasa de Aprendizaje (Learning Rate)", - "description": "La tasa de aprendizaje es un hiperparámetro crucial en algoritmos de aprendizaje automático y redes neuronales. Determina cuánto deben actualizarse los pesos del modelo en cada iteración durante el proceso de entrenamiento. Una tasa de aprendizaje alta puede llevar a la convergencia rápida, pero puede resultar en inestabilidad, mientras que una tasa baja puede llevar a la convergencia lenta o quedarse atrapada en mínimos locales." + "3-image-classification": { + "common": { + "intro": { + "title": "Entrena tu red de imágenes", + "content": "En esta página diseñas y entrenas una red convolucional que reconoce imágenes de 28 por 28 píxeles, y después la pruebas dibujando. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." }, - "number-or-epochs": { - "title": "Número de Épocas (Number of Epochs)", - "description": "Las épocas se refieren al número de veces que todo el conjunto de datos de entrenamiento se ha pasado a través del modelo durante el proceso de entrenamiento. Un mayor número de épocas generalmente permite que el modelo se ajuste mejor a los datos, pero también puede conducir al sobre ajuste si se excede un cierto límite." + "session": { + "title": "Guardar la configuración", + "content": "Con estos botones guardas en un fichero las capas y los hiperparámetros que hayas elegido, y lo cargas otro día para seguir donde lo dejaste o para compartirlo. No se guardan los datos ni los modelos entrenados." + }, + "manual": { + "title": "El manual", + "content": "Si es tu primera vez, despliega el manual: explica con calma cada parte de esta página y qué significa cada opción." + }, + "layers-add": { + "title": "Añadir y quitar capas", + "content": "Con este botón añades una capa al final. Despliega cada capa para elegir su tipo, sus filtros, el tamaño del filtro o sus neuronas, o para quitarla. La primera tiene que ser convolucional." + }, + "learning-rate": { + "title": "Tasa de aprendizaje", + "content": "Es cuánto se corrigen los pesos en cada paso. Con una tasa alta aprende deprisa, pero puede pasarse de largo y no estabilizarse; con una baja es más estable, pero necesita más épocas. 0,01 es un buen punto de partida." }, "test-size": { - "title": "Tamaño del Conjunto de Pruebas (Test Size)", - "description": "Es la cantidad de datos que se reserva para evaluar el rendimiento del modelo después de su entrenamiento. El conjunto de pruebas se utiliza para medir la precisión y el rendimiento general del modelo en datos no vistos." + "title": "Datos de prueba", + "content": "Este porcentaje de los datos se aparta y la red no lo ve al entrenar. Sirve para comprobar después cómo acierta con datos nuevos, que es lo que de verdad importa: una red que solo acierta con lo que ya ha visto ha memorizado, no aprendido." }, "optimizer": { - "title": "Optimizador (Optimizer)", - "description": "El optimizador es un algoritmo que ajusta los parámetros de un modelo de aprendizaje automático durante el entrenamiento. Su objetivo es minimizar la función de pérdida al actualizar los pesos del modelo de manera eficiente. Ejemplos de optimizadores comunes incluyen el Descenso del Gradiente Estocástico (SGD), el Adam y el RMSprop." + "title": "Optimizador", + "content": "Es el método que ajusta los pesos a partir del error. Adam suele funcionar bien sin tocar nada; SGD es el más sencillo, y RMSprop, Adagrad o Adadelta adaptan el paso de cada peso." }, - "loss-function": { - "title": "Función de Pérdida (Loss Function)", - "description": "La función de pérdida es una medida que cuantifica qué tan bien se está desempeñando el modelo en sus predicciones. Ayuda a calcular la diferencia entre las predicciones del modelo y los valores reales del conjunto de datos. El objetivo del entrenamiento es minimizar esta función, ya que un valor bajo de pérdida indica que el modelo se ajusta mejor a los datos." + "models": { + "title": "Modelos generados", + "content": "Cada entrenamiento añade aquí una fila con su configuración y sus resultados, para compararlos. El mejor, el de menor error con los datos de prueba, lleva una marca. Desde aquí también puedes ver su historial o descargarlo." }, - "metric-function": { - "title": "Función de Métrica (Metric Function)", - "description": "A diferencia de la función de pérdida, que se utiliza para optimizar el modelo durante el entrenamiento, las funciones de métrica se utilizan para evaluar el rendimiento del modelo después del entrenamiento. Estas métricas proporcionan información sobre la precisión, la recuperación, la precisión, el F1-score, etc., y ayudan a comprender cómo se desempeña el modelo en tareas específicas." + "dataset-info": { + "title": "El conjunto de imágenes", + "content": "Aquí se describe el conjunto: de dónde salen las imágenes, cuántas hay y qué representa cada una de las diez clases." + }, + "layer-design": { + "title": "Tu red", + "content": "Este dibujo es la red que vas a entrenar: la imagen entra por la izquierda, pasa por las capas convolucionales y de agrupación, se aplana y termina en las capas densas, con una neurona por clase a la derecha. Con el botón de la esquina la ves a pantalla completa." + }, + "layers": { + "title": "Las capas", + "content": "Una red para imágenes combina varios tipos de capa. Las convolucionales buscan patrones, como bordes o curvas, con filtros pequeños que recorren la imagen; las de agrupación, max pooling, la reducen quedándose con lo más destacado; la de aplanado convierte el resultado en una lista de números, y las densas deciden la clase. La última necesita diez neuronas, una por clase, con la activación softmax. Ahora las vemos una a una." + }, + "epochs": { + "title": "Épocas", + "content": "Una época es una pasada completa por todas las imágenes de entrenamiento. Con imágenes cada época tarda bastante más que con una tabla, así que empieza con pocas, como las 5 que vienen, y súbelas si la precisión sigue mejorando." + }, + "loss": { + "title": "Función de pérdida", + "content": "Mide cuánto se equivoca la red con cada imagen, y es lo que el optimizador intenta reducir. Para elegir entre diez clases se usa la entropía cruzada categórica, que es la que viene elegida." + }, + "metrics": { + "title": "Métricas", + "content": "Son lo que se enseña durante el entrenamiento para saber si va bien. Puedes añadir varias, como la precisión: el porcentaje de imágenes que acierta. No cambian cómo aprende la red, solo lo que ves." + }, + "train": { + "title": "Entrenar", + "content": "Al pulsar Entrenar, primero se descargan las imágenes y después la red aprende época a época. Tarda más que con una tabla: el progreso y el visor te dicen cómo va la pérdida y la precisión, y puedes pararlo si hace falta." + }, + "predict": { + "title": "Probar la red", + "content": "Con un modelo entrenado, dibuja en el lienzo, elige una imagen de prueba del conjunto o sube una tuya, y la red dirá qué ve, con la probabilidad de cada clase. Arriba eliges con qué modelo probar." + }, + "explain": { + "title": "Explicabilidad", + "content": "Después de clasificar, LRP colorea los píxeles según cuánto han contado para la decisión. Así ves en qué partes del dibujo se ha fijado la red para decidir." + }, + "end": { + "title": "Ahora tú", + "content": "Entrena con la red de partida y prueba a dibujar. Después añade o quita una capa convolucional, entrena otra vez y compara en la tabla qué modelo acierta más. Puedes volver a abrir esta guía cuando quieras con el botón Guía." + }, + "layer": { + "class-name": "símbolo", + "conv-first": { + "title": "Capa {{number}}: convolución", + "content": "Es la primera: recibe la imagen, de {{inputSize}} píxeles en escala de grises. La recorren {{filters}} filtros de {{kernel}}×{{kernel}}; cada uno aprende a reconocer un patrón pequeño (un trazo, un borde, una curva) y deja un mapa de dónde lo encuentra. Por eso salen {{outputChannels}} mapas de {{outputSize}}: uno por filtro, algo más pequeños que la imagen porque el filtro no se sale del borde. Tiene {{params}} pesos que aprender." + }, + "conv": { + "title": "Capa {{number}}: convolución", + "content": "Recibe los {{inputChannels}} mapas de {{inputSize}} de la capa anterior y los recorre con {{filters}} filtros de {{kernel}}×{{kernel}}. Cada filtro mira todos los mapas a la vez, así que junta patrones sencillos en formas más complejas, como las partes de un {{class}}. Salen {{outputChannels}} mapas de {{outputSize}}, con {{params}} pesos que aprender." + }, + "relu": "Con ReLU, lo negativo pasa a cero: solo sigue adelante lo que se ha encontrado.", + "activation": "Su activación es {{activation}}.", + "pool": { + "title": "Capa {{number}}: max pooling", + "content": "Reduce cada mapa quedándose con el valor más alto de cada ventana de {{pool}}×{{pool}}, que avanza de {{strides}} en {{strides}}: lo más destacado de cada zona. Los {{inputChannels}} mapas pasan de {{inputSize}} a {{outputSize}}. No tiene pesos ni aprende nada, pero hace la red más rápida y menos sensible a que el trazo se mueva un poco." + }, + "flatten": { + "title": "Capa {{number}}: aplanado (flatten)", + "content": "Pone en fila los {{inputChannels}} mapas de {{inputSize}}: una lista de {{values}} números, porque las capas densas no trabajan con imágenes, sino con listas. Tampoco aprende nada." + }, + "dense": { + "title": "Capa {{number}}: densa", + "content": "Cada una de sus {{units}} neuronas está conectada con los {{inputValues}} valores de la capa anterior: combina todo lo que han encontrado los filtros, esté donde esté en la imagen. Tiene {{params}} pesos que aprender; en una red así, las densas suelen ser las que más tienen." + }, + "output": { + "title": "Capa {{number}}: la salida", + "content": "La última capa tiene {{units}} neuronas, una por cada {{class}}, conectadas con los {{inputValues}} valores anteriores ({{params}} pesos). Con softmax, sus valores son la probabilidad de cada {{class}} y suman 1: la respuesta de la red es la más alta.", + "content-other": "La última capa tiene {{units}} neuronas, conectadas con los {{inputValues}} valores anteriores ({{params}} pesos). Su activación es {{activation}}: con softmax, sus valores serían la probabilidad de cada {{class}}. Mira el aviso de arriba del editor." + }, + "broken": { + "title": "Capa {{number}}: no encaja", + "content": "Los datos no le llegan con la forma que necesita (o le falta algún parámetro). Mira el aviso de arriba del editor: dice qué pasa y lo arregla con un botón." + } } - } - }, - "optimization-functions": { - "title": "Funciones de optimización", - "text-1": "Una función de optimización es una técnica matemática utilizada para minimizar o maximizar una función objetivo. En el contexto del aprendizaje automático, las funciones objetivo suelen ser funciones de error que miden la discrepancia entre la salida de la red neuronal y los valores de salida deseados para un conjunto de datos de entrenamiento dado.", - "text-2": "La función de optimización ajusta los parámetros de la red neuronal para minimizar la función objetivo y, por lo tanto, mejorar su capacidad para hacer predicciones precisas en nuevos datos de entrada. Ejemplos comunes de funciones de optimización son el descenso del gradiente estocástico y el algoritmo de Adam.", - "table": { - "sgd": { - "references": "Descenso del gradiente estocástico \n (Instituto Tecnológico Autónomo de México, 2017)", - "description": "El descenso del gradiente es un algoritmo que estima dónde una función genera sus valores más bajos. En el caso de que el modelo de aprendizaje automático sea de gran escala este cálculo puede ser muy costoso.\n Debido a esto surge el descenso del gradiente estocástico que usa una constante y por consiguiente el número de gradientes a calcular es fijo." + }, + "IMAGE-MNIST": { + "intro": { + "title": "Dígitos escritos a mano", + "content": "En esta página entrenas una red convolucional que reconoce los dígitos del 0 al 9 escritos a mano, con las imágenes del conjunto MNIST, y después la pruebas dibujando tus propios números. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." }, - "momentum": { - "references": "-", - "description": "Es una variación de la función anterior. Define un valor que acelera el descenso del gradiente si el signo del gradiente es el mismo durante diferentes épocas." + "layer": { + "class-name": "dígito" + } + }, + "IMAGE-KMNIST": { + "intro": { + "title": "Caracteres japoneses", + "content": "En esta página entrenas una red convolucional que reconoce diez caracteres hiragana del japonés clásico escritos a mano, del conjunto Kuzushiji-MNIST, y después la pruebas dibujándolos. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." }, - "adagrad": { - "references": "(Velasco, 2020)", - "description": "Introduce una variación en el concepto de tasa de entrenamiento. Esta función escala y adapta este valor para cada peso respecto del gradiente acumulado en cada iteración." + "layer": { + "class-name": "carácter" + } + }, + "IMAGE-CIFAR10": { + "intro": { + "title": "Fotos en color", + "content": "En esta página entrenas una red convolucional que reconoce fotos en color de diez clases, de aviones a camiones, con las imágenes del conjunto CIFAR-10, y después la pruebas con fotos de prueba o con las tuyas. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." }, - "adadelta": { - "references": "(Velasco, 2020)", - "description": "Es una variación de AdaGrad en la que se restringe el cálculo de la tasa de entrenamiento de cada peso a una ventana de tamaño fijo de los últimos n gradientes en vez de hacerlo con el gradiente acumulado de cada iteración." + "predict": { + "title": "Probar la red", + "content": "Con un modelo entrenado, elige una foto de prueba del conjunto o sube una tuya y pulsa el botón: la red dirá qué ve, con la probabilidad de cada clase. Arriba eliges con qué modelo probar." }, - "rmsprop": { - "references": "Propagación de raíz cuadrática media \n (Root Mean Square Propagation) \n (Velasco, 2020)", - "description": "Este algoritmo mantiene un factor de entrenamiento diferente para cada dimensión, pero el escalado del factor del entrenamiento se realiza dividiéndolo por la media del declive exponencial del cuadrado de los gradientes." + "explain": { + "title": "Explicabilidad", + "content": "Después de clasificar, LRP colorea los píxeles según cuánto han contado para la decisión. Así ves en qué partes de la foto se ha fijado la red para decidir." }, - "adam": { - "references": "Estimación adaptativa del mo \n (Adaptive moment estimation) \n (Velasco, 2020)", - "description": "Es una combinación de AdaGrad y RMSProp. Se mantiene un factor de entrenamiento por parámetro y se calcula RMSProp, además cada factor de entrenamiento se ve afectado por el momentum del gradiente." + "end": { + "title": "Ahora tú", + "content": "Entrena con la red de partida y mira en la tabla cuánto acierta: con pocas fotos y pocas épocas, bastante menos que el modelo ya entrenado. Después prueba con más épocas o con otra capa convolucional y compara. Puedes volver a abrir esta guía cuando quieras con el botón Guía." }, - "adamax": { - "description": "Combina técnicas de momentum y adaptación del aprendizaje para acelerar la convergencia durante el entrenamiento de redes neuronales. Ajusta automáticamente la tasa de aprendizaje y utiliza un escalado de gradiente para evitar problemas de divergencia." + "layer": { + "class-name": "clase", + "conv-first": { + "title": "Capa {{number}}: convolución", + "content": "Es la primera: recibe la foto, de {{inputSize}} píxeles en color, es decir, {{inputChannels}} mapas: rojo, verde y azul. La recorren {{filters}} filtros de {{kernel}}×{{kernel}}; cada uno mira los tres colores a la vez y aprende a reconocer un patrón pequeño (un borde, una mancha de color, una esquina) y deja un mapa de dónde lo encuentra. Salen {{outputChannels}} mapas de {{outputSize}}, uno por filtro, algo más pequeños que la foto porque el filtro no se sale del borde. Tiene {{params}} pesos que aprender." + } } } }, - "loss-functions": { - "title": "Funciones de pérdida", - "text": { - "0": "En aprendizaje automático, una función de pérdida (también llamada función de costo) es una medida que cuantifica la discrepancia entre la salida predicha por un modelo y la salida real o deseada. En otras palabras, la función de pérdida mide qué tan bien el modelo se ajusta a los datos de entrenamiento.", - "1": "El objetivo de un algoritmo de aprendizaje automático es minimizar la función de pérdida, lo que significa encontrar el conjunto de parámetros del modelo que mejor se ajuste a los datos de entrenamiento. Por lo tanto, la elección de la función de pérdida es muy importante, ya que puede afectar la capacidad del modelo para aprender correctamente los patrones en los datos y hacer predicciones precisas en nuevos datos.", - "2": "En tensorflow.js hay diferentes funciones de pérdida y la aplicación de cada una de ellas depende del tipo de problema que queramos afrontar. Algunos ejemplos se muestran a continuación:" - }, - "table": { - "AbsoluteDifference": { - "references": "Diferencia absoluta \n (Acervolima, s.f.)", - "description": "Calcula en valor absoluto la distancia al objetivo." + "5-time-series": { + "common": { + "intro": { + "title": "Entrena tu red con una serie temporal", + "content": "En esta página preparas una serie, diseñas una red que predice cada valor con los anteriores, la entrenas y ves cómo predice lo que no vio. Te explico cada parte en orden. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." }, - "ComputeWeightedLoss": { - "references": "Media ponderada \n (Acervolima, s.f.)", - "description": "Calcula la pérdida ponderada entre dos tensores dados." + "session": { + "title": "Guardar la configuración", + "content": "Con estos botones guardas en un fichero la red, los hiperparámetros y la preparación (la ventana y si se diferencia), y lo cargas otro día o lo compartes. No se guardan los datos ni los modelos entrenados." }, - "CosineDistance": { - "references": "Distancia del coseno \n (Acervolima, s.f.)", - "description": "Calcula la pérdida aplicando el coseno de la distancia entre dos tensores." + "manual": { + "title": "Cómo funciona", + "content": "Si es tu primera vez, despliega esta parte: explica las ventanas, por qué la prueba es el final de la serie, el escalado, la predicción a un paso y seguida, y con qué se compara la red." }, - "HingeLoss": { - "references": "Pérdida de bisagra \n (Rennie & Srebro, 2005)", - "description": "Calcula la pérdida de bisagra entre dos tensores. Se aplica en problemas de clasificación." + "dataset-info": { + "title": "La serie", + "content": "Aquí se describe la serie: de dónde salen los datos y qué tiene de particular, como una tendencia, estaciones o ciclos." }, - "HuberLoss": { - "references": "(Pérdida Huber)", - "description": "Calcula la pérdida provocada por el procedimiento de estimación." + "process": { + "title": "Sube tu serie", + "content": "Arrastra aquí tu fichero y elige la columna con los valores y, si la tiene, la de las fechas: con ella se ordenan las filas y se pone fecha a lo que se predice." }, - "LogLoss": { - "references": "Pérdida logarítmica \n (Shen, 2005)", - "description": "LogLoss o Logistic Loss es una función convexa que crece linealmente para números negativos y la hace poco sensible a valores atípicos. Calcula la pérdida logarítmica entre dos tensores." + "dataset": { + "title": "Los datos", + "content": "La serie entera, en orden. La línea discontinua marca dónde empieza la prueba: el final de la serie, que la red no verá al entrenar." }, - "MeanSquaredError": { - "references": "Error cuadrático medio \n (Acervolima, s.f.)", - "description": "Calcula de forma geométrica la distancia al cuadrado al objetivo." + "preparation": { + "title": "La preparación", + "content": "La ventana es cuántos valores anteriores mira la red; conviene que abarque una estación. La prueba es el porcentaje final que se aparta. Diferenciar hace que aprenda cambios en lugar de valores, y la estación se usa para compararse con la predicción estacional." }, - "CategoricalCrossEntropy": { - "references": "(Acervolima, s.f.)", - "description": "Mide la distancia entre distribuciones de probabilidad. Es aplicada en redes cuya capa de salida es una probabilidad." + "windows": { + "title": "Lo que aprende la red", + "content": "Así se convierte la serie en ejemplos: cada fila son los valores anteriores (la ventana) y el siguiente, que es lo que tiene que predecir. Cambia la ventana o diferencia y mira cómo cambian." }, - "SigmoidCrossEntropy": { - "references": "(Acervolima, s.f.)", - "description": "Se trata de una variante de la función CategoricalCrossEntropy, en este caso calcula la pérdida en un valor entre 0 y 1." + "layers": { + "title": "Las capas", + "content": "La red termina en una neurona lineal, el valor que predice. Antes puedes poner capas Dense, que reciben la ventana entera, o recurrentes (SimpleRNN, LSTM, GRU), que la leen valor a valor y van delante." }, - "SoftmaxCrossEntropy": { - "references": "(Bendersky, 2016)", - "description": "Se aplica una combinación de las funciones softmax y CrossEntropy calculando la pérdida de la red." - } - } - }, - "metric-functions": { - "title": "Funciones de métrica", - "text-1": "Se utilizan para evaluar el rendimiento del modelo de la red neuronal en un conjunto de datos de prueba. La función de métrica toma las predicciones realizadas por el modelo y las compara con los valores reales de los datos de prueba para determinar la precisión del modelo.", - "text-2": "Existen diferentes tipos de funciones de métrica que se pueden utilizar en una red neuronal, dependiendo del tipo de problema que se esté abordando. Por ejemplo, para un problema de clasificación binaria, se podría utilizar la precisión (accuracy) como métrica, mientras que para un problema de regresión se podría utilizar el error cuadrático medio (mean squared error).", - "text-3": "En resumen, una función de métrica es una herramienta importante para evaluar la capacidad de una red neuronal para realizar predicciones precisas en un conjunto de datos de prueba y para ayudar a ajustar los parámetros del modelo para mejorar su rendimiento.", - "text-4": "Nosotros usamos principalmente la función accuracy. En la clasificación multietiqueta, esta función calcula la precisión del subconjunto: el conjunto de etiquetas previsto para una muestra debe coincidir exactamente con el conjunto de etiquetas correspondiente en y", - "table": { - "BinaryAccuracy": { - "references": "Precisión binaria
(Acervolima, s.f.)", - "description": "Calcula la frecuencia con la que las predicciones coinciden con las etiquetas binarias." + "layers-add": { + "title": "Añadir y quitar capas", + "content": "Con estos botones añades una capa al principio o antes de la salida. Para quitar una, o cambiar su tipo, sus neuronas o su activación, despliégala en la lista." }, - "BinaryCrossentropy": { - "references": "Entropía cruzada binaria
(Saxena, 2021)", - "description": "Es el promedio negativo del logaritmo de las probabilidades predichas que se han corregido." + "learning-rate": { + "title": "Tasa de aprendizaje", + "content": "Es cuánto se corrigen los pesos en cada paso. Alta, aprende deprisa pero puede no estabilizarse; baja, es más estable pero necesita más épocas." }, - "CategoricalAccuracy": { - "references": "Exactitud categórica", - "description": "Calcula la frecuencia con la que las predicciones coinciden con las etiquetas one-hot." + "epochs": { + "title": "Épocas", + "content": "Cuántas veces ve la red todas las ventanas de entrenamiento. Con pocas no le da tiempo a aprender; con demasiadas puede aprenderse el entrenamiento de memoria. Las curvas de los modelos lo dicen." }, - "CategoricalCrossentropy": { - "references": "Entropía cruzada categórica", - "description": "Calcula la métrica de entropía cruzada entre las etiquetas y las predicciones." + "batch-size": { + "title": "Tamaño del lote", + "content": "Cuántas ventanas ve la red antes de corregir sus pesos. Con lotes pequeños corrige más a menudo y con más ruido; con lotes grandes, cada época va más rápido." }, - "CosineProximity": { - "references": "Proximidad del coseno", - "description": "Calcula entre las etiquetas y las predicciones el coseno de la proximidad. Normalmente se obtienen valores negativos." + "optimizer": { + "title": "Optimizador", + "content": "El método que ajusta los pesos a partir del error. Adam, el que viene elegido, suele funcionar bien sin tocar nada." }, - "MeanAbsoluteError": { - "references": "Error absoluto medio", - "description": "En estadística, es una medida de la diferencia entre dos variables continuas, aplicada a los modelos de aprendizaje automático estas variables son las etiquetas y las predicciones." + "loss": { + "title": "Función de pérdida", + "content": "Cómo se mide el error al entrenar. El error cuadrático medio castiga más los errores grandes; el absoluto medio, a todos por igual." }, - "MeanAbsolutePercentageError": { - "references": "Porcentaje de error absoluto medio", - "description": "De igual forma que MeanAbsoluteError calcula la diferencia entre las etiquetas y las predicciones, pero en este caso con un porcentaje." + "train": { + "title": "Entrenar", + "content": "Al pulsar, la red se entrena con las ventanas de entrenamiento y se valida con las de prueba en cada época. Puedes pararla cuando quieras: se queda con lo aprendido." }, - "MeanSquaredError": { - "references": "Error cuadrático medio", - "description": "Determina el error cuadrático medio entre las etiquetas y las predicciones." + "models": { + "title": "Modelos entrenados", + "content": "Cada entrenamiento añade una fila con su preparación, su red y su error con la prueba, a un paso y seguida. El mejor lleva una marca. Debajo, sus curvas de entrenamiento, para compararlas." + }, + "predict": { + "title": "La predicción", + "content": "Aquí ves lo que predice el modelo elegido en la prueba, a un paso o seguida, su error frente a repetir el último valor o la última estación, y lo que viene después del último valor." + }, + "end": { + "title": "¡A predecir!", + "content": "Ya conoces la página. Prueba otra ventana, diferenciar o una capa LSTM, y compara: lo importante es que la red mejore las predicciones sencillas con lo que no vio." } } } }, - "menu": { - "select-model": { - "description": "Descripción" + "glossary": { + "intro": { + "title": "El glosario", + "content": "Aquí están explicados todos los conceptos que usa Nets4Learning: las tareas, las capas, los hiperparámetros, los optimizadores y las funciones de activación, de pérdida y las métricas. Te enseño lo más importante y dónde encontrarlo. Puedes avanzar con Siguiente, saltar a un paso con el selector, silenciar la voz o dejar que la guía avance sola." }, - "select-dataset": { - "description": "Descripción" + "search": { + "title": "Buscar", + "content": "Escribe aquí cualquier término, por ejemplo «época» o «ReLU», y solo quedarán las tarjetas que lo mencionan." + }, + "index": { + "title": "El índice", + "content": "Las secciones del glosario, en orden. Pulsa una para ir directamente a ella; mientras bajas, se marca en la que estás." + }, + "tasks": { + "title": "Las tareas", + "content": "Lo primero: qué problema resuelve cada tarea de la aplicación. Clasificar filas de una tabla, predecir números con la regresión, clasificar imágenes e identificar objetos." + }, + "units": { + "title": "Neuronas", + "content": "Cada capa de la red tiene neuronas: cada una multiplica sus entradas por unos pesos, las suma y aplica una función de activación. Más neuronas permiten aprender relaciones más complejas." + }, + "activation-function": { + "title": "Función de activación", + "content": "Decide qué deja pasar cada neurona. Sin ella, la red solo podría aprender relaciones lineales, por muchas capas que tuviera." + }, + "learning-rate": { + "title": "Tasa de aprendizaje", + "content": "Cuánto se corrigen los pesos en cada paso del entrenamiento. Es quizá el hiperparámetro más importante: demasiado alta y la red no se estabiliza; demasiado baja y aprende muy despacio." + }, + "epochs": { + "title": "Épocas", + "content": "Cuántas veces recorre la red todos los datos de entrenamiento. Pocas no bastan para aprender; demasiadas llevan a memorizar los datos en vez de generalizar." + }, + "test-size": { + "title": "Datos de prueba", + "content": "La parte de los datos que se aparta para comprobar al final cómo acierta la red con datos que no ha visto. Es la medida honesta de lo que ha aprendido." + }, + "optimizer": { + "title": "Optimizadores", + "content": "Los métodos que ajustan los pesos a partir del error, cada uno con su fórmula. Adam, el que viene elegido casi siempre, combina las ideas de Momentum y de RMSProp." + }, + "activation-plots": { + "title": "Las gráficas", + "content": "Cada función de activación tiene su fórmula y su gráfica, y en la pestaña de animación ves cómo transforma cada valor. ReLU, la más usada en las capas ocultas, deja pasar los positivos y anula los negativos." + }, + "softmax": { + "title": "Softmax", + "content": "Va en la última capa cuando se clasifica: convierte las salidas en probabilidades, una por clase, que suman 1." + }, + "loss": { + "title": "Función de pérdida", + "content": "Mide cuánto se equivoca la red y es lo que el entrenamiento intenta reducir. Para elegir entre varias clases se usa la entropía cruzada categórica." + }, + "loss-regression": { + "title": "La pérdida en regresión", + "content": "Para predecir números, la más habitual es el error cuadrático medio, que castiga mucho los errores grandes. El error absoluto medio, justo debajo, los trata a todos por igual." + }, + "metrics": { + "title": "Métricas", + "content": "Dicen cómo de bien funciona la red de una forma fácil de entender, como la precisión: el porcentaje de aciertos. No cambian cómo aprende." + }, + "confusion-matrix": { + "title": "Matriz de confusión", + "content": "Una tabla que cruza la clase real con la predicha: así no solo ves cuánto acierta la red, sino con qué clases se confunde." + }, + "anchor": { + "title": "Enlaces a cada término", + "content": "Cada tarjeta tiene su enlace (#) para compartirla. Los enlaces de «Más información» del playground te traen directamente al término que necesitas." + }, + "end": { + "title": "Ahora tú", + "content": "Busca un término que no conozcas o baja hasta las funciones de activación y mira sus animaciones. Puedes volver a abrir esta guía cuando quieras con el botón Guía." } }, - "terms": { - "title": "Políticas de privacidad y cookies", - "privacy-title": "Políticas de privacidad", - "privacy-text": "En nuestro sitio web, solo recopilamos información estadística sobre las visitas con el fin de mejorar el rendimiento y la funcionalidad del sitio. No recopilamos ni almacenamos ninguna información personal de nuestros usuarios. Utilizamos cookies para contabilizar el número de visitantes y mejorar la experiencia de navegación. Si tienes alguna pregunta o duda sobre nuestra política de privacidad, no dudes en ponerte en contacto con nosotros a través de nuestra página de contacto.", - "cookies-title": "Cookies", - "cookies-text": "Nuestra página web utiliza cookies de Google Analytics para contabilizar el número de visitantes que recibimos. Estas cookies nos permiten recopilar información estadística anónima sobre el uso de nuestro sitio web y nos ayudan a mejorar su rendimiento y funcionalidad. Las cookies de Google Analytics no recopilan información personal de los usuarios. Al navegar por nuestra web, aceptas el uso de estas cookies. Si deseas obtener más información acerca de cómo utilizamos las cookies, por favor consulta nuestra política de privacidad." + "5-time-series": { + "common": { + "intro": { + "title": "Un modelo de una serie temporal", + "content": "En esta página pruebas una red ya entrenada que predice los siguientes valores de una serie con los anteriores. Verás cómo predice la parte final de la serie, que no vio al entrenar, si mejora las predicciones más sencillas y lo que viene después." + }, + "model": { + "title": "El modelo", + "content": "La ficha del modelo: cómo predice la parte final de la serie, que no vio al entrenar, comparado con repetir el valor anterior o el de hace una estación. Debajo, la descripción de la serie." + }, + "model-summary": { + "title": "Resumen del modelo", + "content": "Este botón abre el resumen de la red: sus capas, cuántas neuronas tiene cada una y cuántos pesos ajustó al entrenar. Debajo están el paquete .n4l, para descargarlo, y el enlace para entrenar tu propia red con esta serie." + }, + "dataset": { + "title": "Los datos", + "content": "La serie tal cual: una fila por fecha, con el valor que se predice resaltado." + }, + "dataset-chart": { + "title": "La serie", + "content": "En esta pestaña la ves en una gráfica. La línea discontinua marca dónde empieza la parte de prueba, que la red no vio al entrenar." + }, + "dataset-windows": { + "title": "Preparada para la red", + "content": "Aquí ves cómo se preparó la serie: cuántos valores anteriores recibe la red (la ventana), cómo se escalan y los primeros ejemplos con los que aprendió." + }, + "instances": { + "title": "Valores de la serie", + "content": "Con este selector eliges un valor de la serie y el formulario se rellena con los anteriores. Los marcados como «prueba» son de la parte que la red no vio." + }, + "form": { + "title": "El formulario", + "content": "Estos son los valores anteriores, uno por fecha: lo que la red usa para predecir. Puedes cambiarlos para ver cómo cambia la predicción." + }, + "vector": { + "title": "Lo que recibe la red", + "content": "Así le llegan a la red: escalados entre 0 y 1 con el mínimo y el máximo del entrenamiento." + }, + "predict": { + "title": "Predecir", + "content": "Al pulsar este botón, la red recibe la ventana escalada y predice el valor siguiente." + }, + "result": { + "title": "El resultado", + "content": "Aquí aparece el valor predicho. Si no cambiaste el formulario, también el real y el error. Debajo, la entrada de la red paso a paso." + }, + "mode": { + "title": "A un paso o seguida", + "content": "A un paso, cada valor de prueba se predice con los reales de antes. Seguida, desde el final del entrenamiento, cada valor con los ya predichos: así se predice el futuro, y los errores se acumulan. Con «De cerca» ves solo la prueba." + }, + "chart": { + "title": "La predicción", + "content": "En gris, la serie real; en naranja, lo que predice la red en la prueba, y en morado, lo que viene después. Puedes añadir también la predicción con los datos de entrenamiento." + }, + "errors": { + "title": "¿Mejor que lo más sencillo?", + "content": "El error medio de la red (MAE y RMSE, en las unidades de la serie) junto al de repetir el último valor y el de repetir la última estación. Debajo, si la red las mejora y si se equivoca mucho más con la prueba que con el entrenamiento." + }, + "future": { + "title": "Lo que viene después", + "content": "Elige cuántos valores quieres predecir después del último: se predicen seguidos, cada uno con los anteriores ya predichos, así que cuanto más lejos, menos fiables." + }, + "end": { + "title": "¡Listo!", + "content": "Ya sabes leer la predicción de una serie temporal. Para entrenar tu propia red con esta serie, usa el botón «Entrenar tu red con esta serie»." + } + } } }, - "generator": { - "table-models": { - "list-models-generated": "Lista modelos generados", - "learning-rate": "Tasa de aprendizaje", - "test-size": "Tamaño del conjunto de pruebas", - "n-of-epochs": "N. épocas", - "n-epochs": "N. épocas", - "id-optimizer": "Optimizador", - "id-loss": "Pérdida", - "id-metrics": "Métrica", - "layers": "Capas", - "download": "Descargar", - "features": "Características", - "open-visor": "Abrir visor", - "close-visor": "Cerrar visor", - "history": "Resultados" + "loading-status": { + "page": "Cargando la página…", + "slow": "La primera vez tarda un poco más: se están descargando las librerías de esta sección. Las siguientes visitas irán más rápido.", + "model": "Cargando el modelo…", + "model-progress": "Descargando el modelo: {{loaded}} de {{total}} MB", + "model-loaded": "Descargando el modelo: {{loaded}} MB", + "model-help": "La primera vez puede tardar: el modelo se descarga de internet." + }, + "report": { + "button": "Informe", + "title": "Informe de entrenamiento", + "created": "Creado el {{date}}", + "print": "Imprimir o guardar en PDF", + "back": "Volver al entrenamiento", + "network": "La red", + "hyperparameters": "Hiperparámetros", + "results": "Resultado del entrenamiento", + "results-caption": "Valores de la última época.", + "metric": "Métrica", + "uploaded": "Conjunto de datos subido", + "empty": "No hay ningún informe todavía: entrena un modelo y pulsa «Informe» en su fila de la tabla de modelos.", + "error-storage": "El navegador no deja guardar el informe (almacenamiento desactivado o lleno)." + }, + "offline": { + "bar": "Sin conexión: puedes seguir usando lo que ya habías abierto; lo demás estará disponible al volver la conexión." + }, + "n4l": { + "download": "Descargar .n4l", + "download-title": "Descargar este modelo con sus datos y sus textos en un fichero .n4l, para compartirlo o abrirlo después", + "local": { + "title": "Tus paquetes .n4l", + "text": "Abre un fichero .n4l (un modelo con sus datos y sus textos): se guarda en este navegador y aparece aquí.", + "drop": "Arrastra aquí un fichero .n4l o pulsa para elegirlo", + "files": "Fichero .n4l", + "version": "Versión {{version}}, {{size}}", + "remove": "Quitar", + "remove-title": "Quitar «{{name}}» de este navegador", + "imported": "«{{name}}» está listo: ábrelo desde su tarjeta.", + "error": "No se ha podido abrir el fichero:", + "open-title": "Abrir un fichero .n4l", + "how": "¿De dónde sale uno? En la página de cada modelo ya entrenado, «Descargar .n4l» da su paquete: el modelo, sus datos y sus textos. Después de entrenar, cada modelo de la tabla se descarga igual, con el conjunto con el que lo entrenaste. También puedes abrir uno que te pasen: solo describe qué hay y cómo usarlo, no lleva código.", + "saved": "Guardados en este navegador", + "empty": "Todavía no hay ninguno: abre un fichero .n4l arriba.", + "remove-confirm": "Se quitará «{{name}}» de este navegador; para usarlo otra vez tendrás que volver a abrir su fichero .n4l." + }, + "download-trained-title": "Descargar este modelo en un fichero .n4l, con el conjunto de datos, su preprocesado y sus textos: se abre después en «Paquetes .n4l»", + "metrics": { + "title": "Con datos que no ha visto", + "text": "Con el 20 % del conjunto que se apartó al entrenarlo, se equivoca de media en {{mae}}; prediciendo siempre la media, el error sería {{baseline}}. R²: {{r2}} (1 sería acertar siempre; 0, lo mismo que predecir la media).", + "no-better": "No predice mejor que dar siempre la media: con estos datos no se puede saber mucho más." } }, - "hr": { - "information": "Información", - "editor": "Editor", - "dataset": "Conjunto de datos", - "model": "Modelo", - "generated-models": "Modelos generados", - "predict": "Predecir", - "classify": "Clasificar", - "tasks": "Tareas", - "00-tabular-classification": "Clasificación Tabular", - "tutorial-00-tabular-classification": "Entrenar un modelo para clasificación tabular", - "01-regression": "Regresión", - "02-object-detection": "Detección de objetos", - "03-image-classification": "Clasificación de imágenes", - "optimization-function": "Funciones de optimización", - "activation-functions": "Funciones de activación", - "loss-functions": "Funciones de pérdida", - "metric-function": "Funciones de métrica", - "layers": "Capas", - "process-dataset": "Procesamiento del conjunto de datos", - "project": "Proyecto", - "add-model-dataset": "Añadir modelo al proyecto", - "dataframe": "DataFrame" + "pagination": { + "label": "Páginas de la tabla", + "first": "Primera página", + "previous": "Página anterior", + "next": "Página siguiente", + "last": "Última página", + "page": "Página {{page}}" }, - "form-dataframe": { - "int32": "Entero", - "float32": "Flotante", - "string": "Texto", - "label-encoder": "Label encoder", - "one-hot-encoder": "OneHot encoder", - "drop": "Descartar", - "ignored": "Ignorar", - "submit": "Procesar dataframe" + "skip-to-content": "Saltar al contenido", + "modal": { + "close": "Cerrar" }, - "joyride": { - "back": "Atras", - "close": "Cerrar", - "last": "Anterior", - "next": "Siguiente", - "open": "Abrir", - "skip": "Saltar" + "model-summary-table": { + "layer": "Capa", + "output-shape": "Forma de salida", + "params": "Parámetros", + "total": "Total de parámetros (pesos que se ajustan al entrenar)", + "trainable": "De ellos, entrenables", + "batch-note": "«—» en la forma de salida es el número de ejemplos que entran a la vez (el lote)." }, - "upload-dataset-info": "Debes subir un conjunto de datos para realizar la tarea.", - "upload-model": "Subir modelo", - "upload-model-info": "Debes subir un modelo para realizar la tarea.", - "select-attr": "Selecciona atributo", - "upload-dataset": "Subir conjunto de datos", - "00-tc": { - "car": { - "buying": "Precio de compra", - "maint": "Precio del mantenimiento", - "doors": "Número de puertas", - "persons": "Capacidad de personas", - "lug_boot": "Tamaño del maletero", - "safety": "Seguridad estimada del coche.", - "result": "Resultado", - "unacc": "Inaceptable", - "acc": "Aceptable", - "good": "Bueno", - "vgood": "Muy bueno" - }, - "iris": { - "sepal_length": "Longitud sépalo", - "sepal_width": "Anchura sépalo", - "petal_length": "Longitud pétalo", - "petal_width": "Anchura pétalo", - "class": "Clase", - "Iris-setosa": "Iris setosa", - "Iris-versicolor": "Iris versicolor", - "Iris-virginica": "Iris virginica" - }, - "lymphography": { - "lymphatics": "lymphatics", - "block of affere": "block of affere", - "bl": { - " of lymph": { - " c": "bl. of lymph. c", - " s": "bl. of lymph. s" - } - }, - "by pass": "by pass", - "extravasates": "extravasates", - "regeneration": "regeneration of", - "early uptake in": "early uptake in", - "lym": { - "nodes dimin": "lym.nodes dimin", - "nodes enlar": "lym.nodes enlar" - }, - "changes in lym": "changes in lym.", - "defect in node": "defect in node", - "changes in node": "changes in node", - "changes in stru": "changes in stru", - "special forms": "special forms", - "dislocation of": "dislocation of", - "exclusion of": "exclusion of no", - "no": { - " of nodes in": "no. of nodes in" - }, - "Category": "Category", - "normal find": "Normal", - "metastases": "Metastasis", - "malign lymph": "Linfoma maligno", - "fibrosis": "Fibrosis" + "chart-data": { + "show": "Ver los datos", + "rows": "filas {{from}}–{{to}} de {{total}}", + "columns": { + "variable": "Variable", + "value": "Valor", + "rows": "Filas", + "percent": "Porcentaje", + "bin": "centro del intervalo", + "group": "Grupo", + "lower": "Límite inferior", + "q1": "Primer cuartil", + "median": "Mediana", + "q3": "Tercer cuartil", + "upper": "Límite superior", + "mean": "Media" + } + }, + "page-intro": { + "train": { + "text": "Aquí diseñas una red neuronal y la entrenas con el conjunto de datos elegido. Puedes dejarlo todo como está y pulsar «Entrenar».", + "steps": [ + "Mira el conjunto de datos: qué columnas tiene y qué hay que predecir.", + "Cambia las capas y los hiperparámetros, si quieres.", + "Pulsa «Entrenar» y mira cómo aprende la red.", + "Prueba el modelo con ejemplos y mira en qué se fija." + ] + }, + "review": { + "text": "Este modelo ya está entrenado: aquí lo pruebas con ejemplos y ves en qué se fija.", + "steps": [ + "Lee qué hace el modelo y con qué datos se entrenó.", + "Elige un ejemplo o escribe los valores tú.", + "Mira la predicción y, si quieres, su explicación." + ] + }, + "detect": { + "text": "Este modelo busca cosas en una imagen. Enciende la cámara o sube una foto, y el modelo marcará lo que encuentre.", + "steps": [ + "Enciende la cámara o sube una foto.", + "Mira lo que marca el modelo (también se dice en texto).", + "Si quieres, pide la explicación de lo que ha encontrado." + ] } + }, + "model-code": { + "title": "Ver el código", + "summary": "La red que has diseñado, escrita en TensorFlow.js o en Keras (Python): la misma que entrena la aplicación.", + "language": "Lenguaje del código", + "copy": "Copiar el código", + "copied": "Código copiado", + "code": "El código en {{language}}", + "help-tfjs": "Para usarlo en tu proyecto, instala TensorFlow.js (npm install @tensorflow/tfjs) y prepara XTrain, yTrain, XTest e yTest como tensores, con los datos ya procesados como en esta página.", + "help-keras": "Para usarlo en Python, instala Keras (pip install keras tensorflow) y prepara X_train, y_train, X_test e y_test como matrices de NumPy, con los datos ya procesados como en esta página.", + "data-classification": "X: los atributos de cada fila, ya procesados (escalados); y: su clase en one-hot", + "data-regression": "X: los atributos de cada fila, ya procesados (escalados); y: el valor que hay que predecir", + "data-image": "X: las imágenes, con valores de 0 a 1; y: su clase en one-hot", + "data-series": "X: las ventanas con los {{window}} valores anteriores; y: el valor siguiente de cada ventana" + }, + "training-prediction": { + "title": "Antes de entrenar, ¿qué crees que pasará?", + "optional": "(opcional)", + "chosen": "Tu predicción: {{prediction}}", + "help": "Elige lo que esperas: al terminar lo compararemos con lo que ha pasado de verdad.", + "none": "No lo sé", + "options": { + "good": "Aprenderá bien", + "still-improving": "Le faltarán épocas: seguirá mejorando al acabar", + "overfitting": "Se aprenderá los datos de memoria (sobreajuste)", + "not-learning": "Apenas aprenderá", + "unstable": "Irá a saltos (inestable)", + "diverged": "La pérdida se disparará" + }, + "right": "Predijiste: «{{prediction}}». ¡Acertaste!", + "wrong": "Predijiste: «{{prediction}}». Esta vez ha pasado otra cosa: aquí debajo verás qué y por qué." } } \ No newline at end of file diff --git a/public/locales/ja/translation.json b/public/locales/ja/translation.json index 562794d..38f9da6 100644 --- a/public/locales/ja/translation.json +++ b/public/locales/ja/translation.json @@ -142,32 +142,110 @@ "dataset-web": "元のウェブサイト", "dataset-reference": "参照元", "download-dataset-car": "車両評価データセット", - "download-dataset-hepatitis-c": "C型肝炎データセット", + "download-dataset-hepatitis-c": "C型肝炎", "download-dataset-iris": "アヤメ (Iris) データセット", - "download-dataset-titanic": "タイタニック生存データセット*", - "download-dataset-new-thyroid": "New Thyroid データセット", - "download-dataset-wine": "ワインデータセット", - "download-dataset-ecoli": "E.coli データセット", + "download-dataset-titanic": "タイタニック号の生存", + "download-dataset-new-thyroid": "甲状腺 (New Thyroid)", + "download-dataset-wine": "ワインの品種", + "download-dataset-ecoli": "大腸菌 (E. coli)", "download": { "dataset": { "1-regression": { "salary": "給与データセット", "auto-mpg": "燃費消費量データセット", "housing-prices": "住宅価格データセット", - "breast-cancer-original": "ウィスコンシン乳がんデータセット", - "breast-cancer-wdbc": "ウィスコンシン乳がん (診断) データセット", - "breast-cancer-wpbc": "ウィスコンシン乳がん (予後) データセット", + "breast-cancer-original": "乳がん (ウィスコンシン)", + "breast-cancer-wdbc": "乳がん:診断 (WDBC)", + "breast-cancer-wpbc": "乳がん:予後 (WPBC)", "student-performance-mathematics": "数学の学生成績データセット", "student-performance-portuguese": "ポルトガル語の学生成績データセット", "wine-red": "赤ワインデータセット", "wine-white": "白ワインデータセット" } } + }, + "dataset-info": "データ", + "extra-title": "その他のデータセット", + "extra-text": "アプリのモデルでは使われていません。データの準備を練習するためのものです。「学習」を押すとアップロードのページに読み込まれ、目的変数の列や各列の扱いを選べます。", + "dataset-details": "情報", + "show-info": "情報を見る", + "variables": { + "title": "変数", + "name": "変数名", + "role": "役割", + "type": "型", + "description": "説明", + "units": "単位", + "missing": "欠損値", + "roles": { + "ID": "ID", + "Feature": "特徴量", + "Target": "目的変数", + "Other": "その他" + }, + "types": { + "Integer": "整数", + "Continuous": "連続値", + "Categorical": "カテゴリ", + "Binary": "二値", + "Date": "日付" + }, + "note": "役割・型・説明(英語)・単位はデータセットの出典ページによるものです。欠損値はここでダウンロードできるファイルで数えています。", + "images": "このデータセットは画像で構成されているため、変数の表はありません。" + }, + "analyze-action": "分析する", + "analyze-title": "「{{name}}」を探索的データ分析で開く", + "data": { + "title": "データ", + "describe": "統計", + "file": "ファイル", + "error": "CSV を読み込めませんでした。", + "describe-help": "数値の列ごとに 1 行:値の数(count)、平均(mean)、標準偏差(std)、最小値、四分位数、最大値。" + }, + "intro": "Nets4Learningのデータセットをタスク別に紹介します。学習に使ったり(クラスタリングしたり)、学習済みモデルを試したり、探索的データ分析(EDA)で開いたり、ダウンロードして他のツールで使ったりできます。", + "models-title": "すぐに学習できる", + "models-text": "アプリのモデルが使うデータセットです。準備済みなので、選んで学習するだけです。", + "train": "学習", + "try-model": "モデルを試す", + "files": "ファイル", + "summary": { + "extra": { + "hepatitis-c": "献血者と患者の血液検査から、C型肝炎、線維化、肝硬変を見分けます。", + "ecoli": "大腸菌の中でタンパク質がどこにあるかを当てます。8クラスあり、ごく少数のクラスもあります。", + "new-thyroid": "5つの検査結果から、甲状腺の働きが正常か、亢進か、低下かを判定します。", + "wine": "13の化学成分からイタリアワインの3品種を見分けます。簡単ですが、列ごとのスケールが大きく異なります。", + "titanic": "客室の等級、性別、年齢、同乗の家族から、タイタニック号の沈没で誰が生き残ったかを予測します。", + "breast-cancer-wisconsin": "細胞の9つの特徴から、乳房の腫瘍が良性か悪性かを判定します(欠損値があります)。", + "wpbc": "腫瘍と細胞の測定値から、乳がんが再発するかを予測します。症例は198件だけです。", + "wdbc": "画像に写った細胞核の30の測定値から、乳房の腫瘍が良性か悪性かを判定します。" + }, + "clustering": { + "breast-cancer-wisconsin": "699の腫瘍の細胞の9つの特徴(1〜10):2グループにすると、良性と悪性にほぼ一致します。", + "wdbc": "569の腫瘍の細胞核の30の測定値:2グループにすると、k-meansは良性と悪性をかなりよく分けます。", + "ecoli": "336のタンパク質の7つのスコアと、細菌内の8つの場所(2〜3件しかないものも):その小さなグループは埋もれてしまいます。", + "hepatitis-c": "589人の血液検査:ほとんどが献血者なので純度は高く出ますが、ランド指数は本当のことを示します。グループは診断に似ていません。" + } + }, + "clustering": { + "examples-title": "すぐにクラスタリングできる", + "examples-text": "本当のクラスが入っていますが、k-meansはそれを使いません。ほかの列でグループ分けし、最後にグループとクラスを比べます。", + "extra-text": "クラスタリングに使えるプロジェクトのほかのデータセットです。「グループ分け」でアップロードしたのと同じように読み込まれます。どれも同じようにクラスに似るわけではなく、それも学びになります。", + "run": "グループ分け" + }, + "time-series": { + "examples-title": "代表的な時系列", + "examples-text": "時系列では各行がある時点(1 日、1 か月…)を表し、順序に意味があります。過去の値から次の値を予測するので、行はシャッフルしません。それぞれトレンド、季節性、周期といった異なるパターンを持っています。" } }, "dataframe-original": "データフレーム | 元データ", "dataframe-form": "データフレーム | 前処理フォーム", "dataframe": { + "table": { + "target": "{{column}}: 目的列(予測・分類する列)", + "shape": "{{rows}} 行 × {{columns}} 列", + "scroll-rows": "残りは表の中をスクロールして表示", + "column": "列" + }, "dataframe": { "title": "データフレーム | データセット" }, @@ -203,6 +281,8 @@ "no-numeric": "説明できる数値列がありません。すべての列がカテゴリ列です。" }, "query": { + "error": "クエリが正しくありません: {{message}}", + "no-rows": "クエリに一致する行はありません。", "title": "データフレーム | クエリ", "description": { "0": "論理比較またはブールマスクの結果に基づいてデータフレームをクエリします。", @@ -210,15 +290,202 @@ "title": "説明" }, "query": "クエリ", - "link": "詳細はこちらのリンクをご覧ください" + "link": "詳細はこちらのリンクをご覧ください", + "column": "列" }, "plot": { "link": "詳細はこちらのリンクをご覧ください" } }, "dataframe-processed": "データフレーム | 処理済み", - "dataframe-scatterplot": { - "title": "散布図" + "dataset-process": { + "tabs": { + "original": "1. 元のデータ", + "form": "2. 処理の方法", + "processed": "3. 処理済みのデータ" + }, + "original-help": "ファイルのままの{{rows}}行、{{columns}}列です。強調表示された列が予測する列です。", + "classification": { + "target-title": "どの列がクラスですか?", + "target-help": "ネットワークは、各行がどのクラスに属するかを答えられるように学習します。ふつうは最後の列です。", + "target-badge": "クラス", + "target-transform": "学習のために、各クラスは数値に変換されます。", + "summary_other": "ネットワークには{{count}}列が入力され、「{{target}}」({{classes}}クラス)を予測します。スケーリングは{{scaler}}です。" + }, + "regression": { + "target-title": "どの数値を予測しますか?", + "target-help": "ネットワークは、ほかの列からこの列の値を計算できるように学習します。数値の列である必要があります。", + "target-badge": "予測対象", + "target-transform": "そのまま使います。これが予測する数値です。", + "summary_other": "ネットワークには{{count}}列が入力され、「{{target}}」を予測します。スケーリングは{{scaler}}です。" + }, + "target-classes": "「{{name}}」には{{count}}個のクラスがあります({{sample}})。ネットワークの出力ニューロンは{{count}}個になります。", + "target-too-many": "{{count}}個のクラスは分類には多すぎます。本当にこの列でよいですか?連続した数値なら、回帰のほうが合っているかもしれません。", + "target-range": "「{{name}}」は{{min}}から{{max}}まで、平均は{{mean}}です。", + "target-not-numeric": "「{{name}}」はテキストの列ですが、回帰は数値を予測します。数値の列を選ぶか、表形式の分類を使ってください。", + "scaler-title": "入力のスケーリング", + "scaler-help": "列ごとに単位(年、ユーロ、センチメートル)が違います。スケーリングすると、どの列も同じくらいの重みになり、ネットワークが学びやすくなります。", + "scalers": { + "min-max-scaler": { + "name": "Min-Max", + "help": "各列を0から1の範囲にします。" + }, + "standard-scaler": { + "name": "標準化", + "help": "平均を引いて標準偏差で割ります(平均0、標準偏差1)。極端な値に強くなります。" + } + }, + "columns-title": "入力の列", + "columns-help": "ネットワークが使う列と、その数値への変換方法を選んでください。テキストの列はカテゴリーとして、異なる値ごとに1つの数値に変換されます。", + "use": "使う", + "types": { + "int32": "整数", + "float32": "小数", + "string": "テキスト", + "boolean": "はい/いいえ", + "datetime": "日付" + }, + "transforms": { + "int32": "整数として", + "float32": "小数として", + "label-encoder": "カテゴリーとして(値ごとに1つの数値)", + "drop": "使わない", + "string": "テキストとして", + "boolean": "はい/いいえとして", + "one-hot-encoder": "値ごとに1列(one-hot)" + }, + "transform-of": "「{{name}}」の変換方法", + "distinct_other": "異なる値が{{count}}個(例:{{sample}})", + "range_other": "{{min}}から{{max}}まで(異なる値が{{count}}個)", + "no-inputs": "入力の列がありません。少なくとも1つ有効にしてください。", + "submit": "データを処理する", + "done_other": "データの準備ができました:{{rows}}行、入力の列が{{count}}個、予測するのは「{{target}}」です。下でネットワークを設計できます。", + "view": "表示するデータ", + "views": { + "scaled": "スケーリング済み", + "encoded": "エンコード済み", + "scaled-help": "スケーリング済みの入力の列です。ネットワークが受け取るのはまさにこれです。", + "encoded-help": "スケーリング前の、各カテゴリーを数値に変換したデータです。各列の下に変換方法を示しています。" + } + }, + "dataset-view": { + "file": "ファイル", + "original": "元データ", + "encoded": "エンコード済み", + "scaled": "スケーリング済み(ネットワークの入力)", + "original-help": "ファイルのままのデータです:{{rows}}行、{{columns}}列。強調表示された列「{{target}}」が予測する列です。", + "encoded-help": "テキストのカテゴリーはすでに数値になっていて、使わない列は除かれています。まだスケーリングしていません。", + "scaled-help": "スケーリング済み({{scaler}})の{{columns}}個の入力の列で、ネットワークが受け取るのはまさにこれです。最後の強調表示された列は予測する「{{target}}」で、スケーリングしません。", + "statistics": "各列の統計" + }, + "stored-models": { + "restored_other": "このデータセットで以前に学習した{{count}}個のモデルを復元しました。再読み込みしても失われないよう、モデルはこのブラウザーに保存されます。", + "delete-ask": "このデータセットのモデルを削除", + "confirm": "本当によいですか?このデータセットの保存済みモデルが削除され、表からも消えます。", + "delete": "はい、削除します", + "cancel": "キャンセル" + }, + "training-diagnosis": { + "title": "モデル {{model}} の学習の様子", + "diverged": { + "title": "損失が発散しました", + "text": "エポック {{epoch}} から損失が数値ではなくなりました(NaN)。重みが制御できないほど大きくなっています。", + "tip": "学習率を下げて(たとえば10分の1)、もう一度学習してください。" + }, + "worse": { + "title": "損失が悪化しました", + "text": "損失が{{first}}から{{last}}に上がりました。重みの更新が大きすぎて、行き過ぎています。", + "tip": "学習率を下げて、もう一度学習してください。" + }, + "unstable": { + "title": "損失が大きく揺れています", + "text": "学習の後半で、損失がエポックごとに大きく上下しています({{min}}〜{{max}})。これでは本当に学習しているかどうかわかりません。", + "tip": "学習率を下げましょう。それでも変わらなければ、テストデータの割合を増やしましょう。テストデータが少ないと、エポックごとの変化が大きくなります。" + }, + "not-learning": { + "title": "ほとんど学習していません", + "text": "損失は{{first}}から{{last}}までしか下がっていません。", + "tip": "学習率やエポック数を上げるか、層のニューロンを増やしてみてください。最後の層の活性化関数が適切かも確認しましょう。" + }, + "overfitting": { + "title": "データを暗記しています(過学習)", + "text": "テストデータでの損失はエポック {{epoch}}({{min}})で最小になり、その後{{last}}まで上がりました。その間、学習データでの損失は下がり続けています。", + "tip": "エポック数を減らす({{epoch}}くらい)か、もっと小さいネットワークを使ってください。" + }, + "still-improving": { + "title": "まだ改善中でした", + "text": "{{epochs}}エポックで損失は{{first}}から{{last}}まで下がり、最後もまだ下がっていました。", + "tip": "エポック数を増やせば、もっと学習できそうです。" + }, + "good": { + "title": "うまく学習しました", + "text": "損失は{{first}}から{{last}}まで下がり、テストデータでは{{validation}}になりました。", + "tip": "比べるために、1つだけ(ニューロン数や学習率など)変えて、もう一度学習してみましょう。" + } + }, + "layer-check": { + "title-error": "層を確認してください:このままでは学習できません", + "title-warning": "層を改善できます", + "error": "エラー", + "warning": "注意", + "params": { + "units": "ニューロン数", + "kernelSize": "カーネルサイズ", + "filters": "フィルター数", + "poolSize": "プールサイズ", + "strides": "ストライド" + }, + "param": { + "text": "層{{layer}}:「{{param}}」の値が正しくありません。", + "fix": "{{value}}にする" + }, + "hidden-softmax": { + "text": "層{{layer}}:softmaxはニューロン全体で100 %を分け合うため、出力層でのみ意味があります。隠れ層では学習が遅くなります。", + "fix": "ReLUを使う" + }, + "output-units": { + "text": "最後の層のニューロンは{{units}}個ですが、クラスは{{classes}}個です。クラスごとに1つのニューロンが必要です。", + "fix": "{{classes}}にする" + }, + "output-activation": { + "text": "最後の層は{{activation}}を使っています。{{expected}}にすると、出力が各クラスの確率(合計1)になります。", + "fix": "{{expected}}を使う" + }, + "output-missing": { + "text": "ネットワークの最後は、ニューロン{{classes}}個(クラスごとに1つ)とSoftmaxのDense層である必要があります。", + "fix": "最後に追加する" + }, + "after-flatten": { + "text": "層{{layer}}:Flattenの後、画像はすでに数値のリストになっていますが、{{type}}には2次元の画像が必要です。", + "fix": "この層を削除" + }, + "flatten-again": { + "text": "層{{layer}}:データはすでに平坦化されているため、このFlattenは不要です。", + "fix": "この層を削除" + }, + "dense-before-flatten": { + "text": "層{{layer}}:Dense層は数値のリストを受け取ります。その前に画像を平坦化するFlattenが必要です。", + "fix": "前にFlattenを追加" + }, + "too-small": { + "text": "層{{layer}}:この時点で画像は{{height}}×{{width}}で、{{type}}の{{window}}×{{window}}のウィンドウが入りません。", + "fix": "この層を削除" + }, + "recurrent-after-dense": { + "text": "層 {{layer}}:{{type}} は系列を値 1 つずつ読みますが、Dense 層の後には数値のリストしか残りません。再帰型の層は Dense 層より前に置きます。", + "fix": "再帰型の層を先頭に移す" + }, + "all-fixed": "層に確認すべき点はなくなりました" + }, + "download-consent": { + "title": "このモデルは約{{mb}} MBをダウンロードします", + "reason": { + "save-data": "ブラウザのデータセーバーがオンです。指示したときだけダウンロードします。", + "slow": "通信が遅いようです。ダウンロードに時間がかかる場合があります。", + "always": "設定で、モデルをダウンロードする前に確認するよう指定しています。" + }, + "accept": "ダウンロード({{mb}} MB)", + "settings": "設定で変更できます。" }, "model-selector": { "title": "モデル選択" @@ -227,7 +494,13 @@ "select-dataset": { "title": "データセットを選択", "info": "データセットを選択" - } + }, + "number": { + "range": "{{min}} から {{max}} までの整数を入力してください。", + "at-least": "{{min}} 以上の整数を入力してください。", + "in-use": "それまでは {{value}} を使います。" + }, + "cancel": "キャンセル" }, "preprocessing": { "title": "前処理", @@ -241,9 +514,27 @@ "predict": "予測", "cookies-policies": { "title": "クッキーポリシー", - "text-0": "このウェブサイトは、ユーザーエクスペリエンスを向上させ、アプリケーションの使用状況を分析するためにクッキーを使用しています。クッキーは、お客様が当社のウェブサイトを訪問したときにデバイスに保存される小さなテキストファイルです。これらのクッキーは、ユーザーが当社のウェブサイトとどのようにやり取りしているか、どのページが最も訪問されているか、およびユーザーエクスペリエンスをどのように改善できるかを理解するのに役立ちます。", - "text-1": "当社は、広告目的でお客様のデータを処理することはありません。クッキーは、分析目的およびウェブサイトの機能を向上させる目的でのみ使用します。当社のウェブサイトを引き続き使用する場合、お客様は当社のプライバシーポリシーに記載されているクッキーの使用に同意したものと見なされます。", - "accept": "同意する" + "banner-title": "Nets4Learning の改善にご協力いただけますか?", + "accept": "同意する", + "banner": "Nets4Learning はハエン大学の研究グループ SIMIDAT による教育プロジェクトです。Google Analytics の Cookie に同意いただくと、どのモデル・データセット・セクションが使われ、何がうまくいかないかを匿名で把握でき、改善すべき点を判断できます。同意した場合にのみ有効になり、いつでも変更できます。", + "more-info": "詳細", + "reject": "拒否する", + "settings": "設定", + "close": "変更せずに閉じる", + "details": "計測する内容としない内容", + "measured-title": "計測する内容", + "measured": [ + "閲覧したページと滞在時間。", + "使用したモデルとデータセット、押したボタン。", + "学習(エポック数、オプティマイザー、所要時間)、予測、モデルの読み込み時間。", + "発生したエラー、言語、テーマ、TensorFlow.js のバックエンド。" + ], + "never-title": "送信しない内容", + "never": [ + "アップロードしたファイル、その名前やデータ、描いた絵、カメラの映像。", + "個人情報(アカウントもフォームもありません)。", + "広告に関するもの(Google の広告シグナルは無効です)。" + ] }, "error": { "load-json-csv": "エラー:ファイルを読み込めませんでした", @@ -259,13 +550,22 @@ "layers-length": "ニューロン数とその活性化関数を持つレイヤーが少なくとも1つ必要です", "parsing-csv": "データセットの準備エラー", "file-not-valid": "エラー:ファイルが無効です", - "metrics-length": "エラー:メトリクス数は1から10の間である必要があります" + "metrics-length": "エラー:メトリクス数は1から10の間である必要があります", + "need-model": "まずモデルを作成して学習させてください", + "dataset-not-processed": "データセットが処理されていません", + "model-not-valid": "このデータには使えないモデルです", + "model-compile": "モデルをコンパイルできませんでした。詳細はコンソールを確認してください。", + "option-not-valid": "無効なオプションです", + "prediction": "予測できませんでした", + "load-dataset": "データセットを読み込めませんでした。" }, "warning": { "the-first-layer-need-to-be-__value__": "警告:最初のレイヤーはタイプ {{value}} である必要があります", "not-more-layers": "警告:これ以上レイヤーを追加することはできません", "error-layers": "警告:レイヤーは1から10の間である必要があります", - "need-a-model": "警告:最初にモデルを作成し、トレーニングする必要があります。" + "need-a-model": "警告:最初にモデルを作成し、トレーニングする必要があります。", + "first-layer-cant-be-removed": "最初の層は削除できません", + "first-layer-cant-be-changed": "最初の層は変更できません" }, "success": { "file-upload": "ファイルのアップロードに成功しました" @@ -291,7 +591,8 @@ "model-train-error": "モデルのトレーニングに失敗しました", "prediction": "予測結果: {{index}}", "file-upload-success": "ファイルのアップロードに成功しました", - "file-upload-error-incorrect-format": "ファイルの形式が正しくありません" + "file-upload-error-incorrect-format": "ファイルの形式が正しくありません", + "close": "お知らせを閉じる" }, "header": { "language": "言語", @@ -299,9 +600,24 @@ "glossary": "用語集", "home": "ホーム", "datasets": "データセット", - "theme": "テーマ", "dataframe": "データフレーム", - "analyze": "AED (探索的データ分析)" + "analyze": "AED (探索的データ分析)", + "theme": "テーマ", + "theme-light": "ライト", + "theme-dark": "ダーク", + "backend": "バックエンド", + "backend-default": "既定", + "backend-unavailable": "利用不可", + "backend-software": "ソフトウェア・低速", + "backend-error": "{{backend}} に切り替えられませんでした", + "backend-error-fallback": "このブラウザでは使用できません。TensorFlow.js は引き続き {{backend}} を使用します。", + "menu": "メニュー", + "tasks": "タスク", + "lab": "2D ラボ", + "packages": ".n4l パッケージ", + "packages-saved_other": "このブラウザに {{count}} 個のパッケージを保存済み", + "github": "GitHub(新しいタブで開きます)", + "main-navigation": "メインナビゲーション" }, "footer": { "description-app": "深層学習モデルの設計と実行のためのウェブプラットフォーム。", @@ -312,7 +628,12 @@ "terms": "利用規約", "contribute": "貢献する", "documentation": "ドキュメント", - "version": "バージョン" + "version": "バージョン", + "cookies": "Cookie の設定", + "links": "リンク", + "institutions": "機関", + "settings": "設定", + "accessibility": "アクセシビリティ" }, "drag-and-drop": { "label-files-one": "ファイル:", @@ -321,24 +642,33 @@ "binary": "バイナリファイルを追加", "json": "JSONファイルを追加", "csv": "CSVファイルを追加", - "csv-json": "テンプレートデータファイル template.json を入力" + "csv-json": "テンプレートデータファイル template.json を入力", + "dataset": "データファイル(CSV、ARFF、JSON、JSONL、Parquet)を追加", + "choose-file": "ファイルを選択", + "choose-files": "ファイルを選択", + "errors": { + "file-invalid-type": "対応していない形式です", + "file-too-large": "ファイルが大きすぎます", + "file-too-small": "ファイルが小さすぎます", + "too-many-files": "アップロードできるファイルは 1 つだけです" + } }, "ui": { "blur": { - "enable": "マスクされた領域にブラーを適用", - "kernelSize": "ブラーカーネルサイズ(奇数)", - "passes": "ブラーの回数" + "enable": "隠した領域をぼかす(単色で塗る代わりに)", + "kernelSize": "ぼかしのサイズ(奇数)", + "passes": "ぼかす回数" }, "explain": { - "title": "説明可能性 (SHAP)", + "title": "モデルの説明可能性", "method": "手法", "about-lrp": "LRP(層ごとの関連性伝播)は、予測されたクラスからネットワークを逆向きにたどり、その関連性を入力ピクセルまで分配します。ヒートマップは、モデルの予測を支える画像の領域を示します。", "about-shap": "画像をセグメント(スーパーピクセル)に分割し、さまざまな組み合わせで各セグメントを隠したり表示したりして予測の変化を観察することで、各セグメントの重要度を測定します。ヒートマップは、各セグメントが予測にどれだけ寄与するかで色付けします。", "perturbationSamples": "摂動サンプル:", - "gridSide": "1辺あたりの領域数(画像を N×N のセグメントに分割)", - "nSamples": "nSamples (SHAP)", + "gridSide": "1辺あたりの領域数", + "nSamples": "試す組み合わせの数", "mask": "マスク (SHAP)", - "maskRange": "マスク (0..1)", + "maskRange": "隠した領域の色", "calculating": "計算中...", "explainPrediction": "予測を説明", "hideExplanation": "説明を非表示", @@ -389,12 +719,32 @@ "presence-only": "このモデルは「顔がある」か「顔がない」か(0 か 100%)しか答えません。そのため、説明は顔を見つけるために最低限何を見る必要があるかを示します。通常は肌だけで十分です。", "body-parts": "ポーズ全体と体の各部位に対する信頼度を説明します。モデルはまず人物を見つける必要があるため、胴体の領域も腕や脚の位置を特定するのに役立ちます。", "wrong-prediction": "モデルが間違えましたか?それでも説明は役に立ちます。モデルがその答えに至るまでにどこを見ていたかを示します。" - } - } + }, + "waiting-for-prediction": "説明するには、まず予測してください。", + "waiting-for-model": "予測を説明するには、まずモデルを学習させてください。", + "gridSide-help": "画像を N × N の領域に分けます。多いほど説明は細かくなりますが、時間がかかります。", + "nSamples-help": "各領域の寄与を測るために、異なる領域を隠す回数です(SHAP)。", + "maskRange-help": "0(黒)から1(白)まで。", + "bar-description": "各変数の SHAP 値(予測をどれだけ上げ下げするか)を、影響の大きい順に示します:{{values}}。", + "beeswarm-description": "各変数について {{count}} 個の例の SHAP 値を示します。変数は影響の大きい順(絶対値の平均)です:{{features}}。", + "bar-data": "各変数の SHAP 値", + "beeswarm-data": "{{count}} 件の例における各変数の SHAP 値", + "variable": "変数", + "mean-abs": "絶対値の平均", + "min": "最小", + "max": "最大" + }, + "take-screenshot": "スクリーンショットを撮る", + "table-scroll-hint": "横にスクロールするとすべての列が表示されます →", + "maximize": "最大化", + "minimize": "元のサイズに戻す" }, "custom-canvas-drawer": { - "validate": "検証", - "clear": "クリア" + "validate": "分類する", + "clear": "クリア", + "canvas": "マウス、ペン、指で描くキャンバス", + "preview": "ネットワークが受け取るもの:28 × 28 ピクセルの絵", + "alternative": "描けない場合は、例かテスト画像のいずれかを分類してください。" }, "table": { "dataset": "データセット" @@ -407,7 +757,8 @@ "tabular-classification": "表形式分類", "regression": "回帰", "object-detection": "物体認識", - "image-classification": "画像分類" + "image-classification": "画像分類", + "time-series": "時系列" }, "graphic-red": { "input": "入力", @@ -420,2282 +771,4505 @@ "text": "値をセミコロンで区切って入力してください。", "items": "(パラメータ-1; パラメータ-2; パラメータ-3; ... ; パラメータ-n)。" } + } + }, + "2-object-detection": { + "interface": { + "process-webcam": { + "title": "リアルタイム認識", + "sub-title": "Webカメラ", + "button": "Webカメラ", + "device": "カメラ" + }, + "process-image": { + "title": "画像処理", + "sub-title": "画像をアップロード" + }, + "device-info": { + "camera": "使用中のカメラ", + "camera-off": "カメラの情報を見るにはWebカメラをオンにしてください。", + "name": "名前", + "resolution": "解像度", + "frames": "受信した画像", + "aspect": "アスペクト比", + "frame-rate": "フレームレート(fps)", + "facing": "カメラ", + "facing-user": "前面", + "facing-environment": "背面", + "resize-mode": "リサイズモード", + "displayed": "画面上のサイズ", + "mirrored": "ミラー表示", + "state": "状態", + "state-live": "配信中", + "state-ended": "停止", + "device-id": "デバイスID", + "capabilities": "カメラの機能", + "capabilities-none": "ブラウザがカメラの機能を報告していません。", + "detection": "検出", + "model": "モデル", + "predictions": "1秒あたりの予測数", + "prediction-time": "1回の予測時間", + "limit": "上限", + "limit-value": "1秒あたり{{fps}}回", + "backend": "TensorFlow.jsのバックエンド", + "tensors": "TensorFlow.jsのメモリ", + "devices": "利用できるカメラ", + "devices-none": "カメラが見つかりません。", + "unnamed": "カメラ{{index}}", + "in-use": "使用中", + "browser": "ブラウザとシステム", + "browser-name": "ブラウザ", + "platform": "システム", + "mobile": "モバイル", + "architecture": "アーキテクチャ", + "cores": "CPUコア数", + "memory": "メモリ(概算)", + "language": "言語", + "permission": "カメラの許可", + "permission-granted": "許可済み", + "permission-denied": "拒否", + "permission-prompt": "未許可", + "webview": "WebView", + "secure": "安全な接続(HTTPS)", + "user-agent": "ユーザーエージェント", + "screen": "画面とGPU", + "screen-size": "画面", + "window": "ウィンドウ", + "pixel-ratio": "ピクセル密度", + "orientation": "向き", + "gpu": "GPU", + "webgl2": "WebGL 2", + "software": "ソフトウェアレンダリング", + "yes": "はい", + "no": "いいえ" + }, + "detections": { + "nothing": "何も検出されていません", + "detected": "検出:{{list}}", + "waiting": "最初の検出を待っています…", + "announce": "検出内容を読み上げる" + } }, - "car": { - "title": "CAR - 車両評価分類", + "face-detection": { + "title": "FaceDetector - 顔の幾何学", "description": { - "text-1": "Car Evaluation データセットは、次の構造を通じて車両を評価できます", - "text-2": "このデータセットの詳細については、ics.uci.eduリポジトリをご覧ください。", - "details-1": { - "title": "情報", - "list": { - "1": "buying: 購入価格。", - "2": "maint: 維持費。", - "3": "doors: ドア数。", - "4": "persons: 乗車定員。", - "5": "lug_boot: トランクのサイズ。", - "6": "safety: 車両の推定安全性。" - } - }, - "details-2": { + "text-0": "このモデルは、入力画像またはビデオから、目、耳、鼻、口などの顔のさまざまな部分を認識できます。", + "details-input": { "title": "入力データ", - "text-1": "車両の特徴", "list": { - "1": "buying: vhigh (非常に高い), high (高い), med (中), low (低い)。", - "2": "maint: vhigh, high, med, low。", - "3": "doors: 2, 3, 4, 5more (5以上)。", - "4": "persons: 2, 4, more (それ以上)。", - "5": "lug_boot: small (小), med (中), big (大)。", - "6": "safety: low, med, high (高)。" + "0": "画像またはビデオ。" } }, - "details-3": { + "details-output": { "title": "出力データ", - "text-1": "車両の受容性", "list": { - "1": "unacc: 受け入れられない", - "2": "acc: 受け入れられる", - "3": "good: 良い", - "4": "vgood: 非常に良い" + "0": "顔のさまざまな部分を区切る一連のポイントを持つ元の入力要素。" } }, - "details-4": { + "details-references": { "title": "参照元", "list": { - "1": "データセット" + "0": "tensorflowリポジトリのモデルエントリ" } } }, - "html-example": { - "text": "評価する車両の対応する値を入力してください:", - "items": "(buying; maint; doors; persons; lug_boot; safety)", - "examples": "例:" + "render": { + "face": "顔", + "face-number": "顔 {{number}}", + "eye-right": "右目", + "eye-left": "左目", + "nose": "鼻", + "mouth": "口", + "ear-right": "右耳", + "ear-left": "左耳" } }, - "iris": { - "title": "IRIS - アヤメ分類", + "face-mesh": { + "title": "FaceMesh - 顔メッシュ", "description": { - "text-1": "Iris-Data データセットは、花弁と萼の長さと幅から、アヤメのどのタイプかを検出できます。", - "details-1": { + "text-0": "このモデルは、入力画像またはビデオから、顔のさまざまなポイントを認識し、最終的に顔のメッシュを作成できます。", + "details-input": { "title": "入力データ", "list": { - "1": "Sepal length (萼の長さ): 連続値", - "2": "Sepal width (萼の幅): 連続値", - "3": "Petal length (花弁の長さ): 連続値", - "4": "Petal width (花弁の幅): 連続値" + "0": "画像またはビデオ。" } }, - "details-2": { + "details-output": { "title": "出力データ", "list": { - "1": "0: Iris Setosa", - "2": "1: Iris Versicolor", - "3": "2: Iris Virginica" + "0": "顔のさまざまな部分を区切る一連のポイントを持つ元の入力要素。" } }, - "details-3": { + "details-references": { "title": "参照元", "list": { - "1": "データセット" + "0": "tensorflowリポジトリのモデルエントリ" } } }, - "html-example": { - "text": "評価する植物に対応する値を入力してください:", - "items": "(萼の長さ; 萼の幅; 花弁の長さ; 花弁の幅)。", - "examples": "例:" + "render": { + "face": "顔", + "face-number": "顔 {{number}}", + "points": "{{count}} 点", + "eye-right": "右目", + "eye-left": "左目", + "lips": "唇" } }, - "lymphography": { - "title": "LYMPHOGRAPHY - リンパ腫データ分類", + "move-net--pose-net": { + "title": "MoveNet - 関節検出器", "description": { - "text-1": "lymphography データセットは、リンパ腫の可能な病期と状態を検出できます。", + "text-0": "MoveNetは、身体の位置をリアルタイムで認識できる機械学習モデルです。単一のポーズまたは複数のポーズを同時に推定するために使用できます。", + "text-1": "以下の例では、パフォーマンスへの影響を減らすために、一度に1つのポーズのみを検出します。", "details-input": { "title": "入力データ", "list": { - "0": "lymphatics: normal (正常), arched (アーチ状), deformed (変形), displaced (変位)", - "1": "block of affere (流入リンパ管の閉塞): no (なし), yes (あり)", - "2": "bl. of lymph. c (リンパ管の閉塞 C): no, yes", - "3": "bl. of lymph. s (リンパ管の閉塞 S): no, yes", - "4": "by pass: no, yes", - "5": "extravasates (漏出): no, yes", - "6": "regeneration of (再生): no, yes", - "7": "early uptake in (早期取り込み): no, yes", - "8": "lym.nodes dimin (リンパ節の縮小): 0-3", - "9": "lym.nodes enlar (リンパ節の肥大): 1-4", - "10": "changes in lym. (リンパ管の変化): bean (豆状), oval (卵型), round (円形)", - "11": "defect in node (節の欠陥): no, lacunar (空隙), lac. marginal (空隙縁), lac. central (空隙中央)", - "12": "changes in node (節の変化): No, lacunar, lac. margin, lac. central", - "13": "changes in stru (構造の変化): no, grainy (粒状), drop-like (滴状), coarse (粗い), diluted (希釈), reticular (網状), stripped (縞状), faint (かすか),", - "14": "special forms (特殊な形態): no, chalices (杯状), vesicles (小胞)", - "15": "dislocation of (転位): no, yes", - "16": "exclusion of no (除外なし): no, yes", - "17": "no. of nodes in (節の数): 0-9, 10-19, 20-29, 30-39, 40-49, 50-59, 60-69, >=70" + "0": "カラー画像またはビデオ(Webカメラ)。" } }, "details-output": { "title": "出力データ", "list": { - "0": "normal find (正常所見): normal", - "1": "metastases (転移): Metastasis", - "2": "malign lymph (悪性リンパ腫): Malignant lymphoma", - "3": "fibrosis (線維症): fibrosis" + "0": "肩、肘、手、足、膝、腰に加えて、顔のさまざまな部分を区切る一連のポイントと線を持つ元の入力要素。" } }, "details-references": { "title": "参照元", "list": { - "0": "データセット" + "0": "tensorflowリポジトリへのエントリ", + "1": "TFHubモデル" } } }, - "html-example": { - "text": "評価する患者の対応する値を入力してください:", - "items": "(lymphatics, block of affere, bl. of lymph. c, bl. of lymph. s, by pass, extravasates, regeneration of, early uptake in, lym.nodes dimin, lym.nodes enlar, changes in lym., defect in node, changes in node, changes in stru, special forms, dislocation of, exclusion of no, no. of nodes in)。", - "examples": "例:" + "render": { + "person": "人物", + "person-number": "人物 {{number}}", + "score": "{{percent}}%", + "shoulder-left": "左肩", + "shoulder-right": "右肩", + "elbow-left": "左ひじ", + "elbow-right": "右ひじ", + "wrist-left": "左手首", + "wrist-right": "右手首", + "hip-left": "左腰", + "hip-right": "右腰", + "knee-left": "左ひざ", + "knee-right": "右ひざ", + "ankle-left": "左足首", + "ankle-right": "右足首" } }, - "list-datasets": { - "0-option-1": "データセット - 車両評価分類", - "0-option-2": "データセット - アヤメ分類", - "0-option-3": "データセット - リンパ腫分類" - }, - "list-models": { - "0-option-1": "モデル - 車両評価分類", - "0-option-2": "モデル - アヤメ分類", - "0-option-3": "モデル - リンパ腫分類" - }, - "joyride": { - "title": "チュートリアルをアクティブ化", - "steps": { - "manual": { - "title": "マニュアル", - "content": "情報を探すためにマニュアルを参照できます" - }, - "dataset-info": { - "title": "データセット情報", - "content": "データセットを分析します" - }, - "dataset": { - "title": "データセット", - "content": "データセットを表示し、その説明から統計情報を抽出できます" - }, - "dataset-plot": { - "title": "データセットのグラフ", - "content": "さまざまなグラフ(棒グラフ、円グラフなど)を使用して、データセットを分析することで非常に重要な情報を抽出できます" - }, - "layer-visualizer": { - "title": "ニューラルネットワーク層のビジュアライザー", - "content": "コンパクトモードと拡張モードの2つの形式で、レイヤー、活性化関数を表示できます" - }, - "layer-editor": { - "title": "レイヤーエディタ", - "content": "ニューラルネットワークのレイヤーを編集したり、各レイヤーのニューロン数、活性化関数を変更したり、新しいレイヤーを追加したり削除したりできます。" - }, - "params-editor": { - "title": "ハイパーパラメータエディタ", - "content": "トレーニングがデータセットに合わせてカスタマイズされるように、ニューラルネットワークのハイパーパラメータを設定できます。" - }, - "list-of-models": { - "title": "モデルリスト", - "content": "モデルが生成されたら、モデルをロードまたはダウンロードして、各モデルをテストし、分類を実行できます。" - }, - "classify-and-visualizer": { - "title": "分類と可視化", - "content": "表形式分類のモデルをロードしたら、分類を実行し、結果を可視化できます" - } - } - } - }, - "1-regression": { - "salary": { - "title": "経験年数に基づく給与", + "coco-ssd": { + "title": "COCO SSD - 物体検出器", "description": { - "text": { - "0": "「Salary」データセットは、個人の職務経験年数とそれに対応する給与の関係を関連付ける情報のコレクションです。", - "1": "データセットの各エントリは、「Years of Experience」(経験年数)と「Salary」(給与)の2つの主要な変数で構成されています。「Years of Experience」変数は、従業員が特定の分野で働いた年数を表し、「Salary」変数は、その従業員が年間稼ぐ金額を表します。" - }, - "link": "このデータセットの詳細については、www.kaggle.comリポジトリをご覧ください。", - "details-1-input": { + "text-0": "物体検出のSSD(Single Shot MultiBox Detection)モデルは、単一の画像内の複数の物体を検出し、識別することを目的としています。", + "text-1": "tensorflow物体検出APIの詳細については、Tensorflow/Object_detectionのREADMEを参照してください。", + "text-2": "このモデルは、COCOデータセット(大規模な物体検出、セグメンテーション、キャプション付けのデータセット)で定義された物体を検出します。モデルは80クラスの物体を検出できます", + "text-3": "この例は、COCO-SSDモデルのTensorFlow.jsへの適応です。", + "details-input": { "title": "入力データ", "list": { - "0": "Years of experience - 経験年数", - "1": "Salary - 給与" + "0": "カラー画像またはビデオ(Webカメラ)。" } }, - "details-2-output": { + "details-output": { "title": "出力データ", "list": { - "0": "計算された回帰 (Salary)" + "0": "元の入力要素と同じで、さまざまな物体を区切る一連のボックスとそれらのラベルが表示されます。" } }, - "details-3-references": { + "details-references": { "title": "参照元", "list": { - "0": "データセット 1", - "1": "データセット 2" + "0": "Coco Datasetの詳細情報" } } + }, + "classes": { + "person": "人", + "bicycle": "自転車", + "car": "車", + "motorcycle": "オートバイ", + "airplane": "飛行機", + "bus": "バス", + "train": "電車", + "truck": "トラック", + "boat": "ボート", + "traffic light": "信号機", + "fire hydrant": "消火栓", + "stop sign": "一時停止標識", + "parking meter": "パーキングメーター", + "bench": "ベンチ", + "bird": "鳥", + "cat": "猫", + "dog": "犬", + "horse": "馬", + "sheep": "羊", + "cow": "牛", + "elephant": "象", + "bear": "熊", + "zebra": "シマウマ", + "giraffe": "キリン", + "backpack": "リュックサック", + "umbrella": "傘", + "handbag": "ハンドバッグ", + "tie": "ネクタイ", + "suitcase": "スーツケース", + "frisbee": "フリスビー", + "skis": "スキー板", + "snowboard": "スノーボード", + "sports ball": "ボール", + "kite": "凧", + "baseball bat": "野球のバット", + "baseball glove": "野球のグローブ", + "skateboard": "スケートボード", + "surfboard": "サーフボード", + "tennis racket": "テニスラケット", + "bottle": "ボトル", + "wine glass": "ワイングラス", + "cup": "カップ", + "fork": "フォーク", + "knife": "ナイフ", + "spoon": "スプーン", + "bowl": "ボウル", + "banana": "バナナ", + "apple": "リンゴ", + "sandwich": "サンドイッチ", + "orange": "オレンジ", + "broccoli": "ブロッコリー", + "carrot": "ニンジン", + "hot dog": "ホットドッグ", + "pizza": "ピザ", + "donut": "ドーナツ", + "cake": "ケーキ", + "chair": "椅子", + "couch": "ソファ", + "potted plant": "鉢植え", + "bed": "ベッド", + "dining table": "ダイニングテーブル", + "toilet": "トイレ", + "tv": "テレビ", + "laptop": "ノートパソコン", + "mouse": "マウス", + "remote": "リモコン", + "keyboard": "キーボード", + "cell phone": "携帯電話", + "microwave": "電子レンジ", + "oven": "オーブン", + "toaster": "トースター", + "sink": "シンク", + "refrigerator": "冷蔵庫", + "book": "本", + "clock": "時計", + "vase": "花瓶", + "scissors": "はさみ", + "teddy bear": "テディベア", + "hair drier": "ヘアドライヤー", + "toothbrush": "歯ブラシ" + }, + "render": { + "numbered": "{{label}} {{number}}", + "score": "{{percent}}%" } }, - "auto-mpg": { - "title": "燃費性能", + "face-api": { + "title": "FaceAPI - 顔の表情", "description": { - "text": { - "0": "AUTO MPG データセットは、カーネギーメロン大学で管理されているStatLibライブラリから取得されました。このデータセットは、1983年の米国統計学会の展示会で使用されました。", - "1": "「Auto MPG」(ガロンあたりのマイル)という用語は、一般的に米国で使用される燃費効率の測定単位を指します。この尺度は、車両が1ガロンの燃料で走行できるマイル数を示します。スペイン語では、通常、「consumo de combustible」(燃料消費量)または「rendimiento de combustible」(燃費性能)という用語が使用されます。国によって測定単位が異なることに注意することが重要です。" + "text-0": "顔の管理のためにグループ化された異なるタイプの複数のニューラルネットワーク。複数の顔の検出、年齢、感情、顔のマークの検出、異なる種類の顔を比較するための記述子としてのキーポイントの抽出を可能にします。", + "details-input": { + "title": "入力データ", + "text-0": "カラー画像またはビデオ(Webカメラ)。" }, - "link": "このデータセットの詳細はICS.UCI.edu リポジトリをご覧ください。", - "details-0": { - "title": "情報", + "details-output": { + "title": "出力データ", + "text-0": "元の入力要素と同じで、各感情の表現度を示すパーセンテージと、その人の年齢を示すボックスが表示されます。", "list": { - "0": "MPG: MPG は Miles Per Gallon(1ガロンあたりの走行マイル)の略で、各インスタンスの車両の燃費を表します。任意の車について予測対象の変数としても使用できます", - "1": "cylinders: 各車のシリンダー数を表す属性です。離散値の属性です", - "2": "displacement: エンジンの排気量を表す、連続値の量的属性です", - "3": "horsepower: 車の馬力を表す連続値の変数です", - "4": "weight: 各車の重量を表す連続値の量的変数です", - "5": "acceleration: 車の加速性能です", - "6": "model year: そのモデルが発売された年です", - "7": "origin: 3つの離散値をとる属性で、1 は米国製、2 は欧州製、3 はアジア製の車を表します", - "8": "car name: 車名を表す文字列です" + "0": "年齢", + "1": "ニュートラル", + "2": "幸せ", + "3": "悲しい", + "4": "怒っている", + "5": "恐れている", + "6": "嫌悪", + "7": "驚いている", + "bounding": "境界ボックス" } }, - "details-1": { + "details-references": { + "title": "参照元" + } + }, + "render": { + "face": "顔", + "face-number": "顔 {{number}}", + "age": "約{{age}}歳", + "percent": "{{percent}}%" + } + }, + "hand-sign": { + "title": "手話", + "description": { + "text-0": "手とその21個の点(MediaPipe Hands)を見つけ、指文字のアルファベットを認識するニューラルネットワーク。アメリカ手話(ASL)は実際の2122の手と比較し、スペイン手話(SSL)は各指を記述したルールで認識します。右手でも左手でも使えます。", + "details-input": { "title": "入力データ", "list": { - "0": "MPG: 連続値", - "1": "cylinders: 多値の離散値(4, 6, 8)", - "2": "displacement: 連続値", - "3": "horsepower: 連続値", - "4": "weight: 連続値", - "5": "acceleration: 連続値", - "6": "model year: 多値の離散値", - "7": "origin: 多値の離散値。1 は米国製、2 は欧州製、3 はアジア製の車を表します", - "8": "car name: 文字列(インスタンスごとに一意)" + "0": "カラー画像またはビデオ(Webカメラ)。" } }, - "details-2": { + "details-output": { "title": "出力データ", "list": { - "0": "回帰による計算値(MPG)" + "0": "指の関節", + "1": "対応する文字" } }, - "details-3": { - "title": "参考文献", + "details-movement": { + "title": "動きのある文字", "list": { - "0": "Auto MPG" - } - } - } - }, - "housing-prices": { - "title": "住宅価格", - "description": { - "text": { - "0": "ボストン住宅データセットは、米国国勢調査局がボストン地域の住宅について収集した情報から派生しています。", - "1": "このデータセットは、米国マサチューセッツ州ボストン地域のさまざまな近隣地域の住宅価格の回帰およびモデリングの問題に対処するように設計されています。このデータセットは、教育および研究の例や実践に一般的に使用されています。" - }, - "link": "UCIデータセットエントリ", - "details-input": { - "title": "入力データ", - "california": { - "list": { - "0": "Median House Value: ブロック内の世帯の平均住宅価値(米ドル)[$]。", - "1": "Median Income: ブロック内の世帯の収入中央値(数万米ドル)[10k$]。", - "2": "Median Age: ブロック内の住宅の年齢中央値。値が低いほど新しい建物を意味します [年]。", - "3": "Total Rooms: ブロック内の総部屋数", - "4": "Total Bedrooms: ブロック内の総寝室数", - "5": "Population: ブロック内に居住する総人数", - "6": "Households: ブロック内の世帯総数", - "7": "Latitude: 住宅が北にある距離の測定値 [°]。", - "8": "Longitude: 住宅が西にある距離の測定値 [°]。", - "9": "Distance to coast: 最も近い海岸線までの距離 [m]", - "10": "Distance to Los Angeles: ロサンゼルス中心部までの距離 [m]。", - "11": "Distance to San Diego: サンディエゴ中心部までの距離 [m]", - "12": "Distance to San Jose: サンホセ中心部までの距離 [m]", - "13": "Distance to San Francisco: サンフランシスコ中心部までの距離 [m]", - "14": null - } - }, - "boston": { - "list": { - "0": "CRIM 市内の一人当たりの犯罪率", - "1": "ZN 25,000平方フィート以上の区画の住宅地の割合。", - "2": "INDUS 市内の一人当たりの非小売業の割合", - "3": "CHAS チャールズ川ダミー変数(トラクトが川と接している場合は1、それ以外の場合は0)", - "4": "NOX 窒素酸化物濃度(1000万分の1)", - "5": "RM 住宅あたりの平均部屋数", - "6": "AGE 1940年より前に建てられた所有者居住ユニットの割合", - "7": "DIS 5つのボストン雇用センターまでの加重距離", - "8": "RAD ラジアル高速道路へのアクセス指数", - "9": "TAX 10,000ドルあたりの固定資産税", - "10": "PTRATIO 生徒と教師の比率", - "11": "B 1000 (Bk - 0.63)^2 (Bkは市内の一人当たりの黒人の割合)", - "12": "LSTAT 人口の低所得者層の割合", - "13": "MEDV 所有者居住住宅の平均価値(1000ドル)" - } - } - }, - "details-output": { - "title": "出力データ", - "california": { - "list": { - "0": "計算された回帰" - } - }, - "boston": { - "list": { - "0": "計算された回帰" - } + "0": "LL と RR(SSL):L または R を作り、手をその手の側へ(手のひらの半分以上)動かして止めます。止めるとすぐに文字が出ます。", + "1": "Ñ(SSL):N を作り、手を左右に動かすか、手首をひねる動きを 2〜3 回くり返します。", + "2": "動いている間も文字の形を保ってください。画像がぶれても大丈夫です。動きの前後に見えた形で判断します。" } }, "details-references": { - "title": "参照元", - "california": { - "list": { - "0": "Kaggle California Housing Prices Data (5 new features!)" - } - }, - "boston": { - "list": { - "0": "UCIデータセット情報", - "1": "ボストン住宅データセットに関する論争" - } - } - } - } - }, - "breast-cancer": { - "title": "ウィスコンシン乳がん (診断と予後)", - "description": { - "text": { - "0": "ウィスコンシン大学病院の乳がん関連データセットです。良性か悪性かを区別し、乳がん腫瘍の予測と識別に役立ちます。", - "1": "各レコードは、1984年以来Dr. Wolbergによって治療された浸潤性乳がんの症例追跡データであり、転移の証拠がない症例のみが含まれます。", - "2": "最初の30の特徴量は、乳腺腫瘤の穿刺吸引細胞診(FNAB)のデジタル画像から計算され、画像に存在する細胞核の特徴を記述しています。いくつかの画像はcs wiscで見つけることができます。", - "3": "ファイル wdbc.csv は診断データセットに対応し、wpbc.csv は予後データセットに対応します。" - }, - "link": "UCIデータセット入力", - "details-1-input": { - "title": "入力データ", - "list": { - "0": "ID番号", - "1": "結果 (R = 再発, N = 非再発)", - "2": "時間 (フィールド 2 = R の場合は再発までの時間、フィールド 2 = N の場合は無病期間)", - "3": "4-33 各細胞核について10個の実数値特徴量が計算されます:", - "4": "半径 (中心から周囲までの距離の平均)", - "5": "テクスチャ (グレースケール値の標準偏差)", - "6": "周囲長", - "7": "面積", - "8": "平滑性 (半径の長さの局所的な変動)", - "9": "コンパクトさ (周囲長^2 / 面積 - 1.0)", - "10": "凹面 (輪郭の凹状部分の重症度)", - "11": "凹点 (輪郭の凹状部分の数)", - "12": "対称性", - "13": "フラクタル次元 (「海岸線近似」 - 1)" - } - }, - "details-2-output": { - "title": "出力データ", - "list": { - "0": "計算された回帰 (給与)" - } - }, - "details-3-references": { - "title": "参照元", - "list": { - "0": "Breast Cancer Wisconsin", - "1": "Breast Cancer Wisconsin (Prognostic)", - "2": "Breast Cancer Wisconsin (Diagnostic)" - } - } - } - }, - "student-performance": { - "title": "学生の成績", - "description": { - "text": { - "0": "このデータセットには、2つのポルトガル学校の生徒の学業成績データが含まれています。データには、生徒の人口統計、社会的な特徴、成績などが含まれています。数学(mat)とポルトガル語(por)の2つの異なる科目に関する成績データセットが含まれています。", - "1": "データセットには多変量データ、実数型の属性、649インスタンス、および12個の異なる属性が含まれています。", - "2": "重要な注意: ターゲット属性G3は、G2およびG1属性と強い相関があります。これは、G3が最終学年の成績(3学期に発行)であり、G1およびG2が1学期と2学期の成績に対応しているためです。G2とG1なしでG3を予測することはより困難ですが、そのような予測はより有用です。", - "3": "ファイル student-por.csv はポルトガル語の学生成績データセットに対応し、student-mat.csv は数学の学生成績データセットに対応します。" - }, - "link": "UCIデータセット入力", - "details-1-input": { - "title": "入力データ", - "list": { - "0": "school - 生徒の学校(バイナリ: 'GP' - Gabriel Pereira または 'MS' - Mousinho da Silveira)", - "1": "sex - 生徒の性別(バイナリ: 'F' - 女性 または 'M' - 男性)", - "2": "age - 生徒の年齢(数値: 15歳から22歳)", - "3": "address - 生徒の住居の種類(バイナリ: 'U' - 都市 または 'R' - 地方)", - "4": "famsize - 家族のサイズ(バイナリ: 'LE3' - 3人以下 または 'GT3' - 3人以上)", - "5": "Pstatus - 両親の同居状況(バイナリ: 'T' - 同居 または 'A' - 別居)", - "6": "Medu - 母親の学歴(数値: 0 - なし, 1 - 小学校(4年生), 2 - 5年生から9年生, 3 - 中等教育 または 4 - 高等教育)", - "7": "Fedu - 父親の学歴(数値: 0 - なし, 1 - 小学校(4年生), 2 - 5年生から9年生, 3 - 中等教育 または 4 - 高等教育)", - "8": "Mjob - 母親の職業(名義尺度: 'teacher' (教師), 'health' (医療関連), 'services' (サービス業) (例: 管理職や警察), 'at_home' (主婦) または 'other' (その他))", - "9": "Fjob - 父親の職業(名義尺度: 'teacher', 'health', 'services', 'at_home' または 'other')", - "10": "reason - 学校を選んだ理由(名義尺度: 'home'(家が近い), 'reputation'(評判), 'course'(コース) または 'other'(その他)", - "11": "guardian - 生徒の保護者(名義尺度: 'mother' (母), 'father' (父) または 'other' (その他))", - "12": "traveltime - 通学時間(数値: 1 - 15分未満, 2 - 15分から30分, 3 - 30分から1時間, または 4 - 1時間以上)", - "13": "studytime - 週間の学習時間(数値: 1 - 2時間未満, 2 - 2時間から5時間, 3 - 5時間から10時間, または 4 - 10時間以上)", - "14": "failures - 以前のクラスでの落第回数(数値: nが1 <= n <= 3の場合 n, それ以外の場合は4)", - "15": "schoolsup - 追加の教育サポート(バイナリ: yes または no)", - "16": "famsup - 家族の教育サポート(バイナリ: yes または no)", - "17": "paid - 有料追加クラス(科目内)の有無(バイナリ: yes または no)", - "18": "activities - 課外活動(バイナリ: yes または no)", - "19": "nursery - 幼稚園に通っていたか(バイナリ: yes または no)", - "20": "higher - 高等教育を希望するか(バイナリ: yes または no)", - "21": "internet - 自宅でのインターネットアクセス(バイナリ: yes または no)", - "22": "romantic - 恋愛関係にあるか(バイナリ: yes または no)", - "23": "famrel - 家族関係の質(数値: 1 - 非常に悪い から 5 - 非常に良い)", - "24": "freetime - 放課後の自由時間(数値: 1 - 非常に少ない から 5 - 非常に多い)", - "25": "goout - 友達と外出(数値: 1 - 非常に少ない から 5 - 非常に多い)", - "26": "Dalc - 平日のアルコール消費量(数値: 1 - 非常に少ない から 5 - 非常に多い)", - "27": "Walc - 週末のアルコール消費量(数値: 1 - 非常に少ない から 5 - 非常に多い)", - "28": "health - 現在の健康状態(数値: 1 - 非常に悪い から 5 - 非常に良い)", - "29": "absences - 学校の欠席日数(数値: 0から93)" - } - }, - "details-2-output": { - "title": "出力データ", - "list": { - "0": "計算された回帰" - } - }, - "details-3-references": { - "title": "参照元", - "list": { - "0": "Student Performance" - } - } - } - }, - "wine": { - "title": "ワインの品質", - "description": { - "text": { - "0": "この2つのデータセットは関連しており、ポルトガルワインの赤ワインと白ワインのバリアントが含まれています。このデータセットには、理化学変数(入力)と感覚変数(出力)のみが含まれており、ブドウの品種、ワインのブランド、または販売価格のデータは含まれていません。", - "1": "データセットには多変量データ、実数型の属性、4898インスタンス、および12個の異なる属性が含まれています。", - "2": "このデータセットは、分類タスクまたは回帰タスクに使用できます。クラスは順序付けされていますが、データセットは不均衡です。", - "3": "ファイル wine-quality-red.csv は赤ワインデータセットに対応し、wine-quality-white.csv は白ワインデータセットに対応します。" - }, - "link": "このデータセットの詳細については、archive.ics.uci.eduリポジトリをご覧ください。", - "details-1-input": { - "title": "入力データ", - "list": { - "0": "Fixed Acidity (固定酸度): ワイン中の非揮発性酸の濃度を指します。新鮮さと安定性に貢献します。", - "1": "Volatile Acidity (揮発性酸度): 酢酸などの揮発性酸の濃度を指します。過剰に存在すると不快な味を与える可能性があります。", - "2": "Citric Acid (クエン酸): ワインに存在する天然の有機酸の1つです。風味と新鮮さに影響を与える可能性があります。", - "3": "Residual Sugar (残糖): 発酵後にワインに残る砂糖の量です。", - "4": "Chlorides (塩化物): ワイン中の塩化物濃度は、その風味と香りに影響を与えます。", - "5": "Free Sulfur Dioxide (遊離二酸化硫黄): 酸化や不要な微生物の増殖を防ぐ一般的な防腐剤です。", - "6": "Total Sulfur Dioxide (総二酸化硫黄): 遊離二酸化硫黄と結合した二酸化硫黄の合計を表します。ワインの保存にも関連しています。", - "7": "Density (密度): 単位体積あたりのワインの質量を指します。アルコールと砂糖の濃度に関する情報を提供できます。", - "8": "pH: ワインの酸性度またはアルカリ度を測定します。", - "9": "Sulphates (硫酸塩): ワインの生産で時々使用される添加剤です。安定性と香りに影響を与える可能性があります。", - "10": "Alcohol (アルコール): ワイン中のアルコール濃度。風味と口当たりに影響します。", - "11": "Quality (品質): テイスターの評価に従って、通常0から10のスケールで、ワインの全体的な品質スコア。" - } - }, - "details-2-output": { - "title": "出力データ", - "list": { - "0": "計算された回帰" - } - }, - "details-3-references": { "title": "参照元", "list": { - "0": "ワインの品質" + "0": "TFJS hand pose detection" } } + }, + "render": { + "left": "左手", + "right": "右手", + "movement": "動きあり" } }, - "list-datasets": { - "salary": "データセット - 給与", - "auto-mpg": "データセット - 燃費性能", - "housing-prices": "データセット - 住宅価格", - "breast-cancer": "データセット - 乳がん", - "student-performance": "データセット - 学生成績", - "wine": "データセット - ワイン" - }, "list-models": { - "salary": "モデル - 給与", - "auto-mpg": "モデル - 燃費性能", - "housing-prices": "モデル - 住宅価格", - "breast-cancer": "モデル - 乳がん", - "student-performance": "モデル - 学生成績", - "wine": "モデル - ワイン" - }, - "joyride": { - "title": "チュートリアルをアクティブ化", - "steps": { - "manual": { - "title": "マニュアル", - "content": "情報を探すためにマニュアルを参照できます" - }, - "dataset-info": { - "title": "データセット情報", - "content": "データセットの情報を参照します" - }, - "dataset": { - "title": "データセット", - "content": "データセットを表示し、その説明から統計情報を抽出できます" - }, - "pre-process-dataset": { - "title": "前処理", - "content": "データセットのクリーニングと準備" - }, - "dataset-plot": { - "title": "データセットのグラフ", - "content": "さまざまなグラフ(棒グラフ、円グラフなど)を使用して、データセットを分析することで非常に重要な情報を抽出できます" - }, - "layer-visualizer": { - "title": "ニューラルネットワーク層のビジュアライザー", - "content": "コンパクトモードと拡張モードの2つの形式で、レイヤー、活性化関数を表示できます" - }, - "layer-editor": { - "title": "レイヤーエディタ", - "content": "ニューラルネットワークのレイヤーを編集したり、各レイヤーのニューロン数、活性化関数を変更したり、新しいレイヤーを追加したり削除したりできます。" - }, - "params-editor": { - "title": "ハイパーパラメータエディタ", - "content": "トレーニングがデータセットに合わせてカスタマイズされるように、ニューラルネットワークのハイパーパラメータを設定できます。" - }, - "list-of-models": { - "title": "モデルリスト", - "content": "モデルが生成されたら、モデルをロードまたはダウンロードして、各モデルをテストし、予測を実行できます。" - }, - "predict-and-visualizer": { - "title": "予測と可視化", - "content": "回帰モデルをロードしたら、予測を実行し、結果を可視化できます" - } - } + "2-option-1": "FaceDetector - 顔の幾何学", + "2-option-2": "FaceMesh - 顔メッシュ", + "2-option-3": "MoveNet - 関節検出器", + "2-option-4": "COCO SSD - 物体検出器", + "2-option-5": "Face API - 顔マネージャー", + "2-option-6": "HandSign - サイン検出器" } }, - "2-object-detection": { + "3-image-classifier": { "interface": { - "process-webcam": { - "title": "リアルタイム認識", - "sub-title": "Webカメラ", - "button": "Webカメラ" + "0-upload": { + "title": "モデルをロード", + "sub-title": "最初に.jsonファイル、次に.binファイル" + }, + "process-examples": { + "title": "サンプル画像", + "help": "画像をクリックすると分類します。", + "classify-example": "例 {{index}} を分類", + "forms-help": "各文字の今の書き方と、3 つの昔の字形(変体仮名)を字母とともにフォントで描いています。どれかを押すと分類します。昔の字形はいつも正しく分類されるわけではありません。ネットワークは本に手書きされた字で学習しており、活字では学習していないからです。", + "modern": "今", + "old": "昔", + "classify-modern": "今の{{char}}を分類", + "classify-old": "{{origin}}から生まれた昔の{{char}}を分類", + "classify-example-label": "例 {{index}} を分類:{{label}}" + }, + "process-draw": { + "title": "描画" }, "process-image": { - "title": "画像処理", - "sub-title": "画像をアップロード" - } - }, - "face-detection": { - "title": "FaceDetector - 顔の幾何学", - "description": { - "text-0": "このモデルは、入力画像またはビデオから、目、耳、鼻、口などの顔のさまざまな部分を認識できます。", - "details-input": { - "title": "入力データ", - "list": { - "0": "画像またはビデオ。" - } - }, - "details-output": { - "title": "出力データ", - "list": { - "0": "顔のさまざまな部分を区切る一連のポイントを持つ元の入力要素。" - } - }, - "details-references": { - "title": "参照元", - "list": { - "0": "tensorflowリポジトリのモデルエントリ" - } - } + "title": "画像をアップロード", + "sub-title": "-", + "validate": "分類する" + }, + "result": "結果", + "button-accept": "受け入れる", + "modal": { + "title": "予測" + }, + "test-images": { + "load": "テスト画像を読み込む", + "loading": "画像を読み込み中…" } }, "face-mesh": { - "title": "FaceMesh - 顔メッシュ", - "description": { - "text-0": "このモデルは、入力画像またはビデオから、顔のさまざまなポイントを認識し、最終的に顔のメッシュを作成できます。", - "details-input": { - "title": "入力データ", - "list": { - "0": "画像またはビデオ。" - } - }, - "details-output": { - "title": "出力データ", - "list": { - "0": "顔のさまざまな部分を区切る一連のポイントを持つ元の入力要素。" - } - }, - "details-references": { - "title": "参照元", - "list": { - "0": "tensorflowリポジトリのモデルエントリ" - } - } - } + "title": "-" + } + } + }, + "dataframe-plot": { + "warning": { + "no-columns": "描画できる列がありません。", + "unexpected": "グラフを描画できませんでした。詳細はコンソールを確認してください。" + }, + "title": "データフレーム | プロット", + "info": "情報", + "description": { + "title": "チャートタイプの概要" + }, + "configuration": { + "title": "設定", + "reset": "リセット", + "select-all-columns": "すべての列を選択", + "delete-all-columns": "すべての列を削除", + "layout": { + "plot": { + "title": "チャートのタイトル", + "x-axis": "X軸のタイトル", + "y-axis": "Y軸のタイトル" + }, + "title": "レイアウト" }, - "move-net--pose-net": { - "title": "MoveNet - 関節検出器", - "description": { - "text-0": "MoveNetは、身体の位置をリアルタイムで認識できる機械学習モデルです。単一のポーズまたは複数のポーズを同時に推定するために使用できます。", - "text-1": "以下の例では、パフォーマンスへの影響を減らすために、一度に1つのポーズのみを検出します。", - "details-input": { - "title": "入力データ", - "list": { - "0": "カラー画像またはビデオ(Webカメラ)。" - } - }, - "details-output": { - "title": "出力データ", - "list": { - "0": "肩、肘、手、足、膝、腰に加えて、顔のさまざまな部分を区切る一連のポイントと線を持つ元の入力要素。" - } - }, - "details-references": { - "title": "参照元", - "list": { - "0": "tensorflowリポジトリへのエントリ", - "1": "TFHubモデル" - } - } - } + "columns": { + "title": "データフレームの列" }, - "coco-ssd": { - "title": "COCO SSD - 物体検出器", - "description": { - "text-0": "物体検出のSSD(Single Shot MultiBox Detection)モデルは、単一の画像内の複数の物体を検出し、識別することを目的としています。", - "text-1": "tensorflow物体検出APIの詳細については、Tensorflow/Object_detectionのREADMEを参照してください。", - "text-2": "このモデルは、COCOデータセット(大規模な物体検出、セグメンテーション、キャプション付けのデータセット)で定義された物体を検出します。モデルは80クラスの物体を検出できます", - "text-3": "この例は、COCO-SSDモデルのTensorFlow.jsへの適応です。", - "details-input": { - "title": "入力データ", - "list": { - "0": "カラー画像またはビデオ(Webカメラ)。" - } - }, - "details-output": { - "title": "出力データ", - "list": { - "0": "元の入力要素と同じで、さまざまな物体を区切る一連のボックスとそれらのラベルが表示されます。" - } - }, - "details-references": { - "title": "参照元", - "list": { - "0": "Coco Datasetの詳細情報" - } - } + "pie-charts": { + "labels": "ラベル" + } + }, + "buttons": { + "configuration": "設定", + "description": "概要" + }, + "bar-charts": { + "title": "棒グラフ", + "description": { + "intro": { + "0": "棒グラフは、長方形の棒を使用して異なるカテゴリやグループの比較を示す視覚的表現です。このタイプのグラフは、棒の長さまたは高さを使用して、特定の変数の大きさまたは量を示します。", + "1": "棒グラフでは、横軸がカテゴリやグループを表し、縦軸が分析対象の変数の大きさや頻度を示します。各カテゴリには個別の棒があり、棒の長さまたは高さは対応する値または量に比例します。棒は、チャートの向きに応じて、水平または垂直にすることができます。", + "2": "棒グラフには、いくつかの注目すべき特徴と用途があります。" }, - "classes": { - "person": "人", - "bicycle": "自転車", - "car": "車", - "motorcycle": "オートバイ", - "airplane": "飛行機", - "bus": "バス", - "train": "電車", - "truck": "トラック", - "boat": "ボート", - "traffic light": "信号機", - "fire hydrant": "消火栓", - "stop sign": "一時停止標識", - "parking meter": "パーキングメーター", - "bench": "ベンチ", - "bird": "鳥", - "cat": "猫", - "dog": "犬", - "horse": "馬", - "sheep": "羊", - "cow": "牛", - "elephant": "象", - "bear": "熊", - "zebra": "シマウマ", - "giraffe": "キリン", - "backpack": "リュックサック", - "umbrella": "傘", - "handbag": "ハンドバッグ", - "tie": "ネクタイ", - "suitcase": "スーツケース", - "frisbee": "フリスビー", - "skis": "スキー板", - "snowboard": "スノーボード", - "sports ball": "ボール", - "kite": "凧", - "baseball bat": "野球のバット", - "baseball glove": "野球のグローブ", - "skateboard": "スケートボード", - "surfboard": "サーフボード", - "tennis racket": "テニスラケット", - "bottle": "ボトル", - "wine glass": "ワイングラス", - "cup": "カップ", - "fork": "フォーク", - "knife": "ナイフ", - "spoon": "スプーン", - "bowl": "ボウル", - "banana": "バナナ", - "apple": "リンゴ", - "sandwich": "サンドイッチ", - "orange": "オレンジ", - "broccoli": "ブロッコリー", - "carrot": "ニンジン", - "hot dog": "ホットドッグ", - "pizza": "ピザ", - "donut": "ドーナツ", - "cake": "ケーキ", - "chair": "椅子", - "couch": "ソファ", - "potted plant": "鉢植え", - "bed": "ベッド", - "dining table": "ダイニングテーブル", - "toilet": "トイレ", - "tv": "テレビ", - "laptop": "ノートパソコン", - "mouse": "マウス", - "remote": "リモコン", - "keyboard": "キーボード", - "cell phone": "携帯電話", - "microwave": "電子レンジ", - "oven": "オーブン", - "toaster": "トースター", - "sink": "シンク", - "refrigerator": "冷蔵庫", - "book": "本", - "clock": "時計", - "vase": "花瓶", - "scissors": "はさみ", - "teddy bear": "テディベア", - "hair drier": "ヘアドライヤー", - "toothbrush": "歯ブラシ" + "list": { + "0": "カテゴリの比較: 棒グラフは、異なるカテゴリやグループを視覚的に比較するのに理想的です。棒を見ることで、カテゴリ間の大きさや量の違いをすばやく特定できます。", + "1": "カテゴリデータまたは離散データの表現: 棒グラフは、カテゴリ変数または離散変数を表現するのに適しています。各棒は特定のカテゴリを表し、棒の高さまたは長さは、そのカテゴリに関連付けられた大きさまたは量を示します。", + "2": "カテゴリのソート: 棒グラフのカテゴリは、アルファベット順、大きさの順、またはその他の論理的な順序など、さまざまな基準に基づいてソートできます。これにより、カテゴリ間の特定のパターンや傾向を強調することができます。", + "3": "頻度またはパーセンテージの表示: 棒グラフは、頻度またはパーセンテージを表すためにも使用されます。この場合、棒の高さまたは長さは、各カテゴリに対応する割合またはパーセンテージを表します。", + "4": "効果的なプレゼンテーション: 棒グラフは、情報を明確かつ簡潔に提示するための効果的なツールです。シンプルな構造とカテゴリ間の違いを強調する能力により、レポート、プレゼンテーション、およびドキュメントで広く使用されています。", + "5": "棒グラフは、大きさや量に基づいてカテゴリやグループを視覚化および比較するための効果的な方法です。カテゴリデータまたは離散データを表現するのに理想的であり、情報の効果的な提示を可能にします。その単純さと違いを強調する能力により、データ分析とコミュニケーションで一般的に使用されるツールになっています。" + }, + "end": { + "0": "棒グラフは、大きさや量に基づいてカテゴリやグループを視覚化および比較するための効果的な方法です。カテゴリデータまたは離散データを表現するのに理想的であり、情報の効果的な提示を可能にします。その単純さと違いを強調する能力により、データ分析とコミュニケーションで一般的に使用されるツールになっています。" + } + } + }, + "box-plots": { + "title": "ボックスプロット", + "description": { + "intro": { + "0": "ボックスプロット(箱ひげ図)は、数値データセットの分布と統計的要約を示すために使用される視覚的表現です。このタイプのチャートは、四分位範囲(IQR)を表す長方形に基づいており、中央の線は中央値を示し、ひげと呼ばれる延長線は、IQRを超える値の範囲を表します。", + "1": "ボックスチャートでは、長方形は垂直または水平に描画され、下部と上部の2本の線で区切られています。長方形の中央の線は中央値を表します。これは、順序付けられたデータを2つの等しい部分に分割する値です。ひげは長方形の端から極端な値に向かって伸びており、その長さはデータのばらつきによって決まります。", + "2": "ボックスチャートには、いくつかの注目すべき特徴と用途があります。" + }, + "list": { + "0": "統計的要約: ボックスチャートは、データセットの主要な統計情報の視覚的な要約を提供します。中央値に加えて、データを4つの等しい部分に分割する四分位数(Q1とQ3)や、ひげの外側に点またはアスタリスクとして表示される外れ値も表示できます。", + "1": "非対称性と外れ値の識別: ボックスタイプのチャートを観察することで、データの分布における非対称性を特定できます。ひげの長さが同じでない場合、一方の端に向かって非対称性があることを示している可能性があります。さらに、ひげの外側の外れ値は簡単に強調表示できます。", + "2": "グループまたはカテゴリ間の比較: ボックスチャートは、異なるグループまたはカテゴリ間のデータの分布を比較するためにも使用されます。複数のボックスプロットを同じグラフに重ねることで、グループ間の中央値、四分位範囲、および外れ値の存在の違いを視覚化できます。", + "3": "バイアスと分布の検出: ボックスグラフは、データの分布が対称であるか、一方の端に偏っているかを視覚的に識別できます。長方形の中央線が中央にない場合、反対方向にバイアスがあることを示している可能性があります。", + "4": "分散の視覚化: データの中心位置とばらつきに関する情報を提供するだけでなく、ボックスチャートでは、データの分散とばらつきを単一のグラフで視覚化することもできます。これは、データの全体的な分布とばらつきをすばやく把握するのに役立ちます。" + }, + "end": { + "0": "ボックスプロットは、数値データセットの分布、統計的要約、およびばらつきを視覚化するための便利なツールです。非対称性、外れ値を特定し、グループ間の分布を比較できます。その簡潔で効果的な視覚的表現により、データ分析とコミュニケーションで一般的に使用されるツールになっています。" + } + } + }, + "histograms": { + "title": "ヒストグラム", + "description": { + "intro": { + "0": "ヒストグラムは、数値データまたは連続データの分布を示すために使用される視覚的表現です。このタイプのグラフは、一連の隣接する長方形の棒に基づいており、各棒の幅は値の範囲を表し、棒の高さはその範囲内の観測の頻度または数を示します。", + "1": "ヒストグラムタイプのグラフでは、横軸は、間隔またはビンに分割された、調査中の変数の値の範囲を表すために使用されます。縦軸は、各間隔の観測の頻度または数を表します。各棒の高さは、その特定の区間にいくつの観測値が含まれるかを示します。", + "2": "ヒストグラムタイプのチャートには、いくつかの注目すべき特徴と用途があります。" + }, + "list": { + "0": "分布の表示: ヒストグラムを使用すると、数値データの形状と分布を表示できます。データが対称、歪み、マルチモーダル、または均一な分布に従っているかどうかを示すことができます。", + "1": "外れ値の識別: ヒストグラムを観察することで、ほとんどのデータの範囲外にある外れ値または極値を特定できます。これらの値は、孤立した棒として、または値の主要な範囲を超えて伸びる棒として表されます。", + "2": "傾向とパターンの分析: ヒストグラムは、データのパターンと傾向を明らかにすることができます。たとえば、左または右に歪んだ分布は、データの非対称性を示し、正規分布は近似的な対称性を示します。", + "3": "グループまたはカテゴリの比較: ヒストグラムは、異なるグループまたはカテゴリ間のデータの分布を比較するためにも使用できます。複数のヒストグラムを同じグラフに重ねることで、グループ間の違いと類似性を視覚化できます。", + "4": "密度推定: 絶対頻度を表示するだけでなく、ヒストグラムはデータの確率密度の視覚的な推定値も提供できます。棒の高さを正規化することで、各区間における値の発生確率の相対的な表現を取得できます。" + }, + "end": { + "0": "ヒストグラムは、数値データの分布とパターンを視覚化するための便利なツールです。外れ値を特定し、傾向を分析し、グループ間の分布を比較できます。その明確で簡潔な視覚的表現により、データの分布に関する情報を理解しやすい方法で伝達するための効果的なツールになっています。" + } + } + }, + "line-charts": { + "warning": { + "config": "現在の設定は折れ線グラフには使えません。" + }, + "title": "折れ線グラフ", + "description": { + "intro": { + "0": "折れ線グラフは、時系列または連続変数にわたるデータの関係と進化を示す視覚的表現です。これらのグラフは、デカルト座標系にデータポイントをプロットすることによって構築され、各ポイントは、時間または横軸の独立変数の関数として、垂直軸上の変数の測定値または特定の値を表します。", + "1": "折れ線グラフでは、データポイントは直線で接続され、一連の接続されたポイントが作成されます。これらの線は、時間または独立変数にわたるデータの軌道と変化のパターンを視覚化できます。線の傾きは、増加または減少の傾向を示すことができ、線の方向と形状の変化は、データ内の追加のパターンを明らかにすることができます。", + "2": "折れ線グラフには、いくつかの注目すべき特徴と用途があります。" + }, + "list": { + "0": "傾向の表現: 折れ線グラフは、時間の経過に伴う傾向と変化を示すのに特に役立ちます。時間の経過とともにデータ内の成長、減少、または変動のパターンを明らかにすることができます。", + "1": "変化と変動の識別: 折れ線グラフを観察することで、データの急激な変化や変動を特定できます。これらの変化は、測定された変数に影響を与える重要なイベントまたは要因を示している可能性があります。", + "2": "複数の系列の比較: 折れ線グラフでは、単一のチャートで複数のデータ系列を比較することもできます。これは、時間の経過とともに進化する異なる変数間の関係を分析および視覚化するのに役立ちます。", + "3": "季節性とサイクルの分析: データが季節的または周期的なパターンを示す場合、折れ線グラフはこれらのパターンを識別および分析するのに役立ちます。これは、データに定期的な変動が存在する経済学、気象学、販売分析などの分野で役立ちます。", + "4": "予測と投影: 折れ線グラフは、履歴データに基づいて予測と投影を行うためにも使用されます。過去の傾向を見ることで、データが将来どのように振る舞うかを推測し、予測するための数学的または統計的モデルを構築できます。" + }, + "end": { + "0": "折れ線グラフは、時系列または連続変数にわたるデータの関係と進化を視覚化および分析するための貴重なツールです。傾向、季節的なパターン、変化、および予測に関する貴重な情報を提供し、情報に基づいた決定と比較分析を可能にします。" + } + } + }, + "pie-charts": { + "warning": { + "labels": "設定で円グラフのラベルに使う列を選択してください。" + }, + "title": "円グラフ", + "description": { + "intro": { + "0": "円グラフは、全体に対する異なるカテゴリまたは部分の割合を示す視覚的表現です。これらのグラフは、セクターに分割された円に基づいており、各セクターは特定のカテゴリを表し、その相対的なサイズは、そのカテゴリがデータセット全体に占める割合を反映します。", + "1": "円グラフでは、完全な円が100%またはデータの合計を表します。各セクターは円の一部として表示され、それが表すカテゴリに対応する名前またはラベルでラベル付けされます。セクターの角度の尺度は、そのカテゴリがデータセットに占める割合に比例します。", + "2": "円グラフには、いくつかの注目すべき特徴と用途があります。" + }, + "list": { + "0": "割合の表現: 円グラフは、割合とパーセンテージを表すのに理想的です。データセット全体における各カテゴリの相対的な貢献をすばやく視覚化できます。", + "1": "主要なカテゴリの識別: 円グラフのセクターの相対的なサイズは、主要なカテゴリや最も重要なカテゴリを簡単に識別するのに役立ちます。最大のセクターは、他との関係でより大きな割合または貢献をしているカテゴリを示します。", + "2": "カテゴリ間の比較: 円グラフはカテゴリの割合を示すのに役立ちますが、それらの間で正確な比較を行うには制限される場合があります。これは、人間の知覚が角度やセクターのサイズの違いを正確に評価することが難しいためです。ただし、セクターのサイズ間の相対的な比較は、カテゴリ間の割合に関する一般的な情報を提供することができます。", + "3": "カテゴリデータの表現: 円グラフは、カテゴリが相互に排他的であり、固有の順序がないカテゴリデータを表すのに特に役立ちます。たとえば、異なる費用カテゴリの収入のパーセンテージ分布を示すために使用できます。", + "4": "視覚的プレゼンテーションの改善: 円グラフは、視覚的に魅力的で理解しやすい方法で情報を伝達するために、プレゼンテーションやドキュメントで一般的に使用されます。円形と使用される色は、注意をすばやく引き付け、カテゴリ間の比例関係を強調することができます。" + }, + "end": { + "0": "円グラフは、データセット内のカテゴリの割合とパーセンテージを表すための効果的なツールです。主要なカテゴリを特定し、魅力的な視覚的プレゼンテーションを提供できます。ただし、カテゴリ間の正確な比較とカテゴリデータへの焦点という点での制限に注意することが重要です。" + } + } + }, + "scatter-plots": { + "warning": { + "axes": "設定でX軸とY軸の列を選択してください。" + }, + "title": "散布図", + "description": { + "intro": { + "0": "散布図(またはドットプロット、英語でscatter plot)は、2つの変数間の関係を示すためにデカルト座標を使用する視覚的表現です。このタイプのグラフでは、データは2次元空間の個々の点として表され、各点は2つの変数に対応する値のペアを表します。", + "1": "散布図では、横軸は通常、独立変数に割り当てられ、縦軸は従属変数に割り当てられます。グラフ上の各点は個々の観測値を表し、グラフ上の位置は両方の変数に対して持つ値によって決定されます。グラフ上の点の相対的な位置は、2つの変数間のパターンと関係を明らかにします。", + "2": "散布図には、いくつかの注目すべき用途と特徴があります。" + }, + "list": { + "0": "変数間の関係: 散布図は、2つの変数間の関係を分析できます。正の相関(点が上向きに集まる傾向)、負の相関(点が下向きに集まる傾向)、または相関の欠如(点が明確なパターンを示さない)があるかどうかを示すことができます。", + "1": "傾向の特定: 散布図は、データ内の傾向またはパターンを明らかにすることができます。点の一般的な方向を見ることで、変数間に線形、非線形、または曲線的な関係があるかどうかを特定できます。", + "2": "外れ値の検出: 散布図は、データ内の外れ値または極値を特定するのに役立ちます。これらの点は目立ち、主要なグループから遠く離れており、追加の分析が必要な異常なまたは例外的な観測を示唆しています。", + "3": "クラスターまたはグループの分析: 散布図内の点がグループ化されたり、異なるパターンを形成したりする場合、これはクラスターまたはグループの存在を示している可能性があります。これは、データセグメンテーションまたは分類分析で役立ちます。", + "4": "多次元データの可視化: 追加の色や点のサイズを使用する場合、散布図は2次元空間で追加の情報を表すこともできます。これにより、多次元データをより直感的に表示できます。" + }, + "end": { + "0": "散布図は、2つの変数間の関係を探索および視覚化するための強力なツールです。データ内のパターン、傾向、および外れ値を特定でき、相関分析、クラスター検出、多次元データの可視化などのさまざまなアプリケーションで役立ちます。" + } + }, + "index-info": "座標軸", + "form": { + "x": "X軸 (0)", + "y": "Y軸 (1)" + } + }, + "time-series-plots": { + "title": "時系列プロット", + "description": { + "intro": { + "0": "時系列チャートは、時間を追って一定の間隔で収集および記録されるデータの視覚的表現です。これらのチャートは、経済学、金融、気象学、工学、その他多くの分野で広く使用されており、時間の経過に伴うデータの変化を分析および理解するために使用されます。", + "1": "グラフの横軸は時間を表し、縦軸は観測または記録されているデータ値を表します。データポイントは線で接続され、時間の経過に伴うパターンと傾向を特定できます。", + "2": "時系列チャートには、いくつかの利点と実用的なアプリケーションがあります。" + }, + "list": { + "0": "傾向分析: 時系列グラフは、データ内の長期的な傾向を特定および分析するのに役立ちます。これは、データが将来どのように振る舞うかを予測し、情報に基づいた決定を下すのに役立ちます。", + "1": "季節パターンの識別: 多くのデータセットには、ホリデーシーズン中の売上や農業生産の季節的な変動など、時間とともに定期的に繰り返される季節的なパターンがあります。時系列チャートは、これらの季節的なパターンを特定し、データへの影響を理解するのに役立ちます。", + "2": "変化と異常の検出: 時系列グラフを観察することで、データ内の急激な変化や異常を特定できます。これらの変化は、さらなる調査と分析が必要な重要または異常なイベントを示している可能性があります。", + "3": "モデリングと予測: 時系列グラフは、モデルと予測を開発するための基本的なツールです。過去のパターンを見ることで、関係を捉え、将来に関する予測を行う数学的または統計的モデルを構築できます。", + "4": "比較分析: 時系列チャートは、同じ期間に収集された異なるデータセットを比較するためにも使用されます。これは、観測された変数間の違い、類似性、および関係を特定するのに役立ちます。" + }, + "end": { + "0": "時系列チャートは、時間の経過に伴うデータの変化を分析および理解するための不可欠なツールです。傾向、季節的なパターン、変化、および予測に関する貴重な情報を提供し、情報に基づいた決定と比較分析を可能にします。" + } + }, + "index-info": "選択するインデックスは一意の系列を含み、表示する列の隣のインデックスを選択してはいけません", + "form": { + "index": "インデックス" + } + }, + "time-series": { + "warning": { + "index": "このデータフレームは、一意の値を持つ特性の条件を満たしていないため、適切な視覚化を許可しません" + } + }, + "violin-plots": { + "warning": { + "index": "設定でバイオリン図に使う列を1つ以上選択してください。" + }, + "title": "バイオリンプロット", + "description": { + "intro": { + "0": "バイオリンプロットは、箱ひげ図の特徴と確率密度関数を組み合わせた視覚的表現です。このタイプのチャートは、データの分布の詳細なビューを提供し、単一のチャートで複数のグループまたはカテゴリを比較できます。", + "1": "バイオリンチャートの外観はバイオリンの形状に似ています。データのメジアンを表す中心線と、確率密度分布を表す両側の2つの陰影領域があります。これらの陰影領域は、中心線に沿って対称性を持ち、データの対称性または非対称性を反映します。", + "2": "バイオリンプロットの形状は、データの分布に関する情報を提供します。たとえば、特定のセクションのバイオリンプロットが広いほど、その領域のデータ密度が高いことを示し、セクションが狭いほど、密度が低いことを示します。さらに、バイオリンチャートは、複数のバイオリンをグループ化または重ね合わせることで、異なるグループまたはカテゴリの視覚的な比較を可能にします。", + "3": "バイオリンプロットには、いくつかの実用的なアプリケーションがあります。" + }, + "list": { + "0": "分布の比較: バイオリンプロットを使用すると、異なるグループまたはカテゴリ間のデータ分布を比較できます。これは、データの形状、分散、および傾向の違いや類似性を特定するのに役立ちます。", + "1": "外れ値の識別: バイオリンプロットは、データ内の外れ値または極値の存在に関する視覚的な情報を提供します。これらの値は、陰影領域の外側のポイントとして表され、追加の分析が必要な異常な観測を示している可能性があります。", + "2": "確率密度の可視化: バイオリンプロットは、データの確率密度のグラフィカルな表現も提供します。これにより、高密度または低密度の領域、および分布の可能なバイアスまたは非対称性を簡単に特定できます。", + "3": "効果的なデータ通信: バイオリンチャートは、視覚的に魅力的な方法でデータの分布に関する複雑な情報を伝達するための効果的な方法です。情報を簡潔に要約し、非技術的な聴衆に重要なパターンと特徴を伝えるのに役立ちます。" + }, + "end": { + "0": "バイオリンプロットは、データ分布を視覚化および比較するための便利なツールです。データの形状、分散、対称性、および外れ値の存在を分析でき、複数のグループまたはカテゴリ間の比較が必要な場合に特に役立ちます。その魅力的で簡潔なグラフィカルな表現は、複雑な情報を理解しやすい方法で伝達するための効果的なツールになります。" + } + } + }, + "select-plot": "グラフの種類" + }, + "face-api": { + "years": "年齢", + "neutral": "ニュートラル", + "happy": "幸せ", + "sad": "悲しい", + "angry": "怒っている", + "fearful": "恐れている", + "disgusted": "嫌悪", + "surprised": "驚いている" + }, + "pages": { + "version": { + "title": "バージョン", + "app": "アプリのバージョン", + "environment": "環境・モード", + "backend": "使用中のバックエンド", + "runtime": "このインストール", + "changes": "変更点", + "changes-text": "各バージョンでの変更はすべてリポジトリの履歴に記録されています。", + "commits": "変更履歴(コミット)", + "releases": "公開されたバージョン", + "dependencies": "依存関係", + "dependencies-help": "アプリが依存しているライブラリと、package.jsonで指定しているバージョンです。", + "runtime-dependencies": "アプリ", + "dev-dependencies": "開発用", + "package": "パッケージ", + "declared": "指定バージョン", + "search": "パッケージを検索", + "no-results": "検索に一致するパッケージはありません。" + }, + "index": { + "tabular-classification": { + "1-title": "表形式分類", + "1-description-1": "分類とは、その特徴(独立変数)から要素(従属変数)が属するクラスを決定するタスクです。", + "1-description-2": "予測タスクであり、その値が分類される要素が属することができる異なるクラスである離散変数を持ちます。", + "1-button": "事前訓練済みモデル", + "2-title": "ネットワークアーキテクチャの設計、作成、および編集", + "2-description-1": "このツールを通じて、マルチクラスデータを分類するためのニューラルネットワークを作成できます。", + "2-description-2": "カスタムアーキテクチャを設計、作成、トレーニング、および評価するには、以下が必要です。", + "2-description-list": { + "1": "レイヤーの数、その活性化関数を定義します。", + "2": "学習率を定義します。", + "3": "エポック数を定義します。", + "4": "オプティマイザーを定義します。", + "5": "損失関数を定義します。", + "6": "メトリクス関数を定義します。" + }, + "2-button": "モデルを作成して訓練する" + }, + "regression": { + "1-title": "回帰", + "2-title": "ネットワークアーキテクチャの設計、作成、および編集", + "1-description-1": "回帰とは、その特徴(独立変数)から特定の数値(従属変数)を決定するタスクです。", + "1-description-2": "出力として連続変数を持つ予測タスクであり、データに最もよく適合し、独立変数に基づいて従属変数の数値を予測できる直線を見つけることを目的としています。", + "1-button": "事前訓練済みモデル", + "2-description-1": "このツールを通じて、予測を行うためのニューラルネットワークを作成できます。", + "2-description-2": "モデルで使用される独立変数を定義し、予測しようとしている数値である従属変数を定義します。", + "2-description-3": null, + "2-description-list": { + "1": "レイヤーの数、その活性化関数を定義します。", + "2": "学習率を定義します。", + "3": "エポック数を定義します。", + "4": "オプティマイザーを定義します。", + "5": "損失関数を定義します。", + "6": "メトリクス関数を定義します。", + "title": "回帰を適用し、変数間の関係をモデル化するには、次の手順に従う必要があります。" + } + }, + "object-detection": { + "1-title": "物体認識", + "1-description-1": "物体の分類とは、その違いと類似性に従って要素を整理することから成ります。", + "1-description-2": "これらのモデルは、各物体を特徴づけるものを少しずつ学習できるように、さまざまな画像を多数使用して訓練されます。", + "1-button": "事前訓練済みモデル", + "2-title": "物体認識" + }, + "image-classification": { + "1-title": "画像分類", + "1-description-1": "画像分類は、古典的な分類と同じ方法で、1つ以上の独立変数に応じて従属変数が属するクラスを決定するのに役立ちます。", + "1-button": "事前訓練済みモデル", + "2-title": "ネットワークアーキテクチャの設計、作成、および編集", + "2-description-1": "このツールを通じて、マルチクラスデータを分類するためのニューラルネットワークを作成できます。", + "2-description-2": "カスタムアーキテクチャを設計、作成、トレーニング、および評価するには、以下が必要です。", + "2-description-list": { + "1": "レイヤーの数、その活性化関数を定義します。", + "2": "学習率を定義します。", + "3": "エポック数を定義します。", + "4": "オプティマイザーを定義します。", + "5": "損失関数を定義します。", + "6": "メトリクス関数を定義します。" + }, + "2-button": "モデルを作成して訓練する" + }, + "hero": { + "text": "Nets4Learning は、ニューラルネットワークの仕組みを学ぶためのウェブプラットフォームです。タスクを選び、ネットワークを設計し、学習させて試すまでを、インストール不要でブラウザだけで行えます。学生と教員向けに作られています。" + }, + "clustering": { + "1-title": "クラスタリング", + "1-description-1": "各行が何かを教えずにデータをグループ分けします(教師なし学習)。k-meansは互いに似た行のk個のグループを探します。", + "1-description-2": "グループが少しずつできあがる様子を見られます。本当のクラスがあるデータセットでは、見ていないのにグループがクラスと似ているかもわかります。", + "1-button": "データセットを選ぶ" + }, + "time-series": { + "1-title": "時系列", + "1-description-1": "時系列(毎月の乗客数、毎日の気温など)の次の値を、それまでの値から予測します。ネットワークは過去の値のウィンドウから学習します。", + "1-description-2": "3 つの代表的な系列(航空旅客数、メルボルンの気温、太陽黒点)で学習済みのモデルを試せます。学習で見ていない系列の最後の部分をどう予測するか、最も単純な予測(直前の値や 1 季節前の値を繰り返す)より良いか、そしてその先に何が来るかが分かります。", + "1-button": "学習済みモデル", + "2-title": "系列を予測するアーキテクチャの設計・作成・編集", + "2-description-1": "このツールでは、系列の次の値をそれまでの値から予測するニューラルネットワークを、例の系列または自分の系列で作成できます。", + "2-description-2": "独自のアーキテクチャを設計・作成・学習・評価するには、次のことを行います。", + "2-description-list": { + "1": "ウィンドウを決める:ネットワークが見る直前の値の数。", + "2": "テストのために取り分ける系列の最後の割合と、差分を取るかどうかを決める。", + "3": "層の数、種類(Dense または再帰型:SimpleRNN、LSTM、GRU)、活性化関数を決める。", + "4": "学習率を決める。", + "5": "エポック数とバッチサイズを決める。", + "6": "オプティマイザと損失関数を決める。" + }, + "2-button": "モデルを作成して学習する" + } + }, + "contribute": { + "title": "貢献する", + "github": { + "title": "GitHubのプロジェクト" + }, + "license": { + "title": "ライセンス", + "text": "コードはMITライセンスです。著作権表示を残せば、自由に使用、複製、改変、配布できます。第三者のデータセットやモデルにはそれぞれのライセンスがあり、各説明に記載されています。", + "full": "ライセンスの全文" + }, + "intro": "Nets4Learningは、ハエン大学の研究グループSIMIDATによるMITライセンスのフリーソフトウェアです。バグの報告、改善の提案、翻訳、データセットやモデルの追加、コードの改善など、どんな協力も歓迎します。", + "ways": { + "title": "協力する方法", + "issues": { + "title": "バグを報告する、改善を提案する", + "text": "GitHubでissueを作成し、何が起きたか、どのページでどのブラウザーを使っていたか、またはアプリにどんな機能がほしいかを教えてください。", + "link": "issueを作成する" + }, + "translate": { + "title": "アプリを翻訳する", + "text": "テキストはpublic/localesに言語ごとに1ファイル(スペイン語、英語、日本語)、マニュアルはpublic/docsにあります。修正でも新しい言語でも助かります。", + "link": "翻訳を見る" + }, + "datasets": { + "title": "データセットやモデルを追加する", + "text": "それぞれがタスクのmodelsフォルダーにあるクラスで、MODEL_KEYS.tsのキー、DATA_MODEL.tsのメニュー項目、テキスト、ファイルを持ちます。", + "link": "タスクを見る" + }, + "code": { + "title": "コードを改善する", + "text": "リポジトリをフォークし、変更を加えたブランチを作ってプルリクエストを作成してください。統合する前に自動テストが確認します。", + "link": "プルリクエストを見る" + } + }, + "setup": { + "title": "自分のパソコンで動かす", + "requirements": "Node.js 22以降とpnpm 12が必要です。pnpmの正確なバージョンはCorepackがインストールします。", + "url": "アプリの場所:", + "scripts": [ + "保存すると再読み込みされる開発サーバー", + "単体テスト(Vitest)を1回実行", + "Netlify版でのブラウザーテスト(Playwright)", + "ESLintによるコードチェック", + "型を確認してSIMIDAT版をビルド" + ] + }, + "checklist": { + "title": "変更を送る前に", + "items": [ + "コミットはConventional Commits(feat:、fix:、docs:など)で書いてください。commitlintが確認します。", + "pnpm lint、pnpm test run、pnpm build:simidatを実行してください。GitHubのチェックではpnpm test:e2eも実行されます。", + "インターフェースの新しいテキストは、3つの翻訳ファイルすべてに入れてください。", + "データセットやモデルを追加する場合は、その説明に出典とライセンスを記載してください。" + ] + }, + "cite": { + "title": "論文を引用する", + "text": "授業、課題、論文でNets4Learningを使う場合は、このプラットフォームについての論文を引用してください。", + "copy": "BibTeXをコピー", + "copied": "コピーしました" + }, + "docs": { + "title": "技術文書", + "text": "コードに手を加えたい人のための、リポジトリのガイドです(英語)。", + "i18n": "翻訳(i18n)", + "directory-structure": "フォルダー構成", + "introduction": "表形式データの分類:はじめに", + "add-entry": "表形式データの分類:データセットの追加", + "create-model": "表形式データの分類:モデルの作成" + } + }, + "menu-selection-dataset": { + "0-tabular-classification": { + "csv": "データセットをアップロード", + "csv-text": ".csv、.arff、.json、.jsonl、.parquet 形式のデータセットファイルをアップロード" + }, + "form-description-1": "学習に使うデータセットを選ぶか、自分のデータセットをアップロードしてください。", + "form-label": "データセットを選択", + "form-option-_-1": "データセットを選択", + "form-upload-description": "次に、必要に応じて独自のアーキテクチャをロードできます。そうしない場合は、続行をクリックすると、デフォルトの例のアーキテクチャがロードされます。", + "form-submit": "続行", + "1-regression": { + "csv": "データセットをアップロード", + "csv-text": ".csv、.arff、.json、.jsonl、.parquet 形式のデータセットファイルをアップロード" + }, + "upload-text": "自分のデータセット(CSV、ARFF、JSON、JSONL、Parquet)をアップロードし、学習の前に準備します。", + "own-dataset": "自分のデータセット", + "example-datasets": "サンプルのデータセット", + "clustering": { + "csv": "CSVをアップロード" + }, + "time-series": { + "csv": "系列をアップロード" + } + }, + "menu-selection-model": { + "form-description-1": "作業する訓練済みモデルを選択します。", + "form-description-2": "-", + "form-label": "事前訓練済みモデルを選択", + "form-option-_-1": "事前訓練済みモデルを選択", + "form-submit": "続行" + }, + "playground": { + "form": { + "select-parameter": "パラメータを選択", + "parameter": "パラメータ", + "parameter-integer": "整数パラメータ", + "parameter-decimal": "小数パラメータ", + "parameter-float": "単精度浮動小数点パラメータ", + "parameter-double": "倍精度浮動小数点パラメータ", + "parameter-categorical": "カテゴリパラメータ", + "data-to-check": "テストするデータ", + "vector-to-check": "テストするベクトル", + "button-check-result": "予測", + "type-categorical": "カテゴリ、{{count}} 個の値", + "type-integer": "整数", + "type-decimal": "小数", + "range": "データ内: {{min}} – {{max}}" + }, + "0-tabular-classification": { + "general": { + "model": "モデル", + "description-input": "データエントリの説明", + "dataframe-processed-help": "カテゴリ値をそれぞれ数値に変換した同じデータです(LabelEncoder。対応は「属性」と「クラス」にあります)。モデルはこの形でデータを受け取ります。最後の列が予測すべきクラスです。", + "description-features": "特徴量編集フォーム", + "description-data": "フォームデータ", + "description-vector": "データベクトル", + "explainability": "モデルの解釈性", + "select-class": "クラスを選択", + "n-samples": "サンプル数", + "n-samples-help": "KernelSHAP が使用するサンプル数", + "calculating": "計算中...", + "show-explain": "説明を表示", + "hide-explain": "説明を非表示", + "n-instances": "集約するインスタンス数", + "n-instances-help": "グローバル重要度(平均 |SHAP|)の計算に集約するデータセットのインスタンス数", + "show-global": "グローバル重要度を表示", + "hide-global": "グローバル重要度を非表示", + "no-data": "グローバル重要度を計算するためのデータセットがありません", + "sort-order": "並び替え", + "sort-desc": "重要度の高い順", + "sort-asc": "重要度の低い順", + "sort-none": "元の順序", + "chart-type": "グラフの種類", + "chart-bar": "棒グラフ(平均 |SHAP|)", + "chart-beeswarm": "ビースウォーム", + "beeswarm-shap-value": "SHAP 値", + "beeswarm-feature-value": "特徴量の値", + "beeswarm-low": "低", + "beeswarm-high": "高", + "explain-panel-title": "説明可能性", + "explain-panel-local-title": "局所的な説明(1つのインスタンス)", + "explain-panel-local-body": "SHAP は、この予測とモデルの平均予測(基準値)との差を各特徴量に分配することで、1つの予測を説明します。各バーは、特徴量がどれだけ、どの方向に作用するかを示します。正の値は選択したクラスに向かって、負の値はそれに反して作用します。", + "explain-panel-local-body-regression": "SHAP は、予測値とモデルの平均予測(基準値)との差を各特徴量に分配することで、1つの予測を説明します。各バーは、特徴量がどれだけ、どの方向に作用するかを示します。正の値は予測値を上げ、負の値は予測値を下げます。", + "explain-panel-global-title": "グローバル重要度(すべてのインスタンス)", + "explain-panel-global-body": "グローバル重要度は、多数の局所的な説明を集約します。棒グラフは絶対値の平均(平均 |SHAP|)、つまり各特徴量が平均してどれだけ重要かを示します。ビースウォームは、各点を特徴量の値で色付けし、効果の方向とばらつきを加えて示します。順列重要度などの他の手法では、特に特徴量同士が関連している場合、特徴量の順位が多少異なることがあります。手法ごとに重要度の測り方が違うためです。" + }, + "0_upload": { + "upload": "アップロード", + "upload-your-model": "モデルをロード", + "upload-your-model-description": "モデルをロードするには、.jsonファイルと.binファイルをアップロードする必要があることに注意してください", + "button-upload-your-model": "モデルをロード" + }, + "generator": { + "manual": { + "title": "モデルジェネレーターマニュアル", + "details-edit-layers": { + "title": "レイヤーエディタ", + "text-0": "ニューラルネットワークのレイヤーを編集できます。開始時または終了時に「レイヤーを追加」ボタンを押して、必要な数だけ追加できます。", + "list": { + "0": "レイヤーニューロン:
レイヤー内の各ニューロンには、出力値を重み付けする一連の関連付けられた重みがあります。
レイヤー内のニューロンの数を編集できます。", + "1": "活性化関数:
ニューロンの活性化関数は、受信した入力に基づいて出力を計算する数学関数を指します。各レイヤーのニューロンの活性化関数を編集できます。" + } + }, + "details-hyper-parameters-editor": { + "title": "ハイパーパラメータエディタ", + "text-0": "モデルの作成に必要な一般的なパラメータを編集できます。
これらのパラメータは次のとおりです。", + "list": { + "0": "学習率:
学習の各ステップでネットワークの重みをどれだけ更新するかを表します(例: 0.01)。", + "1": "エポック数:
トレーニング中にトレーニングデータセットがネットワークに提示される回数(数が多いほど、トレーニングに時間がかかります)。", + "2": "テストセットサイズ:
モデルテスト(テストデータ)に使用されるデータセットのパーセンテージ。残りのデータはネットワークトレーニング(トレーニングデータ)に使用されます。", + "3": "オプティマイザー:
ネットワークの重みを調整するために使用される関数です。", + "4": "損失関数:
トレーニング中のモデルの効率を測定するための誤差計算方法です。", + "5": "メトリクス関数:
テストデータを使用した機械学習モデルのパフォーマンスを評価するために使用される平均評価です。" + } + }, + "details-hyper-parameters-info": { + "title": "ハイパーパラメータ情報", + "list": { + "0": "学習率:
学習率は、トレーニング中に計算された誤差に応じて、ニューラルネットワークの重みがどの程度更新される必要があるかを決定するパラメータです。", + "1": "エポック数:
エポック数は、トレーニングプロセス中にトレーニングデータがニューラルネットワークに提示される回数を指します。各反復は、計算された誤差の関数としてのネットワークの重みの更新を意味します。", + "2": "テストセットサイズ:
テストセットのサイズは、トレーニング後にニューラルネットワークのパフォーマンスを評価するために使用されるデータの量を指します。このデータセットはニューラルネットワークのトレーニングには使用されず、新しいデータに一般化するネットワークの能力を測定するために使用されます。", + "3": "オプティマイザー:
オプティマイザーは、トレーニング中に計算された誤差に応じてニューラルネットワークの重みを更新するために使用されるアルゴリズムです。一般的なオプティマイザーの例には、確率的勾配降下法(SGD)、Adam、およびAdagradがあります。", + "4": "損失関数:
損失関数は、ニューラルネットワークの予測と実際の出力との間の不一致を測定する尺度です。トレーニング中にニューラルネットワークを最適化するために使用され、交差エントロピーや平均二乗誤差など、さまざまな損失関数があります。" + } + }, + "details-create-and-train-models": { + "title": "モデルを作成して訓練する", + "text-0": "前のすべてのフィールドが入力されたら、「モデルを作成して訓練する」ボタンを押してモデルを作成できます。", + "text-1": "メトリック関数 Accuracy でモデルを訓練した場合、バイザーに2つのグラフが表示されます。私たちにとって最も関連性の高いのは下のグラフです。tensorflow.jsでは、accとval_accは、ニューラルネットワークのモデルのトレーニングで一般的に使用される評価メトリクスです。
Accは、トレーニングデータセットにおけるモデルの精度(Accuracy)を表します。精度は、正しい予測の数を予測の総数で割ったものとして定義されます。
Val_accは、検証データセットにおけるモデルの精度を表します。検証は、トレーニング中に見られなかった新しいデータに一般化するモデルの能力を評価するために使用されます。", + "text-2": "検証の精度は、モデルがトレーニングデータに過度に適合し、新しいデータにうまく一般化できない場合に発生する過剰適合(overfitting)を検出するために重要です。" + }, + "details-export-models": { + "title": "モデルをエクスポート", + "text-0": "モデルを正しく作成した場合、生成されたモデルのテーブルにエントリが追加されます。生成されたモデルをエクスポートしてローカルに保存できます。" + }, + "details-prediction": { + "title": "分類", + "text-0": "最終フォームでは、クラスを決定するために使用される主要な特徴量を選択できます。", + "text-1": "「分類する」ボタンを押すと、モデルは入力特徴量から例のクラスを予測し、各クラスの確率を表示します。" + } + } + } + }, + "generator": { + "prediction": { + "class_id_name": "ターゲットのID {{class_target_id}} はクラス {{name}} に対応します" + }, + "layer-design": "レイヤー設計", + "neural_network_modes": { + "title": "視覚化モード", + "compact": "コンパクトモード", + "extend": "拡張モード" + }, + "dataset": { + "title": "データセット", + "upload-dataset": "データセットをアップロード", + "attributes": { + "title": "属性", + "int32": "数値", + "float32": "小数", + "string": "テキスト", + "label-encoder": "ラベルエンコーダ", + "one-hot-encoder": "OneHotエンコーダ", + "classes": "クラス" + }, + "details": { + "dataframe-processed": "処理済みデータフレーム", + "description-original": "元のデータフレームの説明", + "description-processed": "処理済みデータフレームの説明", + "data": "データセット情報", + "info": "情報" + } + }, + "layers": { + "title": "レイヤー設計", + "page-info": "netron.appにアクセスしてトポロジ全体を視覚化できます" + }, + "editor-layers": { + "title": "レイヤーエディタ", + "add-layer-start": "最初にレイヤーを追加", + "add-layer-end": "最後にレイヤーを追加", + "delete-layer": "レイヤー {{index}}を削除", + "move-up": "層 {{index}} を上へ", + "move-down": "層 {{index}} を下へ", + "move-group": "層 {{index}} の順番", + "moved": "層 {{index}} を {{position}} 番目に移動しました。", + "drag": "ドラッグして層 {{index}} を移動", + "drag-help": "順番を変えるには、各層の左にあるハンドルをドラッグするか、層を開いて「上へ」「下へ」を使います。", + "layer-id": "レイヤー {{index}}", + "kernel-size": "カーネルサイズ", + "kernel-size-placeholder": "レイヤーのカーネルサイズを入力してください", + "filters-size": "フィルターサイズ", + "filters-size-placeholder": "レイヤーのフィルターを入力してください", + "units": "レイヤーニューロン", + "units-placeholder": "レイヤーのニューロン数を入力してください", + "activation-function-select": "活性化関数を選択", + "activation-function-info": "関数をアクティブ化するために使用されるオプティマイザーになります", + "strides": "ストライド", + "strides-placeholder": "レイヤーのストライドを入力してください", + "pool-size": "プールサイズ", + "pool-size-placeholder": "レイヤーのプールサイズを入力してください", + "layer-class": "層の種類", + "removed": "層 {{index}} を削除しました。層の上の「元に戻す」で取り消せます。", + "removed-short": "層 {{index}} を削除しました。", + "restored": "層 {{index}} を元に戻しました。", + "undo": "元に戻す" + }, + "editor-feature-selector": { + "title": "特徴量セレクター", + "feature-selector-x": "特徴量セレクター / セット (X)", + "feature-selector-y": "特徴量セレクター / ターゲット (Y)", + "add-feature": "特徴量を追加", + "delete-feature": "特徴量 {{value}}を削除" + }, + "general-parameters": { + "title": "ハイパーパラメータエディタ", + "learning-rate": "学習率", + "learning-rate-placeholder": "学習率を入力してください", + "learning-rate-info": "学習の各ステップで重みをどれだけ更新するかを表します。大きい値は学習が速いものの収束しないことがあり、小さい値は安定しますが時間がかかります。", + "number-of-epochs": "エポック数", + "number-of-epochs-placeholder": "エポック数", + "number-of-epochs-info": "値が高いほど、トレーニングの実行に時間がかかります", + "train-rate": "テストセットサイズ", + "train-rate-placeholder": "テストセットのサイズを入力してください", + "train-rate-info": "テストセットサイズの0から100までの値(パーセンテージ)", + "optimizer-id": "オプティマイザーを選択", + "optimizer-id-info": "誤差を修正するために使用されるオプティマイザーになります。", + "loss-id": "損失関数を選択", + "loss-id-info": "ニューロンの誤差を評価するために使用される関数になります。", + "metrics-id": "メトリクスを選択", + "metrics-id-info": "トレーニング評価に使用されるメトリクスタイプになります。", + "test-size": "テストセットサイズ", + "test-size-placeholder": "テストセットサイズ", + "test-size-info": "テストセットサイズの0から100までの値(パーセンテージ)", + "delete-metric": "メトリクス関数 {{index}}を削除", + "add-metric": "メトリクス関数を追加", + "metric-id-__index__": "メトリクス {{index}}", + "metric-id-select": "メトリクス関数を選択", + "metric-id-info": "メトリクス関数の一つになります", + "loss-group-classification": "分類", + "loss-group-regression": "回帰", + "batch-size": "バッチサイズ", + "batch-size-placeholder": "1 バッチあたりの例の数", + "batch-size-info": "重みを 1 回更新するのに使うウィンドウの数です。小さいバッチではノイズの多い学習になり、大きいバッチでは各エポックが速くなります。" }, - "render-label": "{{label}}(信頼度 {{score}}%)" - }, - "face-api": { - "title": "FaceAPI - 顔の表情", - "description": { - "text-0": "顔の管理のためにグループ化された異なるタイプの複数のニューラルネットワーク。複数の顔の検出、年齢、感情、顔のマークの検出、異なる種類の顔を比較するための記述子としてのキーポイントの抽出を可能にします。", - "details-input": { - "title": "入力データ", - "text-0": "カラー画像またはビデオ(Webカメラ)。" + "loaded": "ロード済み", + "load": "ロード", + "waiting-for-file": "始めるにはデータファイル(CSV、ARFF、JSON、JSONL、Parquet)をアップロードしてください。", + "waiting-for-process": "続けるにはデータセットを処理してください。", + "waiting-for-training": "まだ学習済みモデルはありません。ネットワークを設定して学習させると、ここに表示されます。", + "models": { + "title": "モデル", + "history-train": "トレーニング履歴", + "train": "トレーニング履歴", + "button-submit": "モデルを訓練", + "open-visor": "バイザーを開く", + "close-visor": "バイザーを閉じる", + "export-current-model": "現在のモデルをエクスポート" + }, + "table": { + "id": "ID", + "load": "ロード", + "learning-rate": "学習率", + "number-of-epochs": "エポック数", + "train-rate": "テストセットサイズ", + "layers": "レイヤー", + "optimizer-id": "オプティマイザー", + "loss-id": "損失", + "metric-id": "メトリクス", + "download": "ダウンロード" + }, + "dynamic-form-dataset": { + "title": "分類", + "text-0-__column_name_target__": "分類したい例({{column_name_target}})の各入力特徴量の値を入力するか、上のセレクターでデータセットのエンティティを選んでください。", + "select-option": "オプションを選択", + "input-data": "テストするデータを入力", + "input-vector": "テストするベクトルを入力", + "test-vector": "テストするベクトル", + "test-input-data": "フォームデータ", + "test-input-vector": "テストするベクトル", + "selector-entity": "エンティティを選択", + "search-entity": "番号またはクラスで検索…", + "entity-count": "{{total}} 件中 {{shown}} 件", + "no-entity": "検索に一致するものはありません", + "selector-model": "モデルを選択", + "classify-button": "分類する" + }, + "list-models-generated": "生成されたモデルのリスト", + "visor": { + "title": "バイザーの設定", + "rmse": "RMSE", + "val_rmse": "VAL RMSE", + "mae": "MAE", + "val_mae": "VAL MAE", + "history-train": "トレーニング履歴", + "train": "トレーニング履歴", + "summary": "概要", + "scatterplot": { + "__feature____target__": "{{feature}} x {{target}}" }, - "details-output": { - "title": "出力データ", - "text-0": "元の入力要素と同じで、各感情の表現度を示すパーセンテージと、その人の年齢を示すボックスが表示されます。", - "list": { - "0": "年齢", - "1": "ニュートラル", - "2": "幸せ", - "3": "悲しい", - "4": "怒っている", - "5": "恐れている", - "6": "嫌悪", - "7": "驚いている", - "bounding": "境界ボックス" + "original-vs-predictions": "元のデータ/予測", + "model": "モデル", + "dataset": "データセット", + "predictions": "予測結果", + "predicted": "予測", + "confusion-matrix": "混同行列", + "line-chart": "折れ線グラフ" + }, + "waiting-for-models": "予測するには、まずモデルを学習させてください。", + "classify": { + "waiting": "例を分類すると、ここに結果が表示されます。", + "predicted-class": "予測されたクラス", + "confidence": "確率 {{value}}", + "chart-title": "各クラスの確率", + "chart-title-output": "各クラスに対するネットワークの出力", + "chart-help": "強調表示されたバーがモデルの選んだクラス(最も確率の高いもの)です。モデルが迷っているときは、いくつかのバーが同じくらいの高さになります。", + "chart-help-output": "最後の層がソフトマックスを使っていないため、これらの値は確率ではありません。モデルは値が最も高いクラス(強調表示されたバー)を選びます。", + "axis-class": "クラス", + "axis-probability": "確率 (%)", + "axis-output": "出力", + "select-image": "データセットから画像を選択", + "actual-class": "実際のクラス: {{label}}", + "chart-title-top": "最も確率の高い {{count}} クラス", + "chart-help-top": "モデルはさらに多くのクラスを区別します。ここでは確率の高いクラスだけをその確率とともに表示しています。", + "hit": "正解", + "miss": "不正解", + "test-image": "テスト画像", + "class": "クラス" + }, + "waiting-for-prediction": "予測すると、ここに結果が表示されます。", + "training": { + "epoch": "学習中… エポック {{epoch}} / {{total}}", + "preparing": "データとモデルを準備しています…", + "stop": "停止", + "stopping": "停止しています…", + "curves-title": "学習曲線", + "curves-model": "曲線を表示するモデル", + "curves-compare": "モデルを比較", + "compare-pick": "比較するモデル(最大{{max}}個)", + "compare-pick-more": "比較するには、モデルを2つ以上選んでください。", + "compare-same": "ハイパーパラメータは同じです。違いは偶然によるものです(各ネットワークの初期の重みとデータの分け方)。", + "compare-one": "変わっているのは{{name}}だけです。結果の違いは主にそれによるものです。", + "compare-some": "複数の項目が変わっています({{names}})。一度に複数を変えると、どれが影響したのかわかりません。それぞれの効果を知るには、学習ごとに1つだけ変えてみましょう。", + "compare-quote": "「{{name}}」", + "compare-caption": "各モデルのハイパーパラメータ(変わっている項目は強調表示)と最後のエポックの値(括弧内は検証データでの値)。", + "compare-parameter": "パラメータ", + "compare-changed": "変更", + "compare-final": "最終的な{{name}}", + "epoch-axis": "エポック", + "train": "学習", + "validation": "検証", + "best": "最良", + "best-title": "最終エポックの検証損失が最も小さいモデル", + "confusion-title": "混同行列(検証)", + "confusion-accuracy": "正解: {{accuracy}}(学習に使っていない {{total}} 件中 {{correct}} 件)。", + "confusion-real": "実際のクラス", + "confusion-predicted": "予測クラス", + "confusion-total": "合計", + "confusion-recall": "再現率", + "confusion-precision": "適合率", + "confusion-legend": "各セルは、実際のクラス(行)の例のうち列のクラスと予測された件数と、その行に占める割合を示します。緑は正解、赤は誤りで、色が濃いほど件数が多いことを表します。", + "curve-description": "{{epochs}} エポックの {{name}}:学習データでは {{first}} から {{last}}。", + "curve-description-validation": "検証データでは {{first}} から {{last}}。", + "announce-start_other": "学習を開始しました:{{count}} エポック", + "announce-stopped": "エポック {{epoch}}/{{total}} で学習を停止しました。そこまでのモデルを保存します", + "announce-error": "学習を完了できませんでした", + "go-to-result": "結果へ移動", + "curve-data": "各エポックの {{name}}", + "remaining": "残り約 {{time}}", + "last-run_other": "前回の学習には {{time}} かかりました({{count}} エポック、1 エポックあたり {{perEpoch}})。エポックを増やすと時間がかかりますが、いつでも停止できます。" + }, + "help": { + "learning-rate": "データのバッチごとに、オプティマイザーがネットワークの重みを修正する歩幅の大きさです。", + "epochs": "1 エポックは学習データ全体を 1 回通すことです。エポックを増やすと学習の機会が増えますが、過学習もしやすくなります。", + "test-size": "学習中に見ていない例でモデルを確認するために取り分けておくデータの割合(検証用)です。", + "optimizer": "誤差をもとに重みをどう変えるかを決めるアルゴリズムです。Adam は特に調整しなくてもよく機能します。", + "loss": "モデルがどれだけ間違えているかを測ります。学習はこの値をできるだけ小さくしようとします。", + "metric": "学習中にモデルの調子を知るために計算する指標(例: 正解率)です。重みの修正には使われません。", + "recall": "再現率(recall): このクラスに属する例のうち、モデルが正しく予測した割合。", + "precision": "適合率(precision): モデルがこのクラスと予測したうち、正しかった割合。", + "accuracy": "正解率(accuracy): 検証用の全例のうち、正しく予測できた割合。", + "batch-size": "ネットワークが重みを更新する前に見る例の数です。", + "units": "層にあるニューロンの数です。多いほど複雑な関係を学べますが、学習に時間がかかり、データを丸暗記することがあります。", + "activation": "各ニューロンが受け取った和に対して行う処理です。ReLU、シグモイド、tanh を使うと直線ではない関係を学べます。最後の層の softmax は確率をクラスに配分します。" + }, + "example-from-dataset": "データセットの例" + }, + "1-regression": { + "generator": { + "manual": { + "title": "モデルジェネレーターマニュアル", + "simple-regression": "単回帰", + "multiple-regression": "重回帰", + "details-edit-layers": { + "title": "レイヤーエディタ", + "text": { + "0": "ニューラルネットワークのレイヤーを編集できます。開始時または終了時に「レイヤーを追加」ボタンを押して、必要な数だけ追加できます。" + }, + "list": { + "0": "レイヤーニューロン:
レイヤー内の各ニューロンには、出力値を重み付けする一連の関連付けられた重みがあります。
レイヤー内のニューロンの数を編集できます。", + "1": "活性化関数:
ニューロンの活性化関数は、受信した入力に基づいて出力を計算する数学関数を指します。各レイヤーのニューロンの活性化関数を編集できます。" + } + }, + "details-hyper-parameters-editor": { + "title": "ハイパーパラメータエディタ", + "text": { + "0": "モデルの作成に必要な一般的なパラメータを編集できます。
これらのパラメータは次のとおりです。" + }, + "list": { + "0": "学習率:
学習の各ステップでネットワークの重みをどれだけ更新するかを表します(例: 0.01)。", + "1": "エポック数:
トレーニング中にトレーニングデータセットがネットワークに提示される回数(数が多いほど、トレーニングに時間がかかります)。", + "2": "テストセットサイズ:
モデルテスト(テストデータ)に使用されるデータセットのパーセンテージ。残りのデータはネットワークトレーニング(トレーニングデータ)に使用されます。", + "3": "オプティマイザー:
ネットワークの重みを調整するために使用される関数です。", + "4": "損失関数:
トレーニング中のモデルの効率を測定するための誤差計算方法です。", + "5": "メトリクス関数:
テストデータを使用した機械学習モデルのパフォーマンスを評価するために使用される平均評価です。" + } + }, + "details-hyper-parameters-info": { + "title": "ハイパーパラメータ情報", + "list": { + "0": "学習率:
学習率は、トレーニング中に計算された誤差に応じて、ニューラルネットワークの重みがどの程度更新される必要があるかを決定するパラメータです。", + "1": "エポック数:
エポック数は、トレーニングプロセス中にトレーニングデータがニューラルネットワークに提示される回数を指します。各反復は、計算された誤差の関数としてのネットワークの重みの更新を意味します。", + "2": "テストセットサイズ:
テストセットのサイズは、トレーニング後にニューラルネットワークのパフォーマンスを評価するために使用されるデータの量を指します。", + "3": "オプティマイザー:
オプティマイザーは、トレーニング中に計算された誤差に応じてニューラルネットワークの重みを更新するために使用されるアルゴリズムです。一般的なオプティマイザーの例には、確率的勾配降下法(SGD)、Adam、およびAdagradがあります。", + "4": "損失関数:
損失関数は、ニューラルネットワークの予測と実際の出力との間の不一致を測定する尺度です。トレーニング中にニューラルネットワークを最適化するために使用され、交差エントロピーや平均二乗誤差など、さまざまな損失関数があります。" + } + }, + "details-create-and-train-models": { + "title": "モデルを作成して訓練する", + "text": { + "0": "前のすべてのフィールドが入力されたら、「モデルを作成して訓練する」ボタンを押してモデルを作成できます。", + "1": "メトリック関数 Accuracy でモデルを訓練した場合、バイザーに2つのグラフが表示されます。私たちにとって最も関連性の高いのは下のグラフです。tensorflow.jsでは、accとval_accは、ニューラルネットワークのモデルのトレーニングで一般的に使用される評価メトリクスです。
Accは、トレーニングデータセットにおけるモデルの精度(Accuracy)を表します。精度は、正しい予測の数を予測の総数で割ったものとして定義されます。
Val_accは、検証データセットにおけるモデルの精度を表します。検証は、トレーニング中に見られなかった新しいデータに一般化するモデルの能力を評価するために使用されます。", + "2": "検証の精度は、モデルがトレーニングデータに過度に適合し、新しいデータにうまく一般化できない場合に発生する過剰適合(overfitting)を検出するために重要です。" + } + }, + "details-export-models": { + "title": "モデルをエクスポート", + "text": { + "0": "モデルを正しく作成した場合、生成されたモデルのテーブルにエントリが追加されます。生成されたモデルをエクスポートしてローカルに保存できます。" + } + }, + "details-plot-models": { + "title": "予測のプロット", + "text": { + "0": "このタスクには疎なグラフを使用できます。これにより、元のデータを点の雲で表し、線を使用してモデルの予測をプロットします。使用するアーキテクチャに応じて、特定の傾きを持つ直線、またはデータにより適合して湾曲する線が得られます。これを行うには、最初の値から最後の値まで、100個の離散的なx予測が作成されます。" + } } }, - "details-references": { - "title": "参照元" + "simple-regression": "単回帰", + "multiple-regression": "重回帰" + }, + "dataframe": { + "title": "処理済みデータフレーム", + "help": "カテゴリ値をそれぞれ数値に変換した同じデータです(LabelEncoder)。モデルに入る前に属性はスケーリングされます。{{target}} 列が予測すべき値です。" + }, + "selector-instance": { + "option": "インスタンスセレクター" + }, + "selector-model": { + "option": "モデルセレクター" + }, + "details": { + "description-processed": { + "dataset": "データフレーム情報", + "describe": "データフレームの説明" } + }, + "predict": { + "title": "予測", + "instance": { + "__index__": "インスタンス {{index}}" + }, + "model": { + "__index__": "モデル {{index}}" + }, + "button-submit": "予測", + "list-models-generated": "生成されたモデルのリスト", + "list-models": "生成されたモデルのリスト", + "list-instances": "インスタンスのリスト", + "predicted-value": "{{target}} の予測値", + "actual-value": "実際の値: {{value}}", + "error": "誤差: {{value}} ({{percent}})", + "input-details": "モデルへの入力(各段階)", + "choose-instance": "データセットのインスタンスを選ぶとフォームに入力されます。その後、値を変更できます。", + "no-models": "このデータセットには事前学習済みモデルがありません。別のデータセットを選ぶか、回帰のプレイグラウンドで独自のモデルを学習してください。", + "model-selector": "予測に使うモデル" + }, + "model-selector": { + "title": "モデルセレクター", + "option": "モデルを選択" } }, - "hand-sign": { - "title": "手話", - "description": { - "text-0": "手の検出とランドマーク検出のためのニューラルネットワーク。位置記述子と組み合わせて、アメリカ手話(ASL)またはスペイン手話(SSL)の可能なサインを分類するために使用されます。", - "details-input": { - "title": "入力データ", - "list": { - "0": "カラー画像またはビデオ(Webカメラ)。" + "3-image-classification": { + "generator": { + "manual": { + "title": "モデルジェネレーターマニュアル", + "details-edit-layers": { + "title": "レイヤーエディタ", + "text-0": "ニューラルネットワークのレイヤーを編集できます。開始時または終了時に「レイヤーを追加」ボタンを押して、必要な数だけ追加できます。", + "list": { + "0": "レイヤーニューロン:
レイヤー内の各ニューロンには、出力値を重み付けする一連の関連付けられた重みがあります。
レイヤー内のニューロンの数を編集できます。", + "1": "活性化関数:
ニューロンの活性化関数は、受信した入力に基づいて出力を計算する数学関数を指します。各レイヤーのニューロンの活性化関数を編集できます。" + } + }, + "details-edit-layers-more-info": { + "title": "追加情報レイヤー", + "text-0": "さらに、画像分類に焦点を当てた他の機械学習ネットワークに共通するレイヤーが2つあります。", + "list": { + "0": "dense
密な(完全に接続された)レイヤーを作成します。", + "1": "dropout
ドロップアウトは、トレーニング時間中の各更新で入力ユニットの分数率をランダムに0に設定することで構成され、過剰適合を防ぐのに役立ちます。", + "2": "embedding
正の整数(インデックス)を固定サイズの密なベクトルにマッピングします。例:[[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]", + "3": "flatten
Flattenレイヤーは、入力内の各バッチを1Dに平坦化します(出力を2Dにします)。", + "4": "permute
指定されたパターンに従って入力の次元を並べ替えます。", + "5": "repeatVector
入力を新しい次元でn回繰り返します。", + "6": "reshape
入力を特定の形状に再形成します。", + "7": "spatialDropout1d
ドロップアウトの空間1Dバージョン。" + } + }, + "details-hyper-parameters-editor": { + "title": "ハイパーパラメータエディタ", + "text-0": "モデルの作成に必要な一般的なパラメータを編集できます。
これらのパラメータは次のとおりです。", + "list": { + "0": "学習率:
学習の各ステップでネットワークの重みをどれだけ更新するかを表します(例: 0.01)。", + "1": "エポック数:
トレーニング中にトレーニングデータセットがネットワークに提示される回数(数が多いほど、トレーニングに時間がかかります)。", + "2": "テストセットサイズ:
モデルテスト(テストデータ)に使用されるデータセットのパーセンテージ。残りのデータはネットワークトレーニング(トレーニングデータ)に使用されます。", + "3": "オプティマイザー:
ネットワークの重みを調整するために使用される関数です。", + "4": "損失関数:
トレーニング中のモデルの効率を測定するための誤差計算方法です。", + "5": "メトリクス関数:
テストデータを使用した機械学習モデルのパフォーマンスを評価するために使用される平均評価です。" + } + }, + "details-hyper-parameters-info": { + "title": "ハイパーパラメータ情報", + "list": { + "0": "学習率:
学習率は、トレーニング中に計算された誤差に応じて、ニューラルネットワークの重みがどの程度更新される必要があるかを決定するパラメータです。", + "1": "エポック数:
エポック数は、トレーニングプロセス中にトレーニングデータがニューラルネットワークに提示される回数を指します。各反復は、計算された誤差の関数としてのネットワークの重みの更新を意味します。", + "2": "テストセットサイズ:
テストセットのサイズは、トレーニング後にニューラルネットワークのパフォーマンスを評価するために使用されるデータの量を指します。", + "3": "オプティマイザー:
オプティマイザーは、トレーニング中に計算された誤差に応じてニューラルネットワークの重みを更新するために使用されるアルゴリズムです。一般的なオプティマイザーの例には、確率的勾配降下法(SGD)、Adam、およびAdagradがあります。", + "4": "損失関数:
損失関数は、ニューラルネットワークの予測と実際の出力との間の不一致を測定する尺度です。トレーニング中にニューラルネットワークを最適化するために使用され、交差エントロピーや平均二乗誤差など、さまざまな損失関数があります。" + } + }, + "details-create-and-train-models": { + "title": "モデルを作成して訓練する", + "text-0": "前のすべてのフィールドが入力されたら、「モデルを作成して訓練する」ボタンを押してモデルを作成できます。", + "text-1": "メトリック関数 Accuracy でモデルを訓練した場合、バイザーに2つのグラフが表示されます。私たちにとって最も関連性の高いのは下のグラフです。tensorflow.jsでは、accとval_accは、ニューラルネットワークのモデルのトレーニングで一般的に使用される評価メトリクスです。
Accは、トレーニングデータセットにおけるモデルの精度(Accuracy)を表します。精度は、正しい予測の数を予測の総数で割ったものとして定義されます。
Val_accは、検証データセットにおけるモデルの精度を表します。検証は、トレーニング中に見られなかった新しいデータに一般化するモデルの能力を評価するために使用されます。", + "text-2": "検証の精度は、モデルがトレーニングデータに過度に適合し、新しいデータにうまく一般化できない場合に発生する過剰適合(overfitting)を検出するために重要です。" + }, + "details-export-models": { + "title": "モデルをエクスポート", + "text-0": "モデルを正しく作成した場合、生成されたモデルのテーブルにエントリが追加されます。生成されたモデルをエクスポートしてローカルに保存できます。" + }, + "details-prediction": { + "title": "分類", + "text-0": "最終フォームでは、クラスを決定するために使用される主要な特徴量を選択できます。", + "text-1": "「結果を表示」ボタンを押すと、要素の入力特徴量から出力クラスの予測が取得されます。" } + } + } + }, + "step-by-step": { + "title": "ステップごと", + "intro": "ネットワークはこうして学びます。例が左から入り、ネットワークを前向きに進み、どれだけ間違えたかを測り、その誤差が後ろ向きに戻って各重みを修正します。上で設計したネットワークで、初期の重みはランダムです。ニューロンをクリックすると計算が見られます。", + "intro-pretrained": "学習済みのこのモデルは、こうして答えを計算します。例が左から入り、ネットワークを前向きに進み、正しい答えと比べられます。後ろ向きでは、もう1ステップ学習したら各重みがどれだけ変わるかが見られます。ページのモデルは変わりません。ニューロンをクリックすると計算が見られます。", + "too-big": "このネットワークには入力を含めて{{nodes}}個のニューロンがあります({{detail}})。ステップごとの表示は、追えるように{{max}}個未満のときだけ描かれます。層エディターで層やニューロンを減らしてください。たとえば8個の隠れ層を2つにします。", + "too-big-pretrained": "このモデルには入力を含めて{{nodes}}個のニューロンがあります({{detail}})。ステップごとの表示は、追えるように{{max}}個未満のときだけ描かれます。このデータセットの学習ページなら、小さいネットワークで見られます。", + "not-dense": "このモデルは全結合層だけのネットワークではありません。ステップごとの表示は、その種類のネットワークだけを描きます。", + "mismatch": "最後の層のニューロンは{{units}}個ですが、ネットワークは{{classes}}個の出力を出す必要があります。ステップごとに見るには、層エディターで変更してください。", + "example": "例を選ぶ", + "search": "例を検索", + "no-results": "一致する例はありません", + "back": "前のフェーズ", + "next": "次へ", + "play": "再生", + "pause": "一時停止", + "ten": "10個の例でまとめて学習", + "speed": "速度", + "speeds": { + "slow": "遅い", + "normal": "普通", + "fast": "速い" + }, + "same-example": "同じ例を繰り返す", + "reset": "重みをリセット", + "reset-pretrained": "モデルの重みに戻す", + "legend": "青は正の値や重み、赤は負の値。濃いほど、太いほど大きい値です。オレンジは後ろ向きに戻るもの、つまりニューロンのデルタと重みの勾配です。", + "phase-count": "フェーズ {{current}} / {{total}}", + "phase-title": { + "input": "入力", + "forward": "前向き:第{{layer}}層", + "loss": "誤差", + "backward": "後ろ向き:第{{layer}}層", + "update": "重みの更新" + }, + "phase": { + "input": "例 {{row}} が入ります。学習のときと同じようにスケーリングされた{{count}}個の特徴が、入力ニューロンの値になります。", + "input-pretrained": "例 {{row}} が入ります。このモデルが受け取る形の{{count}}個の特徴が、入力ニューロンの値になります。", + "forward": "第{{layer}}層の各ニューロンは、各入力に接続の重みを掛けて、その積とバイアスを足し合わせ(z)、{{activation}} 活性化関数を適用します。強調された接続が関わっている部分です。", + "forward-softmax": "第{{layer}}層は入力に重みを掛けて足し合わせ(z)、softmax がその和を、クラスごとの確率(合計1)に変えます。", + "loss-classification": "ネットワークは正解の「{{target}}」に{{probability}}の確率を与えています。損失(交差エントロピー)は −log({{probability}}) = {{loss}} で、正解のクラスの確率が低いほど大きくなります。今の時点でネットワークは「{{predicted}}」と答えます。", + "loss-regression": "ネットワークの予測は{{prediction}}で、実際の値は{{actual}}です。ステップごとの表示では目標を0から1にスケーリングしており({{output}} と {{target}})、損失は二乗誤差 ({{output}} − {{target}})² = {{loss}} です。", + "loss-regression-raw": "ネットワークの予測は{{prediction}}で、実際の値は{{actual}}です。損失は二乗誤差 ({{output}} − {{target}})² = {{loss}} です。", + "backward-output": "後ろ向きの計算が始まります。各出力ニューロンのデルタは、和 z が変わったら損失がどれだけ変わるかを表します。そこに届く各重みの勾配は、デルタにその接続の入力を掛けたものです。オレンジの接続がそれです。", + "backward": "誤差は第{{layer}}層まで戻ります。各ニューロンのデルタは、次の層のデルタにそれらをつなぐ重みを掛けて足したものに、{{activation}} の導関数を掛けたものです。こうして各重みは、誤差にどれだけ関わったかがわかります。", + "update": "各重みは勾配と反対の向きに少し動きます。w ← w − η × g で、η = {{rate}} は学習率です。この例では、損失が{{before}}から{{after}}になります。学習とは、すべての例でこれをエポックごとに繰り返すことです。選んだオプティマイザーは、各ステップをもっと工夫して調整します。" + }, + "focus": "第{{layer}}層のニューロン {{index}}", + "focus-input": "入力 {{index}}", + "formula-input": "{{name}} = {{value}}", + "formula-pending": "第{{layer}}層のニューロン {{index}} はまだ計算されていません。", + "formula-update": "バイアスは{{before}}から{{after}}になります。最も大きく変わる重み({{from}}からの重み)は{{weight}}から{{weightAfter}}になります。", + "from-neuron": "第{{layer}}層のニューロン {{index}}", + "history_other": "更新ごとの、データの{{sample}}個の例の平均損失:{{first}}から{{last}}へ(使った例は{{count}}個)。ネットワークが学習していれば、線は下がります。", + "history-empty": "各例が終わるたびに、ここで損失の変化が見られます。", + "diagram": "ニューラルネットワーク(層ごと)", + "node-input": "入力 {{name}}:{{value}}", + "node": "第{{layer}}層のニューロン {{index}}:{{value}}", + "column-input": "入力", + "column-layer": "第{{layer}}層({{activation}})", + "column-output": "出力({{activation}})", + "update-rule": "w ← w − {{rate}} × 勾配" + }, + "clustering": { + "intro": "k-meansはk個の重心を置き、各行を最も近い重心に割り当て、各重心をその行の中心に動かします。どの行もグループが変わらなくなるまで繰り返します。ラベルは使わず、選んだ列だけを使います。", + "upload": "データをアップロード", + "rows_other": "{{count}}行", + "features": "グループ分けに使う列", + "features-help": "数値の列だけです。多いほど想像しにくくなりますが、グループはよくなることがあります。", + "label": "本当のクラスの列(任意)", + "label-none": "なし", + "label-help": "グループ分けには使わず、最後に比較するためだけに使います。", + "scale": "列をスケーリングする", + "scale-help": "各列を平均0・標準偏差1にします。しないと、値の大きい列(例:ワインのプロリン)だけで決まってしまいます。", + "k": "グループの数(k)", + "k-help": "いくつあるかわからなければ、グループ分けの後でエルボーを見てください。", + "run": "グループ分け", + "reseed": "別の初期重心で試す", + "waiting": "列とグループの数を選び、「グループ分け」を押してください。", + "groups": "グループ", + "iterations": "反復回数", + "inertia": "慣性", + "silhouette": "シルエット", + "silhouette-good": "シルエットが高い(0.5超):グループがよく分かれています。", + "silhouette-fair": "シルエットが中程度(0.25〜0.5):グループはありますが、互いに接しています。", + "silhouette-weak": "シルエットが低い(0.25未満):グループがほとんど区別できません。別のkや別の列を試してください。", + "scatter-title": "グループ", + "play": "できる様子を見る", + "pause": "一時停止", + "iteration": "反復 {{number}}", + "scatter-help": "各点が1行、×印が重心です。2Dで描くためにPCA(データが最も大きく変化する2方向)で投影していますが、k-meansは選んだすべての列を使います。", + "axis": "成分{{number}}(分散の{{variance}})", + "cluster": "グループ{{number}}", + "centroids": "重心", + "comparison-title": "グループと本当のクラス({{column}})", + "comparison-help": "各クラスの行が各グループにいくつ入り、グループのどれだけを占めるか。k-meansは各クラスが何かを知らないので、グループに名前はありません。各グループの多数派クラスが、どのクラスに似ているかを示します。", + "group": "グループ", + "purity": "純度", + "ari": "調整ランド指数", + "elbow-title": "エルボー", + "elbow-help": "kを増やすと慣性は必ず下がります。下がり方が急に小さくなる「ひじ」が、よいグループ数の目安です。", + "profiles-title": "各グループの特徴", + "size": "行数", + "profiles-help": "各グループの各列の平均(元の単位)。グループに名前を付ける手がかりになります。", + "variable": "変数", + "purity-help": "各グループを多数派クラスの名前で呼んだときに正しくなる行の割合。kを増やすと必ず上がります(1行ごとに1グループなら100%)。", + "ari-help": "行のペアで見て、グループがクラスにどれだけ似ているか:同じクラスの行は同じグループに入っているか。同じグループなら1、偶然と同程度なら0前後。グループを増やすだけでは上がりません。", + "ari-high": "グループはクラスとほぼ同じです。", + "ari-medium": "グループはクラスにかなり似ていますが、分かれたり混ざったりしているクラスがあります。", + "ari-low": "グループはクラスにあまり似ていません。", + "ari-none": "グループはクラスに似ていません:偶然と同じです。", + "majority": "多数派クラス", + "mixed": "混在", + "total": "合計", + "comparison-legend": "背景が濃いほど、グループの中でそのクラスが占める割合が大きいです。「混在」:どのクラスもグループの3分の2に届きません。", + "scatter-data": "グループ、行数、重心", + "rows-column": "行数" + }, + "time-series": { + "manual": { + "title": "しくみ", + "windows": { + "title": "ウィンドウ", + "text": "ネットワークは系列全体を見るのではなく、直前の値(ウィンドウ)を受け取って次の値を予測します。系列の各位置が 1 つの例になります。12 か月のウィンドウなら、1949 年の 12 か月で 1950 年 1 月を予測し、その次の 12 か月で 2 月を予測します。" }, - "details-output": { - "title": "出力データ", - "list": { - "0": "指の関節", - "1": "対応する文字" - } + "split": { + "title": "過去で学習し、未来でテストする", + "text": "テスト部分は系列の最後で、シャッフルしません。月を混ぜると、ネットワークが学習中に未来を見てしまうからです。学習用のウィンドウは、それぞれが自分の履歴を持っているのでシャッフルします。" }, - "details-references": { - "title": "参照元", - "list": { - "0": "TFJS hand pose detection" - } + "scale": { + "title": "スケーリングと差分", + "text": "値は学習部分の最小値と最大値で 0〜1 にスケーリングします(テスト部分は見ません)。系列が増え続けると、テスト部分がその範囲を超えることがあります。差分を取ると、ネットワークは値そのものではなく直前の値からの変化を学習し、トレンドが取り除かれます。" + }, + "modes": { + "title": "1 ステップか、続けてか", + "text": "1 ステップ先では、テストの各値を直前の実際の値で予測します。今日を知って明日を予測するようなものです。続けて(再帰的)では、学習の終わりから、各値をすでに予測した値で予測します。未来の予測はこの方法で行い、誤差が積み重なります。" + }, + "baselines": { + "title": "最も単純な予測より良い?", + "text": "ネットワークを使わない 2 つの予測と比べます。ナイーブ予測(直前の値、続けて予測する場合は最後に分かっている値)と季節予測(1 季節前の値:12 か月前、7 日前など)です。これらより良くないネットワークは役に立ちません。" + }, + "networks": { + "title": "Dense か再帰型か", + "text": "Dense 層はウィンドウ全体を一度に受け取ります。再帰型の層(SimpleRNN、LSTM、GRU)は値を 1 つずつ読み、それまでの内容を覚えています。Dense 層より前に置き、学習は遅くなります。出力は線形のニューロン 1 つで、予測する値です。" } - } + }, + "upload": { + "title": "あなたの系列", + "text": "1 行が 1 時点のファイル(CSV、ARFF、JSON、JSONL、Parquet)をアップロードし、値の列を選んでください。日付の列があれば、行の並べ替えと予測値の日付に使います。", + "no-numeric": "ファイルに数値の列がありません。予測する値がありません。", + "value-column": "値の列", + "value-column-help": "予測する系列です。", + "date-column": "日付の列", + "date-column-help": "省略できます。ない場合は値に 1、2、3… と番号を付けます。", + "no-date": "日付なし(1、2、3…)", + "info": "自分の時系列をアップロードします。値の列と、あれば各値の日付の列です。", + "waiting": "ファイルをアップロードすると、ここに系列が表示されます。" + }, + "data": { + "summary_other": "{{count}} 個の値({{first}} から {{last}} まで)", + "value-column": "予測する列:{{column}}", + "dropped_other": "値の列に数値がない {{count}} 行を取り除きました。", + "sorted": "行が順番に並んでいなかったので、日付順に並べ替えました。", + "range_other": "{{first}} – {{last}}({{count}} 個の値)", + "split": "学習:{{train}}、テスト:{{test}}" + }, + "frequency": { + "hour": "1 時間に 1 つの値", + "day": "1 日に 1 つの値", + "week": "1 週間に 1 つの値", + "month": "1 か月に 1 つの値", + "quarter": "四半期に 1 つの値", + "year": "1 年に 1 つの値" + }, + "chart": { + "test": "テスト", + "description": "{{name}}:{{count}} 個の値({{first}} から {{last}} まで)。", + "train-prediction": "ネットワーク(学習、1 ステップ)", + "test-one-step": "ネットワーク(テスト、1 ステップ)", + "test-recursive": "ネットワーク(テスト、続けて)", + "future": "この先", + "forecast-description": "{{model}} の予測:テスト部分での誤差は平均 {{mae}}。その後に続く {{steps}} 個の値。" + }, + "prep": { + "title": "準備", + "window": "ウィンドウ(直前の値の数)", + "window-help": "ネットワークが次の値を予測するのに使う直前の値の数です。", + "window-season": "繰り返すパターンを捉えるには、1 季節分({{season}} 個の値)をカバーするとよいでしょう。", + "test-size": "テスト(系列の最後の %)", + "test-size-help": "最後の値です。ネットワークは学習中にこれらを見ません。系列では未来を過去から予測するので、シャッフルしません。", + "difference": "変化を予測する(差分)", + "difference-help": "ネットワークは直前の値からの変化を学習し、予測時にはそれを直前の値に足します。トレンドが取り除かれます。", + "season": "季節(値の数)", + "season-help": "パターンが何個の値ごとに繰り返すか(12 か月、7 日など)。季節予測との比較に使います。0 は季節なしです。", + "too-short": "このウィンドウとテスト部分では、データが足りません。学習には少なくとも 10 個のウィンドウ、テストには 2 個の値が必要です。ウィンドウを短くするか、テストを減らしてください。" + }, + "windows": { + "title": "ネットワークが学習するもの", + "text": "各例は直前の {{window}} 個の値と、予測すべき次の値です。最初のいくつか:", + "text-difference": "各例は直前の {{window}} 個の変化(各値から直前の値を引いたもの)と、予測すべき次の変化です。最初のいくつか:", + "date": "日付", + "inputs": "直前の値({{window}} 個)", + "inputs-difference": "直前の変化({{window}} 個)", + "output": "予測する値", + "output-difference": "予測する変化", + "scaled_other": "ネットワークはこれらを 0〜1 にスケーリングして受け取ります。この準備では学習用の例が {{count}} 個あります。" + }, + "layers": { + "class": "層の種類", + "class-help": "Dense はウィンドウ全体を受け取り、SimpleRNN、LSTM、GRU は値を 1 つずつ読みます(Dense 層より前に置きます)。" + }, + "models": { + "yes": "はい", + "no": "いいえ", + "mae-one-step": "1 ステップの誤差(MAE)", + "mae-recursive": "続けた場合の誤差(MAE)", + "show": "表示", + "help": "誤差はテストデータでの平均絶対誤差で、系列の単位で表します。平均してどれだけ外れるかです。", + "evaluating": "予測を計算しています…" + }, + "forecast": { + "title": "予測:{{model}}", + "model": "モデル", + "one-step": "1 ステップ", + "recursive": "続けて(再帰的)", + "range-all": "系列全体", + "range-test": "拡大", + "show-train": "学習部分も表示", + "one-step-help": "テストの各値を、直前の実際の値で予測します。", + "recursive-help": "学習の終わりから、テスト部分を見ずに、各値をすでに予測した値で予測します。未来の予測はこの方法で行い、誤差が積み重なります。", + "errors-title": "テストデータでの誤差", + "prediction": "予測", + "mae-title": "平均絶対誤差:平均してどれだけ外れるか", + "rmse-title": "二乗平均平方根誤差:大きな誤差をより重く扱う", + "network": "ニューラルネットワーク({{model}})", + "naive-one-step": "ナイーブ:直前の値", + "naive-recursive": "ナイーブ:最後に分かっている値の繰り返し", + "seasonal-one-step": "季節:{{season}} 個前の値", + "seasonal-recursive": "季節:最後の季節の繰り返し", + "verdict-better": "ネットワークの誤差は、最も良い単純な予測({{baseline}})より {{percent}} 小さいです。", + "verdict-similar": "ネットワークの誤差は、最も良い単純な予測({{baseline}})とほぼ同じです。あまり役に立っていません。", + "verdict-worse": "ネットワークの誤差は、最も良い単純な予測({{baseline}})より {{percent}} 大きいです。別のウィンドウ、より多いエポック、差分、再帰型の層を試してください。", + "baseline-naive": "ナイーブ予測", + "baseline-seasonal": "季節予測", + "train-vs-test": "学習データでの誤差は平均 {{train}}、テストデータ(1 ステップ)では {{test}} です。", + "overfitting": "テストデータでの誤差が 2 倍以上あります。学習データを丸暗記しているのかもしれません。", + "future-title": "この先", + "future-steps": "予測する値の数", + "future-help": "1 つずつ続けて、すでに予測した値で予測します。先になるほど信頼性は下がります。" + }, + "model": { + "name": "学習済みモデル", + "train-yours": "この系列で自分のネットワークを学習する" + }, + "review": { + "tab-chart": "系列", + "tab-windows": "ネットワーク用に準備したもの", + "preparation": "ネットワークは直前の {{window}} 個の値を受け取り、次の値を予測します。{{last}} までの系列で学習し、テスト部分({{first}} から最後まで)は見ていません。値は学習部分の最小値({{min}})と最大値({{max}})で 0〜1 にスケーリングします。", + "preparation-difference": "ネットワークは直前の {{window}} 個の変化(各値から直前の値を引いたもの)を受け取り、次の変化を予測します。{{last}} までの系列で学習し、テスト部分({{first}} から最後まで)は見ていません。変化は学習部分の最小値({{min}})と最大値({{max}})で 0〜1 にスケーリングします。", + "predict-title": "予測", + "test": "テスト", + "model-select": "予測に使うモデル", + "choose-instance_other": "系列の値を選ぶと、ネットワークが使う直前の {{count}} 個の値でフォームが埋まります。その後で変更できます。", + "vector": "ネットワークが受け取るもの", + "vector-help": "各値を、学習部分の最小値と最大値で 0〜1 にスケーリングしたものです。", + "vector-help-difference": "各変化(値から直前の値を引いたもの)を、学習部分の最小値と最大値で 0〜1 にスケーリングしたものです。", + "button-submit": "予測", + "predicted-value": "{{target}} の予測値({{date}})", + "actual-value": "実際の値:{{value}}", + "error": "誤差:{{value}}({{percent}})", + "input-details": "モデルの入力(ステップごと)", + "step-values": { + "title": "直前の値", + "text": "系列のまま" + }, + "step-changes": { + "title": "変化", + "text": "各値から直前の値を引いたもの" + }, + "step-scaled": { + "title": "スケーリング後", + "text": "ネットワークが受け取る 0〜1 の値" + }, + "metrics": "学習時に取り分けた系列の最後の {{testSize}} % では、1 ステップ先で平均 {{mae}} 外れます。直前の値を繰り返すと {{naive}} です。", + "metrics-seasonal": "1 季節前の値を繰り返すと {{seasonal}} です。", + "metrics-no-better": "最も単純な予測より良くありません。このウィンドウでは、この系列はそれほどうまく予測できません。" + }, + "chart-data": "{{value}}:各日付の実際の値と予測", + "chart-data-series": "各日付の {{value}}" + } + }, + "dataframe": { + "title": "データセットを分析", + "upload-csv": "データセットをアップロード", + "intro": "モデルを学習する前にデータセットを探索します。サイズ、各変数の型と分布、欠損値、変数同士や目的変数との関係、そしてその準備方法を確認できます。", + "waiting": "プロジェクトのデータセットを選ぶか、独自のファイル(CSV、ARFF、JSON、JSONL、Parquet)をアップロードして分析を始めてください。", + "sections": { + "data": "データセット", + "summary": "概要", + "variables": "変数", + "distributions": "分布", + "relations": "関係", + "table": "データとクエリ", + "preprocess": "前処理", + "charts": "その他のグラフ" }, - "list-models": { - "2-option-1": "モデル - FaceDetector - 顔の幾何学", - "2-option-2": "モデル - FaceMesh - 顔メッシュ", - "2-option-3": "モデル - MoveNet - 関節検出器", - "2-option-4": "モデル - COCO SSD - 物体検出器", - "2-option-5": "モデル - Face API - 顔マネージャー", - "2-option-6": "モデル - HandSign - サイン検出器" + "picker": { + "project": "プロジェクトのデータセット", + "project-help": "Nets4Learning のモデルが使う CSV と練習用の CSV。各変数の説明付きです。", + "placeholder": "データセットを選択", + "upload": "独自のファイル", + "upload-help": "CSV(「,」または「;」区切り)、ARFF、JSON、JSONL、Parquet。ブラウザ内で読み込まれ、ファイルはどのサーバーにも送信されません。", + "loading": "読み込み中…" + }, + "info": { + "shape": "{{rows}} 行 × {{columns}} 列", + "source": "出典", + "variables-sheet": "変数の説明あり", + "target": "目的変数", + "target-none": "なし", + "target-help": "予測または分類したい変数です。分析全体で強調表示され、グラフをクラスごとに分けます。", + "problem-classification": "分類、{{count}} クラス", + "problem-regression": "回帰", + "problem-none": "目的変数なし" + }, + "summary": { + "rows": "行", + "columns": "列", + "columns-detail": "数値: {{numeric}}、カテゴリ: {{categorical}}", + "missing": "欠損値", + "missing-detail": "セルの {{percent}}", + "duplicates": "重複行", + "duplicates-detail": "行の {{percent}}", + "target-distribution": "{{target}} の分布", + "target-distribution-none": "目的変数の分布", + "no-target": "目的変数を選ぶと、その値の分布が表示されます。", + "warnings": "データに関する注意", + "no-warnings": "問題は見つかりませんでした。欠損値、重複行、定数列、識別子、不均衡なクラスはありません。" + }, + "warnings": { + "missing": "{{column}} には欠損値が {{count}} 個あります ({{percent}})。", + "constant": "{{column}} は常に同じ値で、情報を持ちません。", + "identifier": "{{column}} は属性ではなく識別子 (レコードごとのコード) のようです。学習には使わない方がよいでしょう。", + "outliers": "{{column}} には四分位範囲の規則による外れ値が {{count}} 個あります ({{percent}})。", + "imbalance": "{{column}} のクラスは不均衡です。「{{minority}}」の行数は最も多いクラスの {{percent}} です。", + "correlation": "{{column}} と {{other}} は強く相関しています (r = {{value}})。ほぼ同じ情報を持っています。", + "duplicates": "重複行が {{count}} 行あります。" + }, + "variables": { + "title": "各変数のプロファイル", + "search": "変数を検索", + "type": "型", + "all": "すべて", + "numeric": "数値", + "categorical": "カテゴリ", + "view-cards": "カード", + "view-table": "表", + "kind-numeric": "数値", + "kind-categorical": "カテゴリ", + "target": "目的", + "missing": "欠損", + "distinct": "異なる値", + "mean": "平均", + "std": "標準偏差", + "min": "最小", + "median": "中央値", + "max": "最大", + "top": "最も多い値", + "more": "ほか {{count}} 個", + "show-distribution": "分布を見る →", + "no-results": "検索に一致する変数はありません。", + "units": "単位: {{units}}", + "column": "変数", + "histogram-of": "{{column}} のヒストグラム" + }, + "distributions": { + "title": "変数の分布", + "variable": "変数", + "bins": "区間数", + "bins-auto": "自動", + "by-class": "{{target}} のクラスごとに分ける", + "histogram": "ヒストグラム", + "frequencies": "各値の度数", + "boxplot": "箱ひげ図", + "count": "行", + "class": "クラス", + "by-class-table": "{{target}} の各クラスにおける {{column}}", + "help-histogram": "各区間に値を持つ行の数です。クラス同士の重なりが少なければ、その変数はクラスの区別に役立ちます。", + "help-frequencies": "各値を持つ行の数です (多い順に 30 個)。", + "help-boxplot": "箱は第1四分位数から第3四分位数まで、中央の線は中央値です。離れた点は外れ値です。" + }, + "relations": { + "title": "相関と散布図", + "correlation": "相関行列", + "correlation-help": "数値変数の各ペアのピアソン相関です。1 は正の線形関係、−1 は負の線形関係、0 は関係なしを表します。", + "target-correlation": "{{target}} との相関", + "target-correlation-help": "目的変数と相関の強い変数ほど、予測に役立つことが多いです。", + "scatter": "散布図", + "x": "X 軸", + "y": "Y 軸", + "color-help": "各点は 1 行で、{{target}} で色分けされています。", + "not-enough": "数値変数が少なくとも 2 つ必要です。" + }, + "table": { + "title": "データ表" + }, + "preprocess": { + "title": "モデル用にデータを準備", + "help": "モデルは数値しか受け取れません。テキストはエンコード (ラベルエンコーダ) し、不要なものは除外します。結果は変更ごとに更新され、CSV としてダウンロードできます。", + "missing": "欠損値", + "missing-keep": "そのままにする", + "missing-drop-rows": "欠損のある行を削除", + "missing-impute": "補完 (平均または最頻値)", + "scaler": "数値属性のスケーリング", + "scaler-none": "なし", + "scaler-min-max": "Min-max (0 から 1)", + "scaler-standard": "標準化 (平均 0、標準偏差 1)", + "scaler-help": "目的変数はスケーリングしません。", + "duplicates": "重複行を削除", + "action": "変換", + "action-keep": "変更なし", + "action-label-encoder": "エンコード (ラベルエンコーダ)", + "action-drop": "除外", + "result": "結果", + "download": "CSV をダウンロード", + "removed-rows": "削除した行: 重複 {{duplicates}} 行、欠損のある行 {{missing}} 行。", + "encodings": "テキスト列のエンコード", + "imputed": "補完に使った値", + "imputed-value": "{{column}}: {{value}}" + }, + "analyzing": "データセットを分析中…", + "charts-sample": "行数が多いため、これらのグラフは {{rows}} 行のうち {{sample}} 行のランダムサンプルを使います。", + "essentials": { + "tab": "分析", + "help": "データセットの探索的分析の要点:サイズ、欠損値と重複行、目的変数の分布、注意点、目的変数と関係のある変数。", + "open": "完全な分析を見る(探索的データ分析)" } }, - "3-image-classifier": { - "interface": { - "0-upload": { - "title": "モデルをロード", - "sub-title": "最初に.jsonファイル、次に.binファイル" + "menu": { + "select-model": { + "description": "説明" + }, + "select-dataset": { + "description": "説明" + }, + "open": "開く", + "info": { + "rows": "{{value}} 行", + "rows-files": "{{files}} ファイル({{values}} 行)", + "features": "特徴量 {{value}}", + "classes": "{{value}} クラス", + "target": "目的変数: {{value}}", + "images": "{{size}} の画像 {{value}} 枚", + "images-color": "{{size}} のカラー画像 {{value}} 枚", + "series": { + "hour": "{{value}} 時間", + "day": "{{value}} 日", + "week": "{{value}} 週", + "month": "{{value}} か月", + "quarter": "{{value}} 四半期", + "year": "{{value}} 年" + } + } + }, + "documentation": { + "title": "ドキュメント" + }, + "manual": { + "title": "マニュアル", + "00-tabular-classification": { + "upload-and-process": { + "title": "ステップ 1: データセットをアップロードして前処理する" }, - "process-examples": { - "title": "サンプルを使用した処理" + "dataset": { + "title": "ステップ 2: データセットを分析する" }, - "process-draw": { - "title": "描画" + "layer-design": { + "title": "ステップ 3: ニューラルネットワークの層構成を確認する" }, - "process-image": { - "title": "画像処理", - "sub-title": "-", - "validate": "検証" + "editor-layers": { + "title": "ステップ 4: ニューラルネットワークの層を編集する" }, - "result": "結果", - "button-accept": "受け入れる", - "modal": { - "title": "予測" + "editor-hyperparameters": { + "title": "ステップ 5: 学習のハイパーパラメータを編集する" + }, + "table-models": { + "title": "ステップ 6: 学習とモデル一覧" + }, + "prediction": { + "title": "ステップ 7: 分類" } }, - "mnist": { - "title": "MNIST - 数字の分類", - "description": { - "text-0": "MNISTデータベースは、手書き数字の大規模なデータベースです。このデータベースは、機械学習の分野でのトレーニングとテストに広く使用されています。", - "text-1": "元のNISTデータセットのサンプルを「再混合」して作成されました。", - "text-2": "NISTトレーニングデータセットは、米国国勢調査局から取得されました。さらに、NISTの白黒画像は、28 x 28ピクセルの境界ボックスに収まるように正規化され、平滑化されました。これにより、グレースケールレベルが導入されました。", - "details-input": { - "title": "入力データ", - "list": { - "0": "28 x 28ピクセルサイズのグレースケール画像" + "app": { + "title": "ツールの目的", + "description-1": "このアプリケーションでは、表形式データの分類、画像分類、物体識別など、人工ニューラルネットワークが実行できる代表的なタスクを紹介します。ニューラルネットワークは機械学習の分野に属する人工知能の手法で、データセットから学習(訓練)するモデルを構築します。", + "description-2": "ニューラルネットワークを学ぶ理由には、次のようなものがあります。", + "list": { + "0": { + "title": "実践的な応用", + "description": "ニューラルネットワークは、音声認識やコンピュータビジョンからデータ分析、結果の予測まで、幅広い用途で使われています。ニューラルネットワークを学ぶことで、医療、工学、データサイエンス、マーケティングなど多くの分野で役立つスキルを身につけることができます。" + }, + "1": { + "title": "複雑な問題の解決", + "description": "ニューラルネットワークは、多数の変数と非線形な関係を持つ複雑な問題の解決に役立ちます。ニューラルネットワークを学ぶことで、こうした問題に対してより効果的な解決策を開発し、分析の精度と効率を高めることができます。" + }, + "2": { + "title": "技術革新", + "description": "ニューラルネットワークは進化と改良を続ける革新的な技術です。ニューラルネットワークを学ぶことで、機械学習と人工知能の分野における最新の動向や発展に追いつくことができます。" + } + }, + "description-3": "ニューラルネットワークは、人間の脳の働きを模倣した機械学習の一形態です。過去のデータや経験から学習して改善し続けるように設計されており、従来のプログラムでは不可能または非常に困難だった複雑なタスクを機械が実行できるようにします。", + "description-4": "まとめると、ニューラルネットワークを学ぶことは、幅広い分野で価値のあるスキルを身につけ、複雑な問題をより効果的に解決し、技術と革新の最新動向に追いつくために重要です。" + }, + "0-tabular-classification": { + "title": "表形式データの分類", + "1-title": "学習済みモデル", + "1-description-1": "学習済みモデルのセクションにアクセスし、利用可能なモデルの中から1つを選択します。", + "1-description-2": "ツールには代表的な例の一覧があり、それを使って特徴量のフォームを変更できます。", + "1-description-3": "モデルのツールセクションでは、予測する要素の特徴量を編集できます。ツールには動的なフォームがあり、ニューラルネットワークへの入力データを変更できます。", + "2-title": "モデルの学習", + "2-description-1": "ツールにはデータセットのクラスと属性を表示するデータビューアと、データモデルを作成・設計・学習・エクスポートするための管理機能があります。", + "2-description-2": "左側には、ニューラルネットワークの各層を編集するエディタがあります。ネットワークの最終層のニューロン数は、予測するクラス数と同じにする必要があります。", + "2-description-3": "エポック数:
学習の過程で学習データをニューラルネットワークに提示する回数です。各反復では、計算された誤差に応じてネットワークの重みが更新されます。", + "2-description-4": "「モデルを作成して学習」ボタンを押すと、ニューラルネットワークの学習が始まります。設定と関数の選択がすべて正しければ、学習済みモデルの行が下の表に追加されます。", + "2-description-5": "データからモデルを学習したら、予測を行うことができます。そのために、データセットの特徴量を含む動的なフォームが用意されています。予測の精度は、学習内容と選択したオプションによって高くも低くもなります。" + }, + "1-regression": { + "title": "回帰", + "1-title": "学習済みモデル", + "1-description": { + "0": "学習済みモデルのセクションにアクセスし、利用可能なモデルの中から1つを選択します。", + "1": null, + "2": null + }, + "2-title": "モデルの学習", + "2-description": { + "0": "このセクションでは、独自のデータセットのアップロード、用意されたデータセット、説明、グラフや統計による可視化ツールを利用できます。", + "1": "回帰モデルの生成機能があり、ニューラルネットワークの層、ハイパーパラメータ、最適化関数、損失関数、評価指標、そして特徴量の選択を管理できます。", + "2": "「モデルを作成して学習」ボタンを押すと、ニューラルネットワークの学習が始まります。設定と関数の選択がすべて正しければ、学習済みモデルの項目が一覧に追加されます。", + "3": "予測には散布図を使い、直線を描きます。" + }, + "2-link": "詳しくは次のリンクをご覧ください" + }, + "2-object-identification": { + "title": "物体識別", + "1-title": "学習済みモデル", + "1-description-1": "物体識別には4つのモデルがあります。使い方は簡単で、Webカメラを有効にするか画像をアップロードするだけです。", + "1-description-2": "このセクションでは4つの物体識別モデルを提供しています。これらのモデルはモバイル端末でも動作するよう最適化されています。モデルは次のとおりです。", + "1-description-3": "Webカメラを入力に使うと、検出中の点を映像上でリアルタイムに確認できるフィルターが生成されます。画像をアップロードする場合は png または jpg 形式のファイルを添付できます。結果として、元の画像、生成されたフィルター、フィルターを適用した画像が表示されます。", + "1-list": { + "0": "顔の形状の識別。", + "1": "顔全体のメッシュの識別。", + "2": "関節の識別。", + "3": "物体の識別(分類器でもあります)。" + } + }, + "3-image-classification": { + "title": "画像分類", + "1-title": "学習済みモデル", + "1-description-1": "画像分類のセクションでは、ニューラルネットワークの代表的な2つの例、MNIST の画像セットと一般画像のセットから選択できます。", + "1-list": { + "0": "MNIST: 数字を識別する画像分類。", + "1": "MobileNet: 1001 カテゴリに属する画像の分類。" + }, + "1-description-2": "MNIST モデルでは、数字を含む画像の一覧から選ぶか、キャンバスに予測したい数字を描くか、数字の画像をアップロードできます。", + "1-description-3": "MobileNet モデルには選択できるサンプル画像の一覧があり、ニューラルネットワークに分類させる画像をアップロードすることもできます。", + "1-description-4": "どちらのモデルでも、予測結果とその確率(パーセンテージ)が表示されます。" + }, + "layer-editor": { + "title": "層エディタ" + }, + "hyperparameters-editor": { + "title": "ハイパーパラメータエディタ" + } + }, + "glossary": { + "title": "用語集", + "intro": "Nets4Learning に出てくる用語:タスク、ネットワークのエディター、オプティマイザー、活性化関数・損失関数・評価指標。", + "search": "用語集を検索", + "search-placeholder": "例:ReLU、Adam、エポック…", + "results_other": "{{count}} 件の用語", + "no-results": "「{{query}}」に一致する用語はありません。", + "anchor": "「{{term}}」へのリンク", + "plot": "{{term}} のグラフ", + "plot-tabs": { + "image": "画像", + "animation": "アニメーション" + }, + "animation": { + "slider": "{{name}} の x の位置", + "play": "再生", + "pause": "一時停止" + }, + "references-title": "参考文献", + "confusion-legend": { + "abbreviation": "略語", + "english": "英語", + "meaning": "意味", + "tp": "真陽性", + "tn": "真陰性", + "fp": "偽陽性", + "fn": "偽陰性" + }, + "table-head": { + "name": "名前", + "description": "説明", + "references": "参考文献", + "characteristics": "特徴", + "function": "関数" + }, + "tabular-classification": { + "title": "表形式データの分類", + "text-1": "表形式データの分類は教師あり学習の一種で、ラベル付きのデータセットを使って機械学習モデルを学習させ、学習に使っていない新しいデータ例のクラスを予測できるようにします。表形式データの分類では、入力と出力のデータが行と列からなる表として表され、各行はデータのインスタンス(例)を、各列はデータの特徴量(属性)を表します。", + "text-2": "例えば、銀行の顧客に返済能力があるかどうかを予測したい場合、収入、負債、信用履歴、年齢などを特徴量(属性)として使えます。表形式データの分類では、データセットの各インスタンスがこれらの特徴量の値と、顧客に返済能力があるかどうかを示すラベル(クラス)を持ちます。", + "text-3": "ラベル付きのデータセットが用意できたら、機械学習アルゴリズムを使って、新しいデータのラベルを予測できるモデルを学習させます。このモデルを使えば、新しいデータに対して正確かつ高速に予測できます。", + "text-4": "表形式データの分類は、医療、電子商取引、銀行、セキュリティなど、さまざまな分野の分類問題を解くのにとても有用な手法です。" + }, + "regression": { + "title": "回帰", + "text": { + "0": "回帰は機械学習で使われる統計的な分析手法で、独立変数と従属変数の間の線形な関係をモデル化し、データに最もよく当てはまる直線を見つけて予測を行います。", + "1": "回帰では、データは通常、デカルト平面上に散らばった点として表されます。独立変数を X 軸、従属変数を Y 軸に置き、それらの点との距離が最小になる直線の方程式(y = mx + b)を求めます。この方程式が得られれば、独立変数の値から従属変数の将来の値を予測できます。", + "2": "例えば、Webサイトの広告量と商品の売上の関係を分析する場合、広告量が独立変数、商品の売上が従属変数になります。回帰を使うと、広告費と売上の間に線形な関係があるかどうかを調べ、関係があれば広告費から将来の売上を予測できます。", + "3": "回帰はデータ分析における強力なツールで、経済学、社会科学、医学研究など多くの分野で変数間の関係を理解し予測するために使われています。" + } + }, + "object-identification": { + "title": "物体識別", + "text-1": "ニューラルネットワークによる物体識別は、機械学習とコンピュータビジョンの分野で画像や動画の中の物体を検出・認識するために使われる手法です。画像解析における重要なタスクで、顔認識、物体のリアルタイム追跡、医用画像での物体分類、自動運転車での物体検出などに応用されています。", + "text-2": "物体識別に使われるニューラルネットワークは、ラベル付きのデータセットで学習した深層学習モデルです。学習では、ラベル付きの大量の画像をネットワークに与え、ニューロン間の結合の重みを調整して、新しい画像の中の物体を高い精度で識別できるようにします。", + "text-3": "学習を終えたニューラルネットワークは、新しい画像の中の物体を識別するために使われます。ネットワークは画像を調べ、複数の層で処理して、対象の物体を識別するための重要な特徴を抽出します。そして、その特徴を使って画像内で検出した各物体にラベルを割り当てます。", + "text-4": "まとめると、ニューラルネットワークによる物体識別は、画像や動画の中の物体を検出・認識するための、コンピュータビジョンと機械学習における重要な手法です。ラベル付きのデータセットで学習した深層ニューラルネットワークを使い、新しい画像の中の物体を高い精度で識別・分類します。" + }, + "image-classification": { + "title": "画像分類", + "text-1": "画像分類は、画像をさまざまなカテゴリ(ラベル)に分類するためにニューラルネットワークで使われる手法です。画像分類器の目的は、入力された画像があらかじめ定められたカテゴリ(ラベル)のどれに属するかを予測することです。", + "text-2": "深層学習では、画像分類器は画像処理に特化したアーキテクチャである畳み込みニューラルネットワーク(CNN)に基づいています。これらのネットワークは複数の層と畳み込み演算を持ち、エッジ、形状、テクスチャなど画像の重要な特徴を抽出できます。", + "text-3": "画像分類器を学習させるには、画像とそれぞれのクラスラベルを含むラベル付きのデータセットを使います。ニューラルネットワークはこのデータセットで学習し、画像のパターンを見つけて対応するクラスラベルと結び付けることを学びます。", + "text-4": "学習を終えたニューラルネットワークは、新しい画像をさまざまなカテゴリに分類するために使えます。画像分類器は入力画像をニューラルネットワークで処理して重要な特徴を抽出し、その画像がどのクラスに属するかを予測します。", + "text-5": "要するに、ニューラルネットワークによる画像分類は、畳み込みニューラルネットワークを使って画像をさまざまなカテゴリ(ラベル)に分類する手法です。ラベル付きのデータセットでニューラルネットワークを学習させ、画像から重要な特徴を抽出して、新しい入力画像がどのクラスに属するかを予測します。" + }, + "activation-functions": { + "title": "活性化関数", + "sub-title-1": "線形層", + "sub-title-2": "非線形活性化(重み付き和、非線形性)", + "sub-title-3": "非線形活性化(その他)", + "text-1": "活性化関数は、人工ニューラルネットワークにおいて、受け取った入力に基づいてニューロン(またはニューロンの集まり)の出力を決める数学的な関数です。活性化関数はニューラルネットワークに非線形性を導入し、入力データのより複雑なパターンを学習できるようにします。代表的な活性化関数は次のとおりです。", + "table": { + "linear": { + "title": "Linear", + "description": "入力をそのまま返します(恒等関数)。回帰の出力層で使う活性化関数で、ネットワークが任意の数値を出力できるようにします。", + "characteristics": { + "0": "出力の範囲を制限しません。", + "1": "線形層だけのネットワークは 1 つの線形層と同じで、非線形な関係を学習できません。" + } + }, + "softmax": { + "title": "Softmax", + "description": "出力を確率の形に変換し、すべての確率の合計が 1 になるようにします", + "characteristics": { + "0": "0 から 1 の範囲に収まる", + "1": "最終層に適している", + "2": "多クラス分類の出力の正規化に使われる" + } + }, + "sigmoid": { + "title": "Sigmoid", + "description": "シグモイド関数は入力値を 0 から 1 の範囲に変換します。ニューラルネットワークでは二値分類の問題によく使われます。", + "characteristics": { + "0": "出力は [0, 1] の範囲。", + "1": "二値分類器の出力層で有用。", + "2": "深いネットワークでは勾配消失の問題が起こることがある。" } }, - "details-output": { - "title": "出力データ", - "list": { - "0": "0から9までの数字" + "hard-sigmoid": { + "title": "Hard Sigmoid", + "description": "Hard Sigmoid は、計算効率のためにシグモイド関数を簡略化したものです。", + "characteristics": { + "0": "シグモイドより高速に計算できる。", + "1": "0 と 1 の間の遷移がなめらかではない。" } }, - "details-references": { - "title": "参照元" - } - } - }, - "kmnist": { - "title": "KMNIST - くずし字の分類", - "description": { - "text-0": "Kuzushiji-MNIST(KMNIST)は MNIST と同じ形式のデータセットです。28 x 28 ピクセルのグレースケール画像で 10 クラスですが、数字の代わりにくずし字で書かれた手書きの日本語の文字が含まれています。", - "text-1": "くずし字は千年以上にわたって日本語の一般的な書き方でしたが、20 世紀初めの表記改革以降は学校で教えられなくなり、現在読める人はごくわずかです。画像は国文学研究資料館がデジタル化した古典籍から取られ、ROIS-DS 人文学オープンデータ共同利用センター(CODH)が作成しました。", - "text-2": "各クラスはひらがな 1 文字(お、き、す、つ、な、は、ま、や、れ、を)で、同じ文字にもさまざまな書き方があるため、MNIST より難しい課題です。", - "details-input": { - "title": "入力データ", - "list": { - "0": "28 x 28 ピクセルのグレースケール画像" + "relu": { + "title": "ReLU (Rectified Linear Unit)", + "description": "ReLU は、負の値に対して 0 を返し、正の値はそのまま保つ、シンプルで効果的な関数です", + "characteristics": { + "0": "計算効率が高い。", + "1": "勾配消失の問題を緩和する。", + "2": "ニューロンをスパースに活性化できる。" } }, - "details-output": { - "title": "出力データ", - "list": { - "0": "10 種類のひらがなのいずれか:お、き、す、つ、な、は、ま、や、れ、を" + "relu6": { + "title": "ReLU 6", + "description": "ReLU と似ていますが、正の値の上限を 6 に制限するため、勾配爆発を防ぐのに役立ちます。", + "characteristics": { + "0": "勾配消失の問題を緩和する。", + "1": "勾配が不安定なネットワークで有用。" } }, - "details-model": { - "title": "モデル", - "list": { - "0": "学習済みモデル:学習用画像 55,000 枚(ほかに検証用 5,000 枚)で学習した畳み込みニューラルネットワークで、テスト画像 10,000 枚での正解率は {{accuracy, number(style: percent; minimumFractionDigits: 1)}} です。", - "1": "ブラウザでの学習:各文字について学習用 2,000 枚、テスト用 500 枚のバランスの取れたサブセットを使用します。" + "leaky-relu": { + "title": "LeakyReLU", + "description": "Leaky ReLU は ReLU の変種で、負の値のごく一部を通過させます。", + "characteristics": { + "0": "ReLU に比べてニューロンが死ぬ問題を緩和する。", + "1": "負の勾配の情報を保つのに役立つ。" } - } - } - }, - "mobilenet": { - "title": "MobileNet - 画像分類", - "description": { - "text-0": "MobileNet V2は、画像分類などに使用されるニューラルネットワークアーキテクチャのファミリーです。", - "text-1": "このモデルは、画像の主要なコンテキストを識別することで、1001のカテゴリを区別できます。", - "details-input": { - "title": "入力データ", - "list": { - "0": "224 x 224ピクセルサイズで、[0, 1]の色の値を持つ画像。" + }, + "elu": { + "title": "ELU (Exponential Linear Unit)", + "description": "ELU は正の値では ReLU に似ていますが、負の値でも勾配が定義されている関数です。", + "characteristics": { + "0": "勾配消失の問題を軽減する。", + "1": "より多くのニューロンを活性な状態に保つのに役立つ。" } }, - "details-output": { - "title": "出力データ", - "list": { - "0": "このリストの各カテゴリに対応する0から1001までの数字" + "tanh": { + "title": "Tanh(双曲線正接)", + "description": "双曲線正接関数は入力値を [-1, 1] の範囲に変換します。", + "characteristics": { + "0": "出力は [-1, 1] の範囲。", + "1": "二値分類の問題で有用。", + "2": "深いネットワークでは勾配消失が起こる。" } }, - "details-references": { - "title": "参照元", - "text-0": "Mark Sandler、Andrew Howard、Menglong Zhu、Andrey Zhmoginov、Liang-Chieh Chenによって最初に公開されました:", - "list": { - "0": "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation 2018" + "soft-plus": { + "title": "SoftPlus", + "description": "SoftPlus はなめらかな関数で、ReLU のなめらかな代替としてよく使われます。", + "characteristics": { + "0": "なめらかで、あらゆる点で微分可能。", + "1": "生成モデルや回帰のネットワークで有用なことがある。" + } + }, + "mish": { + "title": "Mish", + "description": "Mish は比較的新しい活性化関数で、双曲線正接関数やシグモイド関数などの特徴を組み合わせています。", + "characteristics": { + "0": "定義域全体でなめらかかつ微分可能。", + "1": "一部の用途でより良い性能を示す。" + } + }, + "selu": { + "title": "SELU (Scaled Exponential Linear Unit)", + "description": "SELU は特定の正規化の恩恵を受ける関数で、ネットワークの安定性を保つのに役立ちます。", + "characteristics": { + "0": "自己正規化: 層を通じて安定した統計量を伝播する。", + "1": "オートエンコーダ構造のネットワークで有用なことがある。" } } } }, - "face-mesh": { - "title": "-" - }, - "list-models": { - "3-option-1": "モデル - MNIST - 数字の分類", - "3-option-2": "モデル - MobileNet - 画像分類器", - "3-option-3": "モデル - ResNet - 画像分類器", - "3-option-4": "モデル - KMNIST - くずし字の分類" - } - }, - "3-image-classification": { - "list-datasets": { - "mnist": "データセット - MNIST", - "kmnist": "データセット - KMNIST" - }, - "joyride": { - "title": "チュートリアルをアクティブ化", - "steps": { - "manual": { - "title": "マニュアル", - "content": "情報を探すためにマニュアルを参照できます" - }, - "dataset-info": { - "title": "データセット情報", - "content": "データセットの情報を照会します" - }, - "dataset": { - "title": "データセット", - "content": "データセットを表示し、その説明から統計情報を抽出できます" + "editor-layers": { + "title": "層エディタの用語集", + "table": { + "units": { + "title": "層のニューロン(Layer Neurons)", + "description": "ネットワークの特定の層にある個々のユニット(ノード)です。各ニューロンは入力を受け取り、計算を行い、次の層に渡す出力を生成します。層のニューロン数は変えることができ、通常はモデルのハイパーパラメータです。層のニューロン数の選び方は、モデルがデータの表現を学習する能力に影響します。" }, - "dataset-plot": { - "title": "データセットのグラフ", - "content": "さまざまなグラフ(棒グラフ、円グラフなど)を使用して、データセットを分析することで非常に重要な情報を抽出できます" + "activation-function": { + "title": "層の活性化関数(Layer Activation Function)", + "description": "ニューラルネットワークの層の各ニューロンでは、モデルに非線形性を導入するために活性化関数が適用されます。活性化関数は、入力と対応する重みに応じてニューロンの出力を決めます。" + } + } + }, + "editor-hyperparameters": { + "title": "ハイパーパラメータエディタ", + "table": { + "learning-rate": { + "title": "学習率(Learning Rate)", + "description": "学習率は、機械学習アルゴリズムとニューラルネットワークにおける重要なハイパーパラメータです。学習の各反復でモデルの重みをどれだけ更新するかを決めます。学習率が高いと速く収束することがありますが不安定になる可能性があり、低いと収束が遅くなったり局所解にとどまったりすることがあります。" }, - "layer-visualizer": { - "title": "ニューラルネットワーク層のビジュアライザー", - "content": "コンパクトモードと拡張モードの2つの形式で、レイヤー、活性化関数を表示できます" + "number-or-epochs": { + "title": "エポック数(Number of Epochs)", + "description": "エポックとは、学習の過程で学習データセット全体をモデルに通した回数のことです。エポック数を増やすと一般にモデルはデータによく適合しますが、ある限度を超えると過学習につながることがあります。" }, - "layer-editor": { - "title": "レイヤーエディタ", - "content": "ニューラルネットワークのレイヤーを編集したり、各レイヤーのニューロン数、活性化関数を変更したり、新しいレイヤーを追加したり削除したりできます。" + "test-size": { + "title": "テストサイズ(Test Size)", + "description": "学習後にモデルの性能を評価するために取り分けておくデータの割合です。テストセットは、未知のデータに対するモデルの精度と全体的な性能を測るために使われます。" }, - "params-editor": { - "title": "ハイパーパラメータエディタ", - "content": "トレーニングがデータセットに合わせてカスタマイズされるように、ニューラルネットワークのハイパーパラメータを設定できます。" + "optimizer": { + "title": "最適化手法(Optimizer)", + "description": "最適化手法は、学習中に機械学習モデルのパラメータを調整するアルゴリズムです。モデルの重みを効率的に更新して損失関数を最小化することを目的とします。代表的な最適化手法には、確率的勾配降下法(SGD)、Adam、RMSprop などがあります。" }, - "list-of-models": { - "title": "モデルリスト", - "content": "モデルが生成されたら、モデルをロードまたはダウンロードして、各モデルをテストし、予測を実行できます。" + "loss-function": { + "title": "損失関数(Loss Function)", + "description": "損失関数は、モデルの予測がどれだけうまくいっているかを数値化する指標です。モデルの予測とデータセットの実際の値との差を計算します。損失の値が小さいほどモデルがデータによく適合していることを示すため、学習の目的はこの関数を最小化することです。" }, - "classify": { - "title": "予測と可視化", - "content": "回帰モデルをロードしたら、予測を実行し、結果を可視化できます" + "metric-function": { + "title": "評価指標(Metric Function)", + "description": "学習中にモデルを最適化するために使う損失関数とは異なり、評価指標は学習後のモデルの性能を評価するために使います。正解率、再現率、適合率、F1 スコアなどの情報を提供し、特定のタスクでモデルがどのように振る舞うかを理解するのに役立ちます。" } } - } - } - }, - "dataframe-plot": { - "warning": { - "no-columns": "描画できる列がありません。", - "unexpected": "グラフを描画できませんでした。詳細はコンソールを確認してください。" - }, - "title": "データフレーム | プロット", - "info": "情報", - "description": { - "title": "チャートタイプの概要" - }, - "configuration": { - "title": "設定", - "reset": "リセット", - "select-all-columns": "すべての列を選択", - "delete-all-columns": "すべての列を削除", - "layout": { - "plot": { - "title": "チャートのタイトル", - "x-axis": "X軸のタイトル", - "y-axis": "Y軸のタイトル" - }, - "title": "レイアウト" - }, - "columns": { - "title": "データフレームの列" }, - "pie-charts": { - "labels": "ラベル" - } - }, - "buttons": { - "configuration": "設定", - "description": "概要" - }, - "bar-charts": { - "title": "棒グラフ", - "description": { - "intro": { - "0": "棒グラフは、長方形の棒を使用して異なるカテゴリやグループの比較を示す視覚的表現です。このタイプのグラフは、棒の長さまたは高さを使用して、特定の変数の大きさまたは量を示します。", - "1": "棒グラフでは、横軸がカテゴリやグループを表し、縦軸が分析対象の変数の大きさや頻度を示します。各カテゴリには個別の棒があり、棒の長さまたは高さは対応する値または量に比例します。棒は、チャートの向きに応じて、水平または垂直にすることができます。", - "2": "棒グラフには、いくつかの注目すべき特徴と用途があります。" - }, - "list": { - "0": "カテゴリの比較: 棒グラフは、異なるカテゴリやグループを視覚的に比較するのに理想的です。棒を見ることで、カテゴリ間の大きさや量の違いをすばやく特定できます。", - "1": "カテゴリデータまたは離散データの表現: 棒グラフは、カテゴリ変数または離散変数を表現するのに適しています。各棒は特定のカテゴリを表し、棒の高さまたは長さは、そのカテゴリに関連付けられた大きさまたは量を示します。", - "2": "カテゴリのソート: 棒グラフのカテゴリは、アルファベット順、大きさの順、またはその他の論理的な順序など、さまざまな基準に基づいてソートできます。これにより、カテゴリ間の特定のパターンや傾向を強調することができます。", - "3": "頻度またはパーセンテージの表示: 棒グラフは、頻度またはパーセンテージを表すためにも使用されます。この場合、棒の高さまたは長さは、各カテゴリに対応する割合またはパーセンテージを表します。", - "4": "効果的なプレゼンテーション: 棒グラフは、情報を明確かつ簡潔に提示するための効果的なツールです。シンプルな構造とカテゴリ間の違いを強調する能力により、レポート、プレゼンテーション、およびドキュメントで広く使用されています。", - "5": "棒グラフは、大きさや量に基づいてカテゴリやグループを視覚化および比較するための効果的な方法です。カテゴリデータまたは離散データを表現するのに理想的であり、情報の効果的な提示を可能にします。その単純さと違いを強調する能力により、データ分析とコミュニケーションで一般的に使用されるツールになっています。" - }, - "end": { - "0": "棒グラフは、大きさや量に基づいてカテゴリやグループを視覚化および比較するための効果的な方法です。カテゴリデータまたは離散データを表現するのに理想的であり、情報の効果的な提示を可能にします。その単純さと違いを強調する能力により、データ分析とコミュニケーションで一般的に使用されるツールになっています。" - } - } - }, - "box-plots": { - "title": "ボックスプロット", - "description": { - "intro": { - "0": "ボックスプロット(箱ひげ図)は、数値データセットの分布と統計的要約を示すために使用される視覚的表現です。このタイプのチャートは、四分位範囲(IQR)を表す長方形に基づいており、中央の線は中央値を示し、ひげと呼ばれる延長線は、IQRを超える値の範囲を表します。", - "1": "ボックスチャートでは、長方形は垂直または水平に描画され、下部と上部の2本の線で区切られています。長方形の中央の線は中央値を表します。これは、順序付けられたデータを2つの等しい部分に分割する値です。ひげは長方形の端から極端な値に向かって伸びており、その長さはデータのばらつきによって決まります。", - "2": "ボックスチャートには、いくつかの注目すべき特徴と用途があります。" - }, - "list": { - "0": "統計的要約: ボックスチャートは、データセットの主要な統計情報の視覚的な要約を提供します。中央値に加えて、データを4つの等しい部分に分割する四分位数(Q1とQ3)や、ひげの外側に点またはアスタリスクとして表示される外れ値も表示できます。", - "1": "非対称性と外れ値の識別: ボックスタイプのチャートを観察することで、データの分布における非対称性を特定できます。ひげの長さが同じでない場合、一方の端に向かって非対称性があることを示している可能性があります。さらに、ひげの外側の外れ値は簡単に強調表示できます。", - "2": "グループまたはカテゴリ間の比較: ボックスチャートは、異なるグループまたはカテゴリ間のデータの分布を比較するためにも使用されます。複数のボックスプロットを同じグラフに重ねることで、グループ間の中央値、四分位範囲、および外れ値の存在の違いを視覚化できます。", - "3": "バイアスと分布の検出: ボックスグラフは、データの分布が対称であるか、一方の端に偏っているかを視覚的に識別できます。長方形の中央線が中央にない場合、反対方向にバイアスがあることを示している可能性があります。", - "4": "分散の視覚化: データの中心位置とばらつきに関する情報を提供するだけでなく、ボックスチャートでは、データの分散とばらつきを単一のグラフで視覚化することもできます。これは、データの全体的な分布とばらつきをすばやく把握するのに役立ちます。" - }, - "end": { - "0": "ボックスプロットは、数値データセットの分布、統計的要約、およびばらつきを視覚化するための便利なツールです。非対称性、外れ値を特定し、グループ間の分布を比較できます。その簡潔で効果的な視覚的表現により、データ分析とコミュニケーションで一般的に使用されるツールになっています。" - } - } - }, - "histograms": { - "title": "ヒストグラム", - "description": { - "intro": { - "0": "ヒストグラムは、数値データまたは連続データの分布を示すために使用される視覚的表現です。このタイプのグラフは、一連の隣接する長方形の棒に基づいており、各棒の幅は値の範囲を表し、棒の高さはその範囲内の観測の頻度または数を示します。", - "1": "ヒストグラムタイプのグラフでは、横軸は、間隔またはビンに分割された、調査中の変数の値の範囲を表すために使用されます。縦軸は、各間隔の観測の頻度または数を表します。各棒の高さは、その特定の区間にいくつの観測値が含まれるかを示します。", - "2": "ヒストグラムタイプのチャートには、いくつかの注目すべき特徴と用途があります。" - }, - "list": { - "0": "分布の表示: ヒストグラムを使用すると、数値データの形状と分布を表示できます。データが対称、歪み、マルチモーダル、または均一な分布に従っているかどうかを示すことができます。", - "1": "外れ値の識別: ヒストグラムを観察することで、ほとんどのデータの範囲外にある外れ値または極値を特定できます。これらの値は、孤立した棒として、または値の主要な範囲を超えて伸びる棒として表されます。", - "2": "傾向とパターンの分析: ヒストグラムは、データのパターンと傾向を明らかにすることができます。たとえば、左または右に歪んだ分布は、データの非対称性を示し、正規分布は近似的な対称性を示します。", - "3": "グループまたはカテゴリの比較: ヒストグラムは、異なるグループまたはカテゴリ間のデータの分布を比較するためにも使用できます。複数のヒストグラムを同じグラフに重ねることで、グループ間の違いと類似性を視覚化できます。", - "4": "密度推定: 絶対頻度を表示するだけでなく、ヒストグラムはデータの確率密度の視覚的な推定値も提供できます。棒の高さを正規化することで、各区間における値の発生確率の相対的な表現を取得できます。" - }, - "end": { - "0": "ヒストグラムは、数値データの分布とパターンを視覚化するための便利なツールです。外れ値を特定し、傾向を分析し、グループ間の分布を比較できます。その明確で簡潔な視覚的表現により、データの分布に関する情報を理解しやすい方法で伝達するための効果的なツールになっています。" + "optimization-functions": { + "title": "最適化関数", + "text-1": "最適化関数は、目的関数を最小化または最大化するための数学的な手法です。機械学習では、目的関数は通常、ある学習データセットに対するニューラルネットワークの出力と期待される出力との差を測る誤差関数です。", + "text-2": "最適化関数は、目的関数を最小化するようにニューラルネットワークのパラメータを調整し、新しい入力データに対してより正確な予測ができるようにします。代表的な最適化関数には、確率的勾配降下法や Adam アルゴリズムがあります。", + "table": { + "sgd": { + "references": "確率的勾配降下法\n (Instituto Tecnológico Autónomo de México, 2017)", + "description": "勾配降下法は、関数が最小値をとる位置を推定するアルゴリズムです。機械学習モデルの規模が大きい場合、この計算は非常に高コストになることがあります。\n そこで、一定数のサンプルを使い、計算する勾配の数を固定する確率的勾配降下法が生まれました。" + }, + "momentum": { + "references": "-", + "description": "前の関数の変種です。異なるステップで勾配の符号が同じ場合に、勾配降下を加速する値を定義します。" + }, + "adagrad": { + "references": "(Velasco, 2020)", + "description": "学習率の考え方に変化を加えたものです。各反復で累積した勾配に応じて、重みごとに学習率をスケーリング・調整します。" + }, + "adadelta": { + "references": "(Velasco, 2020)", + "description": "AdaGrad の変種で、各重みの学習率の計算を、各反復の累積勾配ではなく直近 n 個の勾配からなる固定サイズの窓に限定します。" + }, + "rmsprop": { + "references": "二乗平均平方根伝播\n (Root Mean Square Propagation)\n (Velasco, 2020)", + "description": "次元ごとに異なる学習率を保持しますが、学習率のスケーリングは勾配の二乗の指数移動平均で割ることで行います。" + }, + "adam": { + "references": "適応的モーメント推定\n (Adaptive Moment Estimation)\n (Velasco, 2020)", + "description": "AdaGrad と RMSProp を組み合わせたものです。パラメータごとの学習率を保持して RMSProp を計算し、さらに各学習率が勾配の momentum の影響を受けます。" + }, + "adamax": { + "description": "モメンタムと適応的な学習の手法を組み合わせ、ニューラルネットワークの学習の収束を加速します。学習率を自動的に調整し、発散の問題を避けるために勾配のスケーリングを使います。" + } } - } - }, - "line-charts": { - "warning": { - "config": "現在の設定は折れ線グラフには使えません。" }, - "title": "折れ線グラフ", - "description": { - "intro": { - "0": "折れ線グラフは、時系列または連続変数にわたるデータの関係と進化を示す視覚的表現です。これらのグラフは、デカルト座標系にデータポイントをプロットすることによって構築され、各ポイントは、時間または横軸の独立変数の関数として、垂直軸上の変数の測定値または特定の値を表します。", - "1": "折れ線グラフでは、データポイントは直線で接続され、一連の接続されたポイントが作成されます。これらの線は、時間または独立変数にわたるデータの軌道と変化のパターンを視覚化できます。線の傾きは、増加または減少の傾向を示すことができ、線の方向と形状の変化は、データ内の追加のパターンを明らかにすることができます。", - "2": "折れ線グラフには、いくつかの注目すべき特徴と用途があります。" + "loss-functions": { + "title": "損失関数", + "text": { + "0": "機械学習において、損失関数(コスト関数とも呼ばれる)は、モデルが予測した出力と実際の(期待される)出力との差を数値化する指標です。言い換えると、損失関数はモデルが学習データにどれだけよく適合しているかを測ります。", + "1": "機械学習アルゴリズムの目的は損失関数を最小化すること、つまり学習データに最もよく適合するモデルのパラメータを見つけることです。そのため損失関数の選択は非常に重要で、モデルがデータのパターンを正しく学習し、新しいデータに対して正確に予測する能力に影響します。", + "2": "Nets4Learning で選べる損失関数を、それぞれが適したタスクの種類ごとに示します。" }, - "list": { - "0": "傾向の表現: 折れ線グラフは、時間の経過に伴う傾向と変化を示すのに特に役立ちます。時間の経過とともにデータ内の成長、減少、または変動のパターンを明らかにすることができます。", - "1": "変化と変動の識別: 折れ線グラフを観察することで、データの急激な変化や変動を特定できます。これらの変化は、測定された変数に影響を与える重要なイベントまたは要因を示している可能性があります。", - "2": "複数の系列の比較: 折れ線グラフでは、単一のチャートで複数のデータ系列を比較することもできます。これは、時間の経過とともに進化する異なる変数間の関係を分析および視覚化するのに役立ちます。", - "3": "季節性とサイクルの分析: データが季節的または周期的なパターンを示す場合、折れ線グラフはこれらのパターンを識別および分析するのに役立ちます。これは、データに定期的な変動が存在する経済学、気象学、販売分析などの分野で役立ちます。", - "4": "予測と投影: 折れ線グラフは、履歴データに基づいて予測と投影を行うためにも使用されます。過去の傾向を見ることで、データが将来どのように振る舞うかを推測し、予測するための数学的または統計的モデルを構築できます。" + "table": { + "categoricalCrossentropy": { + "description": "モデルが予測した確率と正解クラス(one-hot 表現)との差を測ります。softmax 出力の多クラス分類でよく使われる損失です。" + }, + "binaryCrossentropy": { + "description": "2 クラス、または互いに独立した複数ラベルのための交差エントロピーです。sigmoid 出力と組み合わせて使います。" + }, + "kullbackLeiblerDivergence": { + "description": "予測した確率分布が正解の分布からどれだけ離れているかを測ります。モデルの出力が分布のときに使います。" + }, + "hinge": { + "description": "正解クラスに対して一定のマージンを超えない予測にペナルティを与えます。サポートベクターマシン由来で、-1 と 1 のラベルを想定しています。" + }, + "squaredHinge": { + "description": "ヒンジ損失を二乗したものです。大きな誤差をより強く罰します。" + }, + "categoricalHinge": { + "description": "多クラス用のヒンジ損失です。正解クラスのスコアを、最も高い不正解クラスのスコアと比べます。" + }, + "meanSquaredError": { + "description": "正解値と予測値の差の二乗の平均です。大きな誤差を強く罰し、回帰でよく使われる損失です。" + }, + "meanAbsoluteError": { + "description": "正解値と予測値の差の絶対値の平均です。二乗誤差よりも外れ値の影響を受けにくいです。" + }, + "meanAbsolutePercentageError": { + "description": "平均絶対誤差を正解値に対する割合(%)で表したものです。大きさの異なる値の誤差を比べるのに便利ですが、正解値が 0 の場合は使えません。" + }, + "meanSquaredLogarithmicError": { + "description": "値の対数に対する平均二乗誤差です。相対的な誤差を測り、大きな値での誤差をあまり罰しません。" + }, + "logcosh": { + "description": "誤差の双曲線余弦の対数です。小さな誤差では二乗誤差のように、大きな誤差では絶対誤差のように振る舞います。" + }, + "poisson": { + "description": "訪問数や発生件数のような、負でない整数(カウント)を予測するための損失です。" + }, + "cosineProximity": { + "description": "正解ベクトルと予測ベクトルの向き(なす角)を比べます。ベクトルの大きさは考慮しません。" + } }, - "end": { - "0": "折れ線グラフは、時系列または連続変数にわたるデータの関係と進化を視覚化および分析するための貴重なツールです。傾向、季節的なパターン、変化、および予測に関する貴重な情報を提供し、情報に基づいた決定と比較分析を可能にします。" - } - } - }, - "pie-charts": { - "warning": { - "labels": "設定で円グラフのラベルに使う列を選択してください。" + "related": "その他の関連する式" }, - "title": "円グラフ", - "description": { - "intro": { - "0": "円グラフは、全体に対する異なるカテゴリまたは部分の割合を示す視覚的表現です。これらのグラフは、セクターに分割された円に基づいており、各セクターは特定のカテゴリを表し、その相対的なサイズは、そのカテゴリがデータセット全体に占める割合を反映します。", - "1": "円グラフでは、完全な円が100%またはデータの合計を表します。各セクターは円の一部として表示され、それが表すカテゴリに対応する名前またはラベルでラベル付けされます。セクターの角度の尺度は、そのカテゴリがデータセットに占める割合に比例します。", - "2": "円グラフには、いくつかの注目すべき特徴と用途があります。" - }, - "list": { - "0": "割合の表現: 円グラフは、割合とパーセンテージを表すのに理想的です。データセット全体における各カテゴリの相対的な貢献をすばやく視覚化できます。", - "1": "主要なカテゴリの識別: 円グラフのセクターの相対的なサイズは、主要なカテゴリや最も重要なカテゴリを簡単に識別するのに役立ちます。最大のセクターは、他との関係でより大きな割合または貢献をしているカテゴリを示します。", - "2": "カテゴリ間の比較: 円グラフはカテゴリの割合を示すのに役立ちますが、それらの間で正確な比較を行うには制限される場合があります。これは、人間の知覚が角度やセクターのサイズの違いを正確に評価することが難しいためです。ただし、セクターのサイズ間の相対的な比較は、カテゴリ間の割合に関する一般的な情報を提供することができます。", - "3": "カテゴリデータの表現: 円グラフは、カテゴリが相互に排他的であり、固有の順序がないカテゴリデータを表すのに特に役立ちます。たとえば、異なる費用カテゴリの収入のパーセンテージ分布を示すために使用できます。", - "4": "視覚的プレゼンテーションの改善: 円グラフは、視覚的に魅力的で理解しやすい方法で情報を伝達するために、プレゼンテーションやドキュメントで一般的に使用されます。円形と使用される色は、注意をすばやく引き付け、カテゴリ間の比例関係を強調することができます。" + "metric-functions": { + "title": "評価指標", + "text-1": "テストデータセットでニューラルネットワークモデルの性能を評価するために使われます。評価指標はモデルの予測をテストデータの実際の値と比較し、モデルの精度を求めます。", + "text-2": "扱う問題の種類に応じて、ニューラルネットワークではさまざまな評価指標を使えます。例えば、二値分類の問題では正解率(Accuracy)を、回帰問題では平均二乗誤差(Mean Squared Error)を評価指標として使えます。", + "text-3": "まとめると、評価指標は、テストデータセットに対してニューラルネットワークが正確に予測できるかを評価し、性能を高めるためにモデルのパラメータを調整する際に役立つ重要なツールです。", + "text-4": "主に accuracy 関数を使います。マルチラベル分類では、この関数は部分集合の正解率を計算します。つまり、あるサンプルについて予測したラベルの集合が、y の対応するラベルの集合と完全に一致する必要があります", + "table": { + "BinaryAccuracy": { + "references": "二値正解率
(Acervolima, s.f.)", + "description": "予測が二値ラベルと一致する頻度を計算します。" + }, + "BinaryCrossentropy": { + "references": "二値交差エントロピー
(Saxena, 2021)", + "description": "正しいクラスに対して予測された確率の対数の負の平均です。" + }, + "CategoricalAccuracy": { + "references": "カテゴリ正解率", + "description": "予測が one-hot ラベルと一致する頻度を計算します。" + }, + "CategoricalCrossentropy": { + "references": "カテゴリ交差エントロピー", + "description": "ラベルと予測の間の交差エントロピーを計算します。" + }, + "CosineProximity": { + "references": "コサイン近接度", + "description": "ラベルと予測の間のコサイン近接度を計算します。通常は負の値になります。" + }, + "MeanAbsoluteError": { + "references": "平均絶対誤差", + "description": "統計学では、2つの連続変数の差を測る指標です。機械学習モデルに適用する場合、これらの変数はラベルと予測です。" + }, + "MeanAbsolutePercentageError": { + "references": "平均絶対パーセント誤差", + "description": "Mean absolute error と同様にラベルと予測の差を計算しますが、パーセントで表します。" + }, + "MeanSquaredError": { + "references": "平均二乗誤差", + "description": "ラベルと予測の間の平均二乗誤差を求めます。" + } }, - "end": { - "0": "円グラフは、データセット内のカテゴリの割合とパーセンテージを表すための効果的なツールです。主要なカテゴリを特定し、魅力的な視覚的プレゼンテーションを提供できます。ただし、カテゴリ間の正確な比較とカテゴリデータへの焦点という点での制限に注意することが重要です。" + "confusion": { + "title": "混同行列の評価指標", + "description": "混同行列の各クラスの正解と誤りから計算します:陽性と予測したうち正しいものの割合(適合率)、実際の陽性のうち見つけられた割合(再現率・感度)、その調和平均(F1)、実際の陰性のうち正しく認識された割合(特異度)。" } - } - }, - "scatter-plots": { - "warning": { - "axes": "設定でX軸とY軸の列を選択してください。" }, - "title": "散布図", - "description": { - "intro": { - "0": "散布図(またはドットプロット、英語でscatter plot)は、2つの変数間の関係を示すためにデカルト座標を使用する視覚的表現です。このタイプのグラフでは、データは2次元空間の個々の点として表され、各点は2つの変数に対応する値のペアを表します。", - "1": "散布図では、横軸は通常、独立変数に割り当てられ、縦軸は従属変数に割り当てられます。グラフ上の各点は個々の観測値を表し、グラフ上の位置は両方の変数に対して持つ値によって決定されます。グラフ上の点の相対的な位置は、2つの変数間のパターンと関係を明らかにします。", - "2": "散布図には、いくつかの注目すべき用途と特徴があります。" + "time-series": { + "title": "時系列", + "text-1": "時系列とは、一定の間隔で順番に測った値の並びです。毎月の乗客数、毎日の気温、毎週の売上などです。表とは違い順序に意味があり、各値はそれまでの値に左右されます。", + "text-2": "系列を予測するとは、過去の値から次の値を推定することです。ニューラルネットワークはウィンドウで学習します。直前の値を受け取り、次の値を予測します。", + "text-3": "テストでは、系列の最後をシャッフルせずに取り分け、直前の値や 1 季節前の値を繰り返すといった単純な予測と比べます。", + "group-title": "時系列", + "window": { + "title": "ウィンドウ", + "text": "ネットワークが次の値を予測するのに使う直前の値です。月ごとの系列で 12 のウィンドウなら、直近の 1 年を見ます。季節より短いと繰り返すパターンが見えず、長すぎると学習用の例が少なくなります。" }, - "list": { - "0": "変数間の関係: 散布図は、2つの変数間の関係を分析できます。正の相関(点が上向きに集まる傾向)、負の相関(点が下向きに集まる傾向)、または相関の欠如(点が明確なパターンを示さない)があるかどうかを示すことができます。", - "1": "傾向の特定: 散布図は、データ内の傾向またはパターンを明らかにすることができます。点の一般的な方向を見ることで、変数間に線形、非線形、または曲線的な関係があるかどうかを特定できます。", - "2": "外れ値の検出: 散布図は、データ内の外れ値または極値を特定するのに役立ちます。これらの点は目立ち、主要なグループから遠く離れており、追加の分析が必要な異常なまたは例外的な観測を示唆しています。", - "3": "クラスターまたはグループの分析: 散布図内の点がグループ化されたり、異なるパターンを形成したりする場合、これはクラスターまたはグループの存在を示している可能性があります。これは、データセグメンテーションまたは分類分析で役立ちます。", - "4": "多次元データの可視化: 追加の色や点のサイズを使用する場合、散布図は2次元空間で追加の情報を表すこともできます。これにより、多次元データをより直感的に表示できます。" + "trend-seasonality": { + "title": "トレンドと季節性", + "text": "トレンドは系列の長期的な向きです(乗客数は年々増えます)。季節性は一定の周期で繰り返すパターンです(毎年夏は乗客が多い)。太陽黒点のようなサイクルは、一定の周期なしに繰り返します。" }, - "end": { - "0": "散布図は、2つの変数間の関係を探索および視覚化するための強力なツールです。データ内のパターン、傾向、および外れ値を特定でき、相関分析、クラスター検出、多次元データの可視化などのさまざまなアプリケーションで役立ちます。" - } - }, - "index-info": "座標軸", - "form": { - "x": "X軸 (0)", - "y": "Y軸 (1)" - } - }, - "time-series-plots": { - "title": "時系列プロット", - "description": { - "intro": { - "0": "時系列チャートは、時間を追って一定の間隔で収集および記録されるデータの視覚的表現です。これらのチャートは、経済学、金融、気象学、工学、その他多くの分野で広く使用されており、時間の経過に伴うデータの変化を分析および理解するために使用されます。", - "1": "グラフの横軸は時間を表し、縦軸は観測または記録されているデータ値を表します。データポイントは線で接続され、時間の経過に伴うパターンと傾向を特定できます。", - "2": "時系列チャートには、いくつかの利点と実用的なアプリケーションがあります。" + "differencing": { + "title": "差分", + "text": "各値を直前の値からの変化に置き換えることです。トレンドが取り除かれ、ネットワークは学習とテストでより似ている変化を学習します。値に戻すには、各変化を直前の値に足します。" }, - "list": { - "0": "傾向分析: 時系列グラフは、データ内の長期的な傾向を特定および分析するのに役立ちます。これは、データが将来どのように振る舞うかを予測し、情報に基づいた決定を下すのに役立ちます。", - "1": "季節パターンの識別: 多くのデータセットには、ホリデーシーズン中の売上や農業生産の季節的な変動など、時間とともに定期的に繰り返される季節的なパターンがあります。時系列チャートは、これらの季節的なパターンを特定し、データへの影響を理解するのに役立ちます。", - "2": "変化と異常の検出: 時系列グラフを観察することで、データ内の急激な変化や異常を特定できます。これらの変化は、さらなる調査と分析が必要な重要または異常なイベントを示している可能性があります。", - "3": "モデリングと予測: 時系列グラフは、モデルと予測を開発するための基本的なツールです。過去のパターンを見ることで、関係を捉え、将来に関する予測を行う数学的または統計的モデルを構築できます。", - "4": "比較分析: 時系列チャートは、同じ期間に収集された異なるデータセットを比較するためにも使用されます。これは、観測された変数間の違い、類似性、および関係を特定するのに役立ちます。" + "one-step-recursive": { + "title": "1 ステップ予測と再帰的予測", + "text": "1 ステップ先では、各値をそれ以前の実際の値で予測します。再帰的(続けて)では、予測した値を次の予測に使います。未来を何ステップも予測する唯一の方法で、誤差が積み重なります。" }, - "end": { - "0": "時系列チャートは、時間の経過に伴うデータの変化を分析および理解するための不可欠なツールです。傾向、季節的なパターン、変化、および予測に関する貴重な情報を提供し、情報に基づいた決定と比較分析を可能にします。" - } - }, - "index-info": "選択するインデックスは一意の系列を含み、表示する列の隣のインデックスを選択してはいけません", - "form": { - "index": "インデックス" - } - }, - "time-series": { - "warning": { - "index": "このデータフレームは、一意の値を持つ特性の条件を満たしていないため、適切な視覚化を許可しません" - } - }, - "violin-plots": { - "warning": { - "index": "設定でバイオリン図に使う列を1つ以上選択してください。" - }, - "title": "バイオリンプロット", - "description": { - "intro": { - "0": "バイオリンプロットは、箱ひげ図の特徴と確率密度関数を組み合わせた視覚的表現です。このタイプのチャートは、データの分布の詳細なビューを提供し、単一のチャートで複数のグループまたはカテゴリを比較できます。", - "1": "バイオリンチャートの外観はバイオリンの形状に似ています。データのメジアンを表す中心線と、確率密度分布を表す両側の2つの陰影領域があります。これらの陰影領域は、中心線に沿って対称性を持ち、データの対称性または非対称性を反映します。", - "2": "バイオリンプロットの形状は、データの分布に関する情報を提供します。たとえば、特定のセクションのバイオリンプロットが広いほど、その領域のデータ密度が高いことを示し、セクションが狭いほど、密度が低いことを示します。さらに、バイオリンチャートは、複数のバイオリンをグループ化または重ね合わせることで、異なるグループまたはカテゴリの視覚的な比較を可能にします。", - "3": "バイオリンプロットには、いくつかの実用的なアプリケーションがあります。" + "baselines": { + "title": "ナイーブ予測と季節予測", + "text": "モデルと比べる最も単純な予測です。ナイーブ予測は最後に分かっている値を、季節予測は 1 季節前(12 か月前、7 日前など)の値を繰り返します。モデルが役に立つのは、これらより誤差が小さいときだけです。" }, - "list": { - "0": "分布の比較: バイオリンプロットを使用すると、異なるグループまたはカテゴリ間のデータ分布を比較できます。これは、データの形状、分散、および傾向の違いや類似性を特定するのに役立ちます。", - "1": "外れ値の識別: バイオリンプロットは、データ内の外れ値または極値の存在に関する視覚的な情報を提供します。これらの値は、陰影領域の外側のポイントとして表され、追加の分析が必要な異常な観測を示している可能性があります。", - "2": "確率密度の可視化: バイオリンプロットは、データの確率密度のグラフィカルな表現も提供します。これにより、高密度または低密度の領域、および分布の可能なバイアスまたは非対称性を簡単に特定できます。", - "3": "効果的なデータ通信: バイオリンチャートは、視覚的に魅力的な方法でデータの分布に関する複雑な情報を伝達するための効果的な方法です。情報を簡潔に要約し、非技術的な聴衆に重要なパターンと特徴を伝えるのに役立ちます。" + "recurrent": { + "title": "再帰型の層(SimpleRNN、LSTM、GRU)", + "text": "系列を値 1 つずつ読み、それまでに見たものをまとめた状態を保ちます。SimpleRNN は最も単純ですぐに忘れます。LSTM と GRU には何を覚え何を忘れるかを決めるゲートがあり、より長い依存関係を学習します。" }, - "end": { - "0": "バイオリンプロットは、データ分布を視覚化および比較するための便利なツールです。データの形状、分散、対称性、および外れ値の存在を分析でき、複数のグループまたはカテゴリ間の比較が必要な場合に特に役立ちます。その魅力的で簡潔なグラフィカルな表現は、複雑な情報を理解しやすい方法で伝達するための効果的なツールになります。" + "mae-rmse": { + "title": "MAE と RMSE", + "text": "系列の単位で誤差を測る 2 つの方法です。MAE(平均絶対誤差)は平均してどれだけ外れるか、RMSE(二乗平均平方根誤差)は大きな誤差をより重く扱います。" } - } - } - }, - "face-api": { - "years": "年齢", - "neutral": "ニュートラル", - "happy": "幸せ", - "sad": "悲しい", - "angry": "怒っている", - "fearful": "恐れている", - "disgusted": "嫌悪", - "surprised": "驚いている" - }, - "pages": { - "version": { - "title": "バージョン" + }, + "formula": "{{term}} の数式" }, - "index": { - "tabular-classification": { - "1-title": "表形式分類", - "1-description-1": "分類とは、その特徴(独立変数)から要素(従属変数)が属するクラスを決定するタスクです。", - "1-description-2": "予測タスクであり、その値が分類される要素が属することができる異なるクラスである離散変数を持ちます。", - "1-button": "事前訓練済みモデル", - "2-title": "ネットワークアーキテクチャの設計、作成、および編集", - "2-description-1": "このツールを通じて、マルチクラスデータを分類するためのニューラルネットワークを作成できます。", - "2-description-2": "カスタムアーキテクチャを設計、作成、トレーニング、および評価するには、以下が必要です。", - "2-description-list": { - "1": "レイヤーの数、その活性化関数を定義します。", - "2": "学習率を定義します。", - "3": "エポック数を定義します。", - "4": "オプティマイザーを定義します。", - "5": "損失関数を定義します。", - "6": "メトリクス関数を定義します。" - }, - "2-button": "モデルを作成して訓練する" + "terms": { + "title": "利用規約", + "updated": "最終更新日:2026年10月2日", + "summary-title": "要点", + "summary": [ + "Nets4Learningは無料の教育用ツールです。アカウントや登録はありません。", + "データはブラウザーの中にとどまります。モデルの学習と利用はあなたのパソコンで行われます。", + "Google AnalyticsのCookieは同意した場合にのみ有効になり、いつでも変更できます。" + ], + "index": "項目", + "use": { + "title": "アプリの利用", + "items": [ + "Nets4Learningは、深層学習を学び教えるための無料の教育用プラットフォームです。", + "コードはMITライセンスのフリーソフトウェアです。第三者のデータセットやモデルにはそれぞれのライセンスがあり、各説明に記載されています。", + "モデルの結果は学習のためのものです。医療や金銭、人に関する判断など、実際の判断には使わないでください。", + "アプリは現状のまま、保証なしで提供されます。誤りを含むことがあり、いつでも変更されることがあります。" + ] }, - "regression": { - "1-title": "回帰", - "2-title": "ネットワークアーキテクチャの設計、作成、および編集", - "1-description-1": "回帰とは、その特徴(独立変数)から特定の数値(従属変数)を決定するタスクです。", - "1-description-2": "出力として連続変数を持つ予測タスクであり、データに最もよく適合し、独立変数に基づいて従属変数の数値を予測できる直線を見つけることを目的としています。", - "1-button": "事前訓練済みモデル", - "2-description-1": "このツールを通じて、予測を行うためのニューラルネットワークを作成できます。", - "2-description-2": "モデルで使用される独立変数を定義し、予測しようとしている数値である従属変数を定義します。", - "2-description-3": null, - "2-description-list": { - "1": "レイヤーの数、その活性化関数を定義します。", - "2": "学習率を定義します。", - "3": "エポック数を定義します。", - "4": "オプティマイザーを定義します。", - "5": "損失関数を定義します。", - "6": "メトリクス関数を定義します。", - "title": "回帰を適用し、変数間の関係をモデル化するには、次の手順に従う必要があります。" - } + "privacy": { + "title": "あなたのデータ", + "text": "機械学習はすべてTensorFlow.jsによりブラウザーの中で実行されます。あなたのデータを受け取るサーバーはありません。", + "items": [ + "アップロードしたファイル(データセット、モデル、画像)、描いた絵、カメラの映像はあなたのパソコンで処理され、どこにも送られません。", + "サンプルのデータセットで学習したモデルは、ページを再読み込みしても失われないよう、ブラウザーに保存されます(データセットごとに最大10個)。設定から削除でき、持ち出すにはダウンロードしてください。", + "個人情報を求めたり保存したりすることはありません。アカウントもフォームもメールもありません。" + ] }, - "object-detection": { - "1-title": "物体認識", - "1-description-1": "物体の分類とは、その違いと類似性に従って要素を整理することから成ります。", - "1-description-2": "これらのモデルは、各物体を特徴づけるものを少しずつ学習できるように、さまざまな画像を多数使用して訓練されます。", - "1-button": "事前訓練済みモデル", - "2-title": "物体認識" + "storage": { + "title": "ブラウザーに保存されるもの", + "text": "設定を覚えておくため、アプリはブラウザーのローカルストレージ(私たちのサーバーではありません)に次のものを保存します。", + "items": [ + "選んだ言語、テーマ、TensorFlow.jsのバックエンド。", + "ガイドの音声の設定と、各ガイドがどのステップまで進んだか。", + "サンプルのデータセットで学習したモデルと、「ステップごと」を表示するかどうか。", + "Cookieについてのあなたの選択(専用のCookieに保存)。" + ], + "settings": "変更やすべての削除はこちらから行えます:" }, - "image-classification": { - "1-title": "画像分類", - "1-description-1": "画像分類は、古典的な分類と同じ方法で、1つ以上の独立変数に応じて従属変数が属するクラスを決定するのに役立ちます。", - "1-button": "事前訓練済みモデル", - "2-title": "ネットワークアーキテクチャの設計、作成、および編集", - "2-description-1": "このツールを通じて、マルチクラスデータを分類するためのニューラルネットワークを作成できます。", - "2-description-2": "カスタムアーキテクチャを設計、作成、トレーニング、および評価するには、以下が必要です。", - "2-description-list": { - "1": "レイヤーの数、その活性化関数を定義します。", - "2": "学習率を定義します。", - "3": "エポック数を定義します。", - "4": "オプティマイザーを定義します。", - "5": "損失関数を定義します。", - "6": "メトリクス関数を定義します。" + "third-parties": { + "title": "外部サービス", + "items": [ + "Google Analytics(Cookieに同意した場合のみ)。どのセクション・モデル・データセットがどれくらいの時間使われ、どのボタンが押され、どんなエラーが起きたかを知るためです。", + "一部の学習済みモデル(検出モデルとMobileNet)は、開いたときにGoogleとjsDelivrのサーバーからダウンロードされます。どのWebサイトとも同じく、それらのサーバーはリクエストを見ますが、あなたのデータや画像は見ません。", + "ガイドで「オンライン」の音声を選ぶと、ブラウザーは読み上げのためにガイドのテキストを音声サービスへ送ります。" + ] + }, + "cookies": { + "title": "Cookie", + "text": "Cookieの一覧です。Google AnalyticsのCookieは匿名の利用統計を集めるもので、広告には使われず、同意した場合にのみ作成されます。後から拒否すると削除されます。", + "name": "Cookie", + "purpose": "用途", + "duration": "期間", + "consent": { + "purpose": "Google AnalyticsのCookieに同意したか拒否したかを覚えておきます。", + "duration": "120日" }, - "2-button": "モデルを作成して訓練する" + "ga": { + "purpose": "Google Analytics:訪問者を匿名で区別します。", + "duration": "13か月" + }, + "ga-session": { + "purpose": "Google Analytics:訪問の状態を保持します。", + "duration": "13か月" + } + }, + "contact": { + "title": "お問い合わせ", + "text": "Nets4Learningは、ハエン大学の研究グループSIMIDAT(知的システムとデータマイニング)が開発しています。質問や問題があれば:", + "issues": "GitHubでissueを作成する", + "simidat": "SIMIDATグループのWebサイト" } }, - "contribute": { - "title": "貢献する", - "github": { - "title": "GitHubのプロジェクト" + "not-found": { + "title": "ページが見つかりません", + "return-home": "ホームに戻る" + }, + "settings": { + "title": "設定", + "intro": "アプリで調整できることのすべてです。設定はこのブラウザーにだけ保存されます。", + "appearance": { + "title": "言語と外観", + "language": "言語", + "theme": "テーマ", + "theme-system": "システムに合わせる", + "theme-help": "「システムに合わせる」は、OSのライトモードまたはダークモードに従います。", + "summary": "言語とライト・ダークテーマ" }, - "license": { - "title": "ライセンス" - } + "backend": { + "title": "TensorFlow.jsのバックエンド", + "help": "学習と予測のときにTensorFlow.jsが計算を行う場所です。変更はすぐに反映され、すでにあるモデルもそのまま使えます。", + "active": "使用中", + "webgl": "WebGLでグラフィックカードを使います。ほとんどのパソコンで最も高速です。", + "webgpu": "最新のAPIであるWebGPUでグラフィックカードを使います。より高速なこともありますが、対応していないブラウザーもあります。", + "wasm": "WebAssemblyでプロセッサーを使って計算します。グラフィックカードで問題が起きるときに便利です。", + "cpu": "JavaScriptでプロセッサーを使って計算します。どこでも動きますが、最も遅いです。", + "summary": "TensorFlow.js の計算場所:GPU か CPU" + }, + "downloads": { + "title": "モデルのダウンロード", + "help": "一部の学習済みモデル(物体検出、MobileNetなど)は、ページを開くと2〜18 MBをダウンロードします。事前に確認するよう設定できます。", + "auto": "データセーバー使用時や通信が遅いときに確認", + "auto-help": "ブラウザのデータセーバーがオンのとき、または通信が2G・3Gのとき。", + "always": "常に確認", + "always-help": "まだダウンロードしていない2 MBを超えるモデルをダウンロードする前に。", + "never": "確認しない", + "never-help": "ページを開くとモデルをダウンロードします。", + "now-save-data": "現在、ブラウザのデータセーバーがオンです。", + "now-slow": "現在、通信が遅いようです。", + "now-normal": "現在、データセーバーはオフで、通信も遅くないようです(またはブラウザが情報を提供していません)。", + "summary": "大きなモデルをダウンロードする前に確認する", + "saved": "ダウンロードしたモデルは、再ダウンロードしなくて済むようにこのブラウザーに保存されます。容量の確認と削除はこのブラウザーに保存されたデータでできます。" + }, + "speech": { + "title": "ガイドの音声", + "help": "モデルのページのガイドは、システムの音声で各ステップを読み上げることができます。", + "voice": "ガイドを音声で読み上げる", + "auto": "各ステップを読み終えたら自動で進む", + "voice-help": "「オンライン」の音声はブラウザーのサーバーで動作し、ガイドのテキストは読み上げのためにそこへ送られます。", + "no-voices": "システムにこの言語の音声がありません。ブラウザーが選んだ音声を使います。", + "rate": "速さ:{{rate}}×", + "test": "音声を試す", + "stop": "停止", + "sample": "こんにちは。Nets4Learningの各ページのガイドは、このように聞こえます。", + "screen-reader": "スクリーンリーダーを使う場合はオフにしてください。スクリーンリーダーがガイドの各ステップを読み上げるので、2 つの声が重なると聞き取れません。", + "summary": "ガイドの読み上げ、声と速さ" + }, + "tutorials": { + "title": "ガイド", + "guides-help": "各ガイドは今どのステップにいるかを覚えています。リセットすると、すべて最初からやり直せます。", + "guides-reset": "ガイドをリセット", + "done": "完了", + "summary": "ページのガイドを最初からやり直す" + }, + "learning": { + "title": "学習用", + "help": "ページが重くならないよう、初期設定では表示されないツールです。", + "step-by-step": "「ステップごと」を表示:ネットワークが例ごとに、前向きと後ろ向きにどう学ぶか", + "step-by-step-help": "学習ページと、表形式の分類・回帰のモデルページに表示されます。ニューロンが64個未満のネットワークが対象です。", + "summary": "ステップバイステップなどの学習ツール" + }, + "privacy": { + "title": "プライバシーとCookie", + "help": "Google AnalyticsのCookieは、どのセクション・モデル・データセットが使われ、何がうまくいかないかを匿名で教えてくれます。個人情報やアップロードした内容は含みません。同意した場合にのみ有効になります。", + "analytics": "Google AnalyticsのCookieを許可する", + "status-accepted": "現在:Cookieに同意しています。", + "status-rejected": "現在:Cookieを拒否しています。", + "status-undecided": "まだ選択していません。今のところ使われていません。", + "more": "Cookieについての詳細", + "summary": "Google Analytics の Cookie" + }, + "data": { + "title": "このブラウザーに保存されたデータ", + "help": "アプリがこのブラウザーに保存しているデータです。外部に送られることはなく、いつでも削除できます。", + "summary": "保存されているもの、使用容量、すべてのリセット", + "total": "このサイトは、このブラウザーで合計 {{used}} を使用しています。", + "trained": { + "title": "学習させたモデル", + "help": "学習させて保存したモデルです。そのページに戻ると復元されます。", + "count_zero": "なし", + "count_other": "{{count}} 個のモデル", + "delete": "学習させたモデルを削除", + "question_other": "学習させたモデル {{count}} 個を削除します。元に戻せません。" + }, + "pretrained": { + "title": "ダウンロードした事前学習済みモデル", + "help": "物体検出や MobileNet など。再ダウンロードしなくて済むように、初めて使うときに保存されます。", + "count_zero": "なし", + "count_other": "{{count}} 個のモデル", + "delete": "ダウンロードした事前学習済みモデルを削除", + "delete-one": "{{model}} を削除", + "question": "次に使うときに再ダウンロードされます。", + "question-one": "{{model}} をこのブラウザーから削除します。次に使うときに再ダウンロードされます。", + "mobilenet": "MobileNet - 画像分類", + "other": "その他のファイル" + }, + "offline": { + "title": "オフライン用", + "help": "すでに開いたページです。インターネットなしでも使えます。", + "count_zero": "なし", + "count_other": "{{count}} 個のファイル", + "delete": "オフライン用に保存したデータを削除", + "question": "開いたものは、もう一度開くまでインターネットなしでは使えなくなります。" + }, + "settings": { + "title": "設定と進み具合", + "help": "言語、テーマ、アクセシビリティ、バックエンド、ガイドの音声と進み具合、ステップごと、ダウンロードの確認、Cookie についての選択。" + }, + "delete": "削除", + "delete-confirm": "はい、削除します", + "reset": "すべての設定をリセット", + "reset-help": "上記をすべて削除し、初期設定に戻します。ページは再読み込みされます。", + "confirm": "本当によろしいですか?このブラウザーに保存されたすべての設定が削除されます。", + "confirm-button": "はい、削除します", + "cancel": "キャンセル" + }, + "accessibility": { + "title": "アクセシビリティ", + "help": "必要に合わせてアプリを調整できます。このブラウザに保存されます。", + "text-size": "文字の大きさ", + "spacing": "行・文字・単語の間隔を広げる", + "spacing-help": "読みやすくするために WCAG が勧める間隔です。", + "highContrast": "ハイコントラスト", + "highContrast-help": "文字と枠線を黒(ダークテーマでは白)にし、灰色を使いません。", + "reduceMotion": "動きを減らす", + "reduceMotion-help": "グラフも含め、アニメーションやなめらかなスクロールをなくします。", + "underlineLinks": "リンクに常に下線を引く", + "underlineLinks-help": "色に頼らずに本文と区別できます。", + "strongFocus": "フォーカスを太くする", + "strongFocus-help": "キーボード操作時の現在位置を示す枠をより見やすくします。", + "openVisor": "学習時に TensorFlow.js のビジュアライザーを開く", + "openVisor-help": "スクリーンリーダーでは使えないライブラリのパネルです。ページのグラフが同じ内容を示します。", + "system-on": "システムがすでに求めているため、チェックしなくても有効です。", + "guide": "ガイドの音声と自動で進む設定は次で変更します:", + "summary": "文字の大きさ、コントラスト、動き、フォーカス" + }, + "sections": "設定の項目", + "back": "すべての項目" }, - "menu-selection-dataset": { - "0-tabular-classification": { - "csv": "データセットをアップロード - CSV", - "csv-text": ".csv 形式の処理済みデータセットファイル​​をアップロード" + "learn": { + "title": "ここから始める", + "intro": "ニューラルネットワークの基本を手を動かして学ぶ8つの短いステップです。学習済みのネットワークを試すところから、判断の理由を尋ねるところまで。各ステップは実行すると自動でチェックされます。", + "progress": "{{total}}ステップ中{{count}}ステップ完了", + "step": "ステップ{{number}}", + "done": "完了", + "next": "次", + "go": "このステップへ", + "again": "もう一度やる", + "mark-done": "完了にする", + "mark-undone": "チェックを外す", + "reset": "最初からやり直す", + "reset-confirm": "よろしいですか?すべてのステップのチェックが外れます。", + "reset-yes": "はい、やり直す", + "reset-no": "キャンセル", + "finished": { + "title": "コースを完了しました!", + "text": "ニューラルネットワークの学習、比較、修正、説明ができるようになりました。次は自分のデータで試しましょう。表形式の分類や回帰でCSVをアップロードするか、まずEDAで分析してみてください。" }, - "form-description-1": "次に、作業するデータセットを選択するか、独自のデータセットをロードします。", - "form-label": "データセットを選択", - "form-option-_-1": "データセットを選択", - "form-upload-description": "次に、必要に応じて独自のアーキテクチャをロードできます。そうしない場合は、続行をクリックすると、デフォルトの例のアーキテクチャがロードされます。", - "form-submit": "続行", - "1-regression": { - "csv": "データセットをアップロード - CSV", - "csv-text": ".csv 形式の処理済みデータセットファイル​​をアップロード" + "steps": { + "lab": { + "title": "ネットワークで遊ぶ", + "text": "ラボでは、小さなネットワークが平面上の点を分け、学習中の境界が見られます。「試してみよう」の例をやってみましょう。" + }, + "glossary": { + "title": "キーワード", + "text": "用語集で、ニューラルネットワーク、層、ニューロン、エポックとは何かを読みましょう。どのページにも出てきます。" + }, + "pretrained": { + "title": "学習済みのネットワークを試す", + "text": "数字を描いて、何千もの手書き数字(MNIST)で学習したネットワークがどう認識するか見てみましょう。" + }, + "train": { + "title": "初めてのネットワークを学習する", + "text": "アヤメ(Iris)のデータで「モデルを訓練」を押し、損失がエポックごとに下がる様子を見ましょう。下に、学習の結果が言葉で表示されます。" + }, + "step-by-step": { + "title": "ネットワークの学習を見る", + "text": "アヤメの花のデータで、ステップごとに 1 つの例がネットワークを順方向に進み、誤差が逆方向に戻って、各重みがどう変わるかを見せます。少なくとも 1 ステップ進めてください。" + }, + "compare": { + "title": "1つだけ変えて比較する", + "text": "学習率だけを変えてもう一度学習し、曲線の横の「モデルを比較」をオンにしましょう。何が変わり、どちらがよく学習するかがわかります。" + }, + "fix-layers": { + "title": "間違った構成のネットワークを直す", + "text": "層エディタで、最後の層のニューロン数をクラス数と違う値にすると警告が表示されます。ボタンで直すと、出力層がクラスごとに1つのニューロンを持つ理由がわかります。" + }, + "regression": { + "title": "数値を予測する", + "text": "回帰では、ネットワークはクラスを選ぶのではなく値を出します。Auto MPGで学習して車の燃費を予測しましょう。" + }, + "cnn": { + "title": "画像用のネットワークを学習する", + "text": "畳み込みネットワークは画像の中の線や形を探します。MNISTで学習してみましょう(他より少し時間がかかります)。" + }, + "explain": { + "title": "モデルに理由を尋ねる", + "text": "車のモデル(CAR)で予測を行い、その説明を表示しましょう。判断にどの属性が最も影響したかがわかります。" + } + }, + "challenges": { + "title": "チャレンジ", + "intro": "学習のしかたがわかったら、学んだことを試してみましょう。層とハイパーパラメータを調整して達成を目指します。学習すると自動でチェックされます。", + "progress": "{{total}}個中{{count}}個のチャレンジを達成", + "passed": "達成", + "result": "正解率{{value}}で達成しました。", + "hint": "ヒント", + "go": "挑戦する", + "again": "もう一度挑戦する", + "iris-accuracy": { + "title": "完璧なIris", + "goal": "Irisで、テスト用の花(学習中にネットワークが見ないデータ)をすべて正解しましょう。正解率100 %です。", + "hint": "エポック数を増やし(50)、学習率を少し上げてみましょう(0.05)。一度でうまくいかなければ、もう一度学習しましょう。毎回、ネットワークは異なる重みから始まります。" + }, + "iris-tiny": { + "title": "ごく少ないニューロンで", + "goal": "Irisで、隠れニューロン4個以下(出力層を除く)で正解率90 %に到達しましょう。", + "hint": "4ニューロンの隠れ層を1つだけ(または2ニューロンを2つ)にして、エポック数を増やしましょう。簡単な問題に大きなネットワークは不要です。" + }, + "iris-fast": { + "title": "少ないエポックで", + "goal": "Irisで、5エポック以内に正解率90 %に到達しましょう。", + "hint": "エポックが少ないときは、一歩一歩が重要です。学習率を上げ(0.1)、Adamを使いましょう。" + }, + "regression-good": { + "title": "お手本のような学習", + "goal": "回帰で、どのデータセットでもよいので、診断で「よく学習した」と判定される学習を行いましょう。損失が下がって安定し、過学習がない状態です。", + "hint": "まずSalaryで40エポック程度から始めましょう。診断が「まだ改善中」ならエポック数を増やし、損失が大きく揺れている・発散していると表示されたら学習率を下げましょう。" + }, + "mnist-fast": { + "title": "急いで数字を認識", + "goal": "MNISTで、2エポック以内にテスト画像の正解率93 %以上を達成しましょう。", + "hint": "2エポックでは、ネットワークがデータを見るのは2回だけです。学習率を少しずつ上げてみましょう(0.005、0.01…)。上げすぎると、診断で損失が大きく揺れている・発散していると表示されます。" + } + }, + "toast": { + "title": "ステップ{{number}}/{{total}}完了", + "next": "次:{{title}} →", + "finished": "コースを完了しました! →", + "close": "閉じる", + "challenge": "チャレンジ達成!", + "challenges": "チャレンジを見る →" + }, + "home": { + "first": "初めてですか?ここから始める:手を動かして学ぶ8つの短いステップです。", + "continue": "ここから始めるの{{total}}ステップ中{{count}}ステップを完了しています。続きから進めましょう。", + "finished": "ここから始めるを完了しました。自分のデータで試してみましょう。" } }, - "menu-selection-model": { - "form-description-1": "作業する訓練済みモデルを選択します。", - "form-description-2": "-", - "form-label": "事前訓練済みモデルを選択", - "form-option-_-1": "事前訓練済みモデルを選択", - "form-submit": "続行" + "regression-description": { + "title": "線形回帰", + "subtitle": "問題とモデルの説明", + "paragraphs": [ + "データ分析における回帰問題とは、いくつかの入力変数から数値を予測・推定する問題です。線形回帰は、その予測を行うための数学的モデルです。", + "線形回帰モデルは、応答変数(従属変数)と1つ以上の説明変数(独立変数)の間の線形な関係を求める統計的手法です。観測データに最もよく当てはまる直線を見つけ、それを使って説明変数から応答変数を予測することが目的です。", + "モデルはこの関係を直線の式で表し、応答変数の値を説明変数の線形結合として推定します。その係数(回帰係数)は、観測値と予測値の差ができるだけ小さくなるように統計的手法で求めます。", + "当てはめたモデルは、説明変数が分かっているときに応答変数を予測するのに使えます。また、応答のばらつきを説明するうえで各説明変数がどれだけ寄与しているかも分かります。", + "まとめると、線形回帰モデルは、説明変数との線形な関係にもとづいて数値を予測する統計的な道具です。経済学、科学、工学、社会調査などの分野で役立ちます。" + ], + "example": "家の広さ(平方メートル、説明変数 $x$)から家の価格(応答変数 $Y$)を予測したいとします。2つの変数の関係は、次の線形回帰の式で表せます:", + "where": "ここで:", + "terms": [ + "$Y$ は家の価格です。", + "$x$ は家の広さです。", + "$\\beta_0$ は切片で、$x$ が0のときの $Y$ の値です。", + "$\\beta_1$ は直線の傾きで、1平方メートル増えるごとに価格がどれだけ変わるかを表します。", + "$\\epsilon$ は誤差項で、モデルが説明できないばらつきです。" + ], + "closing": [ + "線形回帰の目的は、観測データから $\\beta_0$ と $\\beta_1$ を推定し、散布図の点に最もよく当てはまる直線を求めることです。", + "当てはめたモデルを使えば、新しい家の価格を広さから予測できます。式の $x$ に値を入れて $Y$ を計算するだけです。", + "この例は単純な単回帰の場合です。実際には、多くの説明変数を持ち、それらの組み合わせも考慮するモデルがあります。" + ] }, - "playground": { - "form": { - "select-parameter": "パラメータを選択", - "parameter": "パラメータ", - "parameter-integer": "整数パラメータ", - "parameter-decimal": "小数パラメータ", - "parameter-float": "単精度浮動小数点パラメータ", - "parameter-double": "倍精度浮動小数点パラメータ", - "parameter-categorical": "カテゴリパラメータ", - "data-to-check": "テストするデータ", - "vector-to-check": "テストするベクトル", - "button-check-result": "予測" + "task": { + "pretrained-title": "学習済みモデル", + "pretrained-text": "すでに学習したモデルです。学習を待たずにすぐ試せて、なぜその判断をしたのかも見られます。", + "pretrained-count_other": "{{count}} 個のモデル", + "pretrained-button": "モデルを選ぶ", + "design-title": "アーキテクチャを設計・作成・編集する", + "design-text": "データセットを選び(または自分のものをアップロードし)、ネットワークの層を設計し、学習を調整して、学ぶ様子を見ます。", + "design-count_other": "{{count}} 個のデータセット", + "design-button": "データセットを選ぶ", + "cluster-title": "データセットをクラスタリングする", + "cluster-text": "列とグループの数を選ぶと、k-means が少しずつグループを探します。データセットに本当のクラスがあれば、最後に比較します。", + "upload": "自分のものをアップロード", + "only-pretrained": "このタスクには学習済みモデルしかありません。", + "only-cluster": "クラスタリングはネットワークも学習済みモデルも使いません。k-means がデータを直接グループ分けします。" + }, + "accessibility": { + "title": "アクセシビリティ", + "updated": "2026 年 10 月 12 日に作成し、同日に最終確認しました。", + "summary-title": "概要", + "summary": [ + "スクリーンリーダー、キーボードのみ、ロービジョン、大きな文字でも、だれもが Nets4Learning を使えるようにしたいと考えています。", + "このアプリは WCAG 2.2 レベル AA に部分的に適合しています。以下で説明する点を除き、ほぼすべてが適合しています。", + "使えないところがあればお知らせください。それが改善のいちばんの近道です。" + ], + "index": "項目", + "status": { + "title": "適合状況", + "text": "Nets4Learning は、「アクセシブルでないコンテンツ」に挙げた例外のため、Web コンテンツ・アクセシビリティ・ガイドライン(WCAG)2.2 レベル AA に部分的に適合しています。", + "standard": "WCAG 2.2 AA は、スペインの王令 1112/2018 が公共部門の Web に適用する規格 EN 301 549(WCAG 2.1 AA)の要件を含みます。" }, - "0-tabular-classification": { - "general": { - "model": "モデル", - "description-input": "データエントリの説明", - "description-features": "特徴量編集フォーム", - "description-data": "フォームデータ", - "description-vector": "データベクトル", - "explainability": "モデルの解釈性", - "select-class": "クラスを選択", - "n-samples": "サンプル数", - "n-samples-help": "KernelSHAP が使用するサンプル数", - "calculating": "計算中...", - "show-explain": "説明を表示", - "hide-explain": "説明を非表示", - "n-instances": "集約するインスタンス数", - "n-instances-help": "グローバル重要度(平均 |SHAP|)の計算に集約するデータセットのインスタンス数", - "show-global": "グローバル重要度を表示", - "hide-global": "グローバル重要度を非表示", - "no-data": "グローバル重要度を計算するためのデータセットがありません", - "sort-order": "並び替え", - "sort-desc": "重要度の高い順", - "sort-asc": "重要度の低い順", - "sort-none": "元の順序", - "chart-type": "グラフの種類", - "chart-bar": "棒グラフ(平均 |SHAP|)", - "chart-beeswarm": "ビースウォーム", - "beeswarm-shap-value": "SHAP 値", - "beeswarm-feature-value": "特徴量の値", - "beeswarm-low": "低", - "beeswarm-high": "高", - "explain-panel-title": "説明可能性", - "explain-panel-local-title": "局所的な説明(1つのインスタンス)", - "explain-panel-local-body": "SHAP は、この予測とモデルの平均予測(基準値)との差を各特徴量に分配することで、1つの予測を説明します。各バーは、特徴量がどれだけ、どの方向に作用するかを示します。正の値は選択したクラスに向かって、負の値はそれに反して作用します。", - "explain-panel-local-body-regression": "SHAP は、予測値とモデルの平均予測(基準値)との差を各特徴量に分配することで、1つの予測を説明します。各バーは、特徴量がどれだけ、どの方向に作用するかを示します。正の値は予測値を上げ、負の値は予測値を下げます。", - "explain-panel-global-title": "グローバル重要度(すべてのインスタンス)", - "explain-panel-global-body": "グローバル重要度は、多数の局所的な説明を集約します。棒グラフは絶対値の平均(平均 |SHAP|)、つまり各特徴量が平均してどれだけ重要かを示します。ビースウォームは、各点を特徴量の値で色付けし、効果の方向とばらつきを加えて示します。順列重要度などの他の手法では、特に特徴量同士が関連している場合、特徴量の順位が多少異なることがあります。手法ごとに重要度の測り方が違うためです。" + "not-accessible": { + "title": "アクセシブルでないコンテンツ", + "text": "次の点は完全には適合していません。代わりに使えるものも示します。", + "items": [ + { + "problem": "学習時に開く TensorFlow.js のビジュアライザーはライブラリのもので、キーボードで操作できず、グラフにテキストがありません。", + "instead": "同じ曲線がページにあり、データは表で見られます。「設定」でビジュアライザーを開かないようにできます。" + }, + { + "problem": "データ分析のグラフ(Plotly)のズームボタンはキーボードで操作できません。", + "instead": "各グラフのデータはその表(「データを表示」)にあります。" + }, + { + "problem": "キャンバスに数字を描くにはマウス、ペン、指が必要です。", + "instead": "ページ上の例やテスト画像を分類してください。" + }, + { + "problem": "物体検出のカメラ映像には説明がありません。", + "instead": "検出結果は下にテキストで示され、ボタンで読み上げられます。写真をアップロードすることもできます。" + }, + { + "problem": "数式はスクリーンリーダー向けに MathML で生成していますが、すべてのスクリーンリーダーではまだ確認していません。", + "instead": "うまく読み上げられない数式があればお知らせください(「問題を知らせる」)。" + } + ], + "out-of-scope": "このステートメントの対象外:アプリが使う第三者のモデルやライブラリ、およびリンク先の外部ページ。", + "instead": "代わりに:" + }, + "use": { + "title": "アプリの使い方", + "keyboard-title": "キーボードで", + "keyboard": [ + "Tab キーでページを順に移動します。最初は「メインコンテンツへスキップ」で、メニューを飛ばして本文へ移動します。", + "Enter キーまたはスペースキーでボタンとリンクを操作します。矢印キーでタブ、ドロップダウン、選択肢の一覧、ガイドのステップを移動します。", + "Esc キーでダイアログ、ドロップダウン、モバイルのメニュー、ガイド、用語のヘルプを閉じ、フォーカスは元の位置に戻ります。", + "長いページでは「このページの内容」の目次から各項目へ移動できます。" + ], + "reader-title": "スクリーンリーダーで", + "reader": [ + "各ページにはタイトルと主見出しが 1 つあり、項目の見出しは順序どおりです。", + "各グラフには説明と、描かれた内容をすべて表で示す「データを表示」ボタンがあります。", + "フォーカスを動かさずに変わる内容(予測の結果、読み込んだデータ、学習の進み具合、層の警告、言語やテーマの変更)は読み上げられます。", + "各ページのガイドはスクリーンリーダーで読めます。使う場合は、二つの声が重ならないよう「設定」でガイドの音声をオフにしてください。" + ], + "settings-title": "アクセシビリティの設定", + "settings": "文字を大きくする、行や文字の間隔を広げる、ハイコントラスト、動きを減らす、リンクに下線を引く、フォーカスを太くする、といった設定ができます。ブラウザに保存されます。", + "settings-link": "アクセシビリティの設定へ" + }, + "feedback": { + "title": "問題を知らせる", + "text": "使えないところや、適合していないと思うところがあればお知らせください。改善のために、次の情報があると助かります。", + "items": [ + "どのページで、何をしようとしていたか。", + "何が起きたか。", + "使っているブラウザと、使っていればスクリーンリーダーなどの支援技術。" + ], + "issue": "GitHub で問題を知らせる(テンプレートあり)", + "simidat": "ハエン大学 SIMIDAT グループの Web サイト(連絡用)", + "response": "できるだけ早くお返事し、改善するまでの間に目的を達成する方法があればお伝えします。" + }, + "preparation": { + "title": "作成方法と見直し", + "items": [ + "方法:開発チームによる自己評価。", + "変更のたびに自動テスト:全ページと操作中に現れる状態(ライト・ダークテーマ、アクセシビリティ設定あり)での axe による WCAG 2.2 A・AA の確認、キーボードのみでの操作、幅 320 px と文字 200 % での表示、リンターのアクセシビリティ規則。", + "未実施:スクリーンリーダー(NVDA、VoiceOver、TalkBack)による手動確認と、さまざまな障害のある人によるテスト。" + ], + "review": "このステートメントは毎年、およびアプリのメジャーバージョンごとに見直します。" + }, + "new-tab": "(新しいタブで開きます)" + }, + "lab": { + "title": "ラボ:2D のネットワーク", + "intro": "小さなニューラルネットワークが、オレンジの点と青の点を分けることを学びます。データやネットワークへの入力、層を変えて、学習中に境界がどう変わるかを見てみましょう。", + "data": { + "title": "データ", + "dataset": "データセット", + "noise": "ノイズ:{{value}}", + "count": "点の数", + "new": "別の点" + }, + "datasets": { + "blobs": "2 つの雲", + "circles": "円", + "xor": "XOR(象限)", + "spiral": "らせん" + }, + "features": { + "title": "ネットワークへの入力", + "help": "各点の座標と、必要ならそこから計算した値。", + "x": "x", + "y": "y", + "x2": "x²", + "y2": "y²", + "xy": "x × y" + }, + "network": { + "title": "ネットワーク", + "help": "入力と出力の間の隠れ層。それぞれにニューロンがあります。", + "none": "隠れ層なし:入力がそのまま出力につながります。", + "layer": "層 {{number}}:ニューロン {{units}} 個", + "fewer": "層 {{number}} のニューロンを 1 つ減らす", + "more": "層 {{number}} のニューロンを 1 つ増やす", + "add": "層を追加", + "remove": "最後の層を削除", + "activation": "活性化関数" + }, + "training": { + "title": "学習のしかた", + "learning-rate": "学習率", + "speed": "速度", + "speeds": { + "slow": "ゆっくり(境界が見える)", + "normal": "ふつう", + "fast": "できるだけ速く" }, - "0_upload": { - "upload": "アップロード", - "upload-your-model": "モデルをロード", - "upload-your-model-description": "モデルをロードするには、.jsonファイルと.binファイルをアップロードする必要があることに注意してください", - "button-upload-your-model": "モデルをロード" + "batch-size": "バッチあたりの点の数" + }, + "train": "学習", + "pause": "一時停止", + "step": "1 エポック", + "restart": "最初から", + "restarted": "ネットワークを新しいランダムな重みで最初からやり直します。", + "show-test": "テスト用の点を表示", + "canvas": "{{dataset}} の点がある平面。背景は、各領域でネットワークが予測するクラスです", + "legend": "オレンジ(円)と青(四角)が 2 つのクラスです。塗りつぶしは学習に使う点、白はテスト用の点で、学習中には見ません。背景はネットワークの予測で、濃いほど確信が強いことを表します。", + "not-trained": "まだ学習していません。「学習」か「1 エポック」を押してください。", + "summary": "エポック {{epoch}}:テスト用の点の {{testAccuracy}}、学習用の点の {{trainAccuracy}} を正解。損失:学習用 {{trainLoss}}、テスト用 {{testLoss}}。", + "diverged": "損失が発散し、ネットワークが学習しなくなりました。学習率を下げて最初からやり直してください。", + "loss": { + "title": "損失", + "empty": "学習すると、ここで損失が下がる様子が見られます。", + "train": "学習", + "test": "テスト", + "help": "学習用の損失が下がるのにテスト用が上がるなら、点を丸暗記しています(過学習)。" + }, + "experiments": { + "title": "試してみよう", + "xor-line": { + "title": "隠れ層なしの XOR", + "lesson": "隠れ層がないと直線しか引けません。XOR では半分も正解できません。" }, - "generator": { - "manual": { - "title": "モデルジェネレーターマニュアル", - "details-edit-layers": { - "title": "レイヤーエディタ", - "text-0": "ニューラルネットワークのレイヤーを編集できます。開始時または終了時に「レイヤーを追加」ボタンを押して、必要な数だけ追加できます。", - "list": { - "0": "レイヤーニューロン:
レイヤー内の各ニューロンには、出力値を重み付けする一連の関連付けられた重みがあります。
レイヤー内のニューロンの数を編集できます。", - "1": "活性化関数:
ニューロンの活性化関数は、受信した入力に基づいて出力を計算する数学関数を指します。各レイヤーのニューロンの活性化関数を編集できます。" - } - }, - "details-hyper-parameters-editor": { - "title": "ハイパーパラメータエディタ", - "text-0": "モデルの作成に必要な一般的なパラメータを編集できます。
これらのパラメータは次のとおりです。", - "list": { - "0": "学習率:
0から100までの値で、重み付けされた重みのパーセンテージを示します。", - "1": "エポック数:
トレーニング中にトレーニングデータセットがネットワークに提示される回数(数が多いほど、トレーニングに時間がかかります)。", - "2": "テストセットサイズ:
モデルテスト(テストデータ)に使用されるデータセットのパーセンテージ。残りのデータはネットワークトレーニング(トレーニングデータ)に使用されます。", - "3": "オプティマイザー:
ネットワークの重みを調整するために使用される関数です。", - "4": "損失関数:
トレーニング中のモデルの効率を測定するための誤差計算方法です。", - "5": "メトリクス関数:
テストデータを使用した機械学習モデルのパフォーマンスを評価するために使用される平均評価です。" - } - }, - "details-hyper-parameters-info": { - "title": "ハイパーパラメータ情報", - "list": { - "0": "学習率:
学習率は、トレーニング中に計算された誤差に応じて、ニューラルネットワークの重みがどの程度更新される必要があるかを決定するパラメータです。", - "1": "エポック数:
エポック数は、トレーニングプロセス中にトレーニングデータがニューラルネットワークに提示される回数を指します。各反復は、計算された誤差の関数としてのネットワークの重みの更新を意味します。", - "2": "テストセットサイズ:
テストセットのサイズは、トレーニング後にニューラルネットワークのパフォーマンスを評価するために使用されるデータの量を指します。このデータセットはニューラルネットワークのトレーニングには使用されず、新しいデータに一般化するネットワークの能力を測定するために使用されます。", - "3": "オプティマイザー:
オプティマイザーは、トレーニング中に計算された誤差に応じてニューラルネットワークの重みを更新するために使用されるアルゴリズムです。一般的なオプティマイザーの例には、確率的勾配降下法(SGD)、Adam、およびAdagradがあります。", - "4": "損失関数:
損失関数は、ニューラルネットワークの予測と実際の出力との間の不一致を測定する尺度です。トレーニング中にニューラルネットワークを最適化するために使用され、交差エントロピーや平均二乗誤差など、さまざまな損失関数があります。" - } - }, - "details-create-and-train-models": { - "title": "モデルを作成して訓練する", - "text-0": "前のすべてのフィールドが入力されたら、「モデルを作成して訓練する」ボタンを押してモデルを作成できます。", - "text-1": "メトリック関数 Accuracy でモデルを訓練した場合、バイザーに2つのグラフが表示されます。私たちにとって最も関連性の高いのは下のグラフです。tensorflow.jsでは、accとval_accは、ニューラルネットワークのモデルのトレーニングで一般的に使用される評価メトリクスです。
Accは、トレーニングデータセットにおけるモデルの精度(Accuracy)を表します。精度は、正しい予測の数を予測の総数で割ったものとして定義されます。
Val_accは、検証データセットにおけるモデルの精度を表します。検証は、トレーニング中に見られなかった新しいデータに一般化するモデルの能力を評価するために使用されます。", - "text-2": "検証の精度は、モデルがトレーニングデータに過度に適合し、新しいデータにうまく一般化できない場合に発生する過剰適合(overfitting)を検出するために重要です。" - }, - "details-export-models": { - "title": "モデルをエクスポート", - "text-0": "モデルを正しく作成した場合、生成されたモデルのテーブルにエントリが追加されます。生成されたモデルをエクスポートしてローカルに保存できます。" - }, - "details-prediction": { - "title": "予測", - "text-0": "最終フォームでは、クラスを決定するために使用される主要な特徴量を選択できます。", - "text-1": "「結果を表示」ボタンを押すと、要素の入力特徴量から出力クラスの予測が取得されます。" - } + "xor-hidden": { + "title": "ニューロン 4 個の層がある XOR", + "lesson": "隠れ層があると複数の直線を組み合わせて XOR を分けられます。隠れ層はそのためにあります。" + }, + "circles-features": { + "title": "x² と y² を使った円", + "lesson": "x² と y² を入力にすると、隠れ層なしで円を分けられます。入力をうまく選ぶと層を節約できます。" + }, + "spiral": { + "title": "いちばん難しいらせん", + "lesson": "らせんにはより多くのニューロンと特徴量、そして根気が必要です。数百エポック学習させましょう。" + }, + "learning-rate": { + "title": "とても大きな学習率", + "lesson": "学習率が 3 だと毎回行き過ぎて、損失が下がらずに上下します。0.1 を試してみてください。" + }, + "overfitting": { + "title": "少ない点、多いノイズ、大きなネットワーク", + "lesson": "点を丸暗記してしまい、学習用の損失は下がるのにテスト用は上がります。これが過学習です。" + } + }, + "next": "感覚がつかめたら、次は" + } + }, + "generator": { + "table-models": { + "list-models-generated": "生成されたモデルの一覧", + "learning-rate": "学習率", + "test-size": "テストセットのサイズ", + "n-of-epochs": "エポック数", + "n-epochs": "エポック数", + "id-optimizer": "オプティマイザ", + "id-loss": "損失", + "id-metrics": "評価指標", + "layers": "レイヤー", + "download": "ダウンロード", + "features": "特徴量", + "open-visor": "ビューアを開く", + "close-visor": "ビューアを閉じる", + "history": "最終値(検証)", + "window": "ウィンドウ", + "difference": "差分", + "batch-size": "バッチサイズ" + } + }, + "hr": { + "information": "情報", + "editor": "エディタ", + "dataset": "データセット", + "model": "モデル", + "step-by-step": "ステップごと", + "generated-models": "生成されたモデル", + "predict": "予測", + "classify": "分類", + "explainability": "説明可能性", + "on-this-page": "このページの内容", + "tasks": "タスク", + "00-tabular-classification": "表形式データの分類", + "tutorial-00-tabular-classification": "表形式データ分類のモデルを学習", + "01-regression": "回帰", + "02-object-detection": "物体検出", + "03-image-classification": "画像分類", + "optimization-function": "最適化関数", + "activation-functions": "活性化関数", + "loss-functions": "損失関数", + "metric-function": "評価指標関数", + "layers": "レイヤー", + "process-dataset": "データセットの処理", + "project": "プロジェクト", + "add-model-dataset": "プロジェクトにモデルを追加", + "dataframe": "データフレーム" + }, + "form-dataframe": { + "int32": "整数", + "float32": "浮動小数点数", + "string": "テキスト", + "label-encoder": "ラベルエンコーダ", + "one-hot-encoder": "ワンホットエンコーダ", + "drop": "削除", + "ignored": "無視", + "submit": "データフレームを処理" + }, + "upload-dataset-info": "タスクを実行するにはデータセットをアップロードする必要があります。", + "upload-model": "モデルをアップロード", + "upload-model-info": "タスクを実行するにはモデルをアップロードする必要があります。", + "upload-dataset": "データセットをアップロード", + "model-summary": "モデルの概要", + "breadcrumb": { + "label": "パンくずリスト", + "models": "学習済みモデル", + "datasets": "モデルを学習する", + "change": "リストの別の項目に切り替える", + "train-with-dataset": "このデータセットで学習する", + "try-pretrained": "学習済みモデルを試す" + }, + "neural-network": { + "layer": "レイヤー {{index}}", + "units": "ニューロン {{units}}", + "kernel-size": "カーネル {{value}}", + "filters": "フィルター {{value}}", + "pool-size": "プール {{value}}", + "strides": "ストライド {{value}}", + "description": "入力から出力までのネットワークの層" + }, + "session": { + "export": "設定をエクスポート", + "import": "設定をインポート", + "imported": "設定をインポートしました", + "error-not-json": "ファイルが有効な JSON ではありません", + "error-not-session": "Nets4Learning の設定ファイルではありません", + "error-other-task": "別のタスクの設定です", + "error-link": "リンクに有効な設定が含まれていません(コピーの際に途切れた可能性があります)", + "share": { + "button": "共有", + "title": "この課題を共有", + "text": "リンクを開いた人は、同じネットワークとハイパーパラメータを使って、同じデータセットですぐに学習できます。データと学習済みモデルは共有されません。", + "link": "共有用リンク", + "copy": "コピー", + "copied": "コピーしました!", + "native": "他のアプリで共有…", + "qr": "またはスマートフォンでスキャン", + "close": "閉じる" + } + }, + "guide": { + "button": "ガイド", + "button-title": "このページのステップごとのガイド(音声で読み上げます)", + "resume": "ガイドを続ける(ステップ {{current}} / {{total}})", + "restart": "最初に戻る", + "step": "ステップ {{current}} / {{total}}", + "back": "戻る", + "next": "次へ", + "finish": "終了", + "close": "ガイドを閉じる", + "voice-on": "音声で読み上げる", + "voice-off": "音声をミュート", + "no-voice": "このブラウザーは音声の読み上げに対応していません", + "repeat": "このステップをもう一度読む", + "auto-on": "各ステップの後に自動で進む", + "auto-off": "自動で進むのをやめる", + "0-tabular-classification": { + "CAR": { + "intro": { + "title": "自動車の分類", + "content": "このページでは、学習済みのニューラルネットワークが、購入価格、メンテナンス費用、ドアの数、乗車定員、トランクの大きさ、安全性の6つの特徴から、車が受け入れられるかどうかを判定します。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "model": { + "title": "モデル", + "content": "これはモデルの説明です。データの出典であるUCIリポジトリのCar Evaluationデータセット、ネットワークが受け取る特徴、予測できるクラスが書かれています。" + }, + "model-summary": { + "title": "モデルの概要", + "content": "このボタンでネットワークの概要を開きます。各層とそのニューロン数、そしてパラメーター数、つまり学習中に調整された重みの数がわかります。" + }, + "dataset": { + "title": "データセット", + "content": "これはネットワークの学習に使われた1728台の車です。各行が1台の車、各列がその特徴の1つです。強調表示された最後の列がクラス、つまりネットワークが予測するように学習したものです。" + }, + "dataset-processed": { + "title": "処理済みデータ", + "content": "ニューラルネットワークは数値しか扱えません。このタブでは、同じ車の各カテゴリーが数値に変換されています。たとえば、4種類の価格は0から3の数値になります。モデルが実際に受け取るのはこの形です。" + }, + "instances": { + "title": "例と行", + "content": "このセレクターでフォームを一度に入力できます。上には星印の付いた例がクラスごとに1つずつ、下にはデータセットのすべての行が実際のクラスとともに並んでいます。" + }, + "fields": { + "Buying": { + "title": "購入価格", + "content": "車を買うのにかかる金額です。非常に高い、高い、普通、低いのいずれかです。" + }, + "Maint": { + "title": "メンテナンス費用", + "content": "点検や修理など、車の維持にかかる費用です。これも非常に高いから低いまであります。" + }, + "Doors": { + "title": "ドアの数", + "content": "2、3、4、または5以上です。判定への影響が最も小さい特徴です。" + }, + "Persons": { + "title": "乗車定員", + "content": "乗れる人数で、2人、4人、それ以上のいずれかです。このデータでは、2人乗りの車は必ず「不可」になります。" + }, + "Lug_boot": { + "title": "トランクの大きさ", + "content": "小、中、大のいずれかです。トランクが大きいほど、車は受け入れられやすくなります。" + }, + "Safety": { + "title": "安全性", + "content": "車の推定安全性で、低、中、高のいずれかです。最も重要な特徴で、安全性が低い車は必ず「不可」になります。" } + }, + "vector": { + "title": "言葉から数値へ", + "content": "左はフォームの値、右はネットワークに入るベクトルです。同じ6つの特徴が、学習時に覚えた符号化で数値に変換されています。" + }, + "classify": { + "title": "分類", + "content": "このボタンを押すと、ネットワークがベクトルを受け取り、層ごとに計算して各クラスの確率を出します。" + }, + "result": { + "title": "結果", + "content": "ここに各クラスの確率が表示され、最も高いものが予測です。例や行を変更せずに分類すると実際のクラスも表示されるので、ネットワークが正解したかどうかを確認できます。このモデルの出力は「不可」「可」「優」の3つだけです。「良」の出力はないため、予測されることはありません。" + }, + "explain": { + "title": "解釈性", + "content": "分類した後、ここでネットワークがなぜそう判断したのかを確認できます。SHAPは判断を特徴ごとに分け、どれがそのクラスへ押し上げ、どれが逆に働いたかを示します。全体の重要度は多くの行で同じことを行い、一般にどの特徴が最も効いているかを示します。" + }, + "end": { + "title": "試してみよう", + "content": "例を選んで分類し、そのあと安全性や乗車定員を変えて、予測がどう変わるかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" } }, - "generator": { - "prediction": { - "class_id_name": "ターゲットのID {{class_target_id}} はクラス {{name}} に対応します" + "common": { + "model": { + "title": "モデル", + "content": "これはモデルの説明です。データの出典、ネットワークが受け取る特徴、予測できるクラスが書かれています。" }, - "layer-design": "レイヤー設計", - "neural_network_modes": { - "title": "視覚化モード", - "compact": "コンパクトモード", - "extend": "拡張モード" + "model-summary": { + "title": "モデルの概要", + "content": "このボタンでネットワークの概要を開きます。各層とそのニューロン数、そしてパラメーター数、つまり学習中に調整された重みの数がわかります。" }, "dataset": { "title": "データセット", - "upload-dataset": "データセットをアップロード", - "attributes": { - "title": "属性", - "int32": "数値", - "float32": "小数", - "string": "テキスト", - "label-encoder": "ラベルエンコーダ", - "one-hot-encoder": "OneHotエンコーダ", - "classes": "クラス" + "content": "これはネットワークの学習に使われたデータです。各行が1つの例、各列が1つの特徴です。強調表示された最後の列がクラス、つまりネットワークが予測するように学習したものです。" + }, + "dataset-processed": { + "title": "処理済みデータ", + "content": "ニューラルネットワークは数値しか扱えません。このタブでは、同じデータをモデルが受け取る形で表示しています。各カテゴリーは数値に変換されています。" + }, + "dataset-analysis": { + "title": "分析", + "content": "このタブはデータセットの探索的分析をまとめたものです。サイズ、欠損値、各クラスの例の数、クラスの偏りなどの注意点、そして互いに関係のある特徴がわかります。分類する前にデータを理解するのに便利です。" + }, + "instances": { + "title": "例と行", + "content": "このセレクターでフォームを一度に入力できます。上には星印の付いた例、下にはデータセットのすべての行が実際のクラスとともに並んでいます。" + }, + "form": { + "title": "フォーム", + "content": "ここに分類したいものの値を、特徴ごとに1つの欄に入力します。各欄の下には、データセットでの名前と入力できる値が表示されます。" + }, + "vector": { + "title": "データからベクトルへ", + "content": "左はフォームの値、右はネットワークに入るベクトルです。同じ特徴が、学習時に覚えた符号化で数値に変換されています。" + }, + "classify": { + "title": "分類", + "content": "このボタンを押すと、ネットワークがベクトルを受け取り、層ごとに計算して各クラスの確率を出します。" + }, + "result": { + "title": "結果", + "content": "ここに各クラスの確率が表示され、最も高いものが予測です。例や行を変更せずに分類すると実際のクラスも表示されるので、ネットワークが正解したかどうかを確認できます。" + }, + "explain": { + "title": "解釈性", + "content": "分類した後、ここでネットワークがなぜそう判断したのかを確認できます。SHAPは判断を特徴ごとに分け、どれがそのクラスへ押し上げ、どれが逆に働いたかを示します。全体の重要度は多くの行で同じことを行い、一般にどの特徴が最も効いているかを示します。" + }, + "step-by-step": { + "title": "ステップごと", + "content": "ここでは、このモデルが実際の重みでどう答えを計算するかが見られます。層ごとの前向きの計算、誤差、そして後ろ向きに、もう1ステップ学習したら各重みがどれだけ変わるかです。ニューロンをクリックすると計算が見られます。ニューロンが64個未満のモデルのときだけ描かれます。" + }, + "end": { + "title": "試してみよう", + "content": "例を選んで分類し、そのあと特徴を変えて、予測がどう変わるかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + }, + "IRIS": { + "intro": { + "title": "アヤメの分類", + "content": "このページでは、学習済みのニューラルネットワークが、がく片と花弁の長さと幅という4つの測定値から、アヤメの種類を判定します。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "dataset": { + "title": "データセット", + "content": "統計学者ロナルド・フィッシャーが1936年に紹介した有名なIrisデータセットです。150本の花があり、各種類50本ずつです。各行が1本の花とそのセンチメートル単位の4つの測定値で、強調表示された最後の列がその種類です。" + }, + "fields": { + "sepal_length": { + "title": "がく片の長さ", + "content": "がく片は、花が開く前に花を守る緑の葉です。この欄はその長さで、単位はセンチメートルです。" }, - "details": { - "dataframe-processed": "処理済みデータフレーム", - "description-original": "元のデータフレームの説明", - "description-processed": "処理済みデータフレームの説明", - "data": "データセット情報", - "info": "情報" + "sepal_width": { + "title": "がく片の幅", + "content": "がく片の幅で、単位はセンチメートルです。種類の区別に最も役立たない測定値です。" + }, + "petal_length": { + "title": "花弁の長さ", + "content": "花弁の長さで、単位はセンチメートルです。花弁の幅とともに、種類を最もよく分ける測定値です。setosaは他の2種類よりずっと小さな花弁をしています。" + }, + "petal_width": { + "title": "花弁の幅", + "content": "花弁の幅で、単位はセンチメートルです。このデータでは、花弁の幅が1センチメートル未満の花は必ずsetosaです。" } }, - "layers": { - "title": "レイヤー設計", - "page-info": "netron.appにアクセスしてトポロジ全体を視覚化できます" + "vector": { + "title": "データからベクトルへ", + "content": "ここでは4つの測定値がすでに数値なので、ネットワークに入るベクトルは同じ測定値を同じ順番で並べたものです。" }, - "editor-layers": { - "title": "レイヤーエディタ", - "add-layer-start": "最初にレイヤーを追加", - "add-layer-end": "最後にレイヤーを追加", - "delete-layer": "レイヤー {{index}}を削除", - "layer-id": "レイヤー {{index}}", - "kernel-size": "カーネルサイズ", - "kernel-size-placeholder": "レイヤーのカーネルサイズを入力してください", - "filters-size": "フィルターサイズ", - "filters-size-placeholder": "レイヤーのフィルターを入力してください", - "units": "レイヤーニューロン", - "units-placeholder": "レイヤーのニューロン数を入力してください", - "activation-function-select": "活性化関数を選択", - "activation-function-info": "関数をアクティブ化するために使用されるオプティマイザーになります", - "strides": "ストライド", - "strides-placeholder": "レイヤーのストライドを入力してください", - "pool-size": "プールサイズ", - "pool-size-placeholder": "レイヤーのプールサイズを入力してください" + "result": { + "title": "結果", + "content": "ここにsetosa、versicolor、virginicaの各種類の確率が表示され、最も高いものが予測です。setosaは見分けやすいですが、残りの2種類は似ているため、ネットワークが迷うのはそこです。" }, - "editor-feature-selector": { - "title": "特徴量セレクター", - "feature-selector-x": "特徴量セレクター / セット (X)", - "feature-selector-y": "特徴量セレクター / ターゲット (Y)", - "add-feature": "特徴量を追加", - "delete-feature": "特徴量 {{value}}を削除" + "end": { + "title": "試してみよう", + "content": "versicolorの例を選んで分類し、花弁の長さと幅を少しずつ大きくしてみましょう。ネットワークが迷い始め、最後にはvirginicaと答えるのがわかります。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + }, + "LYMPHOGRAPHY": { + "intro": { + "title": "リンパ管造影の分類", + "content": "このページでは、学習済みのニューラルネットワークが、リンパ系の画像検査であるリンパ管造影の結果を、正常所見、転移、悪性リンパ腫、線維症の4つの診断に分類します。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" }, - "general-parameters": { - "title": "ハイパーパラメータエディタ", - "learning-rate": "学習率", - "learning-rate-placeholder": "学習率を入力してください", - "learning-rate-info": "0から100までの値(パーセンテージ)", - "number-of-epochs": "エポック数", - "number-of-epochs-placeholder": "エポック数", - "number-of-epochs-info": "値が高いほど、トレーニングの実行に時間がかかります", - "train-rate": "テストセットサイズ", - "train-rate-placeholder": "テストセットのサイズを入力してください", - "train-rate-info": "テストセットサイズの0から100までの値(パーセンテージ)", - "optimizer-id": "オプティマイザーを選択", - "optimizer-id-info": "誤差を修正するために使用されるオプティマイザーになります。", - "loss-id": "損失関数を選択", - "loss-id-info": "ニューロンの誤差を評価するために使用される関数になります。", - "metrics-id": "メトリクスを選択", - "metrics-id-info": "トレーニング評価に使用されるメトリクスタイプになります。", - "test-size": "テストセットサイズ", - "test-size-placeholder": "テストセットサイズ", - "test-size-info": "テストセットサイズの0から100までの値(パーセンテージ)", - "delete-metric": "メトリクス関数 {{index}}を削除", - "add-metric": "メトリクス関数を追加", - "metric-id-__index__": "メトリクス {{index}}", - "metric-id-select": "メトリクス関数を選択", - "metric-id-info": "メトリクス関数の一つになります" + "dataset": { + "title": "データセット", + "content": "リュブリャナ大学医療センター腫瘍学研究所の148人の患者のデータです。各行が1人の患者、各列がリンパ管造影で観察された項目です。クラスは大きく偏っていて、転移が81件、悪性リンパ腫が61件ある一方、線維症は4件、正常所見は2件しかありません。" + }, + "form": { + "title": "リンパ管造影でわかること", + "content": "フォームには18の特徴があります。リンパ管が正常か、弓状か、変形しているか、ずれているかを示すもの、閉塞や迂回、造影剤の漏れがあるかを示すもの、そしてリンパ節の数、大きくなったか小さくなったか、形、構造の欠損や変化を表すものです。医学用語ですが、すべてを理解しなくても予測の変化は確認できます。" + }, + "result": { + "title": "結果", + "content": "ここに各診断の確率が表示され、最も高いものが予測です。線維症と正常所見の例がとても少ないため、ネットワークは主に転移と悪性リンパ腫の区別を学習しています。" + }, + "end": { + "title": "試してみよう", + "content": "各診断の例を選んで分類し、解釈性でそれぞれどの特徴が最も効いたかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + } + }, + "1-regression": { + "common": { + "model": { + "title": "モデル", + "content": "これはモデルの説明です。データの出典、ネットワークが受け取る変数、予測する変数が書かれています。" + }, + "model-summary": { + "title": "モデルの概要", + "content": "このボタンでネットワークの概要を開きます。各層とそのニューロン数、そしてパラメーター数、つまり学習中に調整された重みの数がわかります。" + }, + "dataset-select": { + "title": "データセット", + "content": "ここでデータセットを選びます。それぞれに学習済みのネットワークがあります。" + }, + "dataset": { + "title": "データセット", + "content": "これはネットワークの学習に使われたデータです。各行が1つの例、各列が1つの変数です。強調表示された列が目的変数、つまりネットワークが予測するように学習した数値です。" + }, + "dataset-processed": { + "title": "処理済みデータ", + "content": "このタブでは、同じデータをモデルが受け取る形で表示しています。テキストは数値に変換され、その下に各列の統計的な説明があります。" + }, + "dataset-analysis": { + "title": "分析", + "content": "このタブはデータセットの探索的分析をまとめたものです。サイズ、欠損値、目的変数の分布、目的変数と最も関係のある変数がわかります。予測する前にデータを理解するのに便利です。" + }, + "instances": { + "title": "データセットの行", + "content": "このセレクターで、データセットの任意の行をフォームに入力できます。行番号の横には実際の値が表示されるので、あとで予測と比べられます。" }, - "loaded": "ロード済み", - "load": "ロード", - "waiting-for-file": "ファイルを待機中", - "waiting-for-process": "データセット処理を待機中", - "waiting-for-training": "モデルトレーニングを待機中", "models": { "title": "モデル", - "history-train": "トレーニング履歴", - "train": "トレーニング履歴", - "button-submit": "モデルを訓練", - "open-visor": "バイザーを開く", - "close-visor": "バイザーを閉じる", - "export-current-model": "現在のモデルをエクスポート" + "content": "ここで、このデータセット用に学習済みのネットワークを1つ選びます。" }, - "table": { - "id": "ID", - "load": "ロード", - "learning-rate": "学習率", - "number-of-epochs": "エポック数", - "train-rate": "テストセットサイズ", - "layers": "レイヤー", - "optimizer-id": "オプティマイザー", - "loss-id": "損失", - "metric-id": "メトリクス", - "download": "ダウンロード" + "form": { + "title": "フォーム", + "content": "ここに入力変数の値を、変数ごとに1つの欄に入力します。各欄の下には、その種類とデータでの値の範囲が表示されます。" }, - "dynamic-form-dataset": { + "predict": { "title": "予測", - "text-0-__column_name_target__": "予測する例の各入力特徴量の値を入力してください {{column_name_target}}", - "select-option": "オプションを選択", - "input-data": "テストするデータを入力", - "input-vector": "テストするベクトルを入力", - "test-vector": "テストするベクトル", - "test-input-data": "フォームデータ", - "test-input-vector": "テストするベクトル", - "selector-entity": "エンティティを選択", - "selector-model": "モデルを選択" + "content": "このボタンを押すと、ネットワークが符号化とスケーリング済みの値を受け取り、層ごとに計算して1つの数値、つまり予測を返します。" }, - "list-models-generated": "生成されたモデルのリスト", - "visor": { - "title": "バイザーの設定", - "rmse": "RMSE", - "val_rmse": "VAL RMSE", - "mae": "MAE", - "val_mae": "VAL MAE", - "history-train": "トレーニング履歴", - "train": "トレーニング履歴", - "summary": "概要", - "scatterplot": { - "__feature____target__": "{{feature}} x {{target}}" - }, - "original-vs-predictions": "元のデータ/予測", - "model": "モデル", - "dataset": "データセット", - "predictions": "予測結果", - "predicted": "予測", - "confusion-matrix": "混同行列", - "line-chart": "折れ線グラフ" + "result": { + "title": "結果", + "content": "ここに予測値が表示されます。データセットの行を変更せずに使った場合は、実際の値と誤差、つまり両者の差も表示されます。その下には、ネットワークに入る前にデータが通る各段階があります。" + }, + "explain": { + "title": "解釈性", + "content": "予測した後、ここでネットワークがなぜその値を出したのかを確認できます。SHAPは予測を変数ごとに分け、平均的な予測と比べてどれが値を上げ、どれが下げたかを示します。全体の重要度は多くの行で同じことを行い、一般にどの変数が最も効いているかを示します。" + }, + "step-by-step": { + "title": "ステップごと", + "content": "ここでは、このモデルが実際の重みでどう答えを計算するかが見られます。層ごとの前向きの計算、誤差、そして後ろ向きに、もう1ステップ学習したら各重みがどれだけ変わるかです。ニューロンをクリックすると計算が見られます。ニューロンが64個未満のモデルのときだけ描かれます。" }, - "waiting-for-models": "モデルの作成を待機中" + "end": { + "title": "試してみよう", + "content": "行を選んで値を予測し、そのあと変数を変えて、予測がどう変わるかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } }, - "1-regression": { - "generator": { - "manual": { - "title": "モデルジェネレーターマニュアル", - "simple-regression": "単回帰", - "multiple-regression": "重回帰", - "details-edit-layers": { - "title": "レイヤーエディタ", - "text": { - "0": "ニューラルネットワークのレイヤーを編集できます。開始時または終了時に「レイヤーを追加」ボタンを押して、必要な数だけ追加できます。" - }, - "list": { - "0": "レイヤーニューロン:
レイヤー内の各ニューロンには、出力値を重み付けする一連の関連付けられた重みがあります。
レイヤー内のニューロンの数を編集できます。", - "1": "活性化関数:
ニューロンの活性化関数は、受信した入力に基づいて出力を計算する数学関数を指します。各レイヤーのニューロンの活性化関数を編集できます。" - } - }, - "details-hyper-parameters-editor": { - "title": "ハイパーパラメータエディタ", - "text": { - "0": "モデルの作成に必要な一般的なパラメータを編集できます。
これらのパラメータは次のとおりです。" - }, - "list": { - "0": "学習率:
0から100までの値で、重み付けされた重みのパーセンテージを示します。", - "1": "エポック数:
トレーニング中にトレーニングデータセットがネットワークに提示される回数(数が多いほど、トレーニングに時間がかかります)。", - "2": "テストセットサイズ:
モデルテスト(テストデータ)に使用されるデータセットのパーセンテージ。残りのデータはネットワークトレーニング(トレーニングデータ)に使用されます。", - "3": "オプティマイザー:
ネットワークの重みを調整するために使用される関数です。", - "4": "損失関数:
トレーニング中のモデルの効率を測定するための誤差計算方法です。", - "5": "メトリクス関数:
テストデータを使用した機械学習モデルのパフォーマンスを評価するために使用される平均評価です。" - } - }, - "details-hyper-parameters-info": { - "title": "ハイパーパラメータ情報", - "list": { - "0": "学習率:
学習率は、トレーニング中に計算された誤差に応じて、ニューラルネットワークの重みがどの程度更新される必要があるかを決定するパラメータです。", - "1": "エポック数:
エポック数は、トレーニングプロセス中にトレーニングデータがニューラルネットワークに提示される回数を指します。各反復は、計算された誤差の関数としてのネットワークの重みの更新を意味します。", - "2": "テストセットサイズ:
テストセットのサイズは、トレーニング後にニューラルネットワークのパフォーマンスを評価するために使用されるデータの量を指します。", - "3": "オプティマイザー:
オプティマイザーは、トレーニング中に計算された誤差に応じてニューラルネットワークの重みを更新するために使用されるアルゴリズムです。一般的なオプティマイザーの例には、確率的勾配降下法(SGD)、Adam、およびAdagradがあります。", - "4": "損失関数:
損失関数は、ニューラルネットワークの予測と実際の出力との間の不一致を測定する尺度です。トレーニング中にニューラルネットワークを最適化するために使用され、交差エントロピーや平均二乗誤差など、さまざまな損失関数があります。" - } - }, - "details-create-and-train-models": { - "title": "モデルを作成して訓練する", - "text": { - "0": "前のすべてのフィールドが入力されたら、「モデルを作成して訓練する」ボタンを押してモデルを作成できます。", - "1": "メトリック関数 Accuracy でモデルを訓練した場合、バイザーに2つのグラフが表示されます。私たちにとって最も関連性の高いのは下のグラフです。tensorflow.jsでは、accとval_accは、ニューラルネットワークのモデルのトレーニングで一般的に使用される評価メトリクスです。
Accは、トレーニングデータセットにおけるモデルの精度(Accuracy)を表します。精度は、正しい予測の数を予測の総数で割ったものとして定義されます。
Val_accは、検証データセットにおけるモデルの精度を表します。検証は、トレーニング中に見られなかった新しいデータに一般化するモデルの能力を評価するために使用されます。", - "2": "検証の精度は、モデルがトレーニングデータに過度に適合し、新しいデータにうまく一般化できない場合に発生する過剰適合(overfitting)を検出するために重要です。" - } - }, - "details-export-models": { - "title": "モデルをエクスポート", - "text": { - "0": "モデルを正しく作成した場合、生成されたモデルのテーブルにエントリが追加されます。生成されたモデルをエクスポートしてローカルに保存できます。" - } - }, - "details-plot-models": { - "title": "予測のプロット", - "text": { - "0": "このタスクには疎なグラフを使用できます。これにより、元のデータを点の雲で表し、線を使用してモデルの予測をプロットします。使用するアーキテクチャに応じて、特定の傾きを持つ直線、またはデータにより適合して湾曲する線が得られます。これを行うには、最初の値から最後の値まで、100個の離散的なx予測が作成されます。" - } - } + "AUTO_MPG": { + "intro": { + "title": "燃費性能", + "content": "このページでは、学習済みのニューラルネットワークが、シリンダー数、排気量、馬力、重量、加速、モデル年の6つの情報から、車が燃料1ガロンで何マイル走るかを予測します。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "dataset-select": { + "title": "データセット", + "content": "このモデルのデータセットはAuto MPGの1つだけです。" + }, + "dataset": { + "title": "データセット", + "content": "Auto MPGデータセットの、1970年から1982年までの396台の車です。強調表示された列mpgは1ガロンあたりのマイル数で、高いほど燃費の良い車です。このデータでは9から46までです。" + }, + "fields": { + "cylinders": { + "title": "シリンダー数", + "content": "エンジンのシリンダーの数で、3から8までです。シリンダーが多いほど、たいてい燃費は悪くなります。" }, - "simple-regression": "単回帰", - "multiple-regression": "重回帰" + "displacement": { + "title": "排気量", + "content": "エンジンのシリンダーの総容積で、単位は立方インチです。大きいほど、車は燃料を多く使います。" + }, + "horsepower": { + "title": "馬力", + "content": "エンジンの出力です。馬力の大きい車ほど、1ガロンあたりに走れる距離はたいてい短くなります。" + }, + "weight": { + "title": "重量", + "content": "車の重さで、単位はポンドです。燃費と最も関係のある変数で、重い車ほど1ガロンあたりに走れる距離は短くなります。" + }, + "acceleration": { + "title": "加速", + "content": "時速0マイルから60マイルまでにかかる秒数です。数値が大きいほど加速がゆるやかな車で、たいてい燃費が良くなります。" + }, + "model-year": { + "title": "モデル年", + "content": "モデルが発売された年を2桁で表したもので、70から82までです。このデータセットでは新しい車ほど燃費が良く、その一因は当時の燃費規制です。" + } + }, + "result": { + "title": "結果", + "content": "ここに予測された燃費が、1ガロンあたりのマイル数で表示されます。行を変更せずに使った場合は、実際の値と誤差も表示されます。その下には、ネットワークに入る前にデータが通る各段階があります。" + }, + "end": { + "title": "試してみよう", + "content": "車を選んで燃費を予測し、そのあと重量や馬力を上げてみましょう。ネットワークが予測する1ガロンあたりのマイル数が減るのがわかります。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + }, + "STUDENT_PERFORMANCE": { + "intro": { + "title": "学生の成績", + "content": "このページでは、学習済みのニューラルネットワークが、学校生活、家庭、交友に関する30の情報から、中等教育の学生の最終成績を0から20の範囲で予測します。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "model": { + "title": "モデル", + "content": "これはモデルの説明です。データの出典、ネットワークが受け取る変数、予測する変数が書かれています。そこにあるG1とG2についての注記は元のデータの話で、このバージョンでは意図的に除いています。理由はこのあと説明します。" + }, + "dataset-select": { + "title": "データセット", + "content": "ポルトガルの2つの中等学校の、数学の学生とポルトガル語の学生の2つのデータセットがあります。それぞれに学習済みのネットワークがあります。" }, - "dataframe": { - "title": "処理済みデータフレーム" + "dataset": { + "title": "データセット", + "content": "各行が1人の学生で、数学は395人、ポルトガル語は649人です。強調表示された列G3は学年末の最終成績で、0から20までです。ここでは元のデータにあるG1とG2の2列、つまり1学期と2学期の成績を、意図的に除いています。" }, - "selector-instance": { - "option": "インスタンスセレクター" + "form": { + "title": "学生のデータ", + "content": "フォームには30の変数があります。年齢や性別などの個人に関するもの、母親と父親の学歴や職業などの家庭に関するもの、勉強時間、過去の落第、欠席などの学校に関するもの、そして友人との外出や飲酒などの交友に関するものです。過去の落第の数は、最終成績が低いことと最も関係しています。学期の成績はここにはありません。その理由は次のステップで説明します。" }, - "selector-model": { - "option": "モデルセレクター" + "grades": { + "title": "G1とG2の成績は?", + "content": "G1とG2は1学期と2学期の成績で、最終成績ととてもよく似ています。G3との相関は0.8から0.92です。これがあると、ネットワークはほとんど何も学ぶ必要がなく、2学期の成績を写すだけで済んでしまいます。これがなければ、学生の学校生活、家庭、交友だけから最終成績を予測しなければなりません。ずっと難しくなりますが、そのぶん役に立ちます。成績がまだ1つもない時点で予測でき、助けが必要な学生を早めに支援できるからです。そのため、このページのネットワークはG1とG2なしで学習しています。" }, - "details": { - "description-processed": { - "dataset": "データフレーム情報", - "describe": "データフレームの説明" - } + "result": { + "title": "結果", + "content": "ここに0から20の範囲で予測された最終成績が表示されます。行を変更せずに使った場合は、実際の成績と誤差も表示されます。ネットワークは学期の成績を知らないので、数点ずれるのは普通です。成績が出る前に予測できることの代償です。" }, - "predict": { - "title": "予測", - "instance": { - "__index__": "インスタンス {{index}}" - }, - "model": { - "__index__": "モデル {{index}}" - }, - "button-submit": "予測", - "list-models-generated": "生成されたモデルのリスト", - "list-models": "生成されたモデルのリスト", - "list-instances": "インスタンスのリスト" + "end": { + "title": "試してみよう", + "content": "学生を選んで成績を予測し、そのあと過去の落第の数や勉強時間を変えて、予測がどう変わるかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + }, + "WINE": { + "intro": { + "title": "ワインの品質", + "content": "このページでは、学習済みのニューラルネットワークが、11の化学的な測定値から、ポルトガル産ワインの品質、つまりテイスターが付けた点数を予測します。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" }, - "model-selector": { - "title": "モデルセレクター", - "option": "モデルを選択" + "dataset-select": { + "title": "データセット", + "content": "ヴィーニョ・ヴェルデ地方の赤ワインと白ワインの2つのデータセットがあります。それぞれに学習済みのネットワークがあります。" + }, + "dataset": { + "title": "データセット", + "content": "各行が1本のワインで、赤が1599本、白が4898本です。強調表示された列qualityはテイスターの点数で0から10までですが、このデータでは3から9までしかなく、ほとんどのワインが5か6です。" + }, + "form": { + "title": "ワインの測定値", + "content": "フォームには11の化学的な測定値があります。固定酸度と揮発酸度、クエン酸、残留糖分、塩化物、遊離二酸化硫黄と総二酸化硫黄、密度、pH、硫酸塩、アルコールです。品質と最も関係があるのはアルコールで、アルコール度数の高いワインほど点数が高い傾向があります。赤ワインでは、揮発酸度が高いと点数が下がります。" + }, + "result": { + "title": "結果", + "content": "ここに予測された品質が表示されます。整数とは限らず、たとえば5.6のような値になることもあります。行を変更せずに使った場合は、実際の点数と誤差も表示されます。" + }, + "end": { + "title": "試してみよう", + "content": "ワインを選んで品質を予測し、そのあとアルコールを上げて、予測がどう変わるかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" } }, - "3-image-classification": { - "generator": { - "manual": { - "title": "モデルジェネレーターマニュアル", - "details-edit-layers": { - "title": "レイヤーエディタ", - "text-0": "ニューラルネットワークのレイヤーを編集できます。開始時または終了時に「レイヤーを追加」ボタンを押して、必要な数だけ追加できます。", - "list": { - "0": "レイヤーニューロン:
レイヤー内の各ニューロンには、出力値を重み付けする一連の関連付けられた重みがあります。
レイヤー内のニューロンの数を編集できます。", - "1": "活性化関数:
ニューロンの活性化関数は、受信した入力に基づいて出力を計算する数学関数を指します。各レイヤーのニューロンの活性化関数を編集できます。" - } - }, - "details-edit-layers-more-info": { - "title": "追加情報レイヤー", - "text-0": "さらに、画像分類に焦点を当てた他の機械学習ネットワークに共通するレイヤーが2つあります。", - "list": { - "0": "dense
密な(完全に接続された)レイヤーを作成します。", - "1": "dropout
ドロップアウトは、トレーニング時間中の各更新で入力ユニットの分数率をランダムに0に設定することで構成され、過剰適合を防ぐのに役立ちます。", - "2": "embedding
正の整数(インデックス)を固定サイズの密なベクトルにマッピングします。例:[[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]", - "3": "flatten
Flattenレイヤーは、入力内の各バッチを1Dに平坦化します(出力を2Dにします)。", - "4": "permute
指定されたパターンに従って入力の次元を並べ替えます。", - "5": "repeatVector
入力を新しい次元でn回繰り返します。", - "6": "reshape
入力を特定の形状に再形成します。", - "7": "spatialDropout1d
ドロップアウトの空間1Dバージョン。" - } - }, - "details-hyper-parameters-editor": { - "title": "ハイパーパラメータエディタ", - "text-0": "モデルの作成に必要な一般的なパラメータを編集できます。
これらのパラメータは次のとおりです。", - "list": { - "0": "学習率:
0から100までの値で、重み付けされた重みのパーセンテージを示します。", - "1": "エポック数:
トレーニング中にトレーニングデータセットがネットワークに提示される回数(数が多いほど、トレーニングに時間がかかります)。", - "2": "テストセットサイズ:
モデルテスト(テストデータ)に使用されるデータセットのパーセンテージ。残りのデータはネットワークトレーニング(トレーニングデータ)に使用されます。", - "3": "オプティマイザー:
ネットワークの重みを調整するために使用される関数です。", - "4": "損失関数:
トレーニング中のモデルの効率を測定するための誤差計算方法です。", - "5": "メトリクス関数:
テストデータを使用した機械学習モデルのパフォーマンスを評価するために使用される平均評価です。" - } - }, - "details-hyper-parameters-info": { - "title": "ハイパーパラメータ情報", - "list": { - "0": "学習率:
学習率は、トレーニング中に計算された誤差に応じて、ニューラルネットワークの重みがどの程度更新される必要があるかを決定するパラメータです。", - "1": "エポック数:
エポック数は、トレーニングプロセス中にトレーニングデータがニューラルネットワークに提示される回数を指します。各反復は、計算された誤差の関数としてのネットワークの重みの更新を意味します。", - "2": "テストセットサイズ:
テストセットのサイズは、トレーニング後にニューラルネットワークのパフォーマンスを評価するために使用されるデータの量を指します。", - "3": "オプティマイザー:
オプティマイザーは、トレーニング中に計算された誤差に応じてニューラルネットワークの重みを更新するために使用されるアルゴリズムです。一般的なオプティマイザーの例には、確率的勾配降下法(SGD)、Adam、およびAdagradがあります。", - "4": "損失関数:
損失関数は、ニューラルネットワークの予測と実際の出力との間の不一致を測定する尺度です。トレーニング中にニューラルネットワークを最適化するために使用され、交差エントロピーや平均二乗誤差など、さまざまな損失関数があります。" - } - }, - "details-create-and-train-models": { - "title": "モデルを作成して訓練する", - "text-0": "前のすべてのフィールドが入力されたら、「モデルを作成して訓練する」ボタンを押してモデルを作成できます。", - "text-1": "メトリック関数 Accuracy でモデルを訓練した場合、バイザーに2つのグラフが表示されます。私たちにとって最も関連性の高いのは下のグラフです。tensorflow.jsでは、accとval_accは、ニューラルネットワークのモデルのトレーニングで一般的に使用される評価メトリクスです。
Accは、トレーニングデータセットにおけるモデルの精度(Accuracy)を表します。精度は、正しい予測の数を予測の総数で割ったものとして定義されます。
Val_accは、検証データセットにおけるモデルの精度を表します。検証は、トレーニング中に見られなかった新しいデータに一般化するモデルの能力を評価するために使用されます。", - "text-2": "検証の精度は、モデルがトレーニングデータに過度に適合し、新しいデータにうまく一般化できない場合に発生する過剰適合(overfitting)を検出するために重要です。" - }, - "details-export-models": { - "title": "モデルをエクスポート", - "text-0": "モデルを正しく作成した場合、生成されたモデルのテーブルにエントリが追加されます。生成されたモデルをエクスポートしてローカルに保存できます。" - }, - "details-prediction": { - "title": "分類", - "text-0": "最終フォームでは、クラスを決定するために使用される主要な特徴量を選択できます。", - "text-1": "「結果を表示」ボタンを押すと、要素の入力特徴量から出力クラスの予測が取得されます。" - } - } + "SALARY": { + "intro": { + "title": "給与", + "content": "このページでは、学習済みのニューラルネットワークが経験年数から給与を予測します。それぞれが何かを順番に説明します。「次へ」で進んだり、戻ったり、音声を消したり、ガイドを自動で進めたりできます。" + }, + "dataset-select": { + "title": "データセット", + "content": "データセットは 2 つあります。経験年数だけのものと、年齢・性別・学歴・職種を含むものです。学習済みのネットワークは 1 つ目のものです。2 つ目ではデータを見られますが、予測するには自分でネットワークを学習させる必要があります。" + }, + "dataset": { + "title": "データセット", + "content": "1 つ目には 1000 人分のデータがあります。強調された列 Salary が給与で、経験年数(1 年未満から 50 年近くまで)とともに上がる傾向があります。回帰の練習用のサンプルデータです。" + }, + "form": { + "title": "人のデータ", + "content": "1 つ目のデータセットでは、フォームの項目は経験年数だけです。年数が多いほど、ネットワークは高い給与を予測する傾向があります。" + }, + "result": { + "title": "結果", + "content": "ここに予測された給与が、データセットと同じ単位で表示されます。行を変更せずに使った場合は、実際の給与と誤差も表示されます。" + }, + "end": { + "title": "やってみよう", + "content": "人を選んで給与を予測し、そのあと経験年数を変えて予測がどう変わるか見てください。このガイドは「ガイド」ボタンでいつでも開き直せます。" } - } - }, - "dataframe": { - "title": "データセットを分析", - "upload-csv": "データセットをアップロード" - }, - "menu": { - "select-model": { - "description": "説明" }, - "select-dataset": { - "description": "説明" + "HOUSING_PRICES": { + "intro": { + "title": "住宅価格", + "content": "このページでは、学習済みのニューラルネットワークがボストンの地区の住宅価格の中央値を、その地区の 12 のデータから予測します。それぞれが何かを順番に説明します。「次へ」で進んだり、戻ったり、音声を消したり、ガイドを自動で進めたりできます。" + }, + "dataset-select": { + "title": "データセット", + "content": "このモデルのデータセットは Boston Housing の 1 つだけです。" + }, + "dataset": { + "title": "データセット", + "content": "各行は 1970 年代のボストンの 506 地区のひとつです。強調された列 MEDV が住宅価格の中央値(千ドル単位、5〜50)です。このバージョンには元のデータセットの列 B はありません。倫理的な理由で削除されました。" + }, + "form": { + "title": "地区のデータ", + "content": "フォームには 12 の項目があります:犯罪率(CRIM)、住宅用地(ZN)と工業用地(INDUS)の割合、チャールズ川に面しているか(CHAS)、大気汚染(NOX)、住宅あたりの部屋数(RM)、築年数(AGE)、雇用中心地までの距離(DIS)、高速道路へのアクセス(RAD)、税金(TAX)、教師一人あたりの生徒数(PTRATIO)、低所得層の割合(LSTAT)。価格と最も関係が深いのは部屋数と LSTAT です。" + }, + "result": { + "title": "結果", + "content": "ここに予測された価格の中央値が千ドル単位で表示されます。行を変更せずに使った場合は、実際の値と誤差も表示されます。" + }, + "end": { + "title": "やってみよう", + "content": "地区を選んで価格を予測し、そのあと部屋数(RM)を増やして予測がどう変わるか見てください。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } } }, - "documentation": { - "title": "ドキュメント" - }, - "manual": { - "title": "マニュアル", - "00-tabular-classification": { - "upload-and-process": { - "title": "ステップ 1: データセットをアップロードして前処理する" + "2-object-detection": { + "common": { + "model": { + "title": "モデル", + "content": "これはモデルの説明です。何を検出し、何を受け取り、何を返すかが書かれています。学習済みのモデルなので、ここでは使うだけで学習はしません。" }, - "dataset": { - "title": "ステップ 2: データセットを分析する" + "explain-about": { + "title": "説明の仕方", + "content": "この欄は解釈性の計算方法をまとめたものです。画像を小さな部分に分け、さまざまな組み合わせで隠して結果がどれだけ変わるかを調べます。こうして、どの部分が最も効いたかがわかります。" }, - "layer-design": { - "title": "ステップ 3: ニューラルネットワークの層構成を確認する" + "webcam": { + "title": "リアルタイム認識", + "content": "ここにはカメラの映像が表示され、モデルが検出したものが1秒間に最大20回、その上に描かれます。" }, - "editor-layers": { - "title": "ステップ 4: ニューラルネットワークの層を編集する" + "webcam-controls": { + "title": "カメラの操作", + "content": "スイッチでWebカメラをオンにします。初回はブラウザーが許可を求めます。カメラが複数ある場合は、ドロップダウンで選べます。カメラのボタンでキャプチャーをダウンロードし、最後のボタンでカメラを全画面表示にします。" }, - "editor-hyperparameters": { - "title": "ステップ 5: 学習のハイパーパラメータを編集する" + "device-info": { + "title": "デバイス情報", + "content": "ここには、カメラ、ブラウザー、画面の情報と、検出の様子、つまり1秒あたりの予測数と1回の予測時間が表示されます。" }, - "table-models": { - "title": "ステップ 6: 学習とモデル一覧" + "image": { + "title": "画像での認識", + "content": "カメラがない場合は、ここに写真をドラッグするか、パソコンから選んでください。モデルが処理し、検出したものを上に描きます。" }, - "prediction": { - "title": "ステップ 7: 予測" + "explain": { + "title": "解釈性", + "content": "写真を処理した後、ここで説明を計算できます。画像の上のヒートマップで、モデルの検出に最も効いた部分がわかります。" + }, + "end": { + "title": "試してみよう", + "content": "Webカメラをオンにするか写真をアップロードして、モデルが何を検出するかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" } }, - "app": { - "title": "ツールの目的", - "description-1": "このアプリケーションでは、表形式データの分類、画像分類、物体識別など、人工ニューラルネットワークが実行できる代表的なタスクを紹介します。ニューラルネットワークは機械学習の分野に属する人工知能の手法で、データセットから学習(訓練)するモデルを構築します。", - "description-2": "ニューラルネットワークを学ぶ理由には、次のようなものがあります。", - "list": { - "0": { - "title": "実践的な応用", - "description": "ニューラルネットワークは、音声認識やコンピュータビジョンからデータ分析、結果の予測まで、幅広い用途で使われています。ニューラルネットワークを学ぶことで、医療、工学、データサイエンス、マーケティングなど多くの分野で役立つスキルを身につけることができます。" - }, - "1": { - "title": "複雑な問題の解決", - "description": "ニューラルネットワークは、多数の変数と非線形な関係を持つ複雑な問題の解決に役立ちます。ニューラルネットワークを学ぶことで、こうした問題に対してより効果的な解決策を開発し、分析の精度と効率を高めることができます。" - }, - "2": { - "title": "技術革新", - "description": "ニューラルネットワークは進化と改良を続ける革新的な技術です。ニューラルネットワークを学ぶことで、機械学習と人工知能の分野における最新の動向や発展に追いつくことができます。" - } + "FACE-DETECTOR": { + "intro": { + "title": "顔の検出", + "content": "このページでは、MediaPipeのFace Detectorモデルが、写真やカメラの中から最大4つの顔を見つけ、それぞれに目、鼻、口、耳の6つの特徴点を付けます。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" }, - "description-3": "ニューラルネットワークは、人間の脳の働きを模倣した機械学習の一形態です。過去のデータや経験から学習して改善し続けるように設計されており、従来のプログラムでは不可能または非常に困難だった複雑なタスクを機械が実行できるようにします。", - "description-4": "まとめると、ニューラルネットワークを学ぶことは、幅広い分野で価値のあるスキルを身につけ、複雑な問題をより効果的に解決し、技術と革新の最新動向に追いつくために重要です。" + "webcam": { + "title": "リアルタイム認識", + "content": "カメラをオンにすると、顔の上に特徴点とその名前がリアルタイムで表示されます。映像は鏡のように表示されます。" + }, + "end": { + "title": "試してみよう", + "content": "Webカメラをオンにして、顔を回したり、顔の一部を隠したりして、いつ見つからなくなるかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } }, - "0-tabular-classification": { - "title": "表形式データの分類", - "1-title": "学習済みモデル", - "1-description-1": "学習済みモデルのセクションにアクセスし、利用可能なモデルの中から1つを選択します。", - "1-description-2": "ツールには代表的な例の一覧があり、それを使って特徴量のフォームを変更できます。", - "1-description-3": "モデルのツールセクションでは、予測する要素の特徴量を編集できます。ツールには動的なフォームがあり、ニューラルネットワークへの入力データを変更できます。", - "2-title": "モデルの学習", - "2-description-1": "ツールにはデータセットのクラスと属性を表示するデータビューアと、データモデルを作成・設計・学習・エクスポートするための管理機能があります。", - "2-description-2": "左側には、ニューラルネットワークの各層を編集するエディタがあります。ネットワークの最終層のニューロン数は、予測するクラス数と同じにする必要があります。", - "2-description-3": "エポック数:
学習の過程で学習データをニューラルネットワークに提示する回数です。各反復では、計算された誤差に応じてネットワークの重みが更新されます。", - "2-description-4": "「モデルを作成して学習」ボタンを押すと、ニューラルネットワークの学習が始まります。設定と関数の選択がすべて正しければ、学習済みモデルの行が下の表に追加されます。", - "2-description-5": "データからモデルを学習したら、予測を行うことができます。そのために、データセットの特徴量を含む動的なフォームが用意されています。予測の精度は、学習内容と選択したオプションによって高くも低くもなります。" + "FACE-MESH": { + "intro": { + "title": "顔メッシュ", + "content": "このページでは、MediaPipeのFace Meshモデルが、写真やカメラの中から最大4つの顔を見つけ、それぞれに数百の点を置いて、顔の表面の立体的なメッシュを作ります。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "webcam": { + "title": "リアルタイム認識", + "content": "カメラをオンにすると、顔の上に点のメッシュが表示され、表情の動きにリアルタイムで追従します。映像は鏡のように表示されます。" + }, + "end": { + "title": "試してみよう", + "content": "Webカメラをオンにして、口を開けたり、ウインクしたり、眉を上げたりして、メッシュが表情に追従する様子を見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } }, - "1-regression": { - "title": "回帰", - "1-title": "学習済みモデル", - "1-description": { - "0": "学習済みモデルのセクションにアクセスし、利用可能なモデルの中から1つを選択します。", - "1": null, - "2": null + "MOVE-NET--POSE-NET": { + "intro": { + "title": "関節検出器", + "content": "このページでは、MoveNetモデルが体の姿勢を推定します。最大5人まで、1人につき目、耳、肩、肘、手首、腰、膝、足首などの17点を検出します。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" }, - "2-title": "モデルの学習", - "2-description": { - "0": "このセクションでは、独自のデータセットのアップロード、用意されたデータセット、説明、グラフや統計による可視化ツールを利用できます。", - "1": "回帰モデルの生成機能があり、ニューラルネットワークの層、ハイパーパラメータ、最適化関数、損失関数、評価指標、そして特徴量の選択を管理できます。", - "2": "「モデルを作成して学習」ボタンを押すと、ニューラルネットワークの学習が始まります。設定と関数の選択がすべて正しければ、学習済みモデルの項目が一覧に追加されます。", - "3": "予測には散布図を使い、直線を描きます。" + "webcam": { + "title": "リアルタイム認識", + "content": "カメラをオンにすると、各人の点が線で結ばれ、一緒に動く骨格のように表示されます。全身が映るように少し離れてください。" + }, + "end": { + "title": "試してみよう", + "content": "Webカメラをオンにして、全身が映るまで離れ、腕や脚を動かしてみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + }, + "COCO-SSD": { + "intro": { + "title": "物体検出器", + "content": "このページでは、COCO-SSDモデルが写真やカメラの中から物体を見つけ、枠で囲んで、それが何かとその確信度を表示します。人、動物、乗り物、食べ物、家具など、COCOデータセットの80クラスを認識します。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "webcam": { + "title": "リアルタイム認識", + "content": "カメラをオンにすると、認識した物体がそれぞれ枠で囲まれ、名前と確信度のパーセンテージが表示されます。" + }, + "end": { + "title": "試してみよう", + "content": "Webカメラをオンにして、カップ、ボトル、本、スマートフォンなどをかざし、何をどれくらいの確信度で認識するかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + }, + "FACE-API": { + "intro": { + "title": "顔の表情", + "content": "このページでは、複数のニューラルネットワークを組み合わせたface-apiが、写真やカメラの中から顔を見つけ、それぞれのおおよその年齢と表情(無表情、喜び、悲しみ、怒り、恐れ、嫌悪、驚き)を推定します。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "webcam": { + "title": "リアルタイム認識", + "content": "カメラをオンにすると、各顔が枠で囲まれ、推定年齢と、表情が各感情にどれくらい近いかが表示されます。" + }, + "end": { + "title": "試してみよう", + "content": "Webカメラをオンにして、笑ったり、驚いたり、怒った顔をしたりして、各表情のパーセンテージがどう変わるかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + }, + "HAND-SIGN": { + "intro": { + "title": "手話", + "content": "このページでは、ニューラルネットワークが手を見つけ、指と関節の21点を検出します。そのあと別のプログラムが指の位置を指文字のアルファベットと比べます。アプリがスペイン語のときはスペイン手話、それ以外の言語ではアメリカ手話の指文字です。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "webcam": { + "title": "リアルタイム認識", + "content": "カメラをオンにすると、手の点と認識した文字が表示されます。手をカメラに向け、明るい場所で、画面からはみ出さないようにしてください。" + }, + "end": { + "title": "試してみよう", + "content": "Webカメラをオンにして、モデルの説明にあるアルファベットの画像を見ながら、手でいくつかの文字を作ってみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + } + }, + "3-image-classification": { + "common": { + "model": { + "title": "モデル", + "content": "これはモデルの説明です。どんな画像で学習したか、何を受け取り、どのクラスを認識できるかが書かれています。" + }, + "model-summary": { + "title": "モデルの概要", + "content": "このボタンでネットワークの概要を開きます。各層とそのニューロン数、そしてパラメーター数、つまり学習中に調整された重みの数がわかります。" + }, + "explain-about": { + "title": "説明の仕方", + "content": "この欄は予測の説明に使う手法をまとめたものです。LRPはネットワークを逆にたどって判断を画素まで分配し、SHAPは画像の一部をさまざまな組み合わせで隠して結果がどれだけ変わるかを調べます。" + }, + "examples": { + "title": "例の画像", + "content": "これらの画像のどれかを押すと分類されます。結果は下に表示されます。" + }, + "test-images": { + "title": "テスト画像", + "content": "このボタンで、ネットワークが学習中に見なかったテスト画像を読み込みます。そのあと同じ場所で好きな画像を選んで分類し、予測を実際のクラスと比べられます。" + }, + "upload": { + "title": "画像のアップロード", + "content": "自分の画像をここにドラッグするか、パソコンから選び、ボタンを押して分類することもできます。" + }, + "draw": { + "title": "描く", + "content": "または、ここにマウスや指で描き、ボタンを押して絵を分類します。絵は、ネットワークが学習した画像と同じ28×28画素に縮小されます。" + }, + "result": { + "title": "結果", + "content": "ここに分類された画像と、その横に各クラスの確率が表示されます。最も高いものが予測です。" + }, + "explain": { + "title": "解釈性", + "content": "分類した後、ここで画像の上にヒートマップを計算し、ネットワークの判断に最も効いた画素を示します。" + }, + "end": { + "title": "試してみよう", + "content": "例を分類し、自分の画像をアップロードして、解釈性でネットワークがどこに注目したかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + }, + "IMAGE-MNIST": { + "intro": { + "title": "数字の認識", + "content": "このページでは、学習済みの畳み込みニューラルネットワークが、手書きの0から9までの数字を認識します。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "model": { + "title": "モデル", + "content": "このネットワークはMNISTで学習しました。MNISTは7万個の手書き数字(学習用6万個、テスト用1万個)を28×28画素のグレースケール画像にしたもので、機械学習を始めるときに最もよく使われるデータセットの1つです。" }, - "2-link": "詳しくは次のリンクをご覧ください" - }, - "2-object-identification": { - "title": "物体識別", - "1-title": "学習済みモデル", - "1-description-1": "物体識別には4つのモデルがあります。使い方は簡単で、Webカメラを有効にするか画像をアップロードするだけです。", - "1-description-2": "このセクションでは4つの物体識別モデルを提供しています。これらのモデルはモバイル端末でも動作するよう最適化されています。モデルは次のとおりです。", - "1-description-3": "Webカメラを入力に使うと、検出中の点を映像上でリアルタイムに確認できるフィルターが生成されます。画像をアップロードする場合は png または jpg 形式のファイルを添付できます。結果として、元の画像、生成されたフィルター、フィルターを適用した画像が表示されます。", - "1-list": { - "0": "顔の形状の識別。", - "1": "顔全体のメッシュの識別。", - "2": "関節の識別。", - "3": "物体の識別(分類器でもあります)。" + "examples": { + "title": "例の画像", + "content": "これらの数字のどれかを押すと分類されます。結果は下に表示されます。" + }, + "draw": { + "title": "数字を描く", + "content": "ここにマウスや指で0から9の数字を描き、ボタンを押して分類します。絵はMNISTと同じ28×28画素に縮小されるので、大きく中央に描いてください。" + }, + "result": { + "title": "結果", + "content": "ここにネットワークが見た画像と、各数字の確率が表示されます。最も高いものが予測です。テスト画像を分類した場合は、実際の数字も表示されます。" + }, + "explain": { + "title": "LRPによる解釈性", + "content": "分類した後、ここでLRPのヒートマップを計算します。LRPはネットワークの判断を層ごとに逆向きに画素まで分配するので、絵のどの線が最も効いたかがわかります。" + }, + "end": { + "title": "試してみよう", + "content": "横線の入った7や台の付いた1など、自分なりの書き方で数字を描き、ネットワークが認識できるか、どこに注目したかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" } }, - "3-image-classification": { - "title": "画像分類", - "1-title": "学習済みモデル", - "1-description-1": "画像分類のセクションでは、ニューラルネットワークの代表的な2つの例、MNIST の画像セットと一般画像のセットから選択できます。", - "1-list": { - "0": "MNIST: 数字を識別する画像分類。", - "1": "MobileNet: 1001 カテゴリに属する画像の分類。" + "IMAGE-KMNIST": { + "intro": { + "title": "くずし字", + "content": "このページでは、学習済みの畳み込みニューラルネットワークが、何世紀にもわたって日本で使われた草書体、くずし字で手書きされたひらがな10文字を認識します。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" }, - "1-description-2": "MNIST モデルでは、数字を含む画像の一覧から選ぶか、キャンバスに予測したい数字を描くか、数字の画像をアップロードできます。", - "1-description-3": "MobileNet モデルには選択できるサンプル画像の一覧があり、ニューラルネットワークに分類させる画像をアップロードすることもできます。", - "1-description-4": "どちらのモデルでも、予測結果とその確率(パーセンテージ)が表示されます。" + "model": { + "title": "モデル", + "content": "このネットワークはKuzushiji-MNISTで学習しました。MNISTと同じ28×28画素の画像ですが、数字の代わりに文字が書かれています。同じ文字でもまったく違う書き方があるため、MNISTより難しいデータセットです。" + }, + "examples": { + "title": "例の画像", + "content": "各文字が今の書き方と、3 つの昔の字形(変体仮名)とその字母で表示されます。どれほど違うか見てください。どれかを押すと分類され、結果は下に表示されます。" + }, + "draw": { + "title": "文字を描く", + "content": "ここにマウスや指で10文字のどれかを描き、ボタンを押して分類します。ネットワークが学習したのは昔の草書体なので、今のひらがなとは似ていないこともあります。" + }, + "result": { + "title": "結果", + "content": "ここにネットワークが見た画像と、各文字の確率が表示されます。最も高いものが予測です。テスト画像を分類した場合は、実際の文字も表示されます。" + }, + "explain": { + "title": "LRPによる解釈性", + "content": "分類した後、ここでLRPのヒートマップを計算します。LRPはネットワークの判断を層ごとに逆向きに画素まで分配するので、どの線が最も効いたかがわかります。" + }, + "end": { + "title": "試してみよう", + "content": "テスト画像を読み込み、同じ文字のいろいろな書き方を比べてみましょう。まったく違う線でもネットワークが正解するのがわかります。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } }, - "layer-editor": { - "title": "層エディタ" + "IMAGE-CIFAR10": { + "intro": { + "title": "写真の分類", + "content": "このページでは、学習済みの畳み込みニューラルネットワークが、飛行機、自動車、鳥、猫、鹿、犬、カエル、馬、船、トラックの 10 クラスの小さなカラー写真を認識します。それぞれが何かを順番に説明します。「次へ」で進み、戻ったり、音声をミュートしたり、ガイドを自動で進めたりできます。" + }, + "model": { + "title": "モデル", + "content": "このネットワークは CIFAR-10 で学習しました。32×32 ピクセルのカラー写真で、学習用が 50,000 枚、テスト用が 10,000 枚です。各写真には赤、緑、青の 3 つのチャンネルがあるので、ネットワークが受け取る数は MNIST のほぼ 4 倍です。" + }, + "examples": { + "title": "例の画像", + "content": "各クラスのテスト写真が 1 枚ずつ、ピクセルが見えるように拡大して並んでいます。どれかを押すと分類され、結果は下に表示されます。" + }, + "upload": { + "title": "画像をアップロード", + "content": "ここに自分の写真をドラッグするか、パソコンから選び、ボタンを押して分類します。データセットと同じ 32×32 ピクセルに縮小されるので、物が写真のほとんどを占めているとうまくいきます。" + }, + "result": { + "title": "結果", + "content": "ネットワークが見た画像(縮小後)と、各クラスの確率がここに表示されます。いちばん高いものが予測です。テスト画像を分類した場合は、本当のクラスも表示されます。" + }, + "explain": { + "title": "説明可能性", + "content": "分類したあと、ここで写真の上にヒートマップを計算します。LRP では判断を層ごとに後ろへピクセルまで割り振り、SHAP では写真の一部を隠して予測がどれだけ変わるかを見ます。ネットワークがどこに注目したかがわかります。" + }, + "end": { + "title": "やってみよう", + "content": "テスト画像を読み込み、ネットワークがどのクラスでよく間違えるか探してみましょう。猫と犬、自動車とトラックをよく取り違えます。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } }, - "hyperparameters-editor": { - "title": "ハイパーパラメータエディタ" + "IMAGE-MOBILENET": { + "intro": { + "title": "画像分類", + "content": "このページでは、スマートフォン向けに設計された畳み込みニューラルネットワークMobileNetが、動物、物、乗り物、食べ物など1000のカテゴリーの中から、写真に写っているものを認識します。それぞれの意味を順番に説明します。「次へ」で進み、「戻る」で戻れます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "model": { + "title": "モデル", + "content": "ImageNetの1000カテゴリー、100万枚以上の写真で学習したMobileNetです。224×224画素のカラー画像を受け取ります。" + }, + "examples": { + "title": "例の画像", + "content": "これらの写真のどれかを押すと分類されます。結果は下に表示されます。" + }, + "upload": { + "title": "画像のアップロード", + "content": "自分の写真をここにドラッグするか、パソコンから選び、ボタンを押して分類します。認識したいものが写真のほぼ全体を占めていると、よりうまくいきます。" + }, + "result": { + "title": "結果", + "content": "ここにネットワークが見た写真と、可能性の高いカテゴリーが高い順に表示されます。カテゴリーが1000もあるので、2つの犬種のように似たものの間で迷うのは普通です。" + }, + "explain": { + "title": "SHAPによる解釈性", + "content": "分類した後、ここでSHAPのヒートマップを計算します。写真を小さな部分に分け、さまざまな組み合わせで隠して予測がどれだけ変わるかを調べるので、写真のどの部分が最も効いたかがわかります。" + }, + "end": { + "title": "試してみよう", + "content": "身近なものの写真をアップロードして、ネットワークが認識できるか、どこに注目したかを見てみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } } }, - "glossary": { - "title": "用語集", - "table-head": { - "name": "名前", - "description": "説明", - "references": "参考文献", - "characteristics": "特徴", - "function": "関数" - }, - "tabular-classification": { - "title": "表形式データの分類", - "text-1": "表形式データの分類は教師あり学習の一種で、ラベル付きのデータセットを使って機械学習モデルを学習させ、学習に使っていない新しいデータ例のクラスを予測できるようにします。表形式データの分類では、入力と出力のデータが行と列からなる表として表され、各行はデータのインスタンス(例)を、各列はデータの特徴量(属性)を表します。", - "text-2": "例えば、銀行の顧客に返済能力があるかどうかを予測したい場合、収入、負債、信用履歴、年齢などを特徴量(属性)として使えます。表形式データの分類では、データセットの各インスタンスがこれらの特徴量の値と、顧客に返済能力があるかどうかを示すラベル(クラス)を持ちます。", - "text-3": "ラベル付きのデータセットが用意できたら、機械学習アルゴリズムを使って、新しいデータのラベルを予測できるモデルを学習させます。このモデルを使えば、新しいデータに対して正確かつ高速に予測できます。", - "text-4": "表形式データの分類は、医療、電子商取引、銀行、セキュリティなど、さまざまな分野の分類問題を解くのにとても有用な手法です。" - }, - "regression": { - "title": "回帰", - "text": { - "0": "回帰は機械学習で使われる統計的な分析手法で、独立変数と従属変数の間の線形な関係をモデル化し、データに最もよく当てはまる直線を見つけて予測を行います。", - "1": "回帰では、データは通常、デカルト平面上に散らばった点として表されます。独立変数を X 軸、従属変数を Y 軸に置き、それらの点との距離が最小になる直線の方程式(y = mx + b)を求めます。この方程式が得られれば、独立変数の値から従属変数の将来の値を予測できます。", - "2": "例えば、Webサイトの広告量と商品の売上の関係を分析する場合、広告量が独立変数、商品の売上が従属変数になります。回帰を使うと、広告費と売上の間に線形な関係があるかどうかを調べ、関係があれば広告費から将来の売上を予測できます。", - "3": "回帰はデータ分析における強力なツールで、経済学、社会科学、医学研究など多くの分野で変数間の関係を理解し予測するために使われています。" + "go-to": "ステップへ移動", + "voice": "音声", + "voice-auto": "自動", + "voice-online": "オンライン", + "train": { + "0-tabular-classification": { + "common": { + "intro": { + "title": "ネットワークを学習させよう", + "content": "このページでは、データセットを分類する自分のニューラルネットワークを設計して学習させ、そのあと試します。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "session": { + "title": "設定の保存", + "content": "これらのボタンで、選んだ層とハイパーパラメータをファイルに保存し、別の日に読み込んで続きから再開したり、共有したりできます。データと学習済みモデルは保存されません。" + }, + "manual": { + "title": "マニュアル", + "content": "初めての場合はマニュアルを開いてください。このページの各部分と、それぞれのオプションの意味をていねいに説明しています。" + }, + "layers-add": { + "title": "層の追加と削除", + "content": "これらのボタンで、ネットワークの最初または最後に層を追加します。層を削除したり、ニューロン数や活性化関数を変えたりするには、一覧でその層を開いてください。" + }, + "learning-rate": { + "title": "学習率", + "content": "各ステップで重みをどれだけ修正するかです。大きいと速く学習しますが、行き過ぎて安定しないことがあります。小さいと安定しますが、より多くのエポックが必要です。0.01 から始めるのがおすすめです。" + }, + "test-size": { + "title": "テストデータ", + "content": "この割合のデータは取り分けられ、学習中のネットワークには見せません。あとで新しいデータでどれだけ正解するかを確かめるために使います。本当に大事なのはそこです。見たことのあるデータにしか正解できないネットワークは、学んだのではなく暗記しただけです。" + }, + "optimizer": { + "title": "オプティマイザー", + "content": "誤差をもとに重みを調整する方法です。Adam はたいてい何も変えずにうまく動きます。SGD は最もシンプルで、RMSprop、Adagrad、Adadelta は重みごとに更新の幅を調整します。" + }, + "step-by-step": { + "title": "ステップごと", + "content": "本番の学習の前に、ここでネットワークが1つずつ例から学ぶ様子を見られます。層ごとの前向きの計算、誤差、そして誤差が後ろ向きに戻って各重みを修正する様子です。フェーズごとに進めるか再生を押し、ニューロンをクリックすると計算が見られます。追えるように、ニューロンが64個未満のネットワークのときだけ描かれます。" + }, + "models": { + "title": "生成されたモデル", + "content": "学習するたびに、その設定と結果がここに1行追加され、比べることができます。テストデータでの誤差が最も小さいモデルには印が付きます。ここから学習履歴を見たり、モデルをダウンロードしたりもできます。" + }, + "dataset-info": { + "title": "データセット", + "content": "データセットの説明です。データの出典、各列の意味、予測するクラスが書かれています。ネットワークを設計する前に読んでおきましょう。" + }, + "dataset": { + "title": "データ", + "content": "これが学習に使う表です。各行が1つの例、各列が1つの特徴で、強調表示された列がクラスです。下の項目では、処理の前と後の各列の統計を見られます。ネットワークは数値しか扱えないので、カテゴリーはそれぞれ数値に変換されます。" + }, + "layer-design": { + "title": "あなたのネットワーク", + "content": "この図が学習させるネットワークです。左が入力層で、特徴ごとに1つのニューロンがあります。中央が隠れ層、右が出力層で、クラスごとに1つのニューロンがあります。層を編集するとすぐに変わり、隅のボタンで全画面表示にできます。" + }, + "layers": { + "title": "層", + "content": "各層にはニューロンの数と活性化関数があります。ニューロンや層を増やすと、より複雑な関係を学べますが、学習が遅くなり、汎化せずにデータを暗記してしまうことがあります。最後の層が答えを出します。クラスの数と同じだけのニューロンと、出力を確率に変える softmax 活性化関数が必要です。" + }, + "epochs": { + "title": "エポック", + "content": "1エポックは、学習データ全体を1回通すことです。少なすぎるとネットワークは学びきれず、多すぎると時間がかかり、データを暗記してしまうことがあります。10 から始めて、最後まで精度が上がり続けるなら増やしましょう。" + }, + "loss": { + "title": "損失関数", + "content": "各例でネットワークがどれだけ間違えているかを測るもので、オプティマイザーはこれを小さくしようとします。複数のクラスから選ぶには、最初から選ばれているカテゴリカル交差エントロピーを使います。" + }, + "metrics": { + "title": "評価指標", + "content": "学習中に表示され、うまく進んでいるかを判断するためのものです。たとえば正解率は、正しく分類できた例の割合です。ネットワークの学び方は変わらず、見えるものだけが変わります。" + }, + "train": { + "title": "学習", + "content": "「学習」を押すと、ネットワークはエポックごとに学習します。ここに進み具合が表示され、ビューアーでは学習データとテストデータの両方で、損失が下がり正解率が上がる様子を見られます。時間がかかりすぎる場合は止められます。" + }, + "predict": { + "title": "分類", + "content": "学習済みのモデルで、データセットの行を選ぶか例の値を入力して「分類」を押してください。各クラスの確率が表示されます。上でどのモデルで分類するかを選べるので、比べてみましょう。" + }, + "explain": { + "title": "説明可能性", + "content": "分類したあと、SHAP がネットワークの判断の理由を示します。どの特徴が予測されたクラスに押し上げ、どの特徴が反対に働いたかがわかります。全体の重要度は、多くの行で同じことを行い、どの特徴が一般に最も重要かを示します。" + }, + "end": { + "title": "試してみよう", + "content": "最初の値で学習させて、正解率を見てみましょう。次に、エポック数や層のニューロン数など1つだけ変えて学習し直し、表で2つのモデルを比べてください。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + }, + "CAR": { + "intro": { + "title": "自動車の分類", + "content": "このページでは、価格、メンテナンス費用、安全性などの6つの特徴から、車が受け入れられるかどうかを判定するネットワークを、1728台の例で学習させます。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "layers": { + "title": "層", + "content": "各層にはニューロンの数と活性化関数があります。ニューロンや層を増やすと、より複雑な関係を学べますが、学習が遅くなり、汎化せずにデータを暗記してしまうことがあります。最後の層が答えを出します。クラス(不可、可、良、優)ごとに1つ、計4つのニューロンがあり、softmax 活性化関数で確率に変換されます。" + } + }, + "IRIS": { + "intro": { + "title": "アヤメの分類", + "content": "このページでは、花びらとがく片の4つの測定値から、3種類のうちどのアヤメかを見分けるネットワークを、150本の花の例で学習させます。小さなデータセットなので一瞬で学習でき、いろいろ試すのにぴったりです。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "layers": { + "title": "層", + "content": "各層にはニューロンの数と活性化関数があります。ニューロンや層を増やすと、より複雑な関係を学べますが、学習が遅くなり、汎化せずにデータを暗記してしまうことがあります。最後の層が答えを出します。種(setosa、versicolor、virginica)ごとに1つ、計3つのニューロンがあり、softmax 活性化関数で確率に変換されます。" + } + }, + "LYMPHOGRAPHY": { + "intro": { + "title": "リンパ管造影", + "content": "このページでは、18の特徴からリンパ管造影の検査結果を4つの診断に分類するネットワークを、148人の患者の例で学習させます。一部のクラスは例がとても少ないので、クラスごとの正解の具合に注目してください。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "layers": { + "title": "層", + "content": "各層にはニューロンの数と活性化関数があります。ニューロンや層を増やすと、より複雑な関係を学べますが、学習が遅くなり、患者がこれだけ少ないとデータを暗記しやすくなります。最後の層が答えを出します。診断ごとに1つ、計4つのニューロンがあり、softmax 活性化関数で確率に変換されます。" + } + }, + "UPLOAD": { + "intro": { + "title": "自分のデータ", + "content": "このページでは、自分のデータでネットワークを学習させます。データをアップロードし、予測したい列を選び、ネットワークを設計して学習させます。データがブラウザーの外に出ることはありません。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "dataset-info": { + "title": "データのアップロード", + "content": "ここにファイルをドラッグするか、クリックして選んでください。CSV、TSV、ARFF、JSON、JSON Lines、Parquet に対応しています。各行が1つの例で、列の1つが予測したいクラスである必要があります。" + }, + "process": { + "title": "データの準備", + "content": "学習の前にデータを準備します。予測したい列、テキストの列を数値に変換する方法、値のスケーリング方法を選んでください。ボタンを押すとデータの準備が整い、ネットワークが表示されます。" + }, + "layers": { + "title": "層", + "content": "各層にはニューロンの数と活性化関数があります。ニューロンや層を増やすと、より複雑な関係を学べますが、学習が遅くなり、データを暗記してしまうことがあります。最後の層が答えを出します。予測する列のクラスの数と同じだけのニューロンと、確率に変換する softmax 活性化関数が必要です。" + } } }, - "object-identification": { - "title": "物体識別", - "text-1": "ニューラルネットワークによる物体識別は、機械学習とコンピュータビジョンの分野で画像や動画の中の物体を検出・認識するために使われる手法です。画像解析における重要なタスクで、顔認識、物体のリアルタイム追跡、医用画像での物体分類、自動運転車での物体検出などに応用されています。", - "text-2": "物体識別に使われるニューラルネットワークは、ラベル付きのデータセットで学習した深層学習モデルです。学習では、ラベル付きの大量の画像をネットワークに与え、ニューロン間の結合の重みを調整して、新しい画像の中の物体を高い精度で識別できるようにします。", - "text-3": "学習を終えたニューラルネットワークは、新しい画像の中の物体を識別するために使われます。ネットワークは画像を調べ、複数の層で処理して、対象の物体を識別するための重要な特徴を抽出します。そして、その特徴を使って画像内で検出した各物体にラベルを割り当てます。", - "text-4": "まとめると、ニューラルネットワークによる物体識別は、画像や動画の中の物体を検出・認識するための、コンピュータビジョンと機械学習における重要な手法です。ラベル付きのデータセットで学習した深層ニューラルネットワークを使い、新しい画像の中の物体を高い精度で識別・分類します。" - }, - "image-classification": { - "title": "画像分類", - "text-1": "画像分類は、画像をさまざまなカテゴリ(ラベル)に分類するためにニューラルネットワークで使われる手法です。画像分類器の目的は、入力された画像があらかじめ定められたカテゴリ(ラベル)のどれに属するかを予測することです。", - "text-2": "深層学習では、画像分類器は画像処理に特化したアーキテクチャである畳み込みニューラルネットワーク(CNN)に基づいています。これらのネットワークは複数の層と畳み込み演算を持ち、エッジ、形状、テクスチャなど画像の重要な特徴を抽出できます。", - "text-3": "画像分類器を学習させるには、画像とそれぞれのクラスラベルを含むラベル付きのデータセットを使います。ニューラルネットワークはこのデータセットで学習し、画像のパターンを見つけて対応するクラスラベルと結び付けることを学びます。", - "text-4": "学習を終えたニューラルネットワークは、新しい画像をさまざまなカテゴリに分類するために使えます。画像分類器は入力画像をニューラルネットワークで処理して重要な特徴を抽出し、その画像がどのクラスに属するかを予測します。", - "text-5": "要するに、ニューラルネットワークによる画像分類は、畳み込みニューラルネットワークを使って画像をさまざまなカテゴリ(ラベル)に分類する手法です。ラベル付きのデータセットでニューラルネットワークを学習させ、画像から重要な特徴を抽出して、新しい入力画像がどのクラスに属するかを予測します。" - }, - "activation-functions": { - "title": "活性化関数", - "sub-title-1": "線形層", - "sub-title-2": "非線形活性化(重み付き和、非線形性)", - "sub-title-3": "非線形活性化(その他)", - "text-1": "活性化関数は、人工ニューラルネットワークにおいて、受け取った入力に基づいてニューロン(またはニューロンの集まり)の出力を決める数学的な関数です。活性化関数はニューラルネットワークに非線形性を導入し、入力データのより複雑なパターンを学習できるようにします。代表的な活性化関数は次のとおりです。", - "table": { - "softmax": { - "title": "Softmax", - "description": "出力を確率の形に変換し、すべての確率の合計が 1 になるようにします", - "characteristics": { - "0": "0 から 1 の範囲に収まる", - "1": "最終層に適している", - "2": "多クラス分類の出力の正規化に使われる" - } + "1-regression": { + "common": { + "intro": { + "title": "回帰ネットワークを学習させよう", + "content": "このページでは、ほかの列から価格や成績などの数値を予測するニューラルネットワークを設計して学習させ、そのあと試します。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" }, - "sigmoid": { - "title": "Sigmoid", - "description": "シグモイド関数は入力値を 0 から 1 の範囲に変換します。ニューラルネットワークでは二値分類の問題によく使われます。", - "characteristics": { - "0": "出力は [0, 1] の範囲。", - "1": "二値分類器の出力層で有用。", - "2": "深いネットワークでは勾配消失の問題が起こることがある。" - } + "session": { + "title": "設定の保存", + "content": "これらのボタンで、選んだ層とハイパーパラメータをファイルに保存し、別の日に読み込んで続きから再開したり、共有したりできます。データと学習済みモデルは保存されません。" }, - "hard-sigmoid": { - "title": "Hard Sigmoid", - "description": "Hard Sigmoid は、計算効率のためにシグモイド関数を簡略化したものです。", - "characteristics": { - "0": "シグモイドより高速に計算できる。", - "1": "0 と 1 の間の遷移がなめらかではない。" - } + "manual": { + "title": "マニュアル", + "content": "初めての場合はマニュアルを開いてください。このページの各部分と、それぞれのオプションの意味をていねいに説明しています。" }, - "relu": { - "title": "ReLU (Rectified Linear Unit)", - "description": "ReLU は、負の値に対して 0 を返し、正の値はそのまま保つ、シンプルで効果的な関数です", - "characteristics": { - "0": "計算効率が高い。", - "1": "勾配消失の問題を緩和する。", - "2": "ニューロンをスパースに活性化できる。" - } + "layers-add": { + "title": "層の追加と削除", + "content": "これらのボタンで、ネットワークの最初または最後に層を追加します。層を削除したり、ニューロン数や活性化関数を変えたりするには、一覧でその層を開いてください。" }, - "relu6": { - "title": "ReLU 6", - "description": "ReLU と似ていますが、正の値の上限を 6 に制限するため、勾配爆発を防ぐのに役立ちます。", - "characteristics": { - "0": "勾配消失の問題を緩和する。", - "1": "勾配が不安定なネットワークで有用。" - } + "learning-rate": { + "title": "学習率", + "content": "各ステップで重みをどれだけ修正するかです。大きいと速く学習しますが、行き過ぎて安定しないことがあります。小さいと安定しますが、より多くのエポックが必要です。0.01 から始めるのがおすすめです。" }, - "leaky-relu": { - "title": "LeakyReLU", - "description": "Leaky ReLU は ReLU の変種で、負の値のごく一部を通過させます。", - "characteristics": { - "0": "ReLU に比べてニューロンが死ぬ問題を緩和する。", - "1": "負の勾配の情報を保つのに役立つ。" - } + "test-size": { + "title": "テストデータ", + "content": "この割合のデータは取り分けられ、学習中のネットワークには見せません。あとで新しいデータでどれだけ正解するかを確かめるために使います。本当に大事なのはそこです。見たことのあるデータにしか正解できないネットワークは、学んだのではなく暗記しただけです。" }, - "elu": { - "title": "ELU (Exponential Linear Unit)", - "description": "ELU は正の値では ReLU に似ていますが、負の値でも勾配が定義されている関数です。", - "characteristics": { - "0": "勾配消失の問題を軽減する。", - "1": "より多くのニューロンを活性な状態に保つのに役立つ。" - } + "optimizer": { + "title": "オプティマイザー", + "content": "誤差をもとに重みを調整する方法です。最初から選ばれている RMSprop は回帰に向いています。Adam もたいてい何も変えずにうまく動き、SGD は最もシンプルです。" }, - "tanh": { - "title": "Tanh(双曲線正接)", - "description": "双曲線正接関数は入力値を [-1, 1] の範囲に変換します。", - "characteristics": { - "0": "出力は [-1, 1] の範囲。", - "1": "二値分類の問題で有用。", - "2": "深いネットワークでは勾配消失が起こる。" - } + "step-by-step": { + "title": "ステップごと", + "content": "本番の学習の前に、ここでネットワークが1つずつ例から学ぶ様子を見られます。層ごとの前向きの計算、誤差、そして誤差が後ろ向きに戻って各重みを修正する様子です。フェーズごとに進めるか再生を押し、ニューロンをクリックすると計算が見られます。追えるように、ニューロンが64個未満のネットワークのときだけ描かれます。" }, - "soft-plus": { - "title": "SoftPlus", - "description": "SoftPlus はなめらかな関数で、ReLU のなめらかな代替としてよく使われます。", - "characteristics": { - "0": "なめらかで、あらゆる点で微分可能。", - "1": "生成モデルや回帰のネットワークで有用なことがある。" - } + "models": { + "title": "生成されたモデル", + "content": "学習するたびに、その設定と結果がここに1行追加され、比べることができます。テストデータでの誤差が最も小さいモデルには印が付きます。ここから学習履歴を見たり、モデルをダウンロードしたりもできます。" }, - "mish": { - "title": "Mish", - "description": "Mish は比較的新しい活性化関数で、双曲線正接関数やシグモイド関数などの特徴を組み合わせています。", - "characteristics": { - "0": "定義域全体でなめらかかつ微分可能。", - "1": "一部の用途でより良い性能を示す。" - } + "dataset-info": { + "title": "データセット", + "content": "データセットの説明です。データの出典、各列の意味、予測する数値が書かれています。ネットワークを設計する前に読んでおきましょう。" }, - "selu": { - "title": "SELU (Scaled Exponential Linear Unit)", - "description": "SELU は特定の正規化の恩恵を受ける関数で、ネットワークの安定性を保つのに役立ちます。", - "characteristics": { - "0": "自己正規化: 層を通じて安定した統計量を伝播する。", - "1": "オートエンコーダ構造のネットワークで有用なことがある。" - } + "dataset": { + "title": "データ", + "content": "これが学習に使う表で、統計とグラフも見られます。予測する列と一緒に変化する列に注目してください。それがネットワークの一番の手がかりになります。学習の前に、すべての列が同じくらいの重みになるよう値がスケーリングされます。" + }, + "layer-design": { + "title": "あなたのネットワーク", + "content": "この図が学習させるネットワークです。左が入力層で、特徴ごとに1つのニューロンがあります。中央が隠れ層、右は出力ニューロン1つだけで、それが予測する数値です。層を編集するとすぐに変わり、隅のボタンで全画面表示にできます。" + }, + "layers": { + "title": "層", + "content": "各層にはニューロンの数と活性化関数があります。ニューロンや層を増やすと、より複雑な関係を学べますが、学習が遅くなり、データを暗記してしまうことがあります。最後の層は変更できません。結果は確率ではなく任意の数値なので、線形活性化関数のニューロン1つです。" + }, + "epochs": { + "title": "エポック", + "content": "1エポックは、学習データ全体を1回通すことです。少なすぎるとネットワークは学びきれず、多すぎると時間がかかり、データを暗記してしまうことがあります。最初の値で始めて、最後まで誤差が下がり続けているかを確かめましょう。" + }, + "loss": { + "title": "損失関数", + "content": "予測が実際の値からどれだけ離れているかを測るもので、オプティマイザーはこれを小さくしようとします。最初から選ばれている平均二乗誤差は大きな誤差を強く罰し、平均絶対誤差はすべての誤差を同じように扱います。" + }, + "metrics": { + "title": "評価指標", + "content": "学習中に表示され、うまく進んでいるかを判断するためのものです。複数追加できます。たとえば平均絶対誤差は、予測する値と同じ単位で、平均してどれだけ外れているかを示します。" + }, + "train": { + "title": "学習", + "content": "「学習」を押すと、ネットワークはエポックごとに学習します。ここに進み具合が表示され、ビューアーでは学習データとテストデータの両方で誤差が下がる様子を見られます。時間がかかりすぎる場合は止められます。" + }, + "predict": { + "title": "予測", + "content": "学習済みのモデルで、データセットの行を選ぶか値を入力して「予測」を押してください。ネットワークが予測した数値が表示され、行を変更せずに選んだ場合は比較のために実際の値も表示されます。上でどのモデルで予測するかを選べます。" + }, + "explain": { + "title": "説明可能性", + "content": "予測したあと、SHAP がネットワークがその数値を出した理由を示します。どの特徴が値を押し上げ、どの特徴が押し下げたかがわかります。全体の重要度は、多くの行で同じことを行い、どの特徴が一般に最も重要かを示します。" + }, + "end": { + "title": "試してみよう", + "content": "最初の値で学習させて、誤差を見てみましょう。次に、学習率や層のニューロン数など1つだけ変えて学習し直し、表で2つのモデルを比べてください。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + }, + "SALARY": { + "intro": { + "title": "経験年数と給与", + "content": "このページでは、職歴から給与を予測するネットワークを、1000人の例で学習させます。列が少ないので、ネットワークが何を学ぶかがわかりやすいです。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + } + }, + "AUTO_MPG": { + "intro": { + "title": "自動車の燃費", + "content": "このページでは、シリンダー数、馬力、重量などの6つの特徴から、車の燃費(マイル毎ガロン)を予測するネットワークを、396台の例で学習させます。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + } + }, + "HOUSING_PRICES": { + "intro": { + "title": "住宅価格", + "content": "このページでは、部屋の数や地域の犯罪率などの12の特徴から、ボストンの地区ごとの住宅価格の中央値を予測するネットワークを、506地区の例で学習させます。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" } - } - }, - "editor-layers": { - "title": "層エディタの用語集", - "table": { - "activation-function": { - "title": "層のニューロン(Layer Neurons)", - "description": "ネットワークの特定の層にある個々のユニット(ノード)です。各ニューロンは入力を受け取り、計算を行い、次の層に渡す出力を生成します。層のニューロン数は変えることができ、通常はモデルのハイパーパラメータです。層のニューロン数の選び方は、モデルがデータの表現を学習する能力に影響します。" + }, + "STUDENT_PERFORMANCE": { + "intro": { + "title": "生徒の成績", + "content": "このページでは、勉強時間、欠席数、最初の2学期の成績 G1 と G2 などの30の特徴から、生徒の最終成績(0〜20)を予測するネットワークを学習させます。数学(395人)とポルトガル語(649人)の2科目のデータがあります。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + } + }, + "WINE": { + "intro": { + "title": "ワインの品質", + "content": "このページでは、酸度やアルコール度数などの11の化学的な測定値から、ワインの品質(0〜10)を予測するネットワークを学習させます。赤ワイン1599本と白ワイン4898本の2つのファイルがあります。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + } + }, + "UPLOAD": { + "intro": { + "title": "自分のデータ", + "content": "このページでは、自分のデータでネットワークを学習させます。データをアップロードし、予測したい数値の列を選び、ネットワークを設計して学習させます。データがブラウザーの外に出ることはありません。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" }, - "units": { - "title": "層の活性化関数(Layer Activation Function)", - "description": "ニューラルネットワークの層の各ニューロンでは、モデルに非線形性を導入するために活性化関数が適用されます。活性化関数は、入力と対応する重みに応じてニューロンの出力を決めます。" + "dataset-info": { + "title": "データのアップロード", + "content": "ここにファイルをドラッグするか、クリックして選んでください。CSV、TSV、ARFF、JSON、JSON Lines、Parquet に対応しています。各行が1つの例で、列の1つが予測したい数値である必要があります。" + }, + "process": { + "title": "データの準備", + "content": "学習の前にデータを準備します。予測したい列、テキストの列を数値に変換する方法、値のスケーリング方法を選んでください。ボタンを押すと、ネットワークを設計する準備が整います。" } } }, - "editor-hyperparameters": { - "title": "ハイパーパラメータエディタ", - "table": { - "learning-rate": { - "title": "学習率(Learning Rate)", - "description": "学習率は、機械学習アルゴリズムとニューラルネットワークにおける重要なハイパーパラメータです。学習の各反復でモデルの重みをどれだけ更新するかを決めます。学習率が高いと速く収束することがありますが不安定になる可能性があり、低いと収束が遅くなったり局所解にとどまったりすることがあります。" + "3-image-classification": { + "common": { + "intro": { + "title": "画像のネットワークを学習させよう", + "content": "このページでは、28×28ピクセルの画像を認識する畳み込みネットワークを設計して学習させ、そのあと絵を描いて試します。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" }, - "number-or-epochs": { - "title": "エポック数(Number of Epochs)", - "description": "エポックとは、学習の過程で学習データセット全体をモデルに通した回数のことです。エポック数を増やすと一般にモデルはデータによく適合しますが、ある限度を超えると過学習につながることがあります。" + "session": { + "title": "設定の保存", + "content": "これらのボタンで、選んだ層とハイパーパラメータをファイルに保存し、別の日に読み込んで続きから再開したり、共有したりできます。データと学習済みモデルは保存されません。" + }, + "manual": { + "title": "マニュアル", + "content": "初めての場合はマニュアルを開いてください。このページの各部分と、それぞれのオプションの意味をていねいに説明しています。" + }, + "layers-add": { + "title": "層の追加と削除", + "content": "このボタンで最後に層を追加します。各層を開いて、種類、フィルターの数と大きさ、ニューロン数を選んだり、削除したりできます。最初の層は畳み込み層である必要があります。" + }, + "learning-rate": { + "title": "学習率", + "content": "各ステップで重みをどれだけ修正するかです。大きいと速く学習しますが、行き過ぎて安定しないことがあります。小さいと安定しますが、より多くのエポックが必要です。0.01 から始めるのがおすすめです。" }, "test-size": { - "title": "テストサイズ(Test Size)", - "description": "学習後にモデルの性能を評価するために取り分けておくデータの割合です。テストセットは、未知のデータに対するモデルの精度と全体的な性能を測るために使われます。" + "title": "テストデータ", + "content": "この割合のデータは取り分けられ、学習中のネットワークには見せません。あとで新しいデータでどれだけ正解するかを確かめるために使います。本当に大事なのはそこです。見たことのあるデータにしか正解できないネットワークは、学んだのではなく暗記しただけです。" }, "optimizer": { - "title": "最適化手法(Optimizer)", - "description": "最適化手法は、学習中に機械学習モデルのパラメータを調整するアルゴリズムです。モデルの重みを効率的に更新して損失関数を最小化することを目的とします。代表的な最適化手法には、確率的勾配降下法(SGD)、Adam、RMSprop などがあります。" + "title": "オプティマイザー", + "content": "誤差をもとに重みを調整する方法です。Adam はたいてい何も変えずにうまく動きます。SGD は最もシンプルで、RMSprop、Adagrad、Adadelta は重みごとに更新の幅を調整します。" }, - "loss-function": { - "title": "損失関数(Loss Function)", - "description": "損失関数は、モデルの予測がどれだけうまくいっているかを数値化する指標です。モデルの予測とデータセットの実際の値との差を計算します。損失の値が小さいほどモデルがデータによく適合していることを示すため、学習の目的はこの関数を最小化することです。" + "models": { + "title": "生成されたモデル", + "content": "学習するたびに、その設定と結果がここに1行追加され、比べることができます。テストデータでの誤差が最も小さいモデルには印が付きます。ここから学習履歴を見たり、モデルをダウンロードしたりもできます。" }, - "metric-function": { - "title": "評価指標(Metric Function)", - "description": "学習中にモデルを最適化するために使う損失関数とは異なり、評価指標は学習後のモデルの性能を評価するために使います。正解率、再現率、適合率、F1 スコアなどの情報を提供し、特定のタスクでモデルがどのように振る舞うかを理解するのに役立ちます。" + "dataset-info": { + "title": "画像データセット", + "content": "データセットの説明です。画像の出典、枚数、10個のクラスがそれぞれ何を表すかが書かれています。" + }, + "layer-design": { + "title": "あなたのネットワーク", + "content": "この図が学習させるネットワークです。画像は左から入り、畳み込み層とプーリング層を通り、平坦化されて、右のクラスごとに1つのニューロンを持つ全結合層で終わります。隅のボタンで全画面表示にできます。" + }, + "layers": { + "title": "層", + "content": "画像用のネットワークは、いくつかの種類の層を組み合わせます。畳み込み層は、画像の上を動く小さなフィルターで、エッジや曲線などのパターンを探します。プーリング層(max pooling)は、目立つ値だけを残して画像を小さくします。平坦化層は結果を数値のリストに変え、全結合層がクラスを決めます。最後の層には、クラスごとに1つ、計10個のニューロンと softmax 活性化関数が必要です。ここから1層ずつ見ていきましょう。" + }, + "epochs": { + "title": "エポック", + "content": "1エポックは、学習用の画像全体を1回通すことです。画像では表よりも1エポックにずっと時間がかかるので、最初の5のように少なめから始めて、精度が上がり続けるなら増やしましょう。" + }, + "loss": { + "title": "損失関数", + "content": "各画像でネットワークがどれだけ間違えているかを測るもので、オプティマイザーはこれを小さくしようとします。10個のクラスから選ぶには、最初から選ばれているカテゴリカル交差エントロピーを使います。" + }, + "metrics": { + "title": "評価指標", + "content": "学習中に表示され、うまく進んでいるかを判断するためのものです。正しく分類できた画像の割合である正解率など、複数追加できます。ネットワークの学び方は変わらず、見えるものだけが変わります。" + }, + "train": { + "title": "学習", + "content": "「学習」を押すと、まず画像がダウンロードされ、そのあとネットワークがエポックごとに学習します。表より時間がかかりますが、進み具合とビューアーで損失と正解率の様子がわかり、必要なら止められます。" + }, + "predict": { + "title": "ネットワークを試す", + "content": "学習済みのモデルで、キャンバスに描くか、データセットのテスト画像を選ぶか、自分の画像をアップロードすると、ネットワークが何に見えるかを各クラスの確率とともに答えます。上でどのモデルで試すかを選べます。" + }, + "explain": { + "title": "説明可能性", + "content": "分類したあと、LRP が判断にどれだけ影響したかに応じてピクセルを色分けします。ネットワークが絵のどの部分を見て判断したかがわかります。" + }, + "end": { + "title": "試してみよう", + "content": "最初のネットワークで学習させて、絵を描いてみましょう。次に畳み込み層を追加したり削除したりして学習し直し、表でどのモデルがより正解するかを比べてください。このガイドは「ガイド」ボタンでいつでも開き直せます。" + }, + "layer": { + "class-name": "記号", + "conv-first": { + "title": "第{{number}}層:畳み込み", + "content": "最初の層で、{{inputSize}}ピクセルのグレースケール画像を受け取ります。{{kernel}}×{{kernel}}のフィルター{{filters}}個が画像の上をなぞり、それぞれが小さなパターン(線、縁、曲線など)を見分けることを学び、それが見つかった場所のマップを作ります。そのため、フィルターごとに1枚、{{outputSize}}のマップが{{outputChannels}}枚出力されます。フィルターが端からはみ出さないので、画像より少し小さくなります。学習する重みは{{params}}個です。" + }, + "conv": { + "title": "第{{number}}層:畳み込み", + "content": "前の層から{{inputSize}}のマップ{{inputChannels}}枚を受け取り、{{kernel}}×{{kernel}}のフィルター{{filters}}個でなぞります。各フィルターはすべてのマップを同時に見るので、単純なパターンを組み合わせて、{{class}}の一部のような、より複雑な形にします。{{outputSize}}のマップが{{outputChannels}}枚出力され、学習する重みは{{params}}個です。" + }, + "relu": "ReLUでは負の値が0になり、見つかったものだけが先に進みます。", + "activation": "活性化関数は{{activation}}です。", + "pool": { + "title": "第{{number}}層:最大プーリング", + "content": "{{pool}}×{{pool}}の窓を{{strides}}ずつずらしながら、各窓の最大値だけを残してマップを縮小します。各領域で最も目立つ部分です。{{inputChannels}}枚のマップは{{inputSize}}から{{outputSize}}になります。重みはなく何も学習しませんが、ネットワークを速くし、線が少しずれても影響を受けにくくします。" + }, + "flatten": { + "title": "第{{number}}層:平坦化(Flatten)", + "content": "{{inputSize}}のマップ{{inputChannels}}枚を1列に並べ、{{values}}個の数値のリストにします。全結合層は画像ではなくリストを扱うためです。この層も何も学習しません。" + }, + "dense": { + "title": "第{{number}}層:全結合", + "content": "{{units}}個のニューロンのそれぞれが、前の層の{{inputValues}}個の値すべてとつながっています。画像のどこにあっても、フィルターが見つけたものをすべて組み合わせます。学習する重みは{{params}}個で、このようなネットワークでは全結合層の重みが最も多くなるのが普通です。" + }, + "output": { + "title": "第{{number}}層:出力", + "content": "最後の層には{{class}}ごとに1つ、計{{units}}個のニューロンがあり、前の{{inputValues}}個の値とつながっています(重み{{params}}個)。softmaxにより、出力は各{{class}}の確率になり、合計は1です。ネットワークの答えは最も高いものです。", + "content-other": "最後の層には{{units}}個のニューロンがあり、前の{{inputValues}}個の値とつながっています(重み{{params}}個)。活性化関数は{{activation}}です。softmaxなら、出力は各{{class}}の確率になります。エディタ上部の警告を確認してください。" + }, + "broken": { + "title": "第{{number}}層:形が合いません", + "content": "データが必要な形で届いていません(またはパラメータが足りません)。エディタ上部の警告に原因が表示され、ボタンで修正できます。" + } } - } - }, - "optimization-functions": { - "title": "最適化関数", - "text-1": "最適化関数は、目的関数を最小化または最大化するための数学的な手法です。機械学習では、目的関数は通常、ある学習データセットに対するニューラルネットワークの出力と期待される出力との差を測る誤差関数です。", - "text-2": "最適化関数は、目的関数を最小化するようにニューラルネットワークのパラメータを調整し、新しい入力データに対してより正確な予測ができるようにします。代表的な最適化関数には、確率的勾配降下法や Adam アルゴリズムがあります。", - "table": { - "sgd": { - "references": "確率的勾配降下法\n (Instituto Tecnológico Autónomo de México, 2017)", - "description": "勾配降下法は、関数が最小値をとる位置を推定するアルゴリズムです。機械学習モデルの規模が大きい場合、この計算は非常に高コストになることがあります。\n そこで、一定数のサンプルを使い、計算する勾配の数を固定する確率的勾配降下法が生まれました。" + }, + "IMAGE-MNIST": { + "intro": { + "title": "手書きの数字", + "content": "このページでは、0から9までの手書きの数字を認識する畳み込みネットワークを、MNIST データセットの画像で学習させ、そのあと自分で数字を描いて試します。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" }, - "momentum": { - "references": "-", - "description": "前の関数の変種です。異なるステップで勾配の符号が同じ場合に、勾配降下を加速する値を定義します。" + "layer": { + "class-name": "数字" + } + }, + "IMAGE-KMNIST": { + "intro": { + "title": "日本語の文字", + "content": "このページでは、くずし字 MNIST データセットの、古典的な日本語の手書きのひらがな10文字を認識する畳み込みネットワークを学習させ、そのあと文字を描いて試します。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" }, - "adagrad": { - "references": "(Velasco, 2020)", - "description": "学習率の考え方に変化を加えたものです。各反復で累積した勾配に応じて、重みごとに学習率をスケーリング・調整します。" + "layer": { + "class-name": "文字" + } + }, + "IMAGE-CIFAR10": { + "intro": { + "title": "カラー写真", + "content": "このページでは、CIFAR-10 データセットの画像を使って、飛行機からトラックまで 10 クラスのカラー写真を認識する畳み込みネットワークを学習させ、そのあとテスト写真や自分の写真で試します。それぞれの部分を順番に説明します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりもできます。" }, - "adadelta": { - "references": "(Velasco, 2020)", - "description": "AdaGrad の変種で、各重みの学習率の計算を、各反復の累積勾配ではなく直近 n 個の勾配からなる固定サイズの窓に限定します。" + "predict": { + "title": "ネットワークを試す", + "content": "学習済みのモデルがあれば、データセットのテスト写真を選ぶか自分の写真をアップロードしてボタンを押すと、ネットワークが何が見えるかを各クラスの確率とともに答えます。上でどのモデルで試すかを選びます。" }, - "rmsprop": { - "references": "二乗平均平方根伝播\n (Root Mean Square Propagation)\n (Velasco, 2020)", - "description": "次元ごとに異なる学習率を保持しますが、学習率のスケーリングは勾配の二乗の指数移動平均で割ることで行います。" + "explain": { + "title": "説明可能性", + "content": "分類したあと、LRP は判断にどれだけ効いたかに応じてピクセルを色分けします。ネットワークが写真のどこに注目して判断したかがわかります。" }, - "adam": { - "references": "適応的モーメント推定\n (Adaptive Moment Estimation)\n (Velasco, 2020)", - "description": "AdaGrad と RMSProp を組み合わせたものです。パラメータごとの学習率を保持して RMSProp を計算し、さらに各学習率が勾配の momentum の影響を受けます。" + "end": { + "title": "やってみよう", + "content": "最初のネットワークで学習させ、表で正解率を見てみましょう。写真もエポックも少ないので、学習済みモデルよりかなり低くなります。次にエポックを増やしたり畳み込み層を追加したりして比べてみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" }, - "adamax": { - "description": "モメンタムと適応的な学習の手法を組み合わせ、ニューラルネットワークの学習の収束を加速します。学習率を自動的に調整し、発散の問題を避けるために勾配のスケーリングを使います。" + "layer": { + "class-name": "クラス", + "conv-first": { + "title": "第 {{number}} 層:畳み込み", + "content": "最初の層で、{{inputSize}} ピクセルのカラー写真、つまり赤、緑、青の {{inputChannels}} 枚のマップを受け取ります。{{kernel}}×{{kernel}} のフィルター {{filters}} 個がその上をなぞり、各フィルターは 3 つの色を同時に見て小さなパターン(縁、色のまとまり、角)を見分けることを学び、それが見つかった場所のマップを残します。フィルターごとに 1 枚、{{outputSize}} のマップが {{outputChannels}} 枚出てきます。フィルターが端からはみ出さないので、写真より少し小さくなります。学習する重みは {{params}} 個です。" + } } } }, - "loss-functions": { - "title": "損失関数", - "text": { - "0": "機械学習において、損失関数(コスト関数とも呼ばれる)は、モデルが予測した出力と実際の(期待される)出力との差を数値化する指標です。言い換えると、損失関数はモデルが学習データにどれだけよく適合しているかを測ります。", - "1": "機械学習アルゴリズムの目的は損失関数を最小化すること、つまり学習データに最もよく適合するモデルのパラメータを見つけることです。そのため損失関数の選択は非常に重要で、モデルがデータのパターンを正しく学習し、新しいデータに対して正確に予測する能力に影響します。", - "2": "TensorFlow.js にはさまざまな損失関数があり、どれを使うかは扱う問題の種類によって決まります。以下にいくつかの例を示します。" - }, - "table": { - "AbsoluteDifference": { - "references": "絶対差\n (Acervolima, s.f.)", - "description": "目標値との距離を絶対値で計算します。" + "5-time-series": { + "common": { + "intro": { + "title": "時系列でネットワークを学習する", + "content": "このページでは系列を準備し、各値をそれまでの値から予測するネットワークを設計・学習して、見ていない部分をどう予測するかを確認します。各部分を順に説明します。「次へ」で進む、セレクターで任意のステップに移動する、音声を消す、自動で進めるといった操作ができます。" }, - "ComputeWeightedLoss": { - "references": "加重平均\n (Acervolima, s.f.)", - "description": "2つのテンソル間の重み付き損失を計算します。" + "session": { + "title": "設定の保存", + "content": "これらのボタンで、ネットワーク、ハイパーパラメータ、準備(ウィンドウと差分の有無)をファイルに保存し、後日読み込んだり共有したりできます。データと学習済みモデルは保存されません。" }, - "CosineDistance": { - "references": "コサイン距離\n (Acervolima, s.f.)", - "description": "2つのテンソル間の距離のコサインを使って損失を計算します。" + "manual": { + "title": "しくみ", + "content": "初めての場合はここを開いてください。ウィンドウ、テスト部分が系列の最後である理由、スケーリング、1 ステップ予測と続けた予測、ネットワークを何と比べるかを説明しています。" }, - "HingeLoss": { - "references": "ヒンジ損失\n (Rennie & Srebro, 2005)", - "description": "2つのテンソル間のヒンジ損失を計算します。分類問題で使われます。" + "dataset-info": { + "title": "系列", + "content": "系列の説明です。データの出典と、トレンド・季節・周期といった特徴が書かれています。" }, - "HuberLoss": { - "references": "(Huber 損失)", - "description": "推定手法によって生じる損失を計算します。" + "process": { + "title": "系列のアップロード", + "content": "ここにファイルをドロップし、値の列と、あれば日付の列を選びます。日付は行の並べ替えと予測値の日付に使います。" }, - "LogLoss": { - "references": "対数損失\n (Shen, 2005)", - "description": "LogLoss(Logistic Loss)は、負の数に対して線形に増加する凸関数で、外れ値の影響を受けにくい性質を持ちます。2つのテンソル間の対数損失を計算します。" + "dataset": { + "title": "データ", + "content": "順番に並んだ系列全体です。破線はテスト部分の始まりを示します。系列の最後の部分で、ネットワークは学習中に見ません。" }, - "MeanSquaredError": { - "references": "平均二乗誤差\n (Acervolima, s.f.)", - "description": "目標値との二乗距離を幾何的に計算します。この関数は回帰問題で使われます。" + "preparation": { + "title": "準備", + "content": "ウィンドウはネットワークが見る直前の値の数で、1 季節分をカバーするとよいでしょう。テストは最後に取り分ける割合です。差分を取ると値ではなく変化を学習し、季節は季節予測との比較に使います。" }, - "CategoricalCrossEntropy": { - "references": "(Acervolima, s.f.)", - "description": "確率分布間の距離を測ります。出力層が確率を表すネットワークで使われます。" + "windows": { + "title": "ネットワークが学習するもの", + "content": "系列はこのように例に変わります。各行は直前の値(ウィンドウ)と、予測すべき次の値です。ウィンドウや差分を変えて、どう変わるか見てみましょう。" }, - "SigmoidCrossEntropy": { - "references": "(Acervolima, s.f.)", - "description": "CategoricalCrossEntropy 関数の変種で、損失を 0 から 1 の間の値として計算します。" + "layers": { + "title": "層", + "content": "ネットワークの最後は線形のニューロン 1 つで、予測する値です。その前に、ウィンドウ全体を受け取る Dense 層や、値を 1 つずつ読む再帰型の層(SimpleRNN、LSTM、GRU、Dense より前に置く)を追加できます。" }, - "SoftmaxCrossEntropy": { - "references": "(Bendersky, 2016)", - "description": "softmax 関数と CrossEntropy 関数を組み合わせてネットワークの損失を計算します。" - } - } - }, - "metric-functions": { - "title": "評価指標", - "text-1": "テストデータセットでニューラルネットワークモデルの性能を評価するために使われます。評価指標はモデルの予測をテストデータの実際の値と比較し、モデルの精度を求めます。", - "text-2": "扱う問題の種類に応じて、ニューラルネットワークではさまざまな評価指標を使えます。例えば、二値分類の問題では正解率(Accuracy)を、回帰問題では平均二乗誤差(Mean Squared Error)を評価指標として使えます。", - "text-3": "まとめると、評価指標は、テストデータセットに対してニューラルネットワークが正確に予測できるかを評価し、性能を高めるためにモデルのパラメータを調整する際に役立つ重要なツールです。", - "text-4": "主に accuracy 関数を使います。マルチラベル分類では、この関数は部分集合の正解率を計算します。つまり、あるサンプルについて予測したラベルの集合が、y の対応するラベルの集合と完全に一致する必要があります", - "table": { - "BinaryAccuracy": { - "references": "二値正解率
(Acervolima, s.f.)", - "description": "予測が二値ラベルと一致する頻度を計算します。" + "layers-add": { + "title": "層の追加と削除", + "content": "これらのボタンで、先頭または出力の前に層を追加します。削除したり、種類・ニューロン数・活性化関数を変えたりするには、一覧で開いてください。" }, - "BinaryCrossentropy": { - "references": "二値交差エントロピー
(Saxena, 2021)", - "description": "正しいクラスに対して予測された確率の対数の負の平均です。" + "learning-rate": { + "title": "学習率", + "content": "各ステップで重みをどれだけ修正するかです。高いと速く学習しますが安定しないことがあり、低いと安定しますがより多くのエポックが必要です。" }, - "CategoricalAccuracy": { - "references": "カテゴリ正解率", - "description": "予測が one-hot ラベルと一致する頻度を計算します。" + "epochs": { + "title": "エポック", + "content": "ネットワークが学習用のウィンドウ全体を何回見るかです。少なすぎると学習が間に合わず、多すぎると学習データを丸暗記することがあります。モデルの曲線で分かります。" }, - "CategoricalCrossentropy": { - "references": "カテゴリ交差エントロピー", - "description": "ラベルと予測の間の交差エントロピーを計算します。" + "batch-size": { + "title": "バッチサイズ", + "content": "重みを修正する前にネットワークが見るウィンドウの数です。小さいと頻繁にノイズの多い修正をし、大きいと各エポックが速くなります。" }, - "CosineProximity": { - "references": "コサイン近接度", - "description": "ラベルと予測の間のコサイン近接度を計算します。通常は負の値になります。" + "optimizer": { + "title": "オプティマイザ", + "content": "誤差から重みを調整する方法です。選択されている Adam は、たいていそのままでうまく動きます。" }, - "MeanAbsoluteError": { - "references": "平均絶対誤差", - "description": "統計学では、2つの連続変数の差を測る指標です。機械学習モデルに適用する場合、これらの変数はラベルと予測です。" + "loss": { + "title": "損失関数", + "content": "学習中に誤差をどう測るかです。平均二乗誤差は大きな誤差をより重く、平均絶対誤差はすべての誤差を同じように扱います。" }, - "MeanAbsolutePercentageError": { - "references": "平均絶対パーセント誤差", - "description": "Mean absolute error と同様にラベルと予測の差を計算しますが、パーセントで表します。" + "train": { + "title": "学習", + "content": "押すと、ネットワークは学習用のウィンドウで学習し、各エポックでテスト用のウィンドウで検証します。いつでも止められ、それまでに学んだ内容は残ります。" }, - "MeanSquaredError": { - "references": "平均二乗誤差", - "description": "ラベルと予測の間の平均二乗誤差を求めます。" + "models": { + "title": "学習済みのモデル", + "content": "学習するたびに、準備、ネットワーク、テスト部分での誤差(1 ステップと続けた場合)の行が追加されます。最も良いものに印が付きます。その下に、比較のための学習曲線があります。" + }, + "predict": { + "title": "予測", + "content": "選んだモデルがテスト部分をどう予測するか(1 ステップか続けてか)、最後の値や最後の季節を繰り返す予測と比べた誤差、そして最後の値の後に来るものが分かります。" + }, + "end": { + "title": "予測してみよう!", + "content": "これでこのページは分かりました。別のウィンドウ、差分、LSTM 層を試して比べてみましょう。大切なのは、見ていない部分でネットワークが単純な予測より良いことです。" } } } }, - "terms": { - "title": "プライバシーポリシーと Cookie", - "privacy-title": "プライバシーポリシー", - "privacy-text": "当サイトでは、サイトの性能と機能を改善するために、訪問に関する統計情報のみを収集しています。ユーザーの個人情報を収集・保存することはありません。訪問者数の把握と閲覧体験の向上のために Cookie を使用しています。プライバシーポリシーについてご質問やご不明な点があれば、お問い合わせページからお気軽にご連絡ください。", - "cookies-title": "Cookie", - "cookies-text": "当サイトでは、訪問者数を把握するために Google Analytics の Cookie を使用しています。これらの Cookie により、当サイトの利用状況に関する匿名の統計情報を収集し、性能と機能の改善に役立てています。Google Analytics の Cookie はユーザーの個人情報を収集しません。当サイトを閲覧することで、これらの Cookie の使用に同意したものとみなされます。Cookie の使用方法について詳しくは、プライバシーポリシーをご覧ください。" + "glossary": { + "intro": { + "title": "用語集", + "content": "Nets4Learning で使うすべての概念を説明しています。タスク、層、ハイパーパラメータ、オプティマイザー、活性化関数、損失関数、評価指標です。特に大事なものと、その場所を紹介します。「次へ」で進み、セレクターで好きなステップに移動できます。音声をミュートしたり、ガイドを自動で進めたりすることもできます。" + }, + "search": { + "title": "検索", + "content": "「エポック」や「ReLU」など、好きな用語を入力すると、それを含むカードだけが残ります。" + }, + "index": { + "title": "目次", + "content": "用語集のセクションの一覧です。クリックするとそこへ移動し、スクロールすると今いるセクションが強調されます。" + }, + "tasks": { + "title": "タスク", + "content": "まずは、アプリの各タスクが解く問題です。表の行の分類、回帰による数値の予測、画像の分類、物体の識別があります。" + }, + "units": { + "title": "ニューロン", + "content": "ネットワークの各層にはニューロンがあります。各ニューロンは入力に重みを掛けて足し合わせ、活性化関数を適用します。ニューロンを増やすと、より複雑な関係を学べます。" + }, + "activation-function": { + "title": "活性化関数", + "content": "各ニューロンが何を通すかを決めます。これがないと、層をいくつ重ねても線形の関係しか学べません。" + }, + "learning-rate": { + "title": "学習率", + "content": "学習の各ステップで重みをどれだけ修正するかです。おそらく最も重要なハイパーパラメータで、大きすぎると安定せず、小さすぎるととても遅く学びます。" + }, + "epochs": { + "title": "エポック", + "content": "ネットワークが学習データ全体を何回通すかです。少なすぎると学びきれず、多すぎると汎化せずにデータを暗記してしまいます。" + }, + "test-size": { + "title": "テストデータ", + "content": "取り分けておき、最後に見たことのないデータでどれだけ正解するかを確かめるためのデータです。何を学んだかを正直に測るものです。" + }, + "optimizer": { + "title": "オプティマイザー", + "content": "誤差をもとに重みを調整する方法で、それぞれに数式があります。ほとんどの場合に最初から選ばれている Adam は、Momentum と RMSProp の考え方を組み合わせたものです。" + }, + "activation-plots": { + "title": "グラフ", + "content": "各活性化関数には数式とグラフがあり、アニメーションのタブでは各値をどう変換するかが見られます。隠れ層で最もよく使われる ReLU は、正の値を通し、負の値を0にします。" + }, + "softmax": { + "title": "Softmax", + "content": "分類のときに最後の層で使います。出力を、クラスごとの確率(合計1)に変換します。" + }, + "loss": { + "title": "損失関数", + "content": "ネットワークがどれだけ間違えているかを測るもので、学習はこれを小さくしようとします。複数のクラスから選ぶには、カテゴリカル交差エントロピーを使います。" + }, + "loss-regression": { + "title": "回帰の損失", + "content": "数値を予測するときに最もよく使うのは平均二乗誤差で、大きな誤差を強く罰します。そのすぐ下の平均絶対誤差は、すべての誤差を同じように扱います。" + }, + "metrics": { + "title": "評価指標", + "content": "正解率(正しく答えた割合)のように、ネットワークがどれだけうまく動いているかをわかりやすく示します。学び方は変わりません。" + }, + "confusion-matrix": { + "title": "混同行列", + "content": "実際のクラスと予測されたクラスを組み合わせた表です。どれだけ正解するかだけでなく、どのクラスを取り違えるかもわかります。" + }, + "anchor": { + "title": "各用語へのリンク", + "content": "各カードには共有用のリンク(#)があります。プレイグラウンドの「詳細」リンクからは、必要な用語に直接移動できます。" + }, + "end": { + "title": "試してみよう", + "content": "知らない用語を検索したり、活性化関数まで下りてアニメーションを見たりしてみましょう。このガイドは「ガイド」ボタンでいつでも開き直せます。" + } + }, + "5-time-series": { + "common": { + "intro": { + "title": "時系列のモデル", + "content": "このページでは、それまでの値から系列の次の値を予測する学習済みネットワークを試します。学習で見ていない系列の最後の部分をどう予測するか、最も単純な予測より良いか、そしてその先に何が来るかが分かります。" + }, + "model": { + "title": "モデル", + "content": "モデルのカードです。学習で見ていない系列の最後の部分をどう予測するかを、直前の値や 1 季節前の値を繰り返す予測と比べています。その下に系列の説明があります。" + }, + "model-summary": { + "title": "モデルの概要", + "content": "このボタンでネットワークの概要を開きます。層、各層のニューロン数、学習で調整した重みの数が分かります。その下に、ダウンロード用の .n4l パッケージと、この系列で自分のネットワークを学習するリンクがあります。" + }, + "dataset": { + "title": "データ", + "content": "系列そのものです。日付ごとに 1 行で、予測する値が強調されています。" + }, + "dataset-chart": { + "title": "系列", + "content": "このタブではグラフで見られます。破線はテスト部分の始まりを示し、ネットワークは学習中にこの部分を見ていません。" + }, + "dataset-windows": { + "title": "ネットワーク用に準備したもの", + "content": "系列がどう準備されたかが分かります。ネットワークが受け取る直前の値の数(ウィンドウ)、スケーリングの方法、学習に使った最初の例です。" + }, + "instances": { + "title": "系列の値", + "content": "このセレクターで系列の値を選ぶと、直前の値でフォームが埋まります。「テスト」と付いたものは、ネットワークが見ていない部分です。" + }, + "form": { + "title": "フォーム", + "content": "日付ごとの直前の値で、ネットワークが予測に使うものです。変更すると予測がどう変わるか確かめられます。" + }, + "vector": { + "title": "ネットワークが受け取るもの", + "content": "学習部分の最小値と最大値で 0〜1 にスケーリングして、ネットワークに渡します。" + }, + "predict": { + "title": "予測", + "content": "このボタンを押すと、ネットワークはスケーリングしたウィンドウを受け取り、次の値を予測します。" + }, + "result": { + "title": "結果", + "content": "ここに予測値が表示されます。フォームを変更していなければ、実際の値と誤差も表示されます。その下に、ネットワークの入力をステップごとに示します。" + }, + "mode": { + "title": "1 ステップか、続けてか", + "content": "1 ステップ先では、テストの各値を直前の実際の値で予測します。続けてでは、学習の終わりから、各値をすでに予測した値で予測します。未来の予測はこの方法で行い、誤差が積み重なります。「拡大」ではテスト部分だけを表示します。" + }, + "chart": { + "title": "予測", + "content": "灰色が実際の系列、オレンジがテスト部分でのネットワークの予測、紫がその先の予測です。学習データでの予測を加えることもできます。" + }, + "errors": { + "title": "最も単純な予測より良い?", + "content": "ネットワークの平均誤差(系列の単位での MAE と RMSE)を、最後の値を繰り返す予測と最後の季節を繰り返す予測の誤差と並べています。その下に、ネットワークがそれらより良いか、テストデータで学習データよりずっと大きく外れていないかが書かれています。" + }, + "future": { + "title": "この先", + "content": "最後の値の後にいくつの値を予測するか選びます。1 つずつ続けて、すでに予測した値で予測するので、先になるほど信頼性は下がります。" + }, + "end": { + "title": "完了!", + "content": "これで時系列の予測の読み方が分かりました。この系列で自分のネットワークを学習するには、「この系列で自分のネットワークを学習する」ボタンを使ってください。" + } + } } }, - "generator": { - "table-models": { - "list-models-generated": "生成されたモデルの一覧", - "learning-rate": "学習率", - "test-size": "テストセットのサイズ", - "n-of-epochs": "エポック数", - "n-epochs": "エポック数", - "id-optimizer": "オプティマイザ", - "id-loss": "損失", - "id-metrics": "評価指標", - "layers": "レイヤー", - "download": "ダウンロード", - "features": "特徴量", - "open-visor": "ビューアを開く", - "close-visor": "ビューアを閉じる", - "history": "結果" + "loading-status": { + "page": "ページを読み込んでいます…", + "slow": "初回は少し時間がかかります。このセクションのライブラリをダウンロードしています。次回からはもっと速くなります。", + "model": "モデルを読み込んでいます…", + "model-progress": "モデルをダウンロード中:{{loaded}} / {{total}} MB", + "model-loaded": "モデルをダウンロード中:{{loaded}} MB", + "model-help": "初回は時間がかかることがあります。モデルをインターネットからダウンロードしています。" + }, + "report": { + "button": "レポート", + "title": "学習レポート", + "created": "作成日時:{{date}}", + "print": "印刷・PDFで保存", + "back": "学習に戻る", + "network": "ネットワーク", + "hyperparameters": "ハイパーパラメータ", + "results": "学習結果", + "results-caption": "最後のエポックの値。", + "metric": "指標", + "uploaded": "アップロードしたデータセット", + "empty": "まだレポートはありません。モデルを学習し、モデル一覧の行にある「レポート」を押してください。", + "error-storage": "ブラウザがレポートを保存できません(ストレージが無効か容量不足です)。" + }, + "offline": { + "bar": "オフラインです。すでに開いたものは引き続き使えます。それ以外は接続が戻ると使えるようになります。" + }, + "n4l": { + "download": ".n4l をダウンロード", + "download-title": "このモデルをデータとテキストごと .n4l ファイルでダウンロードし、共有したり後で開いたりできます", + "local": { + "title": "あなたの .n4l パッケージ", + "text": ".n4l ファイル(データとテキスト付きのモデル)を開くと、このブラウザに保存されてここに表示されます。", + "drop": ".n4l ファイルをここにドラッグするか、クリックして選択", + "files": ".n4l ファイル", + "version": "バージョン {{version}}、{{size}}", + "remove": "削除", + "remove-title": "「{{name}}」をこのブラウザから削除", + "imported": "「{{name}}」の準備ができました。カードから開いてください。", + "error": "ファイルを開けませんでした:", + "open-title": ".n4l ファイルを開く", + "how": "どこで手に入りますか?学習済みモデルの各ページにある「.n4l をダウンロード」で、そのパッケージ(モデル、データ、テキスト)を取得できます。学習後は、表の各モデルも学習に使ったデータセットと一緒に同じようにダウンロードできます。人から受け取ったものも開けます。中身と使い方を記述しているだけで、コードは含まれていません。", + "saved": "このブラウザに保存済み", + "empty": "まだありません。上で .n4l ファイルを開いてください。", + "remove-confirm": "「{{name}}」をこのブラウザから削除します。もう一度使うには .n4l ファイルを開き直す必要があります。" + }, + "download-trained-title": "このモデルをデータセット、前処理、テキストとともに .n4l ファイルでダウンロードします。後で「.n4l パッケージ」から開けます", + "metrics": { + "title": "見たことのないデータでは", + "text": "学習時に取り分けたデータセットの 20% では、平均誤差は {{mae}} です。常に平均を予測した場合の誤差は {{baseline}} です。R²:{{r2}}(1 は常に正解、0 は平均を予測するのと同じ)。", + "no-better": "常に平均を答えるより良い予測はできていません。このデータからはこれ以上わかりません。" } }, - "hr": { - "information": "情報", - "editor": "エディタ", - "dataset": "データセット", - "model": "モデル", - "generated-models": "生成されたモデル", - "predict": "予測", - "classify": "分類", - "tasks": "タスク", - "00-tabular-classification": "表形式データの分類", - "tutorial-00-tabular-classification": "表形式データ分類のモデルを学習", - "01-regression": "回帰", - "02-object-detection": "物体検出", - "03-image-classification": "画像分類", - "optimization-function": "最適化関数", - "activation-functions": "活性化関数", - "loss-functions": "損失関数", - "metric-function": "評価指標関数", - "layers": "レイヤー", - "process-dataset": "データセットの処理", - "project": "プロジェクト", - "add-model-dataset": "プロジェクトにモデルを追加", - "dataframe": "データフレーム" + "pagination": { + "label": "表のページ", + "first": "最初のページ", + "previous": "前のページ", + "next": "次のページ", + "last": "最後のページ", + "page": "{{page}} ページ" }, - "form-dataframe": { - "int32": "整数", - "float32": "浮動小数点数", - "string": "テキスト", - "label-encoder": "ラベルエンコーダ", - "one-hot-encoder": "ワンホットエンコーダ", - "drop": "削除", - "ignored": "無視", - "submit": "データフレームを処理" + "skip-to-content": "メインコンテンツへスキップ", + "modal": { + "close": "閉じる" }, - "joyride": { - "back": "戻る", - "close": "閉じる", - "last": "最後", - "next": "次へ", - "open": "開く", - "skip": "スキップ" + "model-summary-table": { + "layer": "層", + "output-shape": "出力の形", + "params": "パラメーター", + "total": "パラメーターの合計(学習で調整される重み)", + "trainable": "そのうち学習可能", + "batch-note": "出力の形の「—」は一度に入る例の数(バッチ)です。" }, - "upload-dataset-info": "タスクを実行するにはデータセットをアップロードする必要があります。", - "upload-model": "モデルをアップロード", - "upload-model-info": "タスクを実行するにはモデルをアップロードする必要があります。", - "select-attr": "属性を選択", - "upload-dataset": "データセットをアップロード", - "00-tc": { - "car": { - "buying": "購入価格", - "maint": "メンテナンス費用", - "doors": "ドアの数", - "persons": "乗車定員", - "lug_boot": "トランクの大きさ", - "safety": "車の推定安全性", - "result": "結果", - "unacc": "不可", - "acc": "可", - "good": "良", - "vgood": "優" - }, - "iris": { - "sepal_length": "がく片の長さ", - "sepal_width": "がく片の幅", - "petal_length": "花弁の長さ", - "petal_width": "花弁の幅", - "class": "クラス", - "Iris-setosa": "ヒオウギアヤメ (setosa)", - "Iris-versicolor": "ブルーフラッグ (versicolor)", - "Iris-virginica": "バージニカ (virginica)" - }, - "lymphography": { - "lymphatics": "リンパ管", - "block of affere": "輸入リンパ管の閉塞", - "bl": { - " of lymph": { - " c": "リンパ管(c)の閉塞", - " s": "リンパ管(s)の閉塞" - } - }, - "by pass": "バイパス", - "extravasates": "血管外漏出", - "regeneration": "再生", - "early uptake in": "早期取り込み", - "lym": { - "nodes dimin": "リンパ節の縮小", - "nodes enlar": "リンパ節の腫大" - }, - "changes in lym": "リンパ管の変化", - "defect in node": "リンパ節の欠損", - "changes in node": "リンパ節の変化", - "changes in stru": "構造の変化", - "special forms": "特殊な形態", - "dislocation of": "転位", - "exclusion of": "除外", - "no": { - " of nodes in": "リンパ節の数" - }, - "Category": "カテゴリ", - "normal find": "正常所見", - "metastases": "転移", - "malign lymph": "悪性リンパ腫", - "fibrosis": "線維症" + "chart-data": { + "show": "データを表示", + "rows": "{{total}} 行中 {{from}}–{{to}} 行", + "columns": { + "variable": "変数", + "value": "値", + "rows": "行数", + "percent": "割合", + "bin": "区間の中央", + "group": "グループ", + "lower": "下限", + "q1": "第 1 四分位数", + "median": "中央値", + "q3": "第 3 四分位数", + "upper": "上限", + "mean": "平均" + } + }, + "page-intro": { + "train": { + "text": "ここではニューラルネットワークを設計し、選んだデータセットで学習させます。そのまま「学習」を押してもかまいません。", + "steps": [ + "データセットを確認します:どんな列があり、何を予測するか。", + "必要なら層とハイパーパラメーターを変更します。", + "「学習」を押し、ネットワークが学ぶ様子を見ます。", + "例でモデルを試し、どこに注目しているかを見ます。" + ] + }, + "review": { + "text": "このモデルは学習済みです。ここでは例で試し、どこに注目しているかを見ます。", + "steps": [ + "モデルの働きと、学習に使ったデータを読みます。", + "例を選ぶか、自分で値を入力します。", + "予測と、必要ならその説明を見ます。" + ] + }, + "detect": { + "text": "このモデルは画像の中の物を探します。カメラをオンにするか写真をアップロードすると、見つけた物に印を付けます。", + "steps": [ + "カメラをオンにするか、写真をアップロードします。", + "モデルが印を付けたものを見ます(テキストでも示されます)。", + "必要なら、見つけたものの説明を求めます。" + ] } + }, + "model-code": { + "title": "コードを見る", + "summary": "設計したネットワークを TensorFlow.js または Keras(Python)で書いたものです。アプリが学習させるものと同じです。", + "language": "コードの言語", + "copy": "コードをコピー", + "copied": "コードをコピーしました", + "code": "{{language}} のコード", + "help-tfjs": "自分のプロジェクトで使うには、TensorFlow.js をインストール(npm install @tensorflow/tfjs)し、このページと同じように処理したデータで XTrain、yTrain、XTest、yTest をテンソルとして用意します。", + "help-keras": "Python で使うには、Keras をインストール(pip install keras tensorflow)し、このページと同じように処理したデータで X_train、y_train、X_test、y_test を NumPy 配列として用意します。", + "data-classification": "X: 処理済み(スケーリング済み)の各行の属性、y: one-hot 形式のクラス", + "data-regression": "X: 処理済み(スケーリング済み)の各行の属性、y: 予測する値", + "data-image": "X: 0〜1 の値の画像、y: one-hot 形式のクラス", + "data-series": "X: 直前の {{window}} 個の値のウィンドウ、y: 各ウィンドウの次の値" + }, + "training-prediction": { + "title": "学習の前に、どうなると思いますか?", + "optional": "(任意)", + "chosen": "あなたの予想:{{prediction}}", + "help": "予想を選んでください。終わったら、実際に起きたことと比べます。", + "none": "わからない", + "options": { + "good": "うまく学習する", + "still-improving": "エポックが足りない(終わってもまだ改善している)", + "overfitting": "データを丸暗記する(過学習)", + "not-learning": "ほとんど学習しない", + "unstable": "上下に跳ねる(不安定)", + "diverged": "損失が発散する" + }, + "right": "予想:「{{prediction}}」。当たりです!", + "wrong": "予想:「{{prediction}}」。今回は別のことが起きました。下で何が起きたか、その理由を確認できます。" } } diff --git a/public/logo-64.png b/public/logo-64.png new file mode 100644 index 0000000..bb0229b Binary files /dev/null and b/public/logo-64.png differ diff --git a/public/models/00-tabular-classification/TODO/hepatitis-c/README.md b/public/models/00-tabular-classification/TODO/hepatitis-c/README.md deleted file mode 100644 index 973c484..0000000 --- a/public/models/00-tabular-classification/TODO/hepatitis-c/README.md +++ /dev/null @@ -1,57 +0,0 @@ -HCV data Data Set -================= - -Download: [Data Folder](https://archive.ics.uci.edu/ml/machine-learning-databases/00571/), [Data Set Regression](https://archive.ics.uci.edu/ml/datasets/HCV+data#) - -**Abstract**: The data set contains laboratory values of blood donors and Hepatitis C patients and demographic values like age. - -| **Data Set Characteristics**: | Multivariate | **Number of Instances**: | 615 | **Area**: | Life | -|--------------------------------|----------------------------|---------------------------|-----|-------------------------|------------| -| **Attribute Characteristics**: | Integer, Real | **Number of Attributes**: | 14 | **Date Donated** | 2020-06-10 | -| **Associated Tasks**: | Classification, Clustering | **Missing Values**? | Yes | **Number of Web Hits**: | 86066 | - -## Source: - -Creators: Ralf Lichtinghagen, Frank Klawonn, Georg Hoffmann - -Donor: Ralf Lichtinghagen: Institute of Clinical Chemistry; Medical University Hannover (MHH); Hannover, Germany; lichtinghagen.ralf '@' mh-hannover.de - -Donor: Frank Klawonn; Helmholtz Centre for Infection Research; Braunschweig, Germany; frank.klawonn '@' helmholtz-hzi.de - -Donor: Georg Hoffmann; Trillium GmbH; Grafrath, Germany; georg.hoffmann '@' trillium.de - - -## Data Set Information: - -The target attribute for classification is Category (blood donors vs. Hepatitis C (including its progress ('just' Hepatitis C, Fibrosis, Cirrhosis). - - -## Attribute Information: - -All attributes except Category and Sex are numerical. The laboratory data are the attributes 5-14. -1. X (Patient ID/No.) -2. Category (diagnosis) (values: '0=Blood Donor', '0s=suspect Blood Donor', '1=Hepatitis', '2=Fibrosis', '3=Cirrhosis') -3. Age (in years) -4. Sex (f,m) -5. ALB -6. ALP -7. ALT -8. AST -9. BIL -10. CHE -11. CHOL -12. CREA -13. GGT -14. PROT - - -## Relevant Papers: - -Lichtinghagen R et al. J Hepatol 2013; 59: 236-42 - -Hoffmann G et al. Using machine learning techniques to generate laboratory diagnostic pathways – a case study. J Lab Precis Med 2018; 3: 58-67 - -## Citation Request: - -Please refer to the Machine Learning Repository's citation policy - diff --git a/public/models/00-tabular-classification/TODO/hepatitis-c/hepatitis-c.csv b/public/models/00-tabular-classification/TODO/hepatitis-c/hepatitis-c.csv deleted file mode 100644 index 83ff031..0000000 --- a/public/models/00-tabular-classification/TODO/hepatitis-c/hepatitis-c.csv +++ /dev/null @@ -1,616 +0,0 @@ -"Category","Age","Sex","ALB","ALP","ALT","AST","BIL","CHE","CHOL","CREA","GGT","PROT" -"0=Blood Donor",32,"m",38.5,52.5,7.7,22.1,7.5,6.93,3.23,106,12.1,69 -"0=Blood Donor",32,"m",38.5,70.3,18,24.7,3.9,11.17,4.8,74,15.6,76.5 -"0=Blood Donor",32,"m",46.9,74.7,36.2,52.6,6.1,8.84,5.2,86,33.2,79.3 -"0=Blood Donor",32,"m",43.2,52,30.6,22.6,18.9,7.33,4.74,80,33.8,75.7 -"0=Blood Donor",32,"m",39.2,74.1,32.6,24.8,9.6,9.15,4.32,76,29.9,68.7 -"0=Blood Donor",32,"m",41.6,43.3,18.5,19.7,12.3,9.92,6.05,111,91,74 -"0=Blood Donor",32,"m",46.3,41.3,17.5,17.8,8.5,7.01,4.79,70,16.9,74.5 -"0=Blood Donor",32,"m",42.2,41.9,35.8,31.1,16.1,5.82,4.6,109,21.5,67.1 -"0=Blood Donor",32,"m",50.9,65.5,23.2,21.2,6.9,8.69,4.1,83,13.7,71.3 -"0=Blood Donor",32,"m",42.4,86.3,20.3,20,35.2,5.46,4.45,81,15.9,69.9 -"0=Blood Donor",32,"m",44.3,52.3,21.7,22.4,17.2,4.15,3.57,78,24.1,75.4 -"0=Blood Donor",33,"m",46.4,68.2,10.3,20,5.7,7.36,4.3,79,18.7,68.6 -"0=Blood Donor",33,"m",36.3,78.6,23.6,22,7,8.56,5.38,78,19.4,68.7 -"0=Blood Donor",33,"m",39,51.7,15.9,24,6.8,6.46,3.38,65,7,70.4 -"0=Blood Donor",33,"m",38.7,39.8,22.5,23,4.1,4.63,4.97,63,15.2,71.9 -"0=Blood Donor",33,"m",41.8,65,33.1,38,6.6,8.83,4.43,71,24,72.7 -"0=Blood Donor",33,"m",40.9,73,17.2,22.9,10,6.98,5.22,90,14.7,72.4 -"0=Blood Donor",33,"m",45.2,88.3,32.4,31.2,10.1,9.78,5.51,102,48.5,76.5 -"0=Blood Donor",33,"m",36.6,57.1,38.9,40.3,24.9,9.62,5.5,112,27.6,69.3 -"0=Blood Donor",33,"m",42,63.1,32.6,34.9,11.2,7.01,4.05,105,19.1,68.1 -"0=Blood Donor",33,"m",44.3,49.8,32.1,21.6,13.1,7.44,5.59,103,30.2,74 -"0=Blood Donor",33,"m",46.7,88.3,23.4,23.9,7.8,9.42,4.62,78,29.5,74.3 -"0=Blood Donor",34,"m",42.7,65.3,46.7,30.3,23.4,10.95,5.06,75,99.6,69.1 -"0=Blood Donor",34,"m",43.4,46.1,97.8,46.2,11.3,7.99,3.62,71,35.3,69.6 -"0=Blood Donor",34,"m",40.5,32.4,29.6,27.1,5.8,10.5,4.56,91,26.6,72 -"0=Blood Donor",34,"m",44.8,77.7,36.9,31,19.5,10.51,5.59,80,23.7,78.9 -"0=Blood Donor",34,"m",42.6,27,21.4,21.7,7.2,8.15,6.79,85,13.9,67.7 -"0=Blood Donor",34,"m",29,41.6,29.1,16.1,4.8,6.82,4.03,62,14.5,53.2 -"0=Blood Donor",34,"m",44.6,84.1,19.6,29.8,5.8,7.6,5.07,95,9.9,71.9 -"0=Blood Donor",34,"m",46.8,61.7,24.5,24.2,23.1,10.99,4.6,83,23.8,73.1 -"0=Blood Donor",34,"m",41.8,75.8,30.9,35.5,6.1,9.97,5.94,89,48.5,71.3 -"0=Blood Donor",34,"m",46.1,70.6,35.8,30,7.6,7.7,4.2,93,14.3,78.7 -"0=Blood Donor",34,"m",43.6,58.9,47.1,31.1,18.5,9.14,4.99,95,22.2,69.3 -"0=Blood Donor",35,"m",37.5,69.8,37.1,25,7.8,11.66,5.73,84,27.3,71 -"0=Blood Donor",35,"m",42.1,68.3,37.2,56.2,11.1,9.3,4.63,99,16.8,73.6 -"0=Blood Donor",35,"m",44.7,79.3,53.5,30.8,9.7,11.39,7.04,88,77.3,77.1 -"0=Blood Donor",35,"m",41.5,115.1,24.1,30.4,5.7,9.41,4.33,81,22.2,71.3 -"0=Blood Donor",35,"m",48.7,72.7,24.1,31,45.1,9.4,3.8,90,20,75.8 -"0=Blood Donor",35,"m",47.3,92.2,30.7,25.7,6.6,11.58,5.9,82,36.9,77.8 -"0=Blood Donor",35,"m",44.5,70.3,26.2,25.1,5.1,10.12,4.69,82,20.7,67.2 -"0=Blood Donor",35,"m",47.4,54.5,18.6,21.6,10.3,8.1,6.23,66,28.1,74 -"0=Blood Donor",35,"m",51,82.7,29.3,26.8,8.7,12.32,5.44,89,25,77.3 -"0=Blood Donor",35,"m",27.8,99,30.7,27.8,9.4,6.8,4.27,65,40.5,80.7 -"0=Blood Donor",36,"m",46.1,58.5,26.8,25.3,6,6.61,5.07,71,10.5,79.6 -"0=Blood Donor",36,"m",45.5,57.6,22.5,19.5,7.5,5.28,4.06,88,62.5,71.6 -"0=Blood Donor",36,"m",41.7,77.2,103.6,46.9,10.4,12.21,5.63,88,20.9,69.3 -"0=Blood Donor",36,"m",45.9,58.8,29.7,27.7,11.7,5.6,4.89,93,23.1,70.8 -"0=Blood Donor",36,"m",48.7,65,11.5,18,7.4,8.02,7.35,69,14.2,73.4 -"0=Blood Donor",36,"m",53,66.4,40.8,23.2,7.5,8.73,5.81,75,36.1,77.3 -"0=Blood Donor",36,"m",47.8,89,48.5,38.4,8.6,8.26,5.62,96,21.9,76.2 -"0=Blood Donor",36,"m",42.6,65.3,35.8,27.1,15.7,10.66,4.38,96,34.7,71 -"0=Blood Donor",36,"m",42.4,47.3,23,25.5,6.1,9.46,5.29,79,17.5,73.8 -"0=Blood Donor",36,"m",48.9,82.8,16.9,24.4,8.9,8.91,5.1,97,14.8,79.9 -"0=Blood Donor",37,"m",31.4,106,16.6,17,2.4,5.95,5.3,68,22.9,72.3 -"0=Blood Donor",37,"m",42.9,70.7,16.3,24.1,15.7,9.03,6.8,93,70.1,73.4 -"0=Blood Donor",37,"m",44,57.4,26.1,24.6,9.7,10.41,6.17,83,38.9,76.5 -"0=Blood Donor",37,"m",41.5,64.6,23.7,29.9,9.3,5.49,3.97,100,10.4,69.3 -"0=Blood Donor",37,"m",47.9,68.8,40.3,46.9,6,9.76,6.42,81,22.7,80.6 -"0=Blood Donor",37,"m",44.8,94.3,32.2,36.7,6.3,9.76,4.12,113,23.8,72.5 -"0=Blood Donor",37,"m",38.6,61.2,24.6,31.9,7.9,6.02,4.63,72,10.3,56.3 -"0=Blood Donor",37,"m",51.2,84.5,18.8,24.7,9.9,8.62,6.59,94,25.3,76.3 -"0=Blood Donor",37,"m",41.9,77.5,24.9,25.8,4.1,8.7,4.36,84,16,71.5 -"0=Blood Donor",37,"m",46.1,44.3,42.7,26.5,6.4,10.86,5.05,74,22.2,73.1 -"0=Blood Donor",37,"m",50.4,48.5,19.4,27.5,11.6,5.78,4.93,90,27.8,75 -"0=Blood Donor",37,"m",33.9,64,91.7,44.7,9.1,8.35,5.4,95,30.3,74.7 -"0=Blood Donor",37,"m",42.9,61.8,96.1,44.1,9.6,7.82,5.1,82,32.3,69.3 -"0=Blood Donor",37,"m",40.8,118.9,17.2,19.2,3.2,9.17,4.26,88,13.5,72 -"0=Blood Donor",37,"m",43.6,72.8,51.4,43.7,13.8,8.16,4.88,70,94.5,75.2 -"0=Blood Donor",37,"m",46.4,53.3,20.2,24.9,8.7,8.63,5.9,86,23.3,78.9 -"0=Blood Donor",37,"m",48.7,62.3,21,21.1,41.9,9.71,4.02,84,16,75.1 -"0=Blood Donor",38,"m",48.1,63.2,11.7,14.7,5.1,8.83,3.87,85,9.5,73.1 -"0=Blood Donor",38,"m",39.9,62.9,71.7,43.9,10.4,10.9,7.01,99,88.3,73.1 -"0=Blood Donor",38,"m",45.5,50.2,16.3,22.8,10.9,8.73,5.88,103,13.8,76.1 -"0=Blood Donor",38,"m",43.4,58.9,45.7,45.7,9.2,10.86,5.74,90,30,73.9 -"0=Blood Donor",38,"m",41.2,43.8,19.9,20.5,10.1,5.95,3.91,63,70.8,67.4 -"0=Blood Donor",38,"m",44.7,69.4,47.4,35.1,16.7,6.9,4.14,67,17.3,70.1 -"0=Blood Donor",38,"m",42,42.7,34.8,42.2,3.3,6.1,4.74,96,14.6,66.7 -"0=Blood Donor",38,"m",48.4,44.9,23.4,22.1,7.9,10.53,7.51,87,43.2,82.6 -"0=Blood Donor",38,"m",38.3,81.5,65.9,35.3,14,11,5.46,80,45.2,68.1 -"0=Blood Donor",38,"m",40.5,61.7,18.6,24.7,6.7,8.47,6.05,89,19.6,75.6 -"0=Blood Donor",39,"m",45.1,63.9,26,21.3,9.3,8.57,5.24,79,29.4,71.2 -"0=Blood Donor",39,"m",38.8,52.5,54.3,31.3,10.1,10.68,6.26,81,31.5,77.2 -"0=Blood Donor",39,"m",47,66.5,24.8,29.1,10.5,10.04,6.26,73,49.8,78.4 -"0=Blood Donor",39,"m",36.6,71.3,28.9,25.9,6.1,5.7,4.66,77,22.6,66.3 -"0=Blood Donor",39,"m",43.9,90.1,87.9,60.6,8.6,9.94,4.64,98,99.3,66.2 -"0=Blood Donor",39,"m",43.4,48.6,33.4,35,23.4,9.68,5.55,73,22.1,75.2 -"0=Blood Donor",39,"m",36,36.5,21.5,25.7,3.3,8.43,4.85,93,23.1,70.5 -"0=Blood Donor",39,"m",45.7,73.4,45.5,33.8,5,9.07,4.41,82,20.6,78.9 -"0=Blood Donor",39,"m",37.5,80.2,32.6,25.3,2.7,9.3,6.85,72,27.5,73.1 -"0=Blood Donor",39,"m",46.4,102.9,44.4,26.2,4.1,9.29,8.89,103,64,72.2 -"0=Blood Donor",39,"m",45.8,62.5,20.7,22.8,45.5,8.61,4.78,77,15.9,75.5 -"0=Blood Donor",39,"m",46.1,77.1,34.9,37.6,4.1,13.86,8.11,94,76.9,71.1 -"0=Blood Donor",40,"m",47.8,68,17.5,22.3,7.7,9.94,6.09,88,23.3,73.9 -"0=Blood Donor",40,"m",44.5,45.7,25.9,27.6,9.2,8.93,4.49,87,17,71.2 -"0=Blood Donor",40,"m",41.4,67.5,59.8,36.8,7.3,4.18,6.02,76,92.7,72.5 -"0=Blood Donor",40,"m",45,74.2,20.9,29.1,12,9.1,6.29,92,24.1,74.1 -"0=Blood Donor",40,"m",39.1,66.5,33.3,32.9,14.8,7.87,4.91,88,18.5,68.8 -"0=Blood Donor",40,"m",45.1,63.4,39.6,31.4,19.7,11.31,4.74,91,18.2,81.1 -"0=Blood Donor",40,"m",45.4,52.9,41.3,26.2,10.6,10.27,6.85,82,40.2,76.6 -"0=Blood Donor",40,"m",46.9,61.8,27.4,43,7,7.26,5.09,98,14.2,75.3 -"0=Blood Donor",41,"m",45.1,86.8,24,23.9,10.6,7.84,6.23,72,35.3,75.1 -"0=Blood Donor",41,"m",38.5,63.9,34.3,43.4,9.6,6.8,4.13,90,11.4,64.1 -"0=Blood Donor",41,"m",42.3,55.9,19.6,18.9,10.9,7.15,3.29,86,24.5,76.1 -"0=Blood Donor",41,"m",46.9,69,19.7,27.3,6.1,6.39,4.55,72,21.6,71.3 -"0=Blood Donor",41,"m",40.2,48.2,37,34.9,9.2,11.35,5.56,78,26.6,73.3 -"0=Blood Donor",41,"m",53.3,79,29.5,28.5,14.1,7.96,5.9,87,33.8,83.4 -"0=Blood Donor",41,"m",44.7,74.9,25.2,20.2,6.3,10.34,4.23,74,23.7,72.1 -"0=Blood Donor",41,"m",37.4,75.1,28,25.7,4.1,10.62,5.57,83,18.6,71.9 -"0=Blood Donor",42,"m",45.3,55.3,31,50,18.5,15.43,5.88,83,15.4,72.4 -"0=Blood Donor",42,"m",44.1,46.8,23.8,19.4,7,10.83,6.28,95,19.7,73 -"0=Blood Donor",42,"m",37.8,78.6,51.4,31.8,10.1,9.66,6.15,85,15.1,70.8 -"0=Blood Donor",42,"m",46.3,71.4,30.3,22.5,26.9,7.95,7.3,88,21.8,71.8 -"0=Blood Donor",42,"m",46.4,43.7,18.7,24.3,6.3,6.59,4.78,93,10.1,73.1 -"0=Blood Donor",42,"m",38.1,88.7,46.7,37,12.5,7.26,6.76,54,18.4,72.1 -"0=Blood Donor",42,"m",46.9,68.7,118.1,49.3,20.2,7.93,5.62,86,74.9,73.8 -"0=Blood Donor",42,"m",37.8,83.7,25.3,20,18.6,7.52,5.07,108,17.4,64.1 -"0=Blood Donor",42,"m",46.2,57.7,35.6,22.9,14.8,11.01,8.6,80,70.1,77.5 -"0=Blood Donor",43,"m",37,82,25.3,26.2,5.4,8.42,4.96,79,15.9,68.4 -"0=Blood Donor",43,"m",39.7,126,21.9,28.9,16.2,8.48,5.3,114,21.4,80.3 -"0=Blood Donor",43,"m",54.4,99.3,40.2,29.5,6.1,8.84,5.92,95,22.3,79.3 -"0=Blood Donor",43,"m",36.3,67.3,28.7,27.9,5.5,8.55,5.27,97,17.1,74.2 -"0=Blood Donor",43,"m",48.6,45,10.5,40.5,5.3,7.09,NA,63,25.1,70 -"0=Blood Donor",43,"m",42.9,50.7,26.4,22,6.4,10.2,4.72,81,15.2,71.8 -"0=Blood Donor",43,"m",39.4,61.8,55,32.5,7.1,11.94,7.84,64,153.5,75.6 -"0=Blood Donor",43,"m",41.5,75.6,15.3,21.2,5.2,7.36,4.71,84,12.9,72.2 -"0=Blood Donor",43,"m",42.8,76.9,57.7,33,11.3,9.63,9.43,72,23.3,72.9 -"0=Blood Donor",43,"m",43.9,40.7,35.8,188.7,8.7,7.7,5.41,90,21.6,75.4 -"0=Blood Donor",43,"m",41.2,59.4,34.3,24.2,4.1,9.64,4.93,84,20.8,74.5 -"0=Blood Donor",44,"m",44.4,84.9,28,26.1,33.9,10.28,4.68,84,14.1,76.9 -"0=Blood Donor",44,"m",38.4,110.8,17.2,30.7,4.6,9.51,5.12,74,25.2,73.6 -"0=Blood Donor",44,"m",44.5,93.6,27.5,25.5,5.4,7.79,4.59,108,16.7,76.8 -"0=Blood Donor",44,"m",37.4,105.7,16.2,21.3,5.2,8.69,6.02,67,14,70.9 -"0=Blood Donor",44,"m",35.5,81.7,27.5,29.5,6.4,8.81,6.65,83,24.1,68 -"0=Blood Donor",44,"m",44,84.3,47.4,31.3,4.1,10.28,5.42,105,34.2,75.3 -"0=Blood Donor",44,"m",48.6,73.5,49.6,32.5,22.6,11.24,6.68,95,32.2,74 -"0=Blood Donor",44,"m",40.8,71.6,17.2,21,3.5,7.38,4.46,88,11.4,63.4 -"0=Blood Donor",44,"m",47.3,43.9,16.2,19.3,4.7,10.02,5.85,100,14.9,71.2 -"0=Blood Donor",44,"m",44.6,53.9,28.4,23.8,8.8,9.47,4.87,94,21.3,69.2 -"0=Blood Donor",45,"m",41.4,63.2,41.4,31.6,5.8,12.28,7.29,82,56,70.6 -"0=Blood Donor",45,"m",46.5,77.8,52.9,34,12.1,9.82,5.58,101,34.9,76.2 -"0=Blood Donor",45,"m",36.2,102.6,70.8,40.3,14.5,8.69,5.98,94,80.6,66.6 -"0=Blood Donor",45,"m",41.7,73.2,43.6,29.4,6.4,8.89,5.31,71,67.4,70.3 -"0=Blood Donor",45,"m",43.2,68.2,27.8,42.3,6.6,10.93,6.61,105,27.2,74.5 -"0=Blood Donor",45,"m",40.3,64.4,18.8,27.2,5.2,6.71,4.25,74,19.7,67.2 -"0=Blood Donor",45,"m",46.4,77,60.3,32.9,8.8,9.38,6.27,85,81.1,75.5 -"0=Blood Donor",45,"m",44.3,71.5,15.9,16.3,7.3,8,5.35,83,19.8,71.3 -"0=Blood Donor",45,"m",45.7,75.4,41.4,28.6,7.7,10.88,6.25,99,85.4,78.8 -"0=Blood Donor",46,"m",42.6,61.6,18.6,21.4,10.2,7,6.13,89,19.9,73.7 -"0=Blood Donor",46,"m",35.7,49.2,22.7,23,17.4,8.51,5.85,87,13.4,62.1 -"0=Blood Donor",46,"m",39.7,40.3,14.6,22.3,5.3,6.3,4.66,71,11.7,67.2 -"0=Blood Donor",46,"m",37.9,79.9,17.7,20.1,12.7,10.1,5.38,72,12.7,67.7 -"0=Blood Donor",46,"m",41.8,65.6,30.5,28.2,6.1,10.68,4.72,82,24.8,65 -"0=Blood Donor",46,"m",47.7,51.6,19.7,21.8,6.3,7.25,5.19,84,20.9,75.2 -"0=Blood Donor",46,"m",44.8,98,41,30.6,4,10.92,7.42,91,28.8,79.8 -"0=Blood Donor",46,"m",49.1,60,19.5,20.5,3.1,7.81,5.02,102,20.8,70.2 -"0=Blood Donor",46,"m",43,41,15.1,20.7,5.1,7.87,5.35,84,15.4,73.2 -"0=Blood Donor",46,"m",45.9,80.1,67.5,36.7,2.9,8.73,4.68,113,50.1,68.8 -"0=Blood Donor",46,"m",49.7,48.2,11.5,17.6,11.2,6.74,3.71,106,10.6,75.2 -"0=Blood Donor",46,"m",37.3,91.6,33.4,35.9,2.6,9.74,6.73,78,64.2,69.9 -"0=Blood Donor",46,"m",47.4,55.9,35.2,33.5,10.2,10.61,4.95,96,41.7,76.3 -"0=Blood Donor",46,"m",51.8,82.6,37.3,29.1,13.4,9.97,7.4,90,30.1,80.3 -"0=Blood Donor",47,"m",44.7,59.3,27.8,30.5,6.9,7.37,5.1,101,21.1,77.2 -"0=Blood Donor",47,"m",41.6,61,31.5,25.6,7.3,8.59,5.66,69,39.1,72.9 -"0=Blood Donor",47,"m",49.5,75.2,29.6,29,7.3,10.67,5.96,75,34.9,72.4 -"0=Blood Donor",47,"m",40.8,42.8,39,31.7,23.5,6.44,4.86,96,27.8,66.4 -"0=Blood Donor",47,"m",48,66.5,17.5,23.2,9.9,7.09,5.06,81,14.9,68.1 -"0=Blood Donor",47,"m",42.1,81.6,26.4,26.4,5.5,10.5,5.95,97,35.3,77.5 -"0=Blood Donor",47,"m",42.2,52.9,20.7,27.1,13.9,10.15,5.15,79,28.8,69.5 -"0=Blood Donor",47,"m",48.3,59.3,49.9,31.7,7.1,11.09,5.56,88,91.5,73 -"0=Blood Donor",47,"m",46.2,63,7,17.4,6.5,7.06,5.23,60,26.6,75.4 -"0=Blood Donor",47,"m",45.3,51.6,18.4,16.9,7.1,8.96,4.29,74,15.7,69.1 -"0=Blood Donor",47,"m",36.7,44.8,29.3,23.5,6.9,7.38,4.44,87,24.4,68.3 -"0=Blood Donor",47,"m",48,56.4,23,25.7,6.5,8.32,6.3,89,23.3,78 -"0=Blood Donor",47,"m",55.4,61.2,25.4,32.9,28.3,8.39,5.25,96,10.3,82.1 -"0=Blood Donor",48,"m",42.5,69.2,44.6,28.3,15.8,11.92,6.76,86,42.9,81.5 -"0=Blood Donor",48,"m",46.2,59.9,14.6,25.7,5.3,6.93,6.29,66,23.4,75.8 -"0=Blood Donor",48,"m",38.2,94.9,32,29.4,21.5,7.93,5.36,98,53,71.8 -"0=Blood Donor",48,"m",43.1,83.9,20.8,27.4,18.3,9.82,6.14,90,16.4,74.9 -"0=Blood Donor",48,"m",44.7,56.4,20.9,24.2,17.5,5.49,5.65,74,28.5,75 -"0=Blood Donor",48,"m",38.8,94.7,28.6,33.4,5.1,7.93,4.27,87,14.7,66.8 -"0=Blood Donor",48,"m",43.4,41.2,18.4,21.2,9.8,7.19,6.37,80,15.8,68.9 -"0=Blood Donor",48,"m",46,58.1,21.4,29.3,6.9,9.36,5.7,83,32.3,74.1 -"0=Blood Donor",48,"m",45.7,88.5,59.1,34,6.5,10.81,6.25,87,38.3,74.1 -"0=Blood Donor",48,"m",42.6,69.1,17.6,28.3,7.7,15.4,5.07,81,29.9,77.8 -"0=Blood Donor",48,"m",46.4,64.1,29.3,27.6,13.2,10.07,8.28,98,28.9,83.3 -"0=Blood Donor",48,"m",50.4,34.6,37.2,28,17.3,10.87,6.97,114,45.2,72.9 -"0=Blood Donor",49,"m",39.1,62.1,23.8,19.6,3.5,9.19,4.82,85,19.4,69.8 -"0=Blood Donor",49,"m",39.7,77.3,20.2,19,8.8,7.26,4.98,84,74.5,65.4 -"0=Blood Donor",49,"m",41.2,96,25,27.7,15.6,7.12,5.61,92,37.8,68.7 -"0=Blood Donor",49,"m",44.7,60.2,34.6,28.5,7.1,10.14,5.68,98,87,69.8 -"0=Blood Donor",49,"m",44.4,63.3,13.5,16.4,7.3,11.19,4.49,73,13.6,72.3 -"0=Blood Donor",49,"m",40.2,73.8,17.9,23.6,7.6,7.99,5.31,106,15.9,71.4 -"0=Blood Donor",49,"m",44.3,84.1,29,29,16.2,8.18,4.65,87,21.9,70.8 -"0=Blood Donor",49,"m",47.8,67.9,44.2,29.9,6.9,8.76,6.23,99,26.9,79.5 -"0=Blood Donor",50,"m",40,87.8,87.5,52.6,4.8,8.7,6.46,76,152.5,71 -"0=Blood Donor",50,"m",46.6,66.3,19.5,23.7,18.5,8.27,5.73,92,12.1,76.7 -"0=Blood Donor",50,"m",44.3,82.5,38.6,32.9,7.3,8.57,5.95,83,23.4,66.6 -"0=Blood Donor",50,"m",45.7,62.6,55.9,24.3,12.8,10.79,6.42,89,55.2,74.2 -"0=Blood Donor",50,"m",43.5,76.2,13.1,18.8,5.6,8.11,4.55,57,16.5,67 -"0=Blood Donor",50,"m",36,51,26.1,29,6.5,7.5,5.75,67,64,70.5 -"0=Blood Donor",50,"m",35.5,59.4,43.9,35.8,7.6,11.23,6.56,106,24.9,73.2 -"0=Blood Donor",50,"m",40.3,70.5,46.4,32.3,6.8,8.11,4.06,77,16.9,69.2 -"0=Blood Donor",50,"m",43.8,56.9,29.5,32.8,4.1,7.77,5.8,72,53.6,72.5 -"0=Blood Donor",50,"m",43.1,73.7,19,21.8,2.9,9.45,6.06,91,33.3,68.9 -"0=Blood Donor",50,"m",39.7,96.5,54.8,30.8,3.3,8.98,5.66,82,52.4,65.8 -"0=Blood Donor",50,"m",42.2,145,27.5,37.9,4.5,13.71,8.8,103,239,73.1 -"0=Blood Donor",51,"m",38,54.8,23.8,28.6,13.5,6.33,4.65,99,18.3,66.4 -"0=Blood Donor",51,"m",36.8,98.5,25.5,27.7,5,9.49,6.08,89,18.2,64.9 -"0=Blood Donor",51,"m",47.2,78.1,27.4,23.9,8.4,10.14,6.54,86,35.3,71.6 -"0=Blood Donor",51,"m",42.6,69.1,17.6,28.3,7.7,15.4,5.07,81,29.9,77.8 -"0=Blood Donor",51,"m",42,84.3,14.7,19.2,3.2,8.19,4.68,81,20.9,77.1 -"0=Blood Donor",51,"m",45.9,66.7,31.8,28.1,9,10.08,5.61,85,36.2,73 -"0=Blood Donor",51,"m",50.8,56,33.2,32.9,6.3,11.33,5.93,93,22.4,80.3 -"0=Blood Donor",51,"m",46.3,69.4,20.1,26.8,4.5,9.99,4.14,81,12.3,73.9 -"0=Blood Donor",52,"m",42.3,72.6,47.4,23.8,6,8.62,7.2,86,36.1,77.6 -"0=Blood Donor",52,"m",42.2,72.2,47.9,23.7,8.6,11.91,6.29,96,62.5,72.9 -"0=Blood Donor",52,"m",82.2,82.2,37,23.7,7.8,8.9,6.09,77,87.8,67.4 -"0=Blood Donor",52,"m",39.3,63.6,20.7,25.3,4.4,8.26,5.35,84,18.9,64.4 -"0=Blood Donor",52,"m",46.8,85.5,15.2,31.9,10.3,9.09,6.56,89,21.8,73.3 -"0=Blood Donor",52,"m",44.7,43.5,40.9,47.2,10.4,10.08,5,74,26.5,75.4 -"0=Blood Donor",52,"m",37.2,73.6,28.9,29.8,6.6,6.8,4.94,8,24.1,64.2 -"0=Blood Donor",52,"m",40.7,78.6,43.3,27.1,13.4,10.95,5.22,73,30,80.9 -"0=Blood Donor",52,"m",41.2,67.4,20.4,18.8,4.3,8.51,4.97,82,40.4,68.5 -"0=Blood Donor",52,"m",46.6,72.2,35,41.1,4.6,7.7,6.92,80,21.5,79.6 -"0=Blood Donor",52,"m",41,61.4,28.7,34.8,5.4,9.36,6.66,100,26.8,73.6 -"0=Blood Donor",52,"m",41.6,59.1,26.3,25.6,3,9.55,4.5,94,33,71.1 -"0=Blood Donor",53,"m",45.3,53,39.6,31.3,9.6,9.96,7.22,73,42.9,78.6 -"0=Blood Donor",53,"m",38.7,104,66.9,34.3,7.8,8.07,4.6,106,73.7,73.2 -"0=Blood Donor",53,"m",44.5,61.2,14.4,18.1,8,6.95,5,70,18.3,72 -"0=Blood Donor",53,"m",49,86,28.9,23.9,11.8,6.09,4,74,33.6,75.8 -"0=Blood Donor",53,"m",37.8,98.1,30.5,21.1,4,5.02,4.42,94,23.2,65.2 -"0=Blood Donor",53,"m",44.8,119.7,29.2,20.7,6,13.8,8.78,64,49.3,75.4 -"0=Blood Donor",53,"m",40.5,76.1,27.8,22,6.3,11.14,6.96,90,53.1,71.3 -"0=Blood Donor",53,"m",41.7,45.3,23.2,25.1,10.8,5.68,5.78,119,114.9,67.9 -"0=Blood Donor",53,"m",38.1,82.5,8,17.5,2.4,9.13,6.28,103,35.8,69.9 -"0=Blood Donor",53,"m",49.2,71.8,42.8,29.4,6.8,15.1,6.24,107,48.3,77.8 -"0=Blood Donor",54,"m",46.9,74.7,36.2,52.6,6.1,8.84,5.2,86,33.2,79.3 -"0=Blood Donor",54,"m",46,70.2,18.6,24.7,24.1,7.83,6.24,76,24.3,76.8 -"0=Blood Donor",54,"m",43,67,36.1,26.1,5,10.2,5.98,105,45.4,75.9 -"0=Blood Donor",54,"m",46.4,75.1,54.1,39.6,10.6,6.59,7.43,85,73.2,75.2 -"0=Blood Donor",54,"m",40.8,72,25.9,29.2,8.5,7.1,5.79,89,15.6,67.9 -"0=Blood Donor",54,"m",41.6,100.4,51.8,35.7,4.3,10.37,7.29,92,82.6,72.4 -"0=Blood Donor",55,"m",44.1,60,26.3,25.9,5.1,7.23,7.3,88,41.6,77.7 -"0=Blood Donor",55,"m",39,45.8,23.5,21.2,2.4,8.41,7.73,73,36.3,73 -"0=Blood Donor",55,"m",42.9,92.6,21.6,26.1,7.4,12.86,5.73,94,42.9,70.1 -"0=Blood Donor",55,"m",40,44.9,10.2,14.1,2.6,5.98,4.55,71,8.8,66.3 -"0=Blood Donor",55,"m",46.2,87.1,36.9,21,4.5,7.55,6.33,80,30.2,72.2 -"0=Blood Donor",55,"m",47.6,71.9,25.8,24.5,5.8,9.24,4.63,83,29.1,76.7 -"0=Blood Donor",55,"m",28.1,65.5,16.6,17.5,2.8,5.58,4.39,65,26.2,62.4 -"0=Blood Donor",55,"m",44.7,71.6,22.9,22.1,5.5,6.82,4.61,105,59.2,72.7 -"0=Blood Donor",55,"m",41.5,59.5,15.4,16.2,6.8,6.35,5.22,80,12.4,69.9 -"0=Blood Donor",56,"m",39.9,62.9,27.2,22.8,7.7,5.74,6.75,86,30.7,72.5 -"0=Blood Donor",56,"m",39.4,97.9,28.2,24.7,5.9,10.4,6.61,82,17.8,74.1 -"0=Blood Donor",56,"m",42.9,50,20.4,22.1,5.4,7.28,5.37,90,34.6,76 -"0=Blood Donor",56,"m",37.9,49.2,16.6,15.7,3.7,9.9,5.3,95,20.8,67.1 -"0=Blood Donor",56,"m",42.1,45.6,30,26.7,6.1,8.9,6.4,71,37.6,70.1 -"0=Blood Donor",56,"m",40.2,37.1,30.1,25.1,10.2,9.69,4.93,103,20.7,71.9 -"0=Blood Donor",56,"m",49.5,56.3,22.1,24.9,11.5,8.56,4.69,91,14.7,69.6 -"0=Blood Donor",56,"m",45.7,45.3,19.5,27,9.3,10.62,6.04,94,17.4,74.5 -"0=Blood Donor",57,"m",59.7,64.5,17.3,21.2,18.9,12.07,3.97,106,15.1,77.6 -"0=Blood Donor",57,"m",43.5,56.2,60.4,37.3,7.3,6.79,5.99,110,185.2,71.8 -"0=Blood Donor",57,"m",43.3,86.8,21.2,22.2,6.8,7.87,4.91,65,19.2,71.3 -"0=Blood Donor",57,"m",46.4,80.1,20.2,23.9,19.2,8.02,5.31,74,17.1,77.5 -"0=Blood Donor",58,"m",44,56,30.6,33,4.8,12.37,6.33,74,58.7,75.8 -"0=Blood Donor",58,"m",46.8,79.3,38,24.1,4.7,9.51,5.07,99,22.9,72.4 -"0=Blood Donor",58,"m",41.3,58.9,12.8,23.4,5.4,8.17,5.7,60,10.8,70.1 -"0=Blood Donor",58,"m",40.9,55.8,17.5,23,5.3,8.52,6.41,93,18.5,70.9 -"0=Blood Donor",59,"m",45.7,115.4,16.4,23.8,3.7,8.2,4.46,70,14.3,78.5 -"0=Blood Donor",59,"m",45.3,106.5,13.5,19.2,6.9,7.97,4.86,67,15.7,74.6 -"0=Blood Donor",59,"m",41.9,72.4,19.3,25.5,29.8,5.6,3.09,78,27.2,69 -"0=Blood Donor",59,"m",39.8,49.4,25.4,21.4,24.7,7.5,3.69,86,18.7,71.9 -"0=Blood Donor",59,"m",38.4,61.2,15.9,27.2,3,6.88,6.89,91,14,64.5 -"0=Blood Donor",59,"m",48.9,50.3,23.7,28.1,15.8,8.97,4.33,75,19,77.6 -"0=Blood Donor",59,"m",43.8,46.6,28.3,27.4,6.1,10.56,5.47,83,20.3,78.5 -"0=Blood Donor",59,"m",37.8,83.7,25.3,20,18.6,7.52,5.07,108,17.4,64.1 -"0=Blood Donor",60,"m",42.2,48.8,41,34.8,3.6,9.6,5.6,98,71.4,71.6 -"0=Blood Donor",60,"m",46.3,59.7,24.4,30.4,18,7.05,6.2,91,13.8,66.9 -"0=Blood Donor",60,"m",40.4,46.8,17.7,25.7,13.5,5.79,5.42,92,19.2,70 -"0=Blood Donor",60,"m",43.4,71.5,10.2,17.4,7.5,8.11,5.31,74,13.3,71.5 -"0=Blood Donor",60,"m",41.1,67.2,49,34.4,16.4,10.14,4.65,107,25.5,71.9 -"0=Blood Donor",60,"m",45.2,89.4,38.6,27.2,8.6,5.19,6.01,75,76.9,74.4 -"0=Blood Donor",61,"m",45.9,73.3,17.1,24.3,4.8,10.01,4.95,88,23.5,70.8 -"0=Blood Donor",61,"m",43.4,70.1,19.9,24,3.6,6.89,4.58,64,24.9,74.2 -"0=Blood Donor",61,"m",34.3,60.5,35.4,26.6,15.2,9.03,7.62,74,51.4,76 -"0=Blood Donor",61,"m",44.8,104.9,15,18.8,6.5,9.38,5.42,69,26.2,79.6 -"0=Blood Donor",61,"m",38.9,59.5,22.8,30.9,6.3,9.45,5.23,95,20.3,71.4 -"0=Blood Donor",62,"m",42.1,51.4,11.8,21.8,2.7,5.7,5.25,80,12.9,72 -"0=Blood Donor",62,"m",46.6,98,36.7,29.4,7,7.56,5.52,70,23.1,86.5 -"0=Blood Donor",62,"m",39.6,42.7,31.3,30.9,13.5,7.17,3.81,89,16.3,64.8 -"0=Blood Donor",62,"m",44.7,76.5,43.7,27.5,6.9,9.94,5.74,83,59.3,77.8 -"0=Blood Donor",63,"m",39.5,59.6,26.2,25.4,12.4,6.78,6.18,78,22.6,72.7 -"0=Blood Donor",63,"m",45.3,71.3,16.6,24.1,5.7,8.92,4.69,81,19.8,73.7 -"0=Blood Donor",63,"m",40.8,74.3,25,27.5,5.5,7.74,6.35,107,50.4,69.3 -"0=Blood Donor",64,"m",46,75.9,34.8,30.6,10.8,9.43,6.69,81,53.7,70.7 -"0=Blood Donor",64,"m",40.1,66.7,18.3,22.5,5.7,9.65,6.37,73,19.1,66 -"0=Blood Donor",64,"m",35.1,72.5,27.2,30.5,20.8,7.99,6.47,91,36.2,68.7 -"0=Blood Donor",64,"m",44.5,87.8,15.1,23.2,12.3,9.49,7.7,78,20,74.3 -"0=Blood Donor",65,"m",41,81.8,27.9,23.6,9.1,7.46,5.84,78,21.2,68.2 -"0=Blood Donor",65,"m",43.1,64.8,43.1,35.6,9.5,9.6,4.03,78,21.9,71.5 -"0=Blood Donor",65,"m",34.8,66.2,51.9,37.5,6.6,8.39,5.91,72,112.8,77 -"0=Blood Donor",65,"m",44.7,99.4,31.9,30.5,12.2,7.15,6.31,82,38.5,75.7 -"0=Blood Donor",65,"m",39.1,45.8,23.1,27.5,6.4,7,6.23,73,27.1,64.3 -"0=Blood Donor",65,"m",43.6,104,32.3,34.2,7.7,8.23,4.69,89,20.8,75.5 -"0=Blood Donor",66,"m",48.4,76,31.9,29.6,13.8,8.81,4.17,111,26.2,76.7 -"0=Blood Donor",66,"m",40.6,79.6,27,28,10.1,10.88,5.48,76,29.8,71.8 -"0=Blood Donor",66,"m",32.6,58.3,20.3,27.3,9.4,9.4,6.8,88,24.6,73.1 -"0=Blood Donor",66,"m",41,61.4,28.7,34.8,5.4,9.36,6.66,100,26.8,73.6 -"0=Blood Donor",67,"m",44.8,72.8,39.4,28.4,23.3,7.84,7.02,97,78.3,67.5 -"0=Blood Donor",67,"m",44.4,86.5,25.2,27.3,9.1,8.85,6.43,88,77.2,74.8 -"0=Blood Donor",67,"m",38.7,83.8,19.4,25.8,8.7,7.95,5.53,100,16.6,70.4 -"0=Blood Donor",68,"m",42.9,71.1,15,34.8,9.3,8.39,6.64,89,14.5,75.5 -"0=Blood Donor",68,"m",39.3,76.7,19.7,24.6,6.3,10.51,4.15,74,28.1,74.2 -"0=Blood Donor",70,"m",27.8,85.7,25.4,38.9,4.2,6.06,3.96,63,46,56.9 -"0=Blood Donor",70,"m",41,63.5,16.9,21.6,5.9,6.03,4.74,83,13.5,73.7 -"0=Blood Donor",71,"m",39,87.9,26.1,32.1,12.2,10.3,6.31,90,99.7,69.8 -"0=Blood Donor",76,"m",29.2,48.9,25.2,27.2,8.3,4.52,2.79,127,18.3,58.1 -"0=Blood Donor",76,"m",38,97.1,28.6,33.1,14.1,4.83,5.56,90,117.6,73.8 -"0=Blood Donor",77,"m",52.2,52.2,12,23.5,10.9,5.51,4.41,103,25.8,67.2 -"0=Blood Donor",32,"f",39.9,35.2,22,29.8,6.3,8.16,4.37,60,4.5,72.5 -"0=Blood Donor",32,"f",47.4,52.5,19.1,17.1,4.6,10.19,NA,63,23,72.2 -"0=Blood Donor",32,"f",41.1,42.8,10.1,14.1,23.2,6.08,3.75,53,9.3,68.9 -"0=Blood Donor",32,"f",43.5,66.2,9.2,17.8,5.7,7.14,4.38,71,44.6,76.1 -"0=Blood Donor",33,"f",36,77.5,14.8,22,4.4,8.61,5.26,66,13.1,66.1 -"0=Blood Donor",33,"f",36.9,51.7,17.4,22,8.3,7,5.02,52,19.1,72 -"0=Blood Donor",33,"f",44.3,74,49.7,52.3,8.5,6.49,3.34,73,44.7,73.8 -"0=Blood Donor",33,"f",38.1,35.2,11.9,18.3,3,6.09,5.22,76,15.4,72 -"0=Blood Donor",33,"f",41,61.1,27,28,6,8.36,4.93,70,24.7,70.5 -"0=Blood Donor",33,"f",38.2,54.4,17.3,21.2,7.1,8.67,5.69,68,32.1,66.9 -"0=Blood Donor",33,"f",47.6,95.5,18.8,22.2,2.4,7.84,5.57,71,16.9,75 -"0=Blood Donor",33,"f",42.4,137.2,14.2,13.1,3.4,8.23,NA,48,25.7,74.4 -"0=Blood Donor",33,"f",45.9,72,37.8,33.5,17.7,7.32,4.25,81,21.5,78.3 -"0=Blood Donor",33,"f",35.4,53.5,9.8,17.6,3.8,6,4.48,78,8,71.5 -"0=Blood Donor",33,"f",38.5,82.2,11.9,17,7.3,7.23,3.92,50,7,73.3 -"0=Blood Donor",33,"f",41.2,73.1,14.3,20.8,11.1,7.4,3.22,56,11.4,69.9 -"0=Blood Donor",33,"f",40.6,73.7,12.6,16.3,3.1,7.75,6.36,67,19.5,71.4 -"0=Blood Donor",34,"f",37.3,36.3,19.9,28.7,3.8,3.9,4.94,86,4.9,70.7 -"0=Blood Donor",34,"f",41.9,47.4,20.8,28.5,8,7.66,4.61,97,11.2,71.9 -"0=Blood Donor",34,"f",36.3,63.2,21.4,20.4,4.6,7.41,5.17,75,18.7,64.2 -"0=Blood Donor",34,"f",36.2,70.9,14.3,21.6,3.7,9.82,5.59,65,27.4,74.3 -"0=Blood Donor",34,"f",46.5,52.3,30.5,32.3,5.7,9.05,6.28,90,18.5,80.6 -"0=Blood Donor",34,"f",45.5,76.9,17.4,18.6,3.2,8.45,5.1,53,25.8,79.7 -"0=Blood Donor",34,"f",39.7,39.3,11.2,16.4,8.4,5.27,4.68,61,24.3,71.5 -"0=Blood Donor",35,"f",41,62.6,27.9,12,12.8,10.34,5.9,78,22.8,76.1 -"0=Blood Donor",35,"f",40.5,72.4,14.5,17.9,5.8,9.38,4.13,75,17.8,69.9 -"0=Blood Donor",35,"f",43.4,62.6,19.2,22,3,10.03,5.07,64,12.4,72.8 -"0=Blood Donor",35,"f",45.6,38.2,22,21.9,3,6.94,4.69,64,17.4,70.4 -"0=Blood Donor",35,"f",62.9,51.2,20.7,23,2.9,6.33,4.62,67,15.2,71.9 -"0=Blood Donor",35,"f",42,69,19.9,16.6,10.8,7.85,4.43,67,15.1,64.1 -"0=Blood Donor",35,"f",38,51.3,18.3,15.3,3.9,8.63,4.91,61,16.2,71.8 -"0=Blood Donor",35,"f",46.9,50.8,35.4,22.1,13.1,8.27,5.7,95,37.3,80.7 -"0=Blood Donor",35,"f",46.1,88.7,23.1,20,7.7,8.41,4.79,74,28.1,79.3 -"0=Blood Donor",35,"f",44.7,83.2,25.3,22.6,3.9,8.02,5.73,68,10.8,76.4 -"0=Blood Donor",36,"f",46.4,69.1,17.7,24.3,6.6,6.5,5.62,67,18.5,75.5 -"0=Blood Donor",36,"f",39.7,52,39.9,33.5,2.9,9,4.18,77,27,78.5 -"0=Blood Donor",36,"f",39.9,59,11.3,20.4,9.4,7.6,5.51,69,16,81 -"0=Blood Donor",36,"f",42.7,55.1,12.4,16,6.8,6.63,5.05,75,10.4,72.8 -"0=Blood Donor",37,"f",39.2,58.1,12,21,5.3,5.96,5.8,72,15.6,70.7 -"0=Blood Donor",37,"f",42.1,47.5,18.3,21.7,2.8,8.29,4.36,83,28.9,73.4 -"0=Blood Donor",37,"f",40.5,47.3,15.3,19.4,4.9,5.4,3.95,76,7.1,69 -"0=Blood Donor",38,"f",40,73.5,16.6,19.2,8.3,5.23,5.52,54,24,71 -"0=Blood Donor",38,"f",48.5,56.2,36,27.9,15.3,11.07,6.06,69,23.5,77.3 -"0=Blood Donor",38,"f",50.3,92.1,40.1,30.9,4.2,10.02,3.97,100,30.5,77.3 -"0=Blood Donor",38,"f",41.2,61.9,19.4,22.9,10.5,7.86,3.61,85,19.5,66.6 -"0=Blood Donor",38,"f",40.3,87.2,21.4,23.9,5.5,7.52,5.73,69,20.1,74 -"0=Blood Donor",38,"f",40,79.3,11.9,22,6.5,8.33,4.58,60,13.7,68.1 -"0=Blood Donor",39,"f",31.4,106,16.6,17,2.4,5.95,5.3,68,22.9,72.3 -"0=Blood Donor",39,"f",46.4,59.2,14.1,18.9,4.5,7.9,4.55,61,14.5,77.3 -"0=Blood Donor",40,"f",41.7,55.3,12.4,23.5,8.2,4.8,5.32,75,10.6,73.5 -"0=Blood Donor",40,"f",41.6,60.4,14.7,16.3,5.7,7.61,4.57,72,9.8,73.1 -"0=Blood Donor",40,"f",43.2,42.4,15.7,23.6,9.7,7.56,6.74,88,11.5,73.2 -"0=Blood Donor",40,"f",42.9,54.7,46.2,32.8,11.8,8.29,5.25,105,27.9,73.9 -"0=Blood Donor",40,"f",39.9,50.2,14.9,20.4,5.1,6.49,4.92,68,24.1,72.8 -"0=Blood Donor",41,"f",40.4,75.7,24.3,25.2,6,8.95,6.01,64,15.8,73 -"0=Blood Donor",41,"f",42.4,51.3,16.3,18.3,4,6.68,4.24,65,17.1,71.9 -"0=Blood Donor",41,"f",39.3,67.9,17.6,23.4,3.7,6.57,4.33,71,61,77.1 -"0=Blood Donor",41,"f",46.2,48.3,15.8,16.6,4.3,4.55,5.18,67,13,73.7 -"0=Blood Donor",41,"f",39.8,67.9,19.4,19.5,12.2,7.41,5.02,64,27.3,65.5 -"0=Blood Donor",42,"f",43.4,54,11.3,21.3,1.8,6.43,4.43,54,18.6,82.3 -"0=Blood Donor",42,"f",38.7,64.1,35.9,27.8,6,8.18,4.87,64,15.2,72.1 -"0=Blood Donor",43,"f",37.6,77.1,8.3,15.9,12.5,8.37,4.49,73,68.9,67.1 -"0=Blood Donor",43,"f",44.1,41.4,17.6,19.8,7.4,7.52,6.05,69,21.3,73.2 -"0=Blood Donor",43,"f",41.2,38.2,18.6,20.5,9.3,6.15,5.44,64,9.7,70.9 -"0=Blood Donor",43,"f",39,83.1,21.3,18.8,3.5,12.8,9.03,58,22.7,73.1 -"0=Blood Donor",43,"f",39,63,7.3,17.5,6.4,7.01,4.94,73,14.6,74.4 -"0=Blood Donor",43,"f",34.7,80.7,27,27.9,3.7,7.18,5.55,68,9.2,68.2 -"0=Blood Donor",43,"f",44.8,58.8,23,30.1,6.6,8.7,6.08,70,10.4,72.8 -"0=Blood Donor",43,"f",33.7,57.5,15.1,24.8,6.9,7.91,5.37,71,46,68.4 -"0=Blood Donor",43,"f",47.8,40.9,12.9,17.2,5.5,4.31,3.96,76,10.4,70.7 -"0=Blood Donor",44,"f",37.4,28.9,16.8,25.8,3.1,6.7,4.45,50,9.2,66.3 -"0=Blood Donor",44,"f",45.6,57.6,21,19.1,3.7,10.36,6.68,74,20.8,74.4 -"0=Blood Donor",44,"f",35.5,60,13.7,15,9.1,6.71,5.29,64,7.4,65.2 -"0=Blood Donor",44,"f",44,86.1,15.6,26.1,7.6,6.23,4.72,69,11.8,70.5 -"0=Blood Donor",44,"f",48.3,103.3,37.2,41.5,7,7.49,5.04,62,17.8,77.5 -"0=Blood Donor",44,"f",35.8,65.7,21.2,19.2,4.3,10.19,6.13,61,19.6,69.4 -"0=Blood Donor",44,"f",43,86.5,18.3,25,2.2,8.45,5.9,63,13.6,72.7 -"0=Blood Donor",44,"f",36.3,76.4,17.1,20.8,4.6,6.8,4.27,74,14.3,68 -"0=Blood Donor",44,"f",35.5,71,15.8,30,3.7,7.56,4.43,53,17.8,67.7 -"0=Blood Donor",45,"f",36.7,54.9,25.5,25.3,5.7,6.91,5.42,72,13.7,67.5 -"0=Blood Donor",45,"f",39.5,92.2,18.7,19.4,3.5,8.32,5.38,85,15.8,72.2 -"0=Blood Donor",45,"f",38.6,56,20.6,21.5,14.1,6.92,5.48,69,14.9,69.9 -"0=Blood Donor",45,"f",41.7,62.4,15.9,16.8,3.7,4.38,5.05,90,10,70.5 -"0=Blood Donor",45,"f",41.8,87.5,37.1,25.6,10.3,10.25,4.56,86,92.3,68.4 -"0=Blood Donor",45,"f",46.4,49.1,14.9,25.5,11,8.77,2.86,94,12,77.1 -"0=Blood Donor",45,"f",37.5,54.3,12.9,14.8,5.9,6.95,5.29,66,49.4,70.1 -"0=Blood Donor",45,"f",37,78.2,19.9,19.1,4.3,6.6,4.73,64,31.8,69.6 -"0=Blood Donor",45,"f",59.8,59.8,13.2,17.4,6.9,5.62,6.42,70,12.3,66.6 -"0=Blood Donor",46,"f",48.8,66.3,19.7,23.6,4.3,10.57,5.88,78,24.2,72.4 -"0=Blood Donor",46,"f",36.7,62.3,10.8,17.4,3.7,6.17,4.07,67,15.1,69 -"0=Blood Donor",46,"f",35.8,50.8,18.6,25.2,3.8,8.5,5.85,54,10.1,71.5 -"0=Blood Donor",46,"f",39.9,71.3,15.4,29.5,4.6,5.95,6.94,72,13.4,69.5 -"0=Blood Donor",46,"f",32.4,56.5,23.8,24.8,6.4,8.22,5.19,64,11,72 -"0=Blood Donor",46,"f",40.1,70.1,15.7,23.8,6,8.41,6.03,86,11,76.4 -"0=Blood Donor",46,"f",39.9,73.9,14,17.2,16.3,6.93,5.11,71,12.7,64.7 -"0=Blood Donor",46,"f",42.9,55.1,15.2,29.8,3.6,8.37,NA,61,29,71.9 -"0=Blood Donor",46,"f",41.1,47.5,21,17.7,7.1,7.55,4.42,62,11.9,69.8 -"0=Blood Donor",46,"f",42.3,61.9,20,21.8,9.7,8.8,7.09,67,35,75.2 -"0=Blood Donor",46,"f",37.9,59.5,33,25,3.7,6.06,5.3,92,43.9,70 -"0=Blood Donor",46,"f",36.8,113.2,31.2,24.8,3.8,9.6,4.83,78,19.9,72.7 -"0=Blood Donor",46,"f",51.3,84.1,40.6,43.6,9.2,7.1,5.62,62,74.9,77.1 -"0=Blood Donor",47,"f",35.6,37.5,17.6,18,4.7,4.32,5.59,75,13,66 -"0=Blood Donor",47,"f",38.7,43.4,12.1,19.4,3,5.35,4.6,56,15.7,67.8 -"0=Blood Donor",47,"f",36.4,42,11.1,18.3,7.2,4.97,5.47,74,7.9,67 -"0=Blood Donor",47,"f",34.6,54.1,10.2,15.3,8.4,6.5,5.1,76,10.6,67.7 -"0=Blood Donor",47,"f",40.3,65,13.5,15.2,6.4,7.16,4.55,70,16.5,66.2 -"0=Blood Donor",48,"f",45.6,107.2,24.4,39,13.8,9.77,NA,88,38,75.1 -"0=Blood Donor",48,"f",35.2,45.4,23.4,27.1,4.9,6.83,4.35,70,11.8,72.1 -"0=Blood Donor",48,"f",39.2,51,15.3,18.4,7.6,9.17,6.66,70,16.2,71.7 -"0=Blood Donor",48,"f",32,66.3,14.2,21.3,5.5,4.72,5.23,41,17.2,65.6 -"0=Blood Donor",48,"f",46.3,71.8,23,25.2,11.1,9.41,5.84,85,19.1,77.4 -"0=Blood Donor",48,"f",45.3,40.6,18.5,27.7,5.7,7.48,4.64,66,19.6,70.6 -"0=Blood Donor",48,"f",37.5,88.3,14.7,19.6,5.4,9.28,4.68,61,12.3,67.9 -"0=Blood Donor",48,"f",39.6,65.9,64.3,39.5,2.8,8.8,6.14,77,24.1,75.8 -"0=Blood Donor",48,"f",43.7,50.1,17.3,26.3,8.1,8.15,5.38,64,13.4,73.1 -"0=Blood Donor",48,"f",46.8,93.3,10,23.2,4.3,12.41,NA,52,23.9,72.4 -"0=Blood Donor",48,"f",42.5,62.2,12.1,20.1,23.1,4.01,5.58,67,13,74.2 -"0=Blood Donor",48,"f",44.4,52.5,16.4,23.4,4.5,9.06,6.78,74,10.3,73.1 -"0=Blood Donor",48,"f",44.4,64.5,17.2,21.1,17.3,4.93,4.05,67,12.1,71.2 -"0=Blood Donor",48,"f",38.8,43.9,12.8,13.3,8.6,5.63,5.31,66,21.4,63.2 -"0=Blood Donor",49,"f",38.8,120.2,25.2,21.5,12,8.29,7.11,52,18.6,70.7 -"0=Blood Donor",49,"f",40.9,58.4,20.1,26.5,2.6,9.77,5.99,53,12.7,73.9 -"0=Blood Donor",49,"f",39.1,89.4,15.4,24.1,4.1,10.03,8.36,74,12,68.1 -"0=Blood Donor",49,"f",39.3,59.4,18.3,15,4.8,8.03,4.58,83,12.5,74.3 -"0=Blood Donor",49,"f",40.5,31.3,16.2,19.4,11.2,4.95,5.1,75,14.9,73.2 -"0=Blood Donor",49,"f",34.9,37.9,15.3,19.4,7.1,5.3,5.88,83,7.9,62.5 -"0=Blood Donor",49,"f",45.4,45.9,14.3,15.9,5.8,9.05,6.81,69,14.5,78.2 -"0=Blood Donor",49,"f",43.3,71.5,28.4,26,6.2,7.68,5.91,77,19.1,76.9 -"0=Blood Donor",50,"f",36.9,50.6,15.5,21.7,2.1,9.97,7.01,68,17.6,68.4 -"0=Blood Donor",50,"f",47.6,77.2,24,17.5,4.8,9.27,6.41,77,21.3,73.5 -"0=Blood Donor",50,"f",42.5,74,10.9,23,4.6,9.42,6.33,76,9,68.8 -"0=Blood Donor",50,"f",39.9,80.5,24.2,22.8,5.2,9.25,7.41,84,19.4,71.2 -"0=Blood Donor",50,"f",41.2,45.6,25,25.1,4.1,7.16,6.54,64,15.4,68.2 -"0=Blood Donor",50,"f",34.6,63,24.7,31,12.8,6.55,5.95,70,25.4,70.2 -"0=Blood Donor",51,"f",46.3,70.5,75.2,69.2,6.1,7.68,4.73,69,52.2,78.3 -"0=Blood Donor",51,"f",37.8,80.7,32.9,27.3,6.2,7.29,5.26,68,27.1,70.6 -"0=Blood Donor",51,"f",38.3,52.9,12.4,16.5,3.8,7.22,5.43,55,12.7,70.2 -"0=Blood Donor",51,"f",39.6,63.5,17,25.9,7.3,7,6.97,72,10.4,71.9 -"0=Blood Donor",51,"f",38.3,67.7,17.4,19.9,5.4,7.5,4.94,72,7.9,69 -"0=Blood Donor",51,"f",43.1,52.2,18.5,24.1,8.1,7.52,6.76,60,17.4,71.9 -"0=Blood Donor",51,"f",41.4,136.9,33.2,20,5,10.27,6.24,77,106.7,72.2 -"0=Blood Donor",51,"f",41,81.2,35.1,33.3,5.2,8.9,6.56,70,21.7,72.4 -"0=Blood Donor",51,"f",46,71,18.1,23.8,59.1,5.99,3.25,82,11.4,73.3 -"0=Blood Donor",51,"f",39.6,43,16.3,19.6,7.5,5.57,4.96,83,62.1,72.9 -"0=Blood Donor",51,"f",47.4,117.3,62.1,30.4,3.8,10.43,6.59,86,69.3,71 -"0=Blood Donor",51,"f",43.7,61.3,18,23.3,4.3,9.57,6.04,70,18.6,75.2 -"0=Blood Donor",52,"f",45.5,78.2,25.2,27.7,4.7,8.65,6.04,65,28.3,70.5 -"0=Blood Donor",52,"f",43.8,52,15.5,23.9,6,7.93,5.41,69,11.9,72.4 -"0=Blood Donor",52,"f",36,47.2,19.6,22.5,5.9,7.85,5.69,85,30.4,69.2 -"0=Blood Donor",52,"f",41.7,58.3,22.9,26.7,11.4,9.17,4.33,75,14.5,77.1 -"0=Blood Donor",52,"f",40.2,89.7,26.8,19.1,6.9,9.1,7.04,75,41.6,67.4 -"0=Blood Donor",52,"f",51.5,81.8,26.3,20.6,7.8,6.74,5.9,88,16.3,82.2 -"0=Blood Donor",52,"f",36.7,87.6,34.3,30.8,17.7,10.12,6.98,72,24.2,66.3 -"0=Blood Donor",52,"f",41.3,77.4,16.6,22.2,5,7.57,7.8,66,10.8,70 -"0=Blood Donor",52,"f",38.2,70.3,19.5,17.5,2.7,10.02,6.17,65,35.5,71.1 -"0=Blood Donor",53,"f",42.4,55,20.9,42.4,7.7,6.6,4.26,67,14.2,70.9 -"0=Blood Donor",53,"f",39,76,25.9,20.7,2.8,11.11,6.38,66,50.1,70.8 -"0=Blood Donor",53,"f",40.1,84.6,23,22.1,7.1,8.4,5.16,70,82.6,74.6 -"0=Blood Donor",53,"f",43.7,84.3,18.8,18.6,8.5,10.22,6.65,56,16.5,76.9 -"0=Blood Donor",53,"f",43.5,61.7,16.9,20.3,7,7.19,6.97,74,12.3,69.2 -"0=Blood Donor",53,"f",41.1,91.7,13.8,19.6,3.4,7.87,5.48,72,77.3,77.3 -"0=Blood Donor",53,"f",38,84.7,23.5,19.8,10.8,7.3,4.82,62,11.4,68.5 -"0=Blood Donor",53,"f",47.4,66.9,24.3,32.6,14.9,10.51,6.03,81,25.2,75 -"0=Blood Donor",53,"f",51.3,84.1,40.6,43.6,9.2,7.1,5.62,62,74.9,77.1 -"0=Blood Donor",54,"f",39.9,30.7,17,19.3,6.3,6.99,4.95,68,13.3,70.7 -"0=Blood Donor",54,"f",26.2,72.9,28.5,28.8,5.5,7.49,4.91,58,27.6,57 -"0=Blood Donor",54,"f",44.5,53.4,13.4,17.5,5.4,7.74,5.55,66,15.4,71.9 -"0=Blood Donor",54,"f",39.9,61.2,23.3,24.5,4.5,9.22,5.47,69,58.2,65.8 -"0=Blood Donor",54,"f",43.3,76.5,19.9,22.4,7,8.04,6.77,67,17.7,73.3 -"0=Blood Donor",55,"f",41.9,86.1,19.3,22.3,7,8.21,5.05,71,32.5,75.2 -"0=Blood Donor",55,"f",36.2,101.3,19.2,21.9,4.9,6.5,5.86,66,12.3,70.3 -"0=Blood Donor",55,"f",35.2,69.6,23.6,26,3.8,4.97,4.43,69,29.4,60.5 -"0=Blood Donor",55,"f",39.9,83.6,18.4,27.4,8,8.43,7.67,73,13.6,73.3 -"0=Blood Donor",56,"f",39.7,66,14.2,20.8,3.5,7.48,5.88,66,7.2,67.2 -"0=Blood Donor",56,"f",39.5,86.9,22.5,22.2,4.7,9.4,6.02,66,13,72.6 -"0=Blood Donor",56,"f",34.7,90.3,22.7,21.6,3.5,8.07,5.45,67,9,69.4 -"0=Blood Donor",56,"f",36.6,102.3,13.5,14.9,8.4,6.94,5.5,65,16.2,71 -"0=Blood Donor",56,"f",33.2,54.3,15.5,22.8,8,5.61,3.87,55,19.1,63.1 -"0=Blood Donor",56,"f",45.1,79.1,39,30.5,5.2,6.47,5.1,64,145.3,66.7 -"0=Blood Donor",56,"f",39.9,83.8,19.1,23.6,4.3,7.61,6.06,72,16.4,67.1 -"0=Blood Donor",57,"f",48.4,94.4,2.5,39.6,2.3,8.84,NA,82,6.4,76.8 -"0=Blood Donor",57,"f",41.2,83.5,32.6,39.3,4,10.67,8.46,69,22.4,75.7 -"0=Blood Donor",57,"f",42.6,57.1,15,18.9,5.3,8.9,5.93,61,21.3,74.8 -"0=Blood Donor",57,"f",38.6,80.9,33.1,26.7,6.5,6.45,5.1,59,11.3,70.9 -"0=Blood Donor",57,"f",27.3,85.1,18.4,25.4,2.2,8.96,6.66,68,10.2,62.5 -"0=Blood Donor",57,"f",37.9,50.3,12.2,18.1,3.5,6.72,5.06,71,10,69.3 -"0=Blood Donor",57,"f",38.7,62.8,21.8,29.2,9.2,6.55,7.08,68,13,70.7 -"0=Blood Donor",57,"f",48,56.9,8.6,20.1,4.4,8.14,6.9,63,14.8,73.1 -"0=Blood Donor",57,"f",44.7,60.6,16.5,24.3,4.2,10.47,4.9,68,15.9,68.5 -"0=Blood Donor",57,"f",42.7,62.9,11.2,16.6,11.6,12.7,6.25,62,8.1,71.9 -"0=Blood Donor",58,"f",35.3,91.4,14.7,21,18,6.58,5.51,60,10.2,70.4 -"0=Blood Donor",58,"f",26.3,52.5,39.5,77.2,5.8,5.15,3.53,40,31.2,51 -"0=Blood Donor",58,"f",47,74.8,36.1,28.9,5.3,9.82,6.71,70,32,76.6 -"0=Blood Donor",59,"f",43,82.4,33.1,30,7.5,9.2,7.43,61,30.7,75.4 -"0=Blood Donor",59,"f",45.1,78,26,32.4,9,9.85,7.32,70,12.9,70.9 -"0=Blood Donor",59,"f",40,68.4,13.2,20.3,8.2,9.1,6.38,63,16.3,71.9 -"0=Blood Donor",60,"f",40.5,86,26,27.6,5.7,8.6,4.9,58,20.1,71.7 -"0=Blood Donor",60,"f",35.8,75.5,28.7,21.5,2,9.05,4.56,70,24,71.8 -"0=Blood Donor",60,"f",52.4,88.2,50.2,31.7,8.8,8.49,5,77,47,77 -"0=Blood Donor",60,"f",40.1,80.7,34.6,31.2,11.9,9.32,6.94,68,27.4,76.6 -"0=Blood Donor",60,"f",45.4,51.4,16.4,19,6.8,10.78,6.79,78,12.5,72.8 -"0=Blood Donor",60,"f",41.4,85.1,15.6,18.6,10,8.31,5.34,103,13,71.5 -"0=Blood Donor",61,"f",38.1,66.4,11.8,22.7,6.8,6.35,6.55,65,14.5,78.9 -"0=Blood Donor",61,"f",43.4,47.5,12.8,17.3,5.6,7.52,5.81,71,11.8,69.9 -"0=Blood Donor",62,"f",36.6,82.5,18.2,24.3,10.6,9.82,7.12,54,15.6,67.8 -"0=Blood Donor",62,"f",35.4,59.7,21.2,24.7,3.3,9,7.45,59,17.7,65.4 -"0=Blood Donor",62,"f",44,46.6,24.8,25.5,7.6,6.75,4.59,91,39.5,74.3 -"0=Blood Donor",63,"f",47.6,59.9,21.1,27.8,8.4,9.24,6.08,62,18.3,74.5 -"0=Blood Donor",63,"f",36.1,67.6,13.8,12.2,5.8,9.44,6.88,66,22.4,65 -"0=Blood Donor",63,"f",27.8,85.7,25.4,38.9,4.2,6.06,3.96,63,46,56.9 -"0=Blood Donor",64,"f",39.8,68.1,20.5,24.8,5.8,7.53,7.58,56,14.2,65.8 -"0=Blood Donor",64,"f",43,52.7,31.6,29.2,5.5,11.69,6,63,61.9,73.4 -"0=Blood Donor",65,"f",33,74.3,13.2,16.8,4.1,7.46,5.76,52,9.1,64.2 -"0=Blood Donor",68,"f",41.4,102.3,38.4,26.4,6.8,8.5,6.79,59,23.8,68.9 -"0=Blood Donor",70,"f",40,97.9,15.1,15.9,6.8,11.46,5.08,62,19.2,65.3 -"0s=suspect Blood Donor",47,"m",22.5,124,79.5,46.7,2.3,6.83,4.3,170,345.6,58.6 -"0s=suspect Blood Donor",48,"m",24.9,116.9,49.2,24.3,4.9,3.44,5.25,29,83,47.8 -"0s=suspect Blood Donor",49,"m",21.6,42.2,9.5,10.6,2.4,3.75,3.01,64,38.9,44.8 -"0s=suspect Blood Donor",55,"m",47.3,106,208.8,130.6,0.8,14.8,8.08,76,71.6,78.3 -"0s=suspect Blood Donor",71,"m",14.9,69.8,19.7,95.2,9.8,13.3,2.61,9,7.6,47 -"0s=suspect Blood Donor",74,"m",20.3,84,22.8,43,5.7,4.91,3.19,52,218.3,47.8 -"0s=suspect Blood Donor",59,"f",19.3,208.2,325.3,146.6,6.9,5.33,4.72,32,295.6,53.1 -"1=Hepatitis",38,"m",45,56.3,NA,33.1,7,9.58,6,77.9,18.9,63 -"1=Hepatitis",19,"m",41,NA,87,67,12,7.55,3.9,62,65,75 -"1=Hepatitis",23,"m",47,19.1,38.9,164.2,17,7.09,3.2,79.3,90.4,70.1 -"1=Hepatitis",25,"m",42,38.2,63.3,187.7,14,6,4.28,66.9,40.2,70.5 -"1=Hepatitis",27,"m",45,27.5,10.5,37.8,10,8.77,3.2,55.2,35.9,74.5 -"1=Hepatitis",29,"m",49,NA,53,39,15,8.79,3.6,79,37,90 -"1=Hepatitis",30,"m",45,NA,66,45,14,12.16,6.1,86,43,77 -"1=Hepatitis",32,"m",45,34.6,44.3,96.2,16,10.11,6.28,81.2,48.1,82.1 -"1=Hepatitis",32,"m",41,34.4,12.1,60.9,6,13.8,5.48,45.4,33.1,71.1 -"1=Hepatitis",34,"m",46,36.7,7.4,31.6,9,9.71,5.37,82.3,34.4,71.6 -"1=Hepatitis",35,"m",47,37.9,13.3,48.4,8,10.3,4.14,69.2,68.2,76 -"1=Hepatitis",36,"m",44,32.9,9.4,32,14,11.42,5.73,68.6,40.6,70.9 -"1=Hepatitis",38,"m",41,20.6,15.2,53.5,24,10.23,4.89,81.8,57.9,71.1 -"1=Hepatitis",41,"m",42,39.6,26.5,77.6,42,9.67,9.67,57.7,143.4,75.8 -"1=Hepatitis",44,"m",49,27.3,40.2,31.1,13,8.91,4.07,81.5,27.6,72.8 -"1=Hepatitis",46,"m",48,59.5,11.6,39,7,16.41,4.65,66.4,158.2,72.7 -"1=Hepatitis",50,"m",42,41.6,10.2,38.1,17,9.54,7.04,75.3,92.1,72.3 -"1=Hepatitis",51,"m",43,37.2,21.4,132.8,5,10.12,5.23,76.2,76.4,76.7 -"1=Hepatitis",56,"m",37,114,27.8,324,67,5.75,3.09,97.7,392.2,77.3 -"1=Hepatitis",58,"m",43,99.1,12.2,63.2,13,5.95,6.15,147.3,491,65.6 -"1=Hepatitis",33,"f",43,29.6,3.8,16.7,6,6.88,5.72,58.8,11.5,78.2 -"1=Hepatitis",41,"f",37,31.2,8.2,38.3,7,7.08,5.3,60.8,24.7,82.4 -"1=Hepatitis",50,"f",40,32.7,9,46,10,7.51,4.67,56.6,22.3,70.1 -"1=Hepatitis",61,"f",50,34.4,27.4,114.4,22,9.48,4.62,61.9,169.8,86 -"2=Fibrosis",29,"m",41,43.1,2.4,83.5,6,11.49,5.42,55.2,130,66.5 -"2=Fibrosis",40,"m",39,43.1,23.8,114.7,11,9.64,4.2,70.9,127.3,81.3 -"2=Fibrosis",46,"m",45,26.9,23.1,125,17,6.97,4.01,60.5,72.2,73 -"2=Fibrosis",48,"m",49,45.2,19.3,69.1,30,7.76,4.22,76.7,28.4,72.3 -"2=Fibrosis",49,"m",39,NA,118,62,10,7.28,3.5,72,74,81 -"2=Fibrosis",49,"m",46,NA,114,75,16,10.43,5.2,72,59,82 -"2=Fibrosis",50,"m",42,NA,258,106,15,8.74,4.7,77,80,84 -"2=Fibrosis",53,"m",46,NA,34,43,14,8.77,4,112,203,76 -"2=Fibrosis",54,"m",41,41.8,41.5,187.9,21,8.59,5.85,91,104.9,79.1 -"2=Fibrosis",57,"m",47,29.7,10.2,55.9,12,6.6,4.64,70.9,69.6,80.9 -"2=Fibrosis",59,"m",44,34.5,8.9,74.5,6,9.45,4.45,65,95.3,69.7 -"2=Fibrosis",64,"m",38,35.7,7.1,41.3,13,7.1,4.52,70,53,66.8 -"2=Fibrosis",71,"m",37,NA,130,90,15,9.92,4.7,79,77,76 -"2=Fibrosis",36,"f",46,39.3,67.1,161.9,13,9.24,4.81,65.3,60,73.9 -"2=Fibrosis",38,"f",40,39.8,14.9,68.9,11,8.55,4.31,60.5,40.1,76.5 -"2=Fibrosis",57,"f",43,52.1,8.3,35.8,18,8.61,6.19,71.4,27.9,82 -"2=Fibrosis",68,"f",43,22.9,5,42.1,12,7.29,4.89,80.9,11.9,76.1 -"2=Fibrosis",49,"f",39,NA,46,39,9,10.21,3.1,89,53,79 -"2=Fibrosis",51,"f",37,NA,164,70,9,3.99,4.2,67,43,72 -"2=Fibrosis",56,"f",39,NA,42,34,10,7.75,5,80,84,78 -"2=Fibrosis",75,"f",36,NA,114,125,14,6.65,NA,57,177,72 -"3=Cirrhosis",38,"m",44,NA,94,60,12,4.37,3.2,61,99,77 -"3=Cirrhosis",39,"m",34,137.8,4.8,35.6,9,3.65,4.82,519,133.4,57.5 -"3=Cirrhosis",41,"m",31,85.3,4.8,60.2,200,1.8,5.34,106.4,151,71.8 -"3=Cirrhosis",42,"m",36,69.6,14.9,263.1,40,3.61,3.93,49.6,61,68.6 -"3=Cirrhosis",45,"m",29,11.3,7.1,101.9,31,1.73,3.71,76.7,65.6,70 -"3=Cirrhosis",46,"m",20,NA,62,113,254,1.48,NA,114,138,NA -"3=Cirrhosis",46,"m",35,109.6,2.3,19.2,11,7.1,4.1,1079.1,105.6,69.1 -"3=Cirrhosis",47,"m",42,NA,159,102,11,6.29,5.5,58,201,79 -"3=Cirrhosis",51,"m",39,66,29.6,185,19,2,3.6,58.3,399.5,79.4 -"3=Cirrhosis",51,"m",33,29.6,4.5,66.6,91,4.02,4.08,75.9,28.5,62.3 -"3=Cirrhosis",56,"m",27,81.1,17,319.8,37,1.42,3.54,66.9,93.7,65.3 -"3=Cirrhosis",56,"m",23,105.6,5.1,123,43,1.8,2.4,62.7,35.9,62.8 -"3=Cirrhosis",56,"m",30,40.4,0.9,80.3,119,1.88,1.43,79.3,17.6,54.2 -"3=Cirrhosis",58,"m",31,143.1,7,181.8,58,3.29,3.92,66.4,273.7,78.1 -"3=Cirrhosis",59,"m",36,49.7,5.2,110.1,37,2.29,3.68,118.2,56.9,74.8 -"3=Cirrhosis",59,"m",27,73.8,4,65.2,209,2.47,3.61,71.7,28.5,60.6 -"3=Cirrhosis",59,"m",31,86.3,5.4,95.4,117,1.57,3.51,60.5,53.6,68.5 -"3=Cirrhosis",61,"m",39,102.9,27.3,143.2,15,5.38,4.88,72.3,400.3,73.4 -"3=Cirrhosis",65,"m",NA,NA,40,54,13,7.5,NA,70,107,79 -"3=Cirrhosis",74,"m",23,34.1,2.1,90.4,22,2.5,3.29,51,46.8,57.1 -"3=Cirrhosis",42,"f",33,79,3.7,55.7,200,1.72,5.16,89.1,146.3,69.9 -"3=Cirrhosis",49,"f",33,190.7,1.2,36.3,7,6.92,3.82,485.9,112,58.5 -"3=Cirrhosis",52,"f",39,37,1.3,30.4,21,6.33,3.78,158.2,142.5,82.7 -"3=Cirrhosis",58,"f",34,46.4,15,150,8,6.26,3.98,56,49.7,80.6 -"3=Cirrhosis",59,"f",39,51.3,19.6,285.8,40,5.77,4.51,136.1,101.1,70.5 -"3=Cirrhosis",62,"f",32,416.6,5.9,110.3,50,5.57,6.3,55.7,650.9,68.5 -"3=Cirrhosis",64,"f",24,102.8,2.9,44.4,20,1.54,3.02,63,35.9,71.3 -"3=Cirrhosis",64,"f",29,87.3,3.5,99,48,1.66,3.63,66.7,64.2,82 -"3=Cirrhosis",46,"f",33,NA,39,62,20,3.56,4.2,52,50,71 -"3=Cirrhosis",59,"f",36,NA,100,80,12,9.07,5.3,67,34,68 \ No newline at end of file diff --git a/public/models/00-tabular-classification/TODO/hepatitis-c/model.json b/public/models/00-tabular-classification/TODO/hepatitis-c/model.json deleted file mode 100644 index cd41659..0000000 --- a/public/models/00-tabular-classification/TODO/hepatitis-c/model.json +++ /dev/null @@ -1,367 +0,0 @@ -{ - "format": "layers-model", - "generatedBy": "keras v2.11.0", - "convertedBy": "TensorFlow.js Converter v4.2.0", - "modelTopology": { - "keras_version": "2.11.0", - "backend": "tensorflow", - "model_config": { - "class_name": "Sequential", - "config": { - "name": "sequential", - "layers": [ - { - "class_name": "InputLayer", - "config": { - "batch_input_shape": [ - null, - 12 - ], - "dtype": "float32", - "sparse": false, - "ragged": false, - "name": "dense_input" - } - }, - { - "class_name": "Dense", - "config": { - "name": "dense", - "trainable": true, - "dtype": "float32", - "batch_input_shape": [ - null, - 12 - ], - "units": 10, - "activation": "relu", - "use_bias": true, - "kernel_initializer": { - "class_name": "GlorotUniform", - "config": { - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null - } - }, - { - "class_name": "Dense", - "config": { - "name": "dense_1", - "trainable": true, - "dtype": "float32", - "units": 100, - "activation": "relu", - "use_bias": true, - "kernel_initializer": { - "class_name": "GlorotUniform", - "config": { - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null - } - }, - { - "class_name": "Dense", - "config": { - "name": "dense_2", - "trainable": true, - "dtype": "float32", - "units": 100, - "activation": "relu", - "use_bias": true, - "kernel_initializer": { - "class_name": "GlorotUniform", - "config": { - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null - } - }, - { - "class_name": "Dense", - "config": { - "name": "dense_3", - "trainable": true, - "dtype": "float32", - "units": 100, - "activation": "relu", - "use_bias": true, - "kernel_initializer": { - "class_name": "GlorotUniform", - "config": { - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null - } - }, - { - "class_name": "Dense", - "config": { - "name": "dense_4", - "trainable": true, - "dtype": "float32", - "units": 100, - "activation": "relu", - "use_bias": true, - "kernel_initializer": { - "class_name": "GlorotUniform", - "config": { - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null - } - }, - { - "class_name": "Dense", - "config": { - "name": "dense_5", - "trainable": true, - "dtype": "float32", - "units": 100, - "activation": "relu", - "use_bias": true, - "kernel_initializer": { - "class_name": "GlorotUniform", - "config": { - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null - } - }, - { - "class_name": "Dense", - "config": { - "name": "dense_6", - "trainable": true, - "dtype": "float32", - "units": 5, - "activation": "softmax", - "use_bias": true, - "kernel_initializer": { - "class_name": "GlorotUniform", - "config": { - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null - } - } - ] - } - }, - "training_config": { - "loss": "categorical_crossentropy", - "metrics": [ - [ - { - "class_name": "MeanMetricWrapper", - "config": { - "name": "accuracy", - "dtype": "float32", - "fn": "categorical_accuracy" - } - } - ] - ], - "weighted_metrics": null, - "loss_weights": null, - "optimizer_config": { - "class_name": "Custom>Adam", - "config": { - "name": "Adam", - "weight_decay": null, - "clipnorm": null, - "global_clipnorm": null, - "clipvalue": null, - "use_ema": false, - "ema_momentum": 0.99, - "ema_overwrite_frequency": null, - "jit_compile": false, - "is_legacy_optimizer": false, - "learning_rate": 0.0010000000474974513, - "beta_1": 0.9, - "beta_2": 0.999, - "epsilon": 1e-07, - "amsgrad": false - } - } - } - }, - "weightsManifest": [ - { - "paths": [ - "modelHepatitis.weights.bin" - ], - "weights": [ - { - "name": "dense/kernel", - "shape": [ - 12, - 10 - ], - "dtype": "float32" - }, - { - "name": "dense/bias", - "shape": [ - 10 - ], - "dtype": "float32" - }, - { - "name": "dense_1/kernel", - "shape": [ - 10, - 100 - ], - "dtype": "float32" - }, - { - "name": "dense_1/bias", - "shape": [ - 100 - ], - "dtype": "float32" - }, - { - "name": "dense_2/kernel", - "shape": [ - 100, - 100 - ], - "dtype": "float32" - }, - { - "name": "dense_2/bias", - "shape": [ - 100 - ], - "dtype": "float32" - }, - { - "name": "dense_3/kernel", - "shape": [ - 100, - 100 - ], - "dtype": "float32" - }, - { - "name": "dense_3/bias", - "shape": [ - 100 - ], - "dtype": "float32" - }, - { - "name": "dense_4/kernel", - "shape": [ - 100, - 100 - ], - "dtype": "float32" - }, - { - "name": "dense_4/bias", - "shape": [ - 100 - ], - "dtype": "float32" - }, - { - "name": "dense_5/kernel", - "shape": [ - 100, - 100 - ], - "dtype": "float32" - }, - { - "name": "dense_5/bias", - "shape": [ - 100 - ], - "dtype": "float32" - }, - { - "name": "dense_6/kernel", - "shape": [ - 100, - 5 - ], - "dtype": "float32" - }, - { - "name": "dense_6/bias", - "shape": [ - 5 - ], - "dtype": "float32" - } - ] - } - ] -} \ No newline at end of file diff --git a/public/models/00-tabular-classification/TODO/hepatitis-c/modelHepatitis.weights.bin b/public/models/00-tabular-classification/TODO/hepatitis-c/modelHepatitis.weights.bin deleted file mode 100644 index 7adacd3..0000000 Binary files a/public/models/00-tabular-classification/TODO/hepatitis-c/modelHepatitis.weights.bin and /dev/null differ diff --git a/public/models/00-tabular-classification/TODO/hepatitis/cost/hepatitis.cost b/public/models/00-tabular-classification/TODO/hepatitis/cost/hepatitis.cost deleted file mode 100644 index 143be62..0000000 --- a/public/models/00-tabular-classification/TODO/hepatitis/cost/hepatitis.cost +++ /dev/null @@ -1,19 +0,0 @@ -age: 1.00 -sex: 1.00 -steroid: 1.00 -antviral: 1.00 -fatigue: 1.00 -malaise: 1.00 -anorexia: 1.00 -liver_big: 1.00 -liver_firm: 1.00 -spleen_palpable: 1.00 -spiders: 1.00 -ascites: 1.00 -varices: 1.00 -bilirubin: 7.27 -alk_phosphate: 7.27 -sgot: 7.27 -albumin: 7.27 -protime: 8.30 -histology: 1.00 diff --git a/public/models/00-tabular-classification/TODO/hepatitis/cost/hepatitis.delay b/public/models/00-tabular-classification/TODO/hepatitis/cost/hepatitis.delay deleted file mode 100644 index 4542592..0000000 --- a/public/models/00-tabular-classification/TODO/hepatitis/cost/hepatitis.delay +++ /dev/null @@ -1,19 +0,0 @@ -age: immediate. -sex: immediate. -steroid: immediate. -antviral: immediate. -fatigue: immediate. -malaise: immediate. -anorexia: immediate. -liver_big: immediate. -liver_firm: immediate. -spleen_palpable: immediate. -spiders: immediate. -ascites: immediate. -varices: immediate. -bilirubin: delayed. -alk_phosphate: delayed. -sgot: delayed. -albumin: delayed. -protime: delayed. -histology: immediate. diff --git a/public/models/00-tabular-classification/TODO/hepatitis/cost/hepatitis.expense b/public/models/00-tabular-classification/TODO/hepatitis/cost/hepatitis.expense deleted file mode 100644 index 8732f98..0000000 --- a/public/models/00-tabular-classification/TODO/hepatitis/cost/hepatitis.expense +++ /dev/null @@ -1,19 +0,0 @@ -age: 1.00, 1.00 -sex: 1.00, 1.00 -steroid: 1.00, 1.00 -antviral: 1.00, 1.00 -fatigue: 1.00, 1.00 -malaise: 1.00, 1.00 -anorexia: 1.00, 1.00 -liver_big: 1.00, 1.00 -liver_firm: 1.00, 1.00 -spleen_palpable: 1.00, 1.00 -spiders: 1.00, 1.00 -ascites: 1.00, 1.00 -varices: 1.00, 1.00 -bilirubin: 7.27, 5.17 -alk_phosphate: 7.27, 5.17 -sgot: 7.27, 5.17 -albumin: 7.27, 5.17 -protime: 8.30, 6.20 -histology: 1.00, 1.00 diff --git a/public/models/00-tabular-classification/TODO/hepatitis/cost/hepatitis.group b/public/models/00-tabular-classification/TODO/hepatitis/cost/hepatitis.group deleted file mode 100644 index 64d822f..0000000 --- a/public/models/00-tabular-classification/TODO/hepatitis/cost/hepatitis.group +++ /dev/null @@ -1,7 +0,0 @@ -A. - -bilirubin: A. -alk_phosphate: A. -sgot: A. -albumin: A. -protime: A. diff --git a/public/models/00-tabular-classification/TODO/hepatitis/hepatitis.README.md b/public/models/00-tabular-classification/TODO/hepatitis/hepatitis.README.md deleted file mode 100644 index b3dd9fc..0000000 --- a/public/models/00-tabular-classification/TODO/hepatitis/hepatitis.README.md +++ /dev/null @@ -1,68 +0,0 @@ -Test Costs for the hepatitis Data ---------------------------------- - -Peter Turney -June 7, 1995 - - -There are four files, in a C4.5-like format, that contain information -related to cost: - - 1. hepatitis.cost - 2. hepatitis.delay - 3. hepatitis.expense - 4. hepatitis.group - -For more information on the use and meaning of these files, see: - -http://www.cs.washington.edu/research/jair/volume2/turney95a-html/title.html - -The remainder of this file describes the format of the above four -files. - - -hepatitis.cost --------------- - -Each row has the format ": ". The cost is in Canadian -dollars. The cost information is from the Ontario Health Insurance -Program's fee schedule. The costs in this file are for individual -tests, considered in isolation. When tests are performed in groups, -there may be discounts, due to shared common costs. Groups of tests -with common costs are identified in the file "hepatitis.group". Costs -with discounts are in the file "hepatitis.expense". - - -hepatitis.delay ---------------- - -Each row has the format ": ". Tests with -immediate results are marked "immediate". Tests with delayed results -are marked "delayed". Delayed tests are typically blood tests, which -are usually shipped to a laboratory. The results are sent back to the -doctor the next day. - - -hepatitis.expense ------------------ - -Each row has the format ": , ". The -full cost is charged when the given test is the first test of its group -that has been ordered for a given patient. The discount cost is charged -when the given test is the second or later test of its group that has -been ordered. Typically the difference between the full cost and the -discount cost is $2.10, which is the common (shared) cost of collecting -blood from the patient. - - -hepatitis.group ---------------- - -The first row lists the groups. The remaining rows have the format -": ". The symbols used for groups are arbitrary. The -information in this file is meant to be used together with the -information in "hepatitis.expense". The tests in a group share a -common cost. - - - diff --git a/public/models/00-tabular-classification/TODO/hepatitis/hepatitis.data b/public/models/00-tabular-classification/TODO/hepatitis/hepatitis.data deleted file mode 100644 index 67adc8e..0000000 --- a/public/models/00-tabular-classification/TODO/hepatitis/hepatitis.data +++ /dev/null @@ -1,155 +0,0 @@ -2,30,2,1,2,2,2,2,1,2,2,2,2,2,1.00,85,18,4.0,?,1 -2,50,1,1,2,1,2,2,1,2,2,2,2,2,0.90,135,42,3.5,?,1 -2,78,1,2,2,1,2,2,2,2,2,2,2,2,0.70,96,32,4.0,?,1 -2,31,1,?,1,2,2,2,2,2,2,2,2,2,0.70,46,52,4.0,80,1 -2,34,1,2,2,2,2,2,2,2,2,2,2,2,1.00,?,200,4.0,?,1 -2,34,1,2,2,2,2,2,2,2,2,2,2,2,0.90,95,28,4.0,75,1 -1,51,1,1,2,1,2,1,2,2,1,1,2,2,?,?,?,?,?,1 -2,23,1,2,2,2,2,2,2,2,2,2,2,2,1.00,?,?,?,?,1 -2,39,1,2,2,1,2,2,2,1,2,2,2,2,0.70,?,48,4.4,?,1 -2,30,1,2,2,2,2,2,2,2,2,2,2,2,1.00,?,120,3.9,?,1 -2,39,1,1,1,2,2,2,1,1,2,2,2,2,1.30,78,30,4.4,85,1 -2,32,1,2,1,1,2,2,2,1,2,1,2,2,1.00,59,249,3.7,54,1 -2,41,1,2,1,1,2,2,2,1,2,2,2,2,0.90,81,60,3.9,52,1 -2,30,1,2,2,1,2,2,2,1,2,2,2,2,2.20,57,144,4.9,78,1 -2,47,1,1,1,2,2,2,2,2,2,2,2,2,?,?,60,?,?,1 -2,38,1,1,2,1,1,1,2,2,2,2,1,2,2.00,72,89,2.9,46,1 -2,66,1,2,2,1,2,2,2,2,2,2,2,2,1.20,102,53,4.3,?,1 -2,40,1,1,2,1,2,2,2,1,2,2,2,2,0.60,62,166,4.0,63,1 -2,38,1,2,2,2,2,2,2,2,2,2,2,2,0.70,53,42,4.1,85,2 -2,38,1,1,1,2,2,2,1,1,2,2,2,2,0.70,70,28,4.2,62,1 -2,22,2,2,1,1,2,2,2,2,2,2,2,2,0.90,48,20,4.2,64,1 -2,27,1,2,2,1,1,1,1,1,1,1,2,2,1.20,133,98,4.1,39,1 -2,31,1,2,2,2,2,2,2,2,2,2,2,2,1.00,85,20,4.0,100,1 -2,42,1,2,2,2,2,2,2,2,2,2,2,2,0.90,60,63,4.7,47,1 -2,25,2,1,1,2,2,2,2,2,2,2,2,2,0.40,45,18,4.3,70,1 -2,27,1,1,2,1,1,2,2,2,2,2,2,2,0.80,95,46,3.8,100,1 -2,49,1,1,1,1,1,1,2,1,2,1,2,2,0.60,85,48,3.7,?,1 -2,58,2,2,2,1,2,2,2,1,2,1,2,2,1.40,175,55,2.7,36,1 -2,61,1,1,2,1,2,2,1,1,2,2,2,2,1.30,78,25,3.8,100,1 -2,51,1,1,1,1,1,2,2,2,2,2,2,2,1.00,78,58,4.6,52,1 -1,39,1,1,1,1,1,2,2,1,2,2,2,2,2.30,280,98,3.8,40,1 -1,62,1,1,2,1,1,2,?,?,2,2,2,2,1.00,?,60,?,?,1 -2,41,2,2,1,1,1,1,2,2,2,2,2,2,0.70,81,53,5.0,74,1 -2,26,2,1,2,2,2,2,2,1,2,2,2,2,0.50,135,29,3.8,60,1 -2,35,1,2,2,1,2,2,2,2,2,2,2,2,0.90,58,92,4.3,73,1 -1,37,1,2,2,1,2,2,2,2,2,1,2,2,0.60,67,28,4.2,?,1 -2,23,1,2,2,1,1,1,2,2,1,2,2,2,1.30,194,150,4.1,90,1 -2,20,2,1,2,1,1,1,1,1,1,1,2,2,2.30,150,68,3.9,?,1 -2,42,1,1,2,2,2,2,2,2,2,2,2,2,1.00,85,14,4.0,100,1 -2,65,1,2,2,1,1,2,2,1,1,1,1,2,0.30,180,53,2.9,74,2 -2,52,1,1,1,2,2,2,2,2,2,2,2,2,0.70,75,55,4.0,21,1 -2,23,1,2,2,2,2,2,?,?,?,?,?,?,4.60,56,16,4.6,?,1 -2,33,1,2,2,2,2,2,2,2,2,2,2,2,1.00,46,90,4.4,60,1 -2,56,1,1,2,1,2,2,2,2,2,2,2,2,0.70,71,18,4.4,100,1 -2,34,1,2,2,2,2,2,2,2,2,2,2,2,?,?,86,?,?,1 -2,28,1,2,2,1,1,2,2,2,2,2,2,2,0.70,74,110,4.4,?,1 -2,37,1,1,2,2,2,2,2,1,2,1,2,2,0.60,80,80,3.8,?,1 -2,28,2,2,2,1,1,2,2,1,2,2,2,2,1.80,191,420,3.3,46,1 -2,36,1,1,2,2,2,2,2,2,1,2,2,2,0.80,85,44,4.2,85,1 -2,38,1,2,1,1,1,1,2,2,2,1,2,2,0.70,125,65,4.2,77,1 -2,39,1,1,2,2,2,2,2,2,2,2,2,2,0.90,85,60,4.0,?,1 -2,39,1,2,2,2,2,2,2,2,2,2,2,2,1.00,85,20,4.0,?,1 -2,44,1,2,2,2,2,2,2,2,2,2,2,2,0.60,110,145,4.4,70,1 -2,40,1,2,1,1,2,2,2,1,1,2,2,2,1.20,85,31,4.0,100,1 -2,30,1,2,2,1,2,2,2,2,2,2,2,2,0.70,50,78,4.2,74,1 -2,37,1,1,2,1,1,1,2,2,2,2,2,2,0.80,92,59,?,?,1 -2,34,1,1,2,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1 -2,30,1,2,1,2,2,2,2,2,2,2,2,2,0.70,52,38,3.9,52,1 -2,64,1,2,1,1,1,2,1,1,2,2,2,2,1.00,80,38,4.3,74,1 -2,45,2,1,2,1,1,2,2,2,1,2,2,2,1.00,85,75,?,?,1 -2,37,1,2,2,2,2,2,2,2,2,2,2,2,0.70,26,58,4.5,100,1 -2,32,1,2,2,2,2,2,2,2,2,2,2,2,0.70,102,64,4.0,90,1 -2,32,1,2,2,1,1,1,2,2,2,1,2,1,3.50,215,54,3.4,29,1 -2,36,1,1,2,2,2,2,1,1,1,2,2,2,0.70,164,44,3.1,41,1 -2,49,1,2,2,1,1,2,2,2,2,2,2,2,0.80,103,43,3.5,66,1 -2,27,1,2,2,2,2,2,2,2,2,2,2,2,0.80,?,38,4.2,?,1 -2,56,1,1,2,2,2,2,2,2,2,2,2,2,0.70,62,33,3.0,?,1 -1,57,1,2,2,1,1,1,2,2,2,1,1,2,4.10,?,48,2.6,73,1 -2,39,1,2,2,1,2,2,2,2,2,2,2,2,1.00,34,15,4.0,54,1 -2,44,1,1,2,1,1,2,2,2,2,2,2,2,1.60,68,68,3.7,?,1 -2,24,1,2,2,2,2,2,2,2,2,2,2,2,0.80,82,39,4.3,?,1 -1,34,1,1,2,1,1,2,1,1,2,1,2,2,2.80,127,182,?,?,1 -2,51,1,2,2,1,1,1,?,?,?,?,?,?,0.90,76,271,4.4,?,1 -2,36,1,1,2,1,1,1,2,1,2,2,2,2,1.00,?,45,4.0,57,1 -2,50,1,2,2,2,2,2,2,2,2,2,2,2,1.50,100,100,5.3,?,1 -2,32,1,1,1,1,1,2,2,2,2,2,2,2,1.00,55,45,4.1,56,1 -1,58,1,2,2,1,2,2,1,1,1,1,2,2,2.00,167,242,3.3,?,1 -2,34,2,1,1,2,2,2,2,1,2,2,2,2,0.60,30,24,4.0,76,1 -2,34,1,1,2,1,2,2,1,1,2,1,2,2,1.00,72,46,4.4,57,1 -2,28,1,2,2,2,2,2,2,2,2,2,2,2,0.70,85,31,4.9,?,1 -2,23,1,2,2,1,1,1,2,2,2,2,2,2,0.80,?,14,4.8,?,1 -2,36,1,2,2,2,2,2,2,2,2,2,2,2,0.70,62,224,4.2,100,1 -2,30,1,1,2,2,2,2,2,2,2,2,2,2,0.70,100,31,4.0,100,1 -2,67,2,1,2,1,1,2,2,2,?,?,?,?,1.50,179,69,2.9,?,1 -2,62,2,2,2,1,1,2,2,1,2,1,2,2,1.30,141,156,3.9,58,1 -2,28,1,1,2,1,1,1,2,1,2,2,2,2,1.60,44,123,4.0,46,1 -1,44,1,1,2,1,1,2,2,2,1,2,2,1,0.90,135,55,?,41,2 -1,30,1,2,2,1,1,1,2,1,2,1,1,1,2.50,165,64,2.8,?,2 -1,38,1,1,2,1,1,1,2,1,2,1,1,1,1.20,118,16,2.8,?,2 -2,38,1,1,2,1,1,1,1,1,2,2,2,2,0.60,76,18,4.4,84,2 -2,50,2,1,2,1,2,2,1,1,1,1,2,2,0.90,230,117,3.4,41,2 -1,42,1,1,2,1,1,1,2,2,1,1,2,1,4.60,?,55,3.3,?,2 -2,33,1,2,2,2,2,2,?,?,2,2,2,2,1.00,?,60,4.0,?,2 -2,52,1,1,2,2,2,2,2,2,2,2,2,2,1.50,?,69,2.9,?,2 -1,59,1,1,2,1,1,2,2,1,1,1,2,2,1.50,107,157,3.6,38,2 -2,40,1,1,1,1,1,1,1,1,2,2,2,2,0.60,40,69,4.2,67,2 -2,30,1,1,2,1,1,2,2,1,2,1,2,2,0.80,147,128,3.9,100,2 -2,44,1,1,2,1,1,2,1,1,2,1,2,2,3.00,114,65,3.5,?,2 -1,47,1,2,2,2,2,2,2,2,2,1,2,1,2.00,84,23,4.2,66,2 -2,60,1,1,2,1,2,2,1,1,1,1,2,2,?,?,40,?,?,2 -1,48,1,1,2,1,1,2,2,1,2,1,1,1,4.80,123,157,2.7,31,2 -2,22,1,2,2,2,2,2,2,2,2,2,2,2,0.70,?,24,?,?,2 -2,27,1,1,2,1,2,2,2,1,2,2,2,2,2.40,168,227,3.0,66,2 -2,51,1,1,2,1,1,1,2,1,1,1,2,1,4.60,215,269,3.9,51,2 -1,47,1,2,2,1,1,2,2,1,2,2,1,1,1.70,86,20,2.1,46,2 -2,25,1,2,2,2,2,2,2,2,2,2,2,2,0.60,?,34,6.4,?,2 -1,35,1,1,2,1,2,2,?,?,1,1,1,2,1.50,138,58,2.6,?,2 -2,45,1,1,2,1,1,1,2,2,2,2,2,2,2.30,?,648,?,?,2 -2,54,1,1,1,2,2,2,1,1,2,2,2,2,1.00,155,225,3.6,67,2 -1,33,1,1,2,1,1,2,2,2,2,2,1,2,0.70,63,80,3.0,31,2 -2,7,1,2,2,2,2,2,2,1,1,2,2,2,0.70,256,25,4.2,?,2 -1,42,1,1,1,1,1,2,2,2,2,1,2,2,0.50,62,68,3.8,29,2 -2,52,1,1,2,1,2,2,2,2,2,2,2,2,1.00,85,30,4.0,?,2 -2,45,1,1,2,1,2,2,2,1,1,2,2,2,1.20,81,65,3.0,?,1 -2,36,1,1,2,2,2,2,2,2,2,2,2,2,1.10,141,75,3.3,?,2 -2,69,2,2,2,1,2,2,2,2,2,2,2,2,3.20,119,136,?,?,2 -2,24,1,1,2,1,2,2,2,2,2,2,2,2,1.00,?,34,4.1,?,2 -2,50,1,2,2,2,2,2,2,2,2,2,2,2,1.00,139,81,3.9,62,2 -1,61,1,1,2,1,1,2,?,?,2,1,2,2,?,?,?,?,?,2 -2,54,1,2,2,1,2,2,1,1,2,2,2,2,3.20,85,28,3.8,?,2 -1,56,1,1,2,1,1,1,1,1,2,1,2,2,2.90,90,153,4.0,?,2 -2,20,1,1,2,1,1,1,2,2,2,1,1,2,1.00,160,118,2.9,23,2 -2,42,1,2,2,2,2,2,2,2,1,2,2,2,1.50,85,40,?,?,2 -2,37,1,1,2,1,2,2,2,2,2,1,2,2,0.90,?,231,4.3,?,2 -2,50,1,2,2,2,2,2,2,1,1,1,2,2,1.00,85,75,4.0,72,2 -2,34,2,2,2,1,1,1,1,1,2,1,2,2,0.70,70,24,4.1,100,2 -2,28,1,2,2,1,1,1,?,?,2,1,1,2,1.00,?,20,4.0,?,2 -1,50,1,2,2,1,2,2,2,1,1,2,1,1,2.80,155,75,2.4,32,2 -2,54,1,1,2,1,1,2,2,2,2,2,1,2,1.20,85,92,3.1,66,2 -1,57,1,1,2,1,1,2,2,2,2,1,1,2,4.60,82,55,3.3,30,2 -2,54,1,2,2,2,2,2,2,2,2,2,2,2,1.00,85,30,4.5,0,2 -1,31,1,1,2,1,1,1,2,2,1,2,2,2,8.00,?,101,2.2,?,2 -2,48,1,2,2,1,1,1,2,1,2,1,2,2,2.00,158,278,3.8,?,2 -2,72,1,2,1,1,2,2,2,1,2,2,2,2,1.00,115,52,3.4,50,2 -1,38,1,1,2,2,2,2,2,1,2,2,2,2,0.40,243,49,3.8,90,2 -2,25,1,2,2,1,2,2,1,1,1,1,1,1,1.30,181,181,4.5,57,2 -2,51,1,2,2,2,2,2,1,1,2,1,2,2,0.80,?,33,4.5,?,2 -2,38,1,2,2,2,2,2,2,1,2,1,2,1,1.60,130,140,3.5,56,2 -1,47,1,2,2,1,1,2,2,1,2,1,1,1,1.00,166,30,2.6,31,2 -2,45,1,2,1,2,2,2,2,2,2,2,2,2,1.30,85,44,4.2,85,2 -2,36,1,1,2,1,1,1,1,1,2,1,2,1,1.70,295,60,2.7,?,2 -1,54,1,1,2,1,1,2,?,?,1,2,1,2,3.90,120,28,3.5,43,2 -2,51,1,2,2,1,2,2,2,1,1,1,2,1,1.00,?,20,3.0,63,2 -1,49,1,1,2,1,1,2,2,2,1,1,2,2,1.40,85,70,3.5,35,2 -1,45,1,2,2,1,1,1,2,2,2,1,1,2,1.90,?,114,2.4,?,2 -2,31,1,1,2,1,2,2,2,2,2,2,2,2,1.20,75,173,4.2,54,2 -1,41,1,2,2,1,2,2,2,1,1,1,2,1,4.20,65,120,3.4,?,2 -1,70,1,1,2,1,1,1,?,?,?,?,?,?,1.70,109,528,2.8,35,2 -2,20,1,1,2,2,2,2,2,?,2,2,2,2,0.90,89,152,4.0,?,2 -2,36,1,2,2,2,2,2,2,2,2,2,2,2,0.60,120,30,4.0,?,2 -1,46,1,2,2,1,1,1,2,2,2,1,1,1,7.60,?,242,3.3,50,2 -2,44,1,2,2,1,2,2,2,1,2,2,2,2,0.90,126,142,4.3,?,2 -2,61,1,1,2,1,1,2,1,1,2,1,2,2,0.80,75,20,4.1,?,2 -2,53,2,1,2,1,2,2,2,2,1,1,2,1,1.50,81,19,4.1,48,2 -1,43,1,2,2,1,2,2,2,2,1,1,1,2,1.20,100,19,3.1,42,2 diff --git a/public/models/00-tabular-classification/TODO/hepatitis/hepatitis.names b/public/models/00-tabular-classification/TODO/hepatitis/hepatitis.names deleted file mode 100644 index d846db1..0000000 --- a/public/models/00-tabular-classification/TODO/hepatitis/hepatitis.names +++ /dev/null @@ -1,91 +0,0 @@ -1. Title: Hepatitis Domain - -2. Sources: - (a) unknown - (b) Donor: G.Gong (Carnegie-Mellon University) via - Bojan Cestnik - Jozef Stefan Institute - Jamova 39 - 61000 Ljubljana - Yugoslavia (tel.: (38)(+61) 214-399 ext.287) } - (c) Date: November, 1988 - -3. Past Usage: - 1. Diaconis,P. & Efron,B. (1983). Computer-Intensive Methods in - Statistics. Scientific American, Volume 248. - -- Gail Gong reported a 80% classfication accuracy - 2. Cestnik,G., Konenenko,I, & Bratko,I. (1987). Assistant-86: A - Knowledge-Elicitation Tool for Sophisticated Users. In I.Bratko - & N.Lavrac (Eds.) Progress in Machine Learning, 31-45, Sigma Press. - -- Assistant-86: 83% accuracy - -4. Relevant Information: - Please ask Gail Gong for further information on this database. - -5. Number of Instances: 155 - -6. Number of Attributes: 20 (including the class attribute) - -7. Attribute information: - 1. Class: DIE, LIVE - 2. AGE: 10, 20, 30, 40, 50, 60, 70, 80 - 3. SEX: male, female - 4. STEROID: no, yes - 5. ANTIVIRALS: no, yes - 6. FATIGUE: no, yes - 7. MALAISE: no, yes - 8. ANOREXIA: no, yes - 9. LIVER BIG: no, yes - 10. LIVER FIRM: no, yes - 11. SPLEEN PALPABLE: no, yes - 12. SPIDERS: no, yes - 13. ASCITES: no, yes - 14. VARICES: no, yes - 15. BILIRUBIN: 0.39, 0.80, 1.20, 2.00, 3.00, 4.00 - -- see the note below - 16. ALK PHOSPHATE: 33, 80, 120, 160, 200, 250 - 17. SGOT: 13, 100, 200, 300, 400, 500, - 18. ALBUMIN: 2.1, 3.0, 3.8, 4.5, 5.0, 6.0 - 19. PROTIME: 10, 20, 30, 40, 50, 60, 70, 80, 90 - 20. HISTOLOGY: no, yes - - The BILIRUBIN attribute appears to be continuously-valued. I checked - this with the donater, Bojan Cestnik, who replied: - - About the hepatitis database and BILIRUBIN problem I would like to say - the following: BILIRUBIN is continuous attribute (= the number of it's - "values" in the ASDOHEPA.DAT file is negative!!!); "values" are quoted - because when speaking about the continuous attribute there is no such - thing as all possible values. However, they represent so called - "boundary" values; according to these "boundary" values the attribute - can be discretized. At the same time, because of the continious - attribute, one can perform some other test since the continuous - information is preserved. I hope that these lines have at least roughly - answered your question. - -8. Missing Attribute Values: (indicated by "?") - Attribute Number: Number of Missing Values: - 1: 0 - 2: 0 - 3: 0 - 4: 1 - 5: 0 - 6: 1 - 7: 1 - 8: 1 - 9: 10 - 10: 11 - 11: 5 - 12: 5 - 13: 5 - 14: 5 - 15: 6 - 16: 29 - 17: 4 - 18: 16 - 19: 67 - 20: 0 - -9. Class Distribution: - DIE: 32 - LIVE: 123 diff --git a/public/models/00-tabular-classification/TODO/lung-cancer/lung-cancer.data b/public/models/00-tabular-classification/TODO/lung-cancer/lung-cancer.data deleted file mode 100644 index b4251b3..0000000 --- a/public/models/00-tabular-classification/TODO/lung-cancer/lung-cancer.data +++ /dev/null @@ -1,33 +0,0 @@ -1,0,3,0,?,0,2,2,2,1,1,1,1,3,2,2,1,2,2,0,2,2,2,2,1,2,2,2,3,2,1,1,1,3,3,2,2,1,2,2,2,1,2,2,2,2,2,2,2,2,2,2,1,1,1,2,2 -1,0,3,3,1,0,3,1,3,1,1,1,1,1,3,3,1,2,2,0,0,2,2,2,1,2,1,3,2,3,1,1,1,3,3,2,2,2,1,2,2,2,1,2,2,1,2,2,2,2,2,2,2,2,1,2,2 -1,0,3,3,2,0,3,3,3,1,1,1,0,3,3,3,1,2,1,0,0,2,2,2,1,2,2,3,2,3,1,3,3,3,1,2,2,1,2,2,2,1,2,2,1,2,2,2,2,2,2,2,2,2,2,1,2 -1,0,2,3,2,1,3,3,3,1,2,1,0,3,3,1,1,2,2,0,0,2,2,2,2,1,3,2,3,3,1,3,3,3,1,1,1,1,2,2,2,2,1,2,2,2,1,2,2,2,2,2,2,2,2,2,2 -1,0,3,2,1,1,3,3,3,2,2,2,1,1,2,2,2,2,2,0,0,2,2,2,1,1,2,3,2,2,1,1,1,3,2,1,2,2,1,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,1,2,2 -1,0,3,3,2,0,3,3,3,1,2,2,0,3,3,3,2,2,1,0,0,1,2,2,2,1,3,3,1,2,2,3,3,3,2,1,2,2,1,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,1,2 -1,0,3,2,1,0,3,3,3,1,2,1,2,3,3,3,3,2,2,0,0,2,2,2,2,1,3,2,2,2,2,3,3,3,2,1,1,2,2,1,2,1,2,2,2,2,1,2,2,2,2,1,2,2,2,1,2 -1,0,2,2,1,0,3,1,3,3,3,3,2,1,3,3,1,2,2,0,0,1,1,2,1,2,1,3,2,1,1,3,3,3,2,2,1,2,1,2,2,1,2,2,2,1,2,2,2,1,2,2,2,2,1,2,2 -1,0,3,1,1,0,3,1,3,1,1,1,3,2,3,3,1,2,2,0,0,2,2,2,1,2,1,2,1,1,1,3,3,3,3,2,2,1,2,2,2,1,2,2,1,2,2,2,2,2,2,2,2,2,1,2,2 -2,0,2,3,2,0,2,2,2,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1,3,2,3,3,3,3,3,3,3,3,2,1,2,1,2,2,2,2,2,2,2,2,2,2,2,2,1,3,2,1,1,2,2 -2,0,2,2,0,0,3,2,3,1,1,3,1,3,1,1,2,2,2,0,2,1,1,2,1,1,2,2,2,2,1,3,3,3,1,2,2,1,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 -2,0,2,3,2,0,1,2,1,1,2,1,0,1,2,2,1,2,1,0,2,2,2,2,1,2,1,2,2,3,1,3,3,3,1,2,2,1,2,2,2,2,1,2,2,2,2,2,2,2,2,2,1,1,2,2,1 -2,0,2,1,1,0,1,2,2,1,2,1,1,2,2,2,1,2,2,0,2,2,2,2,1,2,1,3,2,2,1,1,1,1,1,2,2,1,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2 -2,0,2,2,1,1,2,3,3,1,1,1,1,2,2,2,1,2,2,0,1,2,2,2,1,2,1,2,2,2,1,1,1,3,2,1,1,2,1,2,2,2,1,2,2,1,2,2,2,2,2,2,1,1,1,2,2 -2,1,3,0,?,1,1,2,2,1,1,1,1,2,1,1,1,2,2,0,2,2,2,2,1,2,2,2,2,2,3,3,3,3,1,1,2,1,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,1,2,1 -2,0,3,2,2,1,2,2,2,1,1,2,1,2,3,3,2,2,2,0,1,2,2,2,1,2,3,2,2,1,2,2,2,3,1,3,2,1,2,2,2,1,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2 -2,0,3,2,2,0,1,1,3,1,1,1,0,1,3,3,1,2,2,0,2,2,2,2,1,1,2,2,2,2,1,3,3,3,3,3,1,2,2,1,2,1,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2 -2,0,2,1,1,0,2,1,3,1,1,1,0,3,1,3,1,2,2,0,0,1,2,2,3,3,3,2,2,2,1,3,3,3,1,1,1,2,1,2,2,2,1,2,1,2,2,2,2,2,2,2,1,1,1,2,2 -2,0,2,0,?,0,2,3,3,3,2,1,0,2,2,1,1,1,2,0,0,2,1,2,1,2,3,2,2,3,1,3,3,3,2,1,1,2,1,2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,1,2 -2,0,1,2,1,0,3,3,3,1,2,2,1,1,3,3,1,2,2,0,0,2,2,2,1,2,1,3,2,3,1,1,1,3,1,1,2,2,1,2,2,2,1,2,2,2,2,2,2,2,2,2,1,1,2,2,1 -2,0,2,0,?,1,3,3,3,1,2,1,1,3,3,3,1,2,2,0,0,2,2,2,2,1,1,2,3,2,1,1,1,3,1,3,1,1,2,2,2,1,2,2,1,2,2,2,2,2,2,1,2,2,1,2,2 -2,0,3,3,2,0,2,1,3,1,1,3,3,3,3,3,1,2,2,0,0,2,2,1,1,2,2,3,3,3,3,3,3,3,2,2,2,1,2,1,2,1,2,2,2,2,2,2,2,1,2,2,2,2,2,1,2 -3,0,2,3,1,1,2,2,1,1,1,1,1,1,2,2,1,2,2,2,2,1,2,1,1,1,1,2,2,3,1,3,3,3,1,1,1,3,1,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,2,2,1 -3,0,2,3,1,1,1,2,1,1,1,2,1,1,1,2,2,1,1,1,2,1,2,1,1,2,2,2,2,2,1,3,3,3,2,2,2,3,3,1,1,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,1 -3,0,3,3,1,0,3,3,1,1,1,2,1,1,2,2,2,2,2,2,2,1,1,1,1,1,2,2,2,2,3,3,3,3,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,2,2,2,2,1 -3,0,2,3,2,0,1,2,2,1,2,1,2,1,1,1,2,1,2,2,1,2,1,2,2,1,3,2,1,1,2,2,2,2,1,1,2,2,?,2,1,1,1,2,2,2,1,2,2,2,1,3,1,2,2,1,2 -3,0,2,2,2,0,2,1,2,1,1,1,0,2,2,3,1,2,2,2,2,2,2,2,3,3,3,2,2,1,2,2,2,2,3,1,2,2,2,2,1,2,1,1,2,2,1,2,2,2,2,2,2,2,1,2,1 -3,0,2,2,1,0,2,2,2,1,1,2,0,2,2,2,1,2,2,2,2,2,2,2,1,2,1,3,3,3,1,3,3,2,2,3,1,2,1,3,2,2,3,2,2,2,3,3,3,2,2,3,2,2,2,2,1 -3,0,3,2,2,0,2,2,2,1,1,2,0,2,2,2,1,2,2,2,2,2,2,1,1,2,2,2,2,2,2,1,1,1,2,1,1,3,1,3,3,3,2,3,2,2,2,2,2,2,3,1,2,2,2,2,2 -3,0,2,1,1,0,2,2,1,1,1,1,0,1,1,1,2,1,2,0,2,1,1,1,1,1,2,2,1,2,1,3,3,3,1,1,3,3,3,2,3,1,2,2,3,3,2,2,2,3,2,2,2,2,2,2,1 -3,0,2,3,2,1,2,2,3,1,1,2,1,2,2,2,1,2,2,0,2,2,2,1,1,2,2,2,2,2,1,2,2,3,2,2,2,1,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2 -3,0,2,3,1,0,2,3,3,1,1,1,1,2,2,2,1,2,2,0,2,2,2,2,1,2,1,2,2,2,1,1,1,1,1,2,2,1,2,2,2,1,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2 - diff --git a/public/models/00-tabular-classification/TODO/lung-cancer/lung-cancer.names b/public/models/00-tabular-classification/TODO/lung-cancer/lung-cancer.names deleted file mode 100644 index 8ba0652..0000000 --- a/public/models/00-tabular-classification/TODO/lung-cancer/lung-cancer.names +++ /dev/null @@ -1,61 +0,0 @@ - -1. Title: Lung Cancer Data - -2. Source Information: - - Data was published in : - Hong, Z.Q. and Yang, J.Y. "Optimal Discriminant Plane for a Small - Number of Samples and Design Method of Classifier on the Plane", - Pattern Recognition, Vol. 24, No. 4, pp. 317-324, 1991. - - Donor: Stefan Aeberhard, stefan@coral.cs.jcu.edu.au - - Date : May, 1992 - -3. Past Usage: - - Hong, Z.Q. and Yang, J.Y. "Optimal Discriminant Plane for a Small - Number of Samples and Design Method of Classifier on the Plane", - Pattern Recognition, Vol. 24, No. 4, pp. 317-324, 1991. - - Aeberhard, S., Coomans, D, De Vel, O. "Comparisons of - Classification Methods in High Dimensional Settings", - submitted to Technometrics. - - Aeberhard, S., Coomans, D, De Vel, O. "The Dangers of - Bias in High Dimensional Settings", submitted to - pattern Recognition. - -4. Relevant Information: - - This data was used by Hong and Young to illustrate the - power of the optimal discriminant plane even in ill-posed - settings. Applying the KNN method in the resulting plane - gave 77% accuracy. However, these results are strongly - biased (See Aeberhard's second ref. above, or email to - stefan@coral.cs.jcu.edu.au). Results obtained by - Aeberhard et al. are : - RDA : 62.5%, KNN 53.1%, Opt. Disc. Plane 59.4% - - The data described 3 types of pathological lung cancers. - The Authors give no information on the individual - variables nor on where the data was originally used. - - - In the original data 4 values for the fifth attribute were -1. - These values have been changed to ? (unknown). (*) - - In the original data 1 value for the 39 attribute was 4. This - value has been changed to ? (unknown). (*) - - -5. Number of Instances: 32 - -6. Number of Attributes: 57 (1 class attribute, 56 predictive) - -7. Attribute Information: - - attribute 1 is the class label. - - - All predictive attributes are nominal, taking on integer - values 0-3 - -8. Missing Attribute Values: Attributes 5 and 39 (*) - -9. Class Distribution: - - 3 classes, - 1.) 9 observations - 2.) 13 " - 3.) 10 " - diff --git a/public/models/00-tabular-classification/car/my-model-car.json b/public/models/00-tabular-classification/car/my-model-car.json deleted file mode 100644 index 509102b..0000000 --- a/public/models/00-tabular-classification/car/my-model-car.json +++ /dev/null @@ -1,80 +0,0 @@ -{ - "modelTopology": { - "class_name": "Sequential", - "config": { - "name": "sequential_1", - "layers": [ - { - "class_name": "Dense", - "config": { - "units": 10, - "activation": "sigmoid", - "use_bias": true, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1, - "mode": "fan_avg", - "distribution": "normal", - "seed": null - } - }, - "bias_initializer": { "class_name": "Zeros", "config": {} }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null, - "name": "dense_Dense1", - "trainable": true, - "batch_input_shape": [null, 6], - "dtype": "float32" - } - }, - { - "class_name": "Dense", - "config": { - "units": 3, - "activation": "softmax", - "use_bias": true, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1, - "mode": "fan_avg", - "distribution": "normal", - "seed": null - } - }, - "bias_initializer": { "class_name": "Zeros", "config": {} }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null, - "name": "dense_Dense2", - "trainable": true, - "batch_input_shape": [null, 6], - "dtype": "float32" - } - } - ] - }, - "keras_version": "tfjs-layers 3.14.0", - "backend": "tensor_flow.js" - }, - "format": "layers-model", - "generatedBy": "TensorFlow.js tfjs-layers v3.14.0", - "convertedBy": null, - "weightsManifest": [ - { - "paths": ["/my-model-car.weights.bin"], - "weights": [ - { "name": "dense_Dense1/kernel", "shape": [6, 10], "dtype": "float32" }, - { "name": "dense_Dense1/bias", "shape": [10], "dtype": "float32" }, - { "name": "dense_Dense2/kernel", "shape": [10, 3], "dtype": "float32" }, - { "name": "dense_Dense2/bias", "shape": [3], "dtype": "float32" } - ] - } - ] -} diff --git a/public/models/00-tabular-classification/iris/my-model-iris.json b/public/models/00-tabular-classification/iris/my-model-iris.json deleted file mode 100644 index fb98c71..0000000 --- a/public/models/00-tabular-classification/iris/my-model-iris.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "modelTopology": { - "class_name": "Sequential", - "config": { - "name": "sequential_1", - "layers": [ - { - "class_name": "Dense", - "config": { - "units": 10, - "activation": "sigmoid", - "use_bias": true, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1, - "mode": "fan_avg", - "distribution": "normal", - "seed": null - } - }, - "bias_initializer": { "class_name": "Zeros", "config": {} }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null, - "name": "dense_Dense1", - "trainable": true, - "batch_input_shape": [null, 4], - "dtype": "float32" - } - }, - { - "class_name": "Dense", - "config": { - "units": 3, - "activation": "softmax", - "use_bias": true, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1, - "mode": "fan_avg", - "distribution": "normal", - "seed": null - } - }, - "bias_initializer": { "class_name": "Zeros", "config": {} }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null, - "name": "dense_Dense2", - "trainable": true - } - } - ] - }, - "keras_version": "tfjs-layers 3.14.0", - "backend": "tensor_flow.js" - }, - "format": "layers-model", - "generatedBy": "TensorFlow.js tfjs-layers v3.14.0", - "convertedBy": null, - "weightsManifest": [ - { - "paths": ["./my-model-iris.weights.bin"], - "weights": [ - { "name": "dense_Dense1/kernel", "shape": [4, 10], "dtype": "float32" }, - { "name": "dense_Dense1/bias", "shape": [10], "dtype": "float32" }, - { "name": "dense_Dense2/kernel", "shape": [10, 3], "dtype": "float32" }, - { "name": "dense_Dense2/bias", "shape": [3], "dtype": "float32" } - ] - } - ] -} diff --git a/public/models/00-tabular-classification/lymphography/cl-model-0.json b/public/models/00-tabular-classification/lymphography/cl-model-0.json deleted file mode 100644 index a5345e2..0000000 --- a/public/models/00-tabular-classification/lymphography/cl-model-0.json +++ /dev/null @@ -1 +0,0 @@ -{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_1","layers":[{"class_name":"Dense","config":{"units":18,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense1","trainable":true,"batch_input_shape":[null,18],"dtype":"float32"}},{"class_name":"Dense","config":{"units":20,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense2","trainable":true}},{"class_name":"Dense","config":{"units":20,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense3","trainable":true}},{"class_name":"Dense","config":{"units":4,"activation":"softmax","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense4","trainable":true}}]},"keras_version":"tfjs-layers 3.21.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v3.21.0","convertedBy":null,"weightsManifest":[{"paths":["./cl-model-0.weights.bin"],"weights":[{"name":"dense_Dense1/kernel","shape":[18,18],"dtype":"float32"},{"name":"dense_Dense1/bias","shape":[18],"dtype":"float32"},{"name":"dense_Dense2/kernel","shape":[18,20],"dtype":"float32"},{"name":"dense_Dense2/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense3/kernel","shape":[20,20],"dtype":"float32"},{"name":"dense_Dense3/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense4/kernel","shape":[20,4],"dtype":"float32"},{"name":"dense_Dense4/bias","shape":[4],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/00-tabular-classification/lymphography/cl-model-0.weights.bin b/public/models/00-tabular-classification/lymphography/cl-model-0.weights.bin deleted file mode 100644 index f80ed14..0000000 Binary files a/public/models/00-tabular-classification/lymphography/cl-model-0.weights.bin and /dev/null differ diff --git a/public/models/00-tabular-classification/lymphography/lymphography.data b/public/models/00-tabular-classification/lymphography/lymphography.data deleted file mode 100644 index 04257a5..0000000 --- a/public/models/00-tabular-classification/lymphography/lymphography.data +++ /dev/null @@ -1,148 +0,0 @@ -3,4,2,1,1,1,1,1,2,1,2,2,2,4,8,1,1,2,2 -2,3,2,1,1,2,2,1,2,1,3,3,2,3,4,2,2,2,2 -3,3,2,2,2,2,2,2,2,1,4,3,3,4,8,3,2,2,7 -3,3,1,1,1,1,2,1,2,1,3,3,4,4,4,3,1,2,6 -2,3,1,1,1,1,1,1,1,1,2,2,4,3,5,1,2,2,1 -2,2,1,1,1,1,1,1,2,1,3,3,3,3,6,3,1,2,4 -2,2,2,1,1,1,1,1,2,1,2,3,2,3,8,2,1,1,1 -2,3,2,1,1,1,2,1,2,1,2,2,2,2,1,3,1,1,1 -3,2,2,1,1,1,1,1,2,1,3,2,2,2,8,3,1,2,5 -3,2,1,1,1,1,1,1,2,1,2,2,3,3,5,3,1,1,2 -2,2,2,2,1,2,2,1,2,1,3,2,4,3,5,1,2,2,3 -2,4,2,1,1,1,2,1,1,1,3,3,4,3,8,3,2,2,2 -2,4,2,1,1,1,1,1,2,1,2,2,2,2,3,2,1,1,1 -3,4,1,1,1,1,2,1,2,1,4,2,2,4,7,3,2,2,2 -4,3,2,2,2,2,2,2,2,3,1,1,2,2,8,1,2,2,4 -2,2,2,1,1,1,2,1,2,1,2,3,3,3,5,3,2,2,2 -2,3,2,1,1,1,2,1,2,1,2,3,3,3,2,2,2,2,3 -2,2,2,1,1,1,2,1,1,1,2,2,2,3,5,2,1,2,2 -2,3,1,1,1,1,1,1,2,1,2,2,2,3,2,1,2,2,1 -2,2,2,1,1,1,1,1,2,1,3,3,3,3,2,2,2,1,1 -3,3,1,1,1,1,1,1,2,1,2,2,4,2,4,3,2,2,3 -3,4,1,1,1,2,2,1,2,1,3,3,3,4,5,3,2,2,4 -2,4,2,1,1,2,2,1,2,1,4,3,4,3,4,2,2,2,2 -2,3,2,1,1,1,1,1,2,1,2,2,2,2,5,1,1,1,1 -3,3,1,1,1,1,1,1,2,2,1,2,2,2,8,3,1,2,8 -3,3,1,1,1,1,2,1,1,1,3,2,3,3,8,3,2,2,2 -3,4,1,1,1,1,2,1,2,1,3,3,4,2,4,3,2,2,4 -3,4,1,1,1,1,1,1,2,1,3,2,4,4,8,3,2,2,1 -2,4,2,1,1,1,1,1,2,1,2,2,2,3,3,2,2,2,1 -3,3,1,1,1,1,1,1,1,1,2,2,4,2,8,2,2,2,1 -3,4,2,1,1,1,2,1,2,1,4,3,3,3,7,3,2,2,3 -3,2,1,1,1,1,1,1,2,1,3,2,3,3,8,3,2,2,3 -2,2,1,1,1,1,1,1,1,1,2,3,2,2,8,1,2,1,1 -2,2,2,1,1,1,1,1,1,1,1,2,2,3,3,1,1,1,1 -2,4,2,1,1,2,2,1,2,1,3,3,4,3,4,3,2,2,2 -2,2,2,2,1,2,2,1,2,1,3,3,3,3,8,3,1,2,2 -4,3,1,1,1,2,2,2,1,3,1,1,4,2,5,3,1,2,4 -3,3,1,1,1,1,2,1,2,1,4,3,4,2,4,3,2,2,6 -3,2,1,1,1,1,1,1,2,1,3,3,2,3,4,3,2,2,2 -3,2,1,1,1,1,1,1,2,1,2,2,2,1,7,1,2,2,2 -3,2,1,1,1,1,2,1,2,1,2,2,3,3,3,3,1,2,1 -3,2,2,2,1,2,2,2,2,1,4,2,2,2,4,3,2,2,6 -2,3,2,2,1,1,2,1,1,1,3,2,3,3,4,3,1,2,2 -2,4,2,1,1,2,1,1,2,1,3,3,3,3,2,2,2,2,3 -4,3,2,2,2,2,2,2,1,2,2,2,4,2,4,3,2,2,7 -3,2,1,1,1,1,1,1,2,1,2,2,2,2,8,2,2,2,1 -2,3,2,2,1,2,1,1,2,1,2,2,3,3,8,3,1,2,1 -2,4,1,1,1,1,1,1,1,2,1,3,4,2,8,1,2,2,1 -2,3,2,2,1,1,2,1,1,1,2,3,3,3,5,2,1,2,2 -2,2,2,2,1,1,1,1,2,1,2,2,4,3,8,2,2,2,2 -2,2,1,1,1,1,1,1,1,1,1,1,2,2,3,1,2,2,1 -3,3,2,1,1,1,2,1,2,1,2,2,2,4,8,3,1,2,3 -2,3,1,1,1,1,1,2,1,1,2,2,4,3,5,2,1,2,1 -2,2,2,1,1,2,2,1,1,1,3,3,4,3,4,3,1,1,1 -2,2,2,2,1,2,2,1,1,1,2,2,3,3,4,2,1,2,1 -3,4,1,1,1,1,1,1,2,1,2,2,3,3,3,3,2,1,1 -3,2,1,1,1,1,1,1,2,1,3,2,4,2,8,3,2,2,4 -2,4,2,1,1,2,2,1,2,1,2,3,2,3,2,3,2,2,4 -3,4,2,2,2,2,2,2,2,1,4,3,4,4,7,3,2,2,8 -2,2,2,2,1,2,2,1,2,1,3,3,3,3,8,3,2,2,2 -3,4,1,1,1,1,1,1,2,1,4,2,2,4,7,3,2,2,7 -2,3,2,2,1,2,2,1,2,1,3,2,2,3,4,1,2,2,1 -3,3,1,1,1,1,2,1,2,1,4,2,4,4,2,3,2,2,3 -2,4,2,1,1,1,2,1,1,1,2,3,2,3,2,2,1,1,1 -2,2,2,1,1,1,1,1,1,1,2,2,3,3,5,2,2,2,1 -3,4,1,1,1,2,1,2,2,1,3,2,3,4,5,3,2,2,7 -3,2,1,1,1,1,1,1,2,1,4,3,4,4,5,3,2,2,5 -2,3,2,2,1,2,2,1,1,1,3,3,4,3,4,2,2,2,3 -3,2,1,1,1,1,1,1,1,1,2,3,2,3,3,2,2,1,1 -3,2,1,1,1,1,1,1,2,1,3,2,2,2,6,3,2,2,6 -2,3,2,1,1,1,2,1,2,1,3,3,3,3,4,3,2,2,1 -3,3,1,1,1,1,1,1,1,1,2,2,2,2,5,1,1,2,2 -2,4,2,1,1,2,2,1,1,1,1,3,3,3,3,3,2,2,3 -3,3,1,1,1,1,1,1,2,1,4,3,3,4,5,3,2,2,3 -3,2,1,1,1,1,2,1,1,1,2,2,2,2,3,1,1,1,1 -2,4,2,2,1,2,2,1,2,1,3,3,4,3,8,2,2,2,3 -2,4,2,2,1,1,1,1,2,1,2,2,2,3,3,2,2,2,2 -2,3,1,1,1,2,1,1,2,1,2,3,3,3,5,3,1,1,1 -1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 -3,3,2,1,1,1,1,1,2,1,3,2,2,4,8,3,2,2,3 -3,2,2,1,1,1,2,1,2,1,3,3,3,4,8,3,2,2,2 -2,4,2,1,1,1,1,1,1,1,4,3,3,3,4,2,2,1,1 -3,2,1,1,1,1,1,1,2,1,3,2,2,2,8,3,2,2,5 -3,2,2,2,1,2,2,2,2,1,3,3,4,4,5,3,2,2,5 -3,4,1,1,1,1,2,1,2,1,4,3,4,2,5,3,2,2,2 -2,2,2,1,1,2,2,1,1,1,2,2,4,2,8,3,2,2,1 -2,2,2,1,1,1,1,1,2,1,2,3,3,3,5,2,1,2,1 -2,2,2,1,1,1,1,1,2,1,2,2,2,3,8,3,1,2,1 -3,2,2,1,1,1,2,1,2,1,3,3,4,2,8,3,2,2,2 -2,3,1,1,1,1,1,1,2,1,3,2,2,2,8,1,1,1,1 -3,4,2,2,1,2,2,1,2,1,1,2,2,1,3,1,2,2,2 -2,2,2,2,1,1,2,1,1,1,2,3,2,3,3,2,1,1,1 -2,3,2,2,1,2,2,1,2,1,2,3,3,4,2,2,2,1,1 -2,2,1,1,1,1,1,1,1,1,1,2,2,3,3,1,2,2,1 -3,2,1,1,1,1,1,1,2,1,3,2,4,4,4,3,2,2,5 -3,2,1,1,1,1,1,1,2,1,2,2,4,2,8,3,2,2,3 -2,3,2,1,1,1,1,1,1,1,2,2,3,3,3,3,1,1,2 -2,2,2,1,1,1,2,1,2,1,2,3,2,2,4,2,1,1,2 -2,3,2,1,1,1,1,1,1,1,2,2,3,3,5,1,1,1,1 -2,3,2,1,1,1,2,1,1,1,2,2,4,3,4,1,2,2,2 -3,2,1,1,1,1,2,1,2,1,3,3,4,2,8,3,2,2,3 -2,2,2,1,1,1,1,1,2,1,2,2,3,3,2,3,2,2,2 -2,2,1,1,1,1,1,1,2,1,2,2,2,2,4,1,2,1,2 -2,3,2,1,1,2,2,1,1,1,2,2,4,3,2,1,2,2,3 -2,4,1,1,1,1,1,1,2,1,3,3,2,2,4,2,2,2,2 -3,2,2,1,1,1,1,1,2,1,4,3,4,2,7,3,2,2,5 -2,3,2,1,1,1,1,1,2,1,2,3,3,3,8,2,2,2,1 -3,2,2,1,1,1,2,1,2,1,4,3,4,4,8,3,2,2,7 -2,3,2,1,1,1,2,1,1,1,2,3,4,2,4,1,1,1,1 -2,2,2,1,1,1,1,1,2,1,2,3,3,3,5,3,1,2,1 -2,2,1,1,1,1,1,1,1,1,2,3,3,3,8,3,1,1,1 -3,4,1,1,1,1,2,1,2,1,4,3,4,3,3,3,2,2,5 -2,2,1,1,1,1,1,1,1,1,2,2,2,2,8,1,1,1,1 -3,2,1,1,1,1,2,1,2,1,2,2,2,2,8,2,1,2,2 -3,3,1,1,1,1,1,1,2,1,2,2,4,4,2,3,2,1,1 -3,3,1,1,1,1,2,1,2,1,2,2,4,3,8,2,2,2,1 -3,4,1,1,1,1,1,1,2,1,3,2,2,4,3,2,2,1,1 -2,4,2,2,1,1,2,1,2,1,2,2,3,3,8,3,2,2,2 -3,2,1,1,1,1,2,1,2,1,3,2,2,2,4,3,1,2,5 -3,4,2,1,1,2,2,1,2,1,3,3,4,2,5,3,2,2,3 -2,2,1,1,1,1,1,1,1,1,1,2,4,3,8,2,2,2,2 -2,2,1,1,1,1,1,1,1,1,2,2,2,3,8,2,1,2,1 -2,2,2,2,2,2,2,1,1,1,2,2,4,3,8,2,2,2,3 -2,3,1,1,1,1,1,1,1,1,2,3,3,3,4,3,1,2,2 -2,4,2,1,1,1,2,1,1,1,2,2,3,3,5,2,1,2,1 -3,3,1,1,1,1,2,1,2,1,4,2,2,2,4,3,2,2,7 -2,2,2,1,1,1,1,1,2,1,3,3,3,3,3,2,1,2,1 -2,2,2,1,1,1,2,1,2,1,2,2,3,3,4,2,1,2,1 -3,2,1,1,1,1,2,1,2,1,2,2,2,4,8,1,2,2,2 -2,3,2,1,1,1,2,1,2,1,3,2,4,3,4,2,2,2,2 -2,2,2,1,1,1,1,1,2,1,4,3,4,2,8,2,1,2,4 -3,4,2,2,2,2,2,1,2,1,4,3,4,4,7,3,2,2,6 -3,4,1,1,1,1,1,1,2,1,4,2,4,2,8,3,2,2,6 -2,3,2,1,1,1,1,1,2,1,2,3,3,3,5,2,2,1,1 -2,2,2,1,1,1,2,1,2,1,2,2,4,4,5,3,2,2,1 -2,3,2,2,2,2,2,1,2,1,2,3,3,3,4,3,2,2,7 -1,1,1,1,1,1,2,1,2,1,2,2,1,1,2,1,1,1,2 -3,2,1,1,1,1,2,1,2,1,3,3,2,2,4,3,2,2,6 -2,2,2,1,1,1,1,1,1,1,2,3,3,3,3,3,1,2,1 -4,3,1,1,1,2,2,2,1,3,1,1,2,1,5,3,1,1,7 -2,2,2,1,1,1,1,1,1,1,2,3,3,3,2,2,2,2,1 -3,2,1,1,1,1,1,1,2,1,2,2,4,4,8,2,1,2,2 -2,2,2,1,1,1,2,1,2,1,2,3,3,3,5,3,2,2,1 -3,3,2,1,1,2,2,1,2,1,2,2,4,3,5,2,2,2,4 -2,2,1,1,1,1,1,1,1,1,1,1,1,1,3,1,2,2,1 -3,2,2,1,1,1,2,1,2,1,3,3,3,3,8,3,2,2,4 -2,2,1,1,1,1,1,1,2,1,2,2,4,2,2,1,2,2,1 -2,2,2,2,1,2,2,1,2,1,3,3,4,3,4,3,2,2,6 diff --git a/public/models/00-tabular-classification/lymphography/my-model-lymphography.json b/public/models/00-tabular-classification/lymphography/my-model-lymphography.json deleted file mode 100644 index ba778d9..0000000 --- a/public/models/00-tabular-classification/lymphography/my-model-lymphography.json +++ /dev/null @@ -1,158 +0,0 @@ -{ - "modelTopology": { - "class_name": "Sequential", - "config": { - "name": "sequential_1", - "layers": [ - { - "class_name": "Dense", - "config": { - "units": 18, - "activation": "sigmoid", - "use_bias": true, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1, - "mode": "fan_avg", - "distribution": "normal", - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null, - "name": "dense_Dense1", - "trainable": true, - "batch_input_shape": [ - null, - 18 - ], - "dtype": "float32" - } - }, - { - "class_name": "Dense", - "config": { - "units": 10, - "activation": "relu", - "use_bias": true, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1, - "mode": "fan_avg", - "distribution": "normal", - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null, - "name": "dense_Dense2", - "trainable": true - } - }, - { - "class_name": "Dense", - "config": { - "units": 4, - "activation": "softmax", - "use_bias": true, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1, - "mode": "fan_avg", - "distribution": "normal", - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null, - "name": "dense_Dense3", - "trainable": true - } - } - ] - }, - "keras_version": "tfjs-layers 3.21.0", - "backend": "tensor_flow.js" - }, - "format": "layers-model", - "generatedBy": "TensorFlow.js tfjs-layers v3.21.0", - "convertedBy": null, - "weightsManifest": [ - { - "paths": [ - "./my-model-lymphography.weights.bin" - ], - "weights": [ - { - "name": "dense_Dense1/kernel", - "shape": [ - 18, - 18 - ], - "dtype": "float32" - }, - { - "name": "dense_Dense1/bias", - "shape": [ - 18 - ], - "dtype": "float32" - }, - { - "name": "dense_Dense2/kernel", - "shape": [ - 18, - 10 - ], - "dtype": "float32" - }, - { - "name": "dense_Dense2/bias", - "shape": [ - 10 - ], - "dtype": "float32" - }, - { - "name": "dense_Dense3/kernel", - "shape": [ - 10, - 4 - ], - "dtype": "float32" - }, - { - "name": "dense_Dense3/bias", - "shape": [ - 4 - ], - "dtype": "float32" - } - ] - } - ] -} \ No newline at end of file diff --git a/public/models/00-tabular-classification/titanic/titanic.csv b/public/models/00-tabular-classification/titanic/titanic.csv deleted file mode 100644 index 686c317..0000000 --- a/public/models/00-tabular-classification/titanic/titanic.csv +++ /dev/null @@ -1,888 +0,0 @@ -Pclass,TName,Name,Sex,Age,Siblings/Spouses Aboard,Parents/Children Aboard,Fare,Survived -3,Mr,Owen Harris Braund,male,22,1,0,7.25,0 -1,Mrs,John Bradley (Florence Briggs Thayer) Cumings,female,38,1,0,71.2833,1 -3,Miss,Laina Heikkinen,female,26,0,0,7.925,1 -1,Mrs,Jacques Heath (Lily May Peel) Futrelle,female,35,1,0,53.1,1 -3,Mr,William Henry Allen,male,35,0,0,8.05,0 -3,Mr,James Moran,male,27,0,0,8.4583,0 -1,Mr,Timothy J McCarthy,male,54,0,0,51.8625,0 -3,Master,Gosta Leonard Palsson,male,2,3,1,21.075,0 -3,Mrs,Oscar W (Elisabeth Vilhelmina Berg) Johnson,female,27,0,2,11.1333,1 -2,Mrs,Nicholas (Adele Achem) Nasser,female,14,1,0,30.0708,1 -3,Miss,Marguerite Rut Sandstrom,female,4,1,1,16.7,1 -1,Miss,Elizabeth Bonnell,female,58,0,0,26.55,1 -3,Mr,William Henry Saundercock,male,20,0,0,8.05,0 -3,Mr,Anders Johan Andersson,male,39,1,5,31.275,0 -3,Miss,Hulda Amanda Adolfina Vestrom,female,14,0,0,7.8542,0 -2,Mrs,(Mary D Kingcome) Hewlett,female,55,0,0,16,1 -3,Master,Eugene Rice,male,2,4,1,29.125,0 -2,Mr,Charles Eugene Williams,male,23,0,0,13,1 -3,Mrs,Julius (Emelia Maria Vandemoortele) Vander Planke,female,31,1,0,18,0 -3,Mrs,Fatima Masselmani,female,22,0,0,7.225,1 -2,Mr,Joseph J Fynney,male,35,0,0,26,0 -2,Mr,Lawrence Beesley,male,34,0,0,13,1 -3,Miss,Anna McGowan,female,15,0,0,8.0292,1 -1,Mr,William Thompson Sloper,male,28,0,0,35.5,1 -3,Miss,Torborg Danira Palsson,female,8,3,1,21.075,0 -3,Mrs,Carl Oscar (Selma Augusta Emilia Johansson) Asplund,female,38,1,5,31.3875,1 -3,Mr,Farred Chehab Emir,male,26,0,0,7.225,0 -1,Mr,Charles Alexander Fortune,male,19,3,2,263,0 -3,Miss,Ellen O'Dwyer,female,24,0,0,7.8792,1 -3,Mr,Lalio Todoroff,male,23,0,0,7.8958,0 -1,Don,Manuel E Uruchurtu,male,40,0,0,27.7208,0 -1,Mrs,William Augustus (Marie Eugenie) Spencer,female,48,1,0,146.5208,1 -3,Miss,Mary Agatha Glynn,female,18,0,0,7.75,1 -2,Mr,Edward H Wheadon,male,66,0,0,10.5,0 -1,Mr,Edgar Joseph Meyer,male,28,1,0,82.1708,0 -1,Mr,Alexander Oskar Holverson,male,42,1,0,52,0 -3,Mr,Hanna Mamee,male,18,0,0,7.2292,1 -3,Mr,Ernest Charles Cann,male,21,0,0,8.05,0 -3,Miss,Augusta Maria Vander Planke,female,18,2,0,18,0 -3,Miss,Jamila Nicola-Yarred,female,14,1,0,11.2417,1 -3,Mrs,Johan (Johanna Persdotter Larsson) Ahlin,female,40,1,0,9.475,0 -2,Mrs,William John Robert (Dorothy Ann Wonnacott) Turpin,female,27,1,0,21,0 -2,Miss,Simonne Marie Anne Andree Laroche,female,3,1,2,41.5792,1 -3,Miss,Margaret Delia Devaney,female,19,0,0,7.8792,1 -3,Mr,William John Rogers,male,30,0,0,8.05,0 -3,Mr,Denis Lennon,male,20,1,0,15.5,0 -3,Miss,Bridget O'Driscoll,female,27,0,0,7.75,1 -3,Mr,Youssef Samaan,male,16,2,0,21.6792,0 -3,Mrs,Josef (Josefine Franchi) Arnold-Franchi,female,18,1,0,17.8,0 -3,Master,Juha Niilo Panula,male,7,4,1,39.6875,0 -3,Mr,Richard Cater Nosworthy,male,21,0,0,7.8,0 -1,Mrs,Henry Sleeper (Myna Haxtun) Harper,female,49,1,0,76.7292,1 -2,Mrs,Lizzie (Elizabeth Anne Wilkinson) Faunthorpe,female,29,1,0,26,1 -1,Mr,Engelhart Cornelius Ostby,male,65,0,1,61.9792,0 -1,Mr,Hugh Woolner,male,46,0,0,35.5,1 -2,Miss,Emily Rugg,female,21,0,0,10.5,1 -3,Mr,Mansouer Novel,male,28.5,0,0,7.2292,0 -2,Miss,Constance Mirium West,female,5,1,2,27.75,1 -3,Master,William Frederick Goodwin,male,11,5,2,46.9,0 -3,Mr,Orsen Sirayanian,male,22,0,0,7.2292,0 -1,Miss,Amelie Icard,female,38,0,0,80,1 -1,Mr,Henry Birkhardt Harris,male,45,1,0,83.475,0 -3,Master,Harald Skoog,male,4,3,2,27.9,0 -1,Mr,Albert A Stewart,male,64,0,0,27.7208,0 -3,Master,Gerios Moubarek,male,7,1,1,15.2458,1 -2,Mrs,(Elizabeth Ramell) Nye,female,29,0,0,10.5,1 -3,Mr,Ernest James Crease,male,19,0,0,8.1583,0 -3,Miss,Erna Alexandra Andersson,female,17,4,2,7.925,1 -3,Mr,Vincenz Kink,male,26,2,0,8.6625,0 -2,Mr,Stephen Curnow Jenkin,male,32,0,0,10.5,0 -3,Miss,Lillian Amy Goodwin,female,16,5,2,46.9,0 -2,Mr,Ambrose Jr Hood,male,21,0,0,73.5,0 -3,Mr,Apostolos Chronopoulos,male,26,1,0,14.4542,0 -3,Mr,Lee Bing,male,32,0,0,56.4958,1 -3,Mr,Sigurd Hansen Moen,male,25,0,0,7.65,0 -3,Mr,Ivan Staneff,male,23,0,0,7.8958,0 -3,Mr,Rahamin Haim Moutal,male,28,0,0,8.05,0 -2,Master,Alden Gates Caldwell,male,0.83,0,2,29,1 -3,Miss,Elizabeth Dowdell,female,30,0,0,12.475,1 -3,Mr,Achille Waelens,male,22,0,0,9,0 -3,Mr,Jan Baptist Sheerlinck,male,29,0,0,9.5,1 -3,Miss,Brigdet Delia McDermott,female,31,0,0,7.7875,1 -1,Mr,Francisco M Carrau,male,28,0,0,47.1,0 -2,Miss,Bertha Ilett,female,17,0,0,10.5,1 -3,Mrs,Karl Alfred (Maria Mathilda Gustafsson) Backstrom,female,33,3,0,15.85,1 -3,Mr,William Neal Ford,male,16,1,3,34.375,0 -3,Mr,Selman Francis Slocovski,male,20,0,0,8.05,0 -1,Miss,Mabel Helen Fortune,female,23,3,2,263,1 -3,Mr,Francesco Celotti,male,24,0,0,8.05,0 -3,Mr,Emil Christmann,male,29,0,0,8.05,0 -3,Mr,Paul Edvin Andreasson,male,20,0,0,7.8542,0 -1,Mr,Herbert Fuller Chaffee,male,46,1,0,61.175,0 -3,Mr,Bertram Frank Dean,male,26,1,2,20.575,0 -3,Mr,Daniel Coxon,male,59,0,0,7.25,0 -3,Mr,Charles Joseph Shorney,male,22,0,0,8.05,0 -1,Mr,George B Goldschmidt,male,71,0,0,34.6542,0 -1,Mr,William Bertram Greenfield,male,23,0,1,63.3583,1 -2,Mrs,John T (Ada Julia Bone) Doling,female,34,0,1,23,1 -2,Mr,Sinai Kantor,male,34,1,0,26,0 -3,Miss,Matilda Petranec,female,28,0,0,7.8958,0 -3,Mr,Pastcho Petroff,male,29,0,0,7.8958,0 -1,Mr,Richard Frasar White,male,21,0,1,77.2875,0 -3,Mr,Gustaf Joel Johansson,male,33,0,0,8.6542,0 -3,Mr,Anders Vilhelm Gustafsson,male,37,2,0,7.925,0 -3,Mr,Stoytcho Mionoff,male,28,0,0,7.8958,0 -3,Miss,Anna Kristine Salkjelsvik,female,21,0,0,7.65,1 -3,Mr,Albert Johan Moss,male,29,0,0,7.775,1 -3,Mr,Tido Rekic,male,38,0,0,7.8958,0 -3,Miss,Bertha Moran,female,28,1,0,24.15,1 -1,Mr,Walter Chamberlain Porter,male,47,0,0,52,0 -3,Miss,Hileni Zabour,female,14.5,1,0,14.4542,0 -3,Mr,David John Barton,male,22,0,0,8.05,0 -3,Miss,Katriina Jussila,female,20,1,0,9.825,0 -3,Miss,Malake Attalah,female,17,0,0,14.4583,0 -3,Mr,Edvard Pekoniemi,male,21,0,0,7.925,0 -3,Mr,Patrick Connors,male,70.5,0,0,7.75,0 -2,Mr,William John Robert Turpin,male,29,1,0,21,0 -1,Mr,Quigg Edmond Baxter,male,24,0,1,247.5208,0 -3,Miss,Ellis Anna Maria Andersson,female,2,4,2,31.275,0 -2,Mr,Stanley George Hickman,male,21,2,0,73.5,0 -3,Mr,Leonard Charles Moore,male,19,0,0,8.05,0 -2,Mr,Nicholas Nasser,male,32.5,1,0,30.0708,0 -2,Miss,Susan Webber,female,32.5,0,0,13,1 -1,Mr,Percival Wayland White,male,54,0,1,77.2875,0 -3,Master,Elias Nicola-Yarred,male,12,1,0,11.2417,1 -3,Mr,Martin McMahon,male,19,0,0,7.75,0 -3,Mr,Fridtjof Arne Madsen,male,24,0,0,7.1417,1 -3,Miss,Anna Peter,female,2,1,1,22.3583,1 -3,Mr,Johan Ekstrom,male,45,0,0,6.975,0 -3,Mr,Jozef Drazenoic,male,33,0,0,7.8958,0 -3,Mr,Domingos Fernandeo Coelho,male,20,0,0,7.05,0 -3,Mrs,Alexander A (Grace Charity Laury) Robins,female,47,1,0,14.5,0 -2,Mrs,Leopold (Mathilde Francoise Pede) Weisz,female,29,1,0,26,1 -2,Mr,Samuel James Hayden Sobey,male,25,0,0,13,0 -2,Mr,Emile Richard,male,23,0,0,15.0458,0 -1,Miss,Helen Monypeny Newsom,female,19,0,2,26.2833,1 -1,Mr,Jacques Heath Futrelle,male,37,1,0,53.1,0 -3,Mr,Olaf Elon Osen,male,16,0,0,9.2167,0 -1,Mr,Victor Giglio,male,24,0,0,79.2,0 -3,Mrs,Joseph (Sultana) Boulos,female,40,0,2,15.2458,0 -3,Miss,Anna Sofia Nysten,female,22,0,0,7.75,1 -3,Mrs,Pekka Pietari (Elin Matilda Dolck) Hakkarainen,female,24,1,0,15.85,1 -3,Mr,Jeremiah Burke,male,19,0,0,6.75,0 -2,Mr,Edgardo Samuel Andrew,male,18,0,0,11.5,0 -2,Mr,Joseph Charles Nicholls,male,19,1,1,36.75,0 -3,Mr,August Edvard Andersson,male,27,0,0,7.7958,1 -3,Miss,Robina Maggie Ford,female,9,2,2,34.375,0 -2,Mr,Michel Navratil,male,36.5,0,2,26,0 -2,Rev,Thomas Roussel Davids Byles,male,42,0,0,13,0 -2,Rev,Robert James Bateman,male,51,0,0,12.525,0 -1,Mrs,Thomas (Edith Wearne) Pears,female,22,1,0,66.6,1 -3,Mr,Alfonzo Meo,male,55.5,0,0,8.05,0 -3,Mr,Austin Blyler van Billiard,male,40.5,0,2,14.5,0 -3,Mr,Ole Martin Olsen,male,27,0,0,7.3125,0 -1,Mr,Charles Duane Williams,male,51,0,1,61.3792,0 -3,Miss,Katherine Gilnagh,female,16,0,0,7.7333,1 -3,Mr,Harry Corn,male,30,0,0,8.05,0 -3,Mr,Mile Smiljanic,male,37,0,0,8.6625,0 -3,Master,Thomas Henry Sage,male,5,8,2,69.55,0 -3,Mr,John Hatfield Cribb,male,44,0,1,16.1,0 -2,Mrs,James (Elizabeth Inglis Milne) Watt,female,40,0,0,15.75,1 -3,Mr,John Viktor Bengtsson,male,26,0,0,7.775,0 -3,Mr,Jovo Calic,male,17,0,0,8.6625,0 -3,Master,Eino Viljami Panula,male,1,4,1,39.6875,0 -3,Master,Frank John William Goldsmith,male,9,0,2,20.525,1 -1,Mrs,(Edith Martha Bowerman) Chibnall,female,48,0,1,55,1 -3,Mrs,William (Anna Bernhardina Karlsson) Skoog,female,45,1,4,27.9,0 -1,Mr,John D Baumann,male,60,0,0,25.925,0 -3,Mr,Lee Ling,male,28,0,0,56.4958,0 -1,Mr,Wyckoff Van der hoef,male,61,0,0,33.5,0 -3,Master,Arthur Rice,male,4,4,1,29.125,0 -3,Miss,Eleanor Ileen Johnson,female,1,1,1,11.1333,1 -3,Mr,Antti Wilhelm Sivola,male,21,0,0,7.925,0 -1,Mr,James Clinch Smith,male,56,0,0,30.6958,0 -3,Mr,Klas Albin Klasen,male,18,1,1,7.8542,0 -3,Master,Henry Forbes Lefebre,male,5,3,1,25.4667,0 -1,Miss,Ann Elizabeth Isham,female,50,0,0,28.7125,0 -2,Mr,Reginald Hale,male,30,0,0,13,0 -3,Mr,Lionel Leonard,male,36,0,0,0,0 -3,Miss,Constance Gladys Sage,female,8,8,2,69.55,0 -2,Mr,Rene Pernot,male,39,0,0,15.05,0 -3,Master,Clarence Gustaf Hugo Asplund,male,9,4,2,31.3875,0 -2,Master,Richard F Becker,male,1,2,1,39,1 -3,Miss,Luise Gretchen Kink-Heilmann,female,4,0,2,22.025,1 -1,Mr,Hugh Roscoe Rood,male,39,0,0,50,0 -3,Mrs,Thomas (Johanna Godfrey) O'Brien,female,26,1,0,15.5,1 -1,Mr,Charles Hallace Romaine,male,45,0,0,26.55,1 -3,Mr,John Bourke,male,40,1,1,15.5,0 -3,Mr,Stjepan Turcin,male,36,0,0,7.8958,0 -2,Mrs,(Rosa) Pinsky,female,32,0,0,13,1 -2,Mr,William Carbines,male,19,0,0,13,0 -3,Miss,Carla Christine Nielsine Andersen-Jensen,female,19,1,0,7.8542,1 -2,Master,Michel M Navratil,male,3,1,1,26,1 -1,Mrs,James Joseph (Margaret Tobin) Brown,female,44,0,0,27.7208,1 -1,Miss,Elise Lurette,female,58,0,0,146.5208,1 -3,Mr,Robert Mernagh,male,28,0,0,7.75,0 -3,Mr,Karl Siegwart Andreas Olsen,male,42,0,1,8.4042,0 -3,Miss,Margaret Madigan,female,21,0,0,7.75,1 -2,Miss,Henriette Yrois,female,24,0,0,13,0 -3,Mr,Nestor Cyriel Vande Walle,male,28,0,0,9.5,0 -3,Mr,Frederick Sage,male,17,8,2,69.55,0 -3,Mr,Jakob Alfred Johanson,male,34,0,0,6.4958,0 -3,Mr,Gerious Youseff,male,45.5,0,0,7.225,0 -3,Mr,Gurshon Cohen,male,18,0,0,8.05,1 -3,Miss,Telma Matilda Strom,female,2,0,1,10.4625,0 -3,Mr,Karl Alfred Backstrom,male,32,1,0,15.85,0 -3,Mr,Nassef Cassem Albimona,male,26,0,0,18.7875,1 -3,Miss,Helen Carr,female,16,0,0,7.75,1 -1,Mr,Henry Blank,male,40,0,0,31,1 -3,Mr,Ahmed Ali,male,24,0,0,7.05,0 -2,Miss,Clear Annie Cameron,female,35,0,0,21,1 -3,Mr,John Henry Perkin,male,22,0,0,7.25,0 -2,Mr,Hans Kristensen Givard,male,30,0,0,13,0 -3,Mr,Philip Kiernan,male,22,1,0,7.75,0 -1,Miss,Madeleine Newell,female,31,1,0,113.275,1 -3,Miss,Eliina Honkanen,female,27,0,0,7.925,1 -2,Mr,Sidney Samuel Jacobsohn,male,42,1,0,27,0 -1,Miss,Albina Bazzani,female,32,0,0,76.2917,1 -2,Mr,Walter Harris,male,30,0,0,10.5,0 -3,Mr,Victor Francis Sunderland,male,16,0,0,8.05,1 -2,Mr,James H Bracken,male,27,0,0,13,0 -3,Mr,George Henry Green,male,51,0,0,8.05,0 -3,Mr,Christo Nenkoff,male,22,0,0,7.8958,0 -1,Mr,Frederick Maxfield Hoyt,male,38,1,0,90,1 -3,Mr,Karl Ivar Sven Berglund,male,22,0,0,9.35,0 -2,Mr,William John Mellors,male,19,0,0,10.5,1 -3,Mr,John Hall Lovell,male,20.5,0,0,7.25,0 -2,Mr,Arne Jonas Fahlstrom,male,18,0,0,13,0 -3,Miss,Mathilde Lefebre,female,12,3,1,25.4667,0 -1,Mrs,Henry Birkhardt (Irene Wallach) Harris,female,35,1,0,83.475,1 -3,Mr,Bengt Edvin Larsson,male,29,0,0,7.775,0 -2,Mr,Ernst Adolf Sjostedt,male,59,0,0,13.5,0 -3,Miss,Lillian Gertrud Asplund,female,5,4,2,31.3875,1 -2,Mr,Robert William Norman Leyson,male,24,0,0,10.5,0 -3,Miss,Alice Phoebe Harknett,female,21,0,0,7.55,0 -2,Mr,Stephen Hold,male,44,1,0,26,0 -2,Miss,Marjorie Collyer,female,8,0,2,26.25,1 -2,Mr,Frederick William Pengelly,male,19,0,0,10.5,0 -2,Mr,George Henry Hunt,male,33,0,0,12.275,0 -3,Miss,Thamine Zabour,female,19,1,0,14.4542,0 -3,Miss,Katherine Murphy,female,18,1,0,15.5,1 -2,Mr,Reginald Charles Coleridge,male,29,0,0,10.5,0 -3,Mr,Matti Alexanteri Maenpaa,male,22,0,0,7.125,0 -3,Mr,Sleiman Attalah,male,30,0,0,7.225,0 -1,Dr,William Edward Minahan,male,44,2,0,90,0 -3,Miss,Agda Thorilda Viktoria Lindahl,female,25,0,0,7.775,0 -2,Mrs,William (Anna) Hamalainen,female,24,0,2,14.5,1 -1,Mr,Richard Leonard Beckwith,male,37,1,1,52.5542,1 -2,Rev,Ernest Courtenay Carter,male,54,1,0,26,0 -3,Mr,James George Reed,male,18,0,0,7.25,0 -3,Mrs,Wilhelm (Elna Matilda Persson) Strom,female,29,1,1,10.4625,0 -1,Mr,William Thomas Stead,male,62,0,0,26.55,0 -3,Mr,William Arthur Lobb,male,30,1,0,16.1,0 -3,Mrs,Viktor (Helena Wilhelmina) Rosblom,female,41,0,2,20.2125,0 -3,Mrs,Darwis (Hanne Youssef Razi) Touma,female,29,0,2,15.2458,1 -1,Mrs,Gertrude Maybelle Thorne,female,38,0,0,79.2,1 -1,Miss,Gladys Cherry,female,30,0,0,86.5,1 -1,Miss,Anna Ward,female,35,0,0,512.3292,1 -2,Mrs,(Lutie Davis) Parrish,female,50,0,1,26,1 -3,Master,Edvin Rojj Felix Asplund,male,3,4,2,31.3875,1 -1,Mr,Emil Taussig,male,52,1,1,79.65,0 -1,Mr,William Harrison,male,40,0,0,0,0 -3,Miss,Delia Henry,female,21,0,0,7.75,0 -2,Mr,David Reeves,male,36,0,0,10.5,0 -3,Mr,Ernesti Arvid Panula,male,16,4,1,39.6875,0 -3,Mr,Ernst Ulrik Persson,male,25,1,0,7.775,1 -1,Mrs,William Thompson (Edith Junkins) Graham,female,58,0,1,153.4625,1 -1,Miss,Amelia Bissette,female,35,0,0,135.6333,1 -1,Mr,Alexander Cairns,male,28,0,0,31,0 -3,Mr,William Henry Tornquist,male,25,0,0,0,1 -2,Mrs,(Elizabeth Anne Maidment) Mellinger,female,41,0,1,19.5,1 -1,Mr,Charles H Natsch,male,37,0,1,29.7,0 -3,Miss,Hanora Healy,female,33,0,0,7.75,1 -1,Miss,Kornelia Theodosia Andrews,female,63,1,0,77.9583,1 -3,Miss,Augusta Charlotta Lindblom,female,45,0,0,7.75,0 -2,Mr,Francis Parkes,male,21,0,0,0,0 -3,Master,Eric Rice,male,7,4,1,29.125,0 -3,Mrs,Stanton (Rosa Hunt) Abbott,female,35,1,1,20.25,1 -3,Mr,Frank Duane,male,65,0,0,7.75,0 -3,Mr,Nils Johan Goransson Olsson,male,28,0,0,7.8542,0 -3,Mr,Alfons de Pelsmaeker,male,16,0,0,9.5,0 -3,Mr,Edward Arthur Dorking,male,19,0,0,8.05,1 -1,Mr,Richard William Smith,male,57,0,0,26,0 -3,Mr,Ivan Stankovic,male,33,0,0,8.6625,0 -3,Mr,Theodore de Mulder,male,30,0,0,9.5,1 -3,Mr,Penko Naidenoff,male,22,0,0,7.8958,0 -2,Mr,Masabumi Hosono,male,42,0,0,13,1 -3,Miss,Kate Connolly,female,22,0,0,7.75,1 -1,Miss,Ellen Barber,female,26,0,0,78.85,1 -1,Mrs,Dickinson H (Helen Walton) Bishop,female,19,1,0,91.0792,1 -2,Mr,Rene Jacques Levy,male,36,0,0,12.875,0 -3,Miss,Aloisia Haas,female,24,0,0,8.85,0 -3,Mr,Ivan Mineff,male,24,0,0,7.8958,0 -1,Mr,Ervin G Lewy,male,30,0,0,27.7208,0 -3,Mr,Mansour Hanna,male,23.5,0,0,7.2292,0 -1,Miss,Helen Loraine Allison,female,2,1,2,151.55,0 -1,Mr,Adolphe Saalfeld,male,47,0,0,30.5,1 -1,Mrs,James (Helene DeLaudeniere Chaput) Baxter,female,50,0,1,247.5208,1 -3,Miss,Anna Katherine Kelly,female,20,0,0,7.75,1 -3,Mr,Bernard McCoy,male,24,2,0,23.25,1 -3,Mr,William Cahoone Jr Johnson,male,19,0,0,0,0 -2,Miss,Nora A Keane,female,46,0,0,12.35,1 -3,Mr,Howard Hugh Williams,male,28,0,0,8.05,0 -1,Master,Hudson Trevor Allison,male,0.92,1,2,151.55,1 -1,Miss,Margaret Fleming,female,42,0,0,110.8833,1 -1,Mrs,Victor de Satode (Maria Josefa Perez de Soto y Vallejo) Penasco y Castellana,female,17,1,0,108.9,1 -2,Mr,Samuel Abelson,male,30,1,0,24,0 -1,Miss,Laura Mabel Francatelli,female,30,0,0,56.9292,1 -1,Miss,Margaret Bechstein Hays,female,24,0,0,83.1583,1 -1,Miss,Emily Borie Ryerson,female,18,2,2,262.375,1 -2,Mrs,William (Anna Sylfven) Lahtinen,female,26,1,1,26,0 -3,Mr,Ignjac Hendekovic,male,28,0,0,7.8958,0 -2,Mr,Benjamin Hart,male,43,1,1,26.25,0 -3,Miss,Helmina Josefina Nilsson,female,26,0,0,7.8542,1 -2,Mrs,Sinai (Miriam Sternin) Kantor,female,24,1,0,26,1 -2,Dr,Ernest Moraweck,male,54,0,0,14,0 -1,Miss,Mary Natalie Wick,female,31,0,2,164.8667,1 -1,Mrs,Frederic Oakley (Margaretta Corning Stone) Spedden,female,40,1,1,134.5,1 -3,Mr,Samuel Dennis,male,22,0,0,7.25,0 -3,Mr,Yoto Danoff,male,27,0,0,7.8958,0 -2,Miss,Hilda Mary Slayter,female,30,0,0,12.35,1 -2,Mrs,Albert Francis (Sylvia Mae Harbaugh) Caldwell,female,22,1,1,29,1 -3,Mr,George John Jr Sage,male,20,8,2,69.55,0 -1,Miss,Marie Grice Young,female,36,0,0,135.6333,1 -3,Mr,Johan Hansen Nysveen,male,61,0,0,6.2375,0 -2,Mrs,(Ada E Hall) Ball,female,36,0,0,13,1 -3,Mrs,Frank John (Emily Alice Brown) Goldsmith,female,31,1,1,20.525,1 -1,Miss,Jean Gertrude Hippach,female,16,0,1,57.9792,1 -3,Miss,Agnes McCoy,female,28,2,0,23.25,1 -1,Mr,Austen Partner,male,45.5,0,0,28.5,0 -1,Mr,George Edward Graham,male,38,0,1,153.4625,0 -3,Mr,Leo Edmondus Vander Planke,male,16,2,0,18,0 -1,Mrs,Henry William (Clara Heinsheimer) Frauenthal,female,42,1,0,133.65,1 -3,Mr,Mitto Denkoff,male,30,0,0,7.8958,0 -1,Mr,Thomas Clinton Pears,male,29,1,0,66.6,0 -1,Miss,Elizabeth Margaret Burns,female,41,0,0,134.5,1 -3,Mr,Karl Edwart Dahl,male,45,0,0,8.05,1 -1,Mr,Stephen Weart Blackwell,male,45,0,0,35.5,0 -2,Master,Edmond Roger Navratil,male,2,1,1,26,1 -1,Miss,Alice Elizabeth Fortune,female,24,3,2,263,1 -2,Mr,Erik Gustaf Collander,male,28,0,0,13,0 -2,Mr,Charles Frederick Waddington Sedgwick,male,25,0,0,13,0 -2,Mr,Stanley Hubert Fox,male,36,0,0,13,0 -2,Miss,Amelia Brown,female,24,0,0,13,1 -2,Miss,Marion Elsie Smith,female,40,0,0,13,1 -3,Mrs,Thomas Henry (Mary E Finck) Davison,female,34,1,0,16.1,1 -3,Master,William Loch Coutts,male,3,1,1,15.9,1 -3,Mr,Jovan Dimic,male,42,0,0,8.6625,0 -3,Mr,Nils Martin Odahl,male,23,0,0,9.225,0 -1,Mr,Fletcher Fellows Williams-Lambert,male,43,0,0,35,0 -3,Mr,Tannous Elias,male,15,1,1,7.2292,0 -3,Mr,Josef Arnold-Franchi,male,25,1,0,17.8,0 -3,Mr,Wazli Yousif,male,23,0,0,7.225,0 -3,Mr,Leo Peter Vanden Steen,male,28,0,0,9.5,0 -1,Miss,Elsie Edith Bowerman,female,22,0,1,55,1 -2,Miss,Annie Clemmer Funk,female,38,0,0,13,0 -3,Miss,Mary McGovern,female,22,0,0,7.8792,1 -3,Miss,Helen Mary Mockler,female,23,0,0,7.8792,1 -3,Mr,Wilhelm Skoog,male,40,1,4,27.9,0 -2,Mr,Sebastiano del Carlo,male,29,1,0,27.7208,0 -3,Mrs,(Catherine David) Barbara,female,45,0,1,14.4542,0 -3,Mr,Adola Asim,male,35,0,0,7.05,0 -3,Mr,Thomas O'Brien,male,27,1,0,15.5,0 -3,Mr,Mauritz Nils Martin Adahl,male,30,0,0,7.25,0 -1,Mrs,Frank Manley (Anna Sophia Atkinson) Warren,female,60,1,0,75.25,1 -3,Mrs,(Mantoura Boulos) Moussa,female,35,0,0,7.2292,1 -3,Miss,Annie Jermyn,female,22,0,0,7.75,1 -1,Mme,Leontine Pauline Aubart,female,24,0,0,69.3,1 -1,Mr,George Achilles Harder,male,25,1,0,55.4417,1 -3,Mr,Jakob Alfred Wiklund,male,18,1,0,6.4958,0 -3,Mr,William Thomas Beavan,male,19,0,0,8.05,0 -1,Mr,Sante Ringhini,male,22,0,0,135.6333,0 -3,Miss,Stina Viola Palsson,female,3,3,1,21.075,0 -1,Mrs,Edgar Joseph (Leila Saks) Meyer,female,25,1,0,82.1708,1 -3,Miss,Aurora Adelia Landergren,female,22,0,0,7.25,1 -1,Mr,Harry Elkins Widener,male,27,0,2,211.5,0 -3,Mr,Tannous Betros,male,20,0,0,4.0125,0 -3,Mr,Karl Gideon Gustafsson,male,19,0,0,7.775,0 -1,Miss,Rosalie Bidois,female,42,0,0,227.525,1 -3,Miss,Maria Nakid,female,1,0,2,15.7417,1 -3,Mr,Juho Tikkanen,male,32,0,0,7.925,0 -1,Mrs,Alexander Oskar (Mary Aline Towner) Holverson,female,35,1,0,52,1 -3,Mr,Vasil Plotcharsky,male,27,0,0,7.8958,0 -2,Mr,Charles Henry Davies,male,18,0,0,73.5,0 -3,Master,Sidney Leonard Goodwin,male,1,5,2,46.9,0 -2,Miss,Kate Buss,female,36,0,0,13,1 -3,Mr,Matthew Sadlier,male,19,0,0,7.7292,0 -2,Miss,Bertha Lehmann,female,17,0,0,12,1 -1,Mr,William Ernest Carter,male,36,1,2,120,1 -3,Mr,Carl Olof Jansson,male,21,0,0,7.7958,1 -3,Mr,Johan Birger Gustafsson,male,28,2,0,7.925,0 -1,Miss,Marjorie Newell,female,23,1,0,113.275,1 -3,Mrs,Hjalmar (Agnes Charlotta Bengtsson) Sandstrom,female,24,0,2,16.7,1 -3,Mr,Erik Johansson,male,22,0,0,7.7958,0 -3,Miss,Elina Olsson,female,31,0,0,7.8542,0 -2,Mr,Peter David McKane,male,46,0,0,26,0 -2,Dr,Alfred Pain,male,23,0,0,10.5,0 -2,Mrs,William H (Jessie L) Trout,female,28,0,0,12.65,1 -3,Mr,Juha Niskanen,male,39,0,0,7.925,1 -3,Mr,John Adams,male,26,0,0,8.05,0 -3,Miss,Mari Aina Jussila,female,21,1,0,9.825,0 -3,Mr,Pekka Pietari Hakkarainen,male,28,1,0,15.85,0 -3,Miss,Marija Oreskovic,female,20,0,0,8.6625,0 -2,Mr,Shadrach Gale,male,34,1,0,21,0 -3,Mr,Carl/Charles Peter Widegren,male,51,0,0,7.75,0 -2,Master,William Rowe Richards,male,3,1,1,18.75,1 -3,Mr,Hans Martin Monsen Birkeland,male,21,0,0,7.775,0 -3,Miss,Ida Lefebre,female,3,3,1,25.4667,0 -3,Mr,Todor Sdycoff,male,42,0,0,7.8958,0 -3,Mr,Henry Hart,male,27,0,0,6.8583,0 -1,Miss,Daisy E Minahan,female,33,1,0,90,1 -2,Mr,Alfred Fleming Cunningham,male,22,0,0,0,0 -3,Mr,Johan Julian Sundman,male,44,0,0,7.925,1 -3,Mrs,Thomas (Annie Louise Rowley) Meek,female,32,0,0,8.05,0 -2,Mrs,James Vivian (Lulu Thorne Christian) Drew,female,34,1,1,32.5,1 -2,Miss,Lyyli Karoliina Silven,female,18,0,2,13,1 -2,Mr,William John Matthews,male,30,0,0,13,0 -3,Miss,Catharina Van Impe,female,10,0,2,24.15,0 -3,Mr,David Charters,male,21,0,0,7.7333,0 -3,Mr,Leo Zimmerman,male,29,0,0,7.875,0 -3,Mrs,Ernst Gilbert (Anna Sigrid Maria Brogren) Danbom,female,28,1,1,14.4,0 -3,Mr,Viktor Richard Rosblom,male,18,1,1,20.2125,0 -3,Mr,Phillippe Wiseman,male,54,0,0,7.25,0 -2,Mrs,Charles V (Ada Maria Winfield) Clarke,female,28,1,0,26,1 -2,Miss,Kate Florence Phillips,female,19,0,0,26,1 -3,Mr,James Flynn,male,28,0,0,7.75,0 -3,Mr,Berk (Berk Trembisky) Pickard,male,32,0,0,8.05,1 -1,Mr,Mauritz Hakan Bjornstrom-Steffansson,male,28,0,0,26.55,1 -3,Mrs,Percival (Florence Kate White) Thorneycroft,female,33,1,0,16.1,1 -2,Mrs,Charles Alexander (Alice Adelaide Slow) Louch,female,42,1,0,26,1 -3,Mr,Nikolai Erland Kallio,male,17,0,0,7.125,0 -1,Mr,William Baird Silvey,male,50,1,0,55.9,0 -1,Miss,Lucile Polk Carter,female,14,1,2,120,1 -3,Miss,Doolina Margaret Ford,female,21,2,2,34.375,0 -2,Mrs,Sidney (Emily Hocking) Richards,female,24,2,3,18.75,1 -1,Mr,Mark Fortune,male,64,1,4,263,0 -2,Mr,Johan Henrik Johannesson Kvillner,male,31,0,0,10.5,0 -2,Mrs,Benjamin (Esther Ada Bloomfield) Hart,female,45,1,1,26.25,1 -3,Mr,Leon Hampe,male,20,0,0,9.5,0 -3,Mr,Johan Emil Petterson,male,25,1,0,7.775,0 -2,Ms,Encarnacion Reynaldo,female,28,0,0,13,1 -3,Mr,Bernt Johannesen-Bratthammer,male,29,0,0,8.1125,1 -1,Master,Washington Dodge,male,4,0,2,81.8583,1 -2,Miss,Madeleine Violet Mellinger,female,13,0,1,19.5,1 -1,Mr,Frederic Kimber Seward,male,34,0,0,26.55,1 -3,Miss,Marie Catherine Baclini,female,5,2,1,19.2583,1 -1,Major,Arthur Godfrey Peuchen,male,52,0,0,30.5,1 -2,Mr,Edwy Arthur West,male,36,1,2,27.75,0 -3,Mr,Ingvald Olai Olsen Hagland,male,28,1,0,19.9667,0 -1,Mr,Benjamin Laventall Foreman,male,30,0,0,27.75,0 -1,Mr,Samuel L Goldenberg,male,49,1,0,89.1042,1 -3,Mr,Joseph Peduzzi,male,24,0,0,8.05,0 -3,Mr,Ivan Jalsevac,male,29,0,0,7.8958,1 -1,Mr,Francis Davis Millet,male,65,0,0,26.55,0 -1,Mrs,Frederick R (Marion) Kenyon,female,41,1,0,51.8625,1 -2,Miss,Ellen Toomey,female,50,0,0,10.5,1 -3,Mr,Maurice O'Connor,male,17,0,0,7.75,0 -1,Mr,Harry Anderson,male,48,0,0,26.55,1 -3,Mr,William Morley,male,34,0,0,8.05,0 -1,Mr,Arthur H Gee,male,47,0,0,38.5,0 -2,Mr,Jacob Christian Milling,male,48,0,0,13,0 -3,Mr,Simon Maisner,male,34,0,0,8.05,0 -3,Mr,Manuel Estanslas Goncalves,male,38,0,0,7.05,0 -2,Mr,William Campbell,male,21,0,0,0,0 -1,Mr,John Montgomery Smart,male,56,0,0,26.55,0 -3,Mr,James Scanlan,male,22,0,0,7.725,0 -3,Miss,Helene Barbara Baclini,female,0.75,2,1,19.2583,1 -3,Mr,Arthur Keefe,male,39,0,0,7.25,0 -3,Mr,Luka Cacic,male,38,0,0,8.6625,0 -2,Mrs,Edwy Arthur (Ada Mary Worth) West,female,33,1,2,27.75,1 -2,Mrs,Amin S (Marie Marthe Thuillard) Jerwan,female,23,0,0,13.7917,1 -3,Miss,Ida Sofia Strandberg,female,22,0,0,9.8375,0 -1,Mr,George Quincy Clifford,male,40,0,0,52,0 -2,Mr,Peter Henry Renouf,male,34,1,0,21,0 -3,Mr,Lewis Richard Braund,male,29,1,0,7.0458,0 -3,Mr,Nils August Karlsson,male,22,0,0,7.5208,0 -3,Miss,Hildur E Hirvonen,female,2,0,1,12.2875,1 -3,Master,Harold Victor Goodwin,male,9,5,2,46.9,0 -2,Mr,Anthony Wood Frost,male,37,0,0,0,0 -3,Mr,Richard Henry Rouse,male,50,0,0,8.05,0 -3,Mrs,(Hedwig) Turkula,female,63,0,0,9.5875,1 -1,Mr,Dickinson H Bishop,male,25,1,0,91.0792,1 -3,Miss,Jeannie Lefebre,female,8,3,1,25.4667,0 -1,Mrs,Frederick Maxfield (Jane Anne Forby) Hoyt,female,35,1,0,90,1 -1,Mr,Edward Austin Kent,male,58,0,0,29.7,0 -3,Mr,Francis William Somerton,male,30,0,0,8.05,0 -3,Master,Eden Leslie Coutts,male,9,1,1,15.9,1 -3,Mr,Konrad Mathias Reiersen Hagland,male,19,1,0,19.9667,0 -3,Mr,Einar Windelov,male,21,0,0,7.25,0 -1,Mr,Harry Markland Molson,male,55,0,0,30.5,0 -1,Mr,Ramon Artagaveytia,male,71,0,0,49.5042,0 -3,Mr,Edward Roland Stanley,male,21,0,0,8.05,0 -3,Mr,Gerious Yousseff,male,26,0,0,14.4583,0 -1,Miss,Elizabeth Mussey Eustis,female,54,1,0,78.2667,1 -3,Mr,Frederick William Shellard,male,55,0,0,15.1,0 -1,Mrs,Hudson J C (Bessie Waldo Daniels) Allison,female,25,1,2,151.55,0 -3,Mr,Olof Svensson,male,24,0,0,7.7958,0 -3,Mr,Petar Calic,male,17,0,0,8.6625,0 -3,Miss,Mary Canavan,female,21,0,0,7.75,0 -3,Miss,Bridget Mary O'Sullivan,female,21,0,0,7.6292,0 -3,Miss,Kristina Sofia Laitinen,female,37,0,0,9.5875,0 -1,Miss,Roberta Maioni,female,16,0,0,86.5,1 -1,Mr,Victor de Satode Penasco y Castellana,male,18,1,0,108.9,0 -2,Mrs,Frederick Charles (Jane Richards) Quick,female,33,0,2,26,1 -1,Mr,George Bradley,male,37,0,0,26.55,1 -3,Mr,Henry Margido Olsen,male,28,0,0,22.525,0 -3,Mr,Fang Lang,male,26,0,0,56.4958,1 -3,Mr,Eugene Patrick Daly,male,29,0,0,7.75,1 -3,Mr,James Webber,male,66,0,0,8.05,0 -1,Mr,James Robert McGough,male,36,0,0,26.2875,1 -1,Mrs,Martin (Elizabeth L. Barrett) Rothschild,female,54,1,0,59.4,1 -3,Mr,Satio Coleff,male,24,0,0,7.4958,0 -1,Mr,William Anderson Walker,male,47,0,0,34.0208,0 -2,Mrs,(Amelia Milley) Lemore,female,34,0,0,10.5,1 -3,Mr,Patrick Ryan,male,30,0,0,24.15,0 -2,Mrs,William A (Florence Agnes Hughes) Angle,female,36,1,0,26,1 -3,Mr,Stefo Pavlovic,male,32,0,0,7.8958,0 -1,Miss,Anne Perreault,female,30,0,0,93.5,1 -3,Mr,Janko Vovk,male,22,0,0,7.8958,0 -3,Mr,Sarkis Lahoud,male,35,0,0,7.225,0 -1,Mrs,Louis Albert (Ida Sophia Fischer) Hippach,female,44,0,1,57.9792,1 -3,Mr,Fared Kassem,male,18,0,0,7.2292,0 -3,Mr,James Farrell,male,40.5,0,0,7.75,0 -2,Miss,Lucy Ridsdale,female,50,0,0,10.5,1 -1,Mr,John Farthing,male,49,0,0,221.7792,0 -3,Mr,Johan Werner Salonen,male,39,0,0,7.925,0 -2,Mr,Richard George Hocking,male,23,2,1,11.5,0 -2,Miss,Phyllis May Quick,female,2,1,1,26,1 -3,Mr,Nakli Toufik,male,17,0,0,7.2292,0 -3,Mr,Joseph Jr Elias,male,17,1,1,7.2292,0 -3,Mrs,Catherine (Catherine Rizk) Peter,female,24,0,2,22.3583,1 -3,Miss,Marija Cacic,female,30,0,0,8.6625,0 -2,Miss,Eva Miriam Hart,female,7,0,2,26.25,1 -1,Major,Archibald Willingham Butt,male,45,0,0,26.55,0 -1,Miss,Bertha LeRoy,female,30,0,0,106.425,1 -3,Mr,Samuel Beard Risien,male,69,0,0,14.5,0 -1,Miss,Hedwig Margaritha Frolicher,female,22,0,2,49.5,1 -1,Miss,Harriet R Crosby,female,36,0,2,71,1 -3,Miss,Ingeborg Constanzia Andersson,female,9,4,2,31.275,0 -3,Miss,Sigrid Elisabeth Andersson,female,11,4,2,31.275,0 -2,Mr,Edward Beane,male,32,1,0,26,1 -1,Mr,Walter Donald Douglas,male,50,1,0,106.425,0 -1,Mr,Arthur Ernest Nicholson,male,64,0,0,26,0 -2,Mrs,Edward (Ethel Clarke) Beane,female,19,1,0,26,1 -2,Mr,Julian Padro y Manent,male,27,0,0,13.8625,1 -3,Mr,Frank John Goldsmith,male,33,1,1,20.525,0 -2,Master,John Morgan Jr Davies,male,8,1,1,36.75,1 -1,Mr,John Borland Jr Thayer,male,17,0,2,110.8833,1 -2,Mr,Percival James R Sharp,male,27,0,0,26,0 -3,Mr,Timothy O'Brien,male,21,0,0,7.8292,0 -3,Mr,Fahim Leeni,male,22,0,0,7.225,1 -3,Miss,Velin Ohman,female,22,0,0,7.775,1 -1,Mr,George Wright,male,62,0,0,26.55,0 -1,Lady,(Lucille Christiana Sutherland)Duff Gordon,female,48,1,0,39.6,1 -1,Mr,Victor Robbins,male,45,0,0,227.525,0 -1,Mrs,Emil (Tillie Mandelbaum) Taussig,female,39,1,1,79.65,1 -3,Mrs,Guillaume Joseph (Emma) de Messemaeker,female,36,1,0,17.4,1 -3,Mr,Thomas Rowan Morrow,male,30,0,0,7.75,0 -3,Mr,Husein Sivic,male,40,0,0,7.8958,0 -2,Mr,Robert Douglas Norman,male,28,0,0,13.5,0 -3,Mr,John Simmons,male,40,0,0,8.05,0 -3,Miss,(Marion Ogden) Meanwell,female,62,0,0,8.05,0 -3,Mr,Alfred J Davies,male,24,2,0,24.15,0 -3,Mr,Ilia Stoytcheff,male,19,0,0,7.8958,0 -3,Mrs,Nils (Alma Cornelia Berglund) Palsson,female,29,0,4,21.075,0 -3,Mr,Tannous Doharr,male,28,0,0,7.2292,0 -3,Mr,Carl Jonsson,male,32,0,0,7.8542,1 -2,Mr,George Harris,male,62,0,0,10.5,1 -1,Mrs,Edward Dale (Charlotte Lamson) Appleton,female,53,2,0,51.4792,1 -1,Mr,John Irwin Flynn,male,36,0,0,26.3875,1 -3,Miss,Mary Kelly,female,22,0,0,7.75,1 -3,Mr,Alfred George John Rush,male,16,0,0,8.05,0 -3,Mr,George Patchett,male,19,0,0,14.5,0 -2,Miss,Ethel Garside,female,34,0,0,13,1 -1,Mrs,William Baird (Alice Munger) Silvey,female,39,1,0,55.9,1 -3,Mrs,Joseph (Maria Elias) Caram,female,18,1,0,14.4583,0 -3,Mr,Eiriik Jussila,male,32,0,0,7.925,1 -2,Miss,Julie Rachel Christy,female,25,1,1,30,1 -1,Mrs,John Borland (Marian Longstreth Morris) Thayer,female,39,1,1,110.8833,1 -2,Mr,William James Downton,male,54,0,0,26,0 -1,Mr,John Hugo Ross,male,36,0,0,40.125,0 -3,Mr,Uscher Paulner,male,16,0,0,8.7125,0 -1,Miss,Ruth Taussig,female,18,0,2,79.65,1 -2,Mr,John Denzil Jarvis,male,47,0,0,15,0 -1,Mr,Maxmillian Frolicher-Stehli,male,60,1,1,79.2,1 -3,Mr,Eliezer Gilinski,male,22,0,0,8.05,0 -3,Mr,Joseph Murdlin,male,22,0,0,8.05,0 -3,Mr,Matti Rintamaki,male,35,0,0,7.125,0 -1,Mrs,Walter Bertram (Martha Eustis) Stephenson,female,52,1,0,78.2667,1 -3,Mr,William James Elsbury,male,47,0,0,7.25,0 -3,Miss,Mary Bourke,female,40,0,2,7.75,0 -2,Mr,John Henry Chapman,male,37,1,0,26,0 -3,Mr,Jean Baptiste Van Impe,male,36,1,1,24.15,0 -2,Miss,Jessie Wills Leitch,female,31,0,0,33,1 -3,Mr,Alfred Johnson,male,49,0,0,0,0 -3,Mr,Hanna Boulos,male,18,0,0,7.225,0 -1,Sir,Cosmo Edmund Duff Gordon,male,49,1,0,56.9292,1 -2,Mrs,Sidney Samuel (Amy Frances Christy) Jacobsohn,female,24,2,1,27,1 -3,Mr,Petco Slabenoff,male,42,0,0,7.8958,0 -1,Mr,Charles H Harrington,male,37,0,0,42.4,0 -3,Mr,Ernst William Torber,male,44,0,0,8.05,0 -1,Mr,Harry Homer,male,35,0,0,26.55,1 -3,Mr,Edvard Bengtsson Lindell,male,36,1,0,15.55,0 -3,Mr,Milan Karaic,male,30,0,0,7.8958,0 -1,Mr,Robert Williams Daniel,male,27,0,0,30.5,1 -2,Mrs,Joseph (Juliette Marie Louise Lafargue) Laroche,female,22,1,2,41.5792,1 -1,Miss,Elizabeth W Shutes,female,40,0,0,153.4625,1 -3,Mrs,Anders Johan (Alfrida Konstantia Brogren) Andersson,female,39,1,5,31.275,0 -3,Mr,Jose Neto Jardin,male,21,0,0,7.05,0 -3,Miss,Margaret Jane Murphy,female,18,1,0,15.5,1 -3,Mr,John Horgan,male,22,0,0,7.75,0 -3,Mr,William Alfred Brocklebank,male,35,0,0,8.05,0 -2,Miss,Alice Herman,female,24,1,2,65,1 -3,Mr,Ernst Gilbert Danbom,male,34,1,1,14.4,0 -3,Mrs,William Arthur (Cordelia K Stanlick) Lobb,female,26,1,0,16.1,0 -2,Miss,Marion Louise Becker,female,4,2,1,39,1 -2,Mr,Lawrence Gavey,male,26,0,0,10.5,0 -3,Mr,Antoni Yasbeck,male,27,1,0,14.4542,0 -1,Mr,Edwin Nelson Jr Kimball,male,42,1,0,52.5542,1 -3,Mr,Sahid Nakid,male,20,1,1,15.7417,1 -3,Mr,Henry Damsgaard Hansen,male,21,0,0,7.8542,0 -3,Mr,David John Bowen,male,21,0,0,16.1,0 -1,Mr,Frederick Sutton,male,61,0,0,32.3208,0 -2,Rev,Charles Leonard Kirkland,male,57,0,0,12.35,0 -1,Miss,Gretchen Fiske Longley,female,21,0,0,77.9583,1 -3,Mr,Guentcho Bostandyeff,male,26,0,0,7.8958,0 -3,Mr,Patrick D O'Connell,male,18,0,0,7.7333,0 -1,Mr,Algernon Henry Wilson Barkworth,male,80,0,0,30,1 -3,Mr,Johan Svensson Lundahl,male,51,0,0,7.0542,0 -1,Dr,Max Stahelin-Maeglin,male,32,0,0,30.5,1 -1,Mr,William Henry Marsh Parr,male,30,0,0,0,0 -3,Miss,Mabel Skoog,female,9,3,2,27.9,0 -2,Miss,Mary Davis,female,28,0,0,13,1 -3,Mr,Antti Gustaf Leinonen,male,32,0,0,7.925,0 -2,Mr,Harvey Collyer,male,31,1,1,26.25,0 -3,Mrs,Juha (Maria Emilia Ojala) Panula,female,41,0,5,39.6875,0 -3,Mr,Percival Thorneycroft,male,37,1,0,16.1,0 -3,Mr,Hans Peder Jensen,male,20,0,0,7.8542,0 -1,Mlle,Emma Sagesser,female,24,0,0,69.3,1 -3,Miss,Margit Elizabeth Skoog,female,2,3,2,27.9,0 -3,Mr,Choong Foo,male,32,0,0,56.4958,1 -3,Miss,Eugenie Baclini,female,0.75,2,1,19.2583,1 -1,Mr,Henry Sleeper Harper,male,48,1,0,76.7292,1 -3,Mr,Liudevit Cor,male,19,0,0,7.8958,0 -1,Col,Oberst Alfons Simonius-Blumer,male,56,0,0,35.5,1 -3,Mr,Edward Willey,male,21,0,0,7.55,0 -3,Miss,Amy Zillah Elsie Stanley,female,23,0,0,7.55,1 -3,Mr,Mito Mitkoff,male,23,0,0,7.8958,0 -2,Miss,Elsie Doling,female,18,0,1,23,1 -3,Mr,Johannes Halvorsen Kalvik,male,21,0,0,8.4333,0 -3,Miss,Hanora O'Leary,female,16,0,0,7.8292,1 -3,Miss,Hanora Hegarty,female,18,0,0,6.75,0 -2,Mr,Leonard Mark Hickman,male,24,2,0,73.5,0 -3,Mr,Alexander Radeff,male,27,0,0,7.8958,0 -3,Mrs,John (Catherine) Bourke,female,32,1,1,15.5,0 -2,Mr,George Floyd Eitemiller,male,23,0,0,13,0 -1,Mr,Arthur Webster Newell,male,58,0,2,113.275,0 -1,Dr,Henry William Frauenthal,male,50,2,0,133.65,1 -3,Mr,Mohamed Badt,male,40,0,0,7.225,0 -1,Mr,Edward Pomeroy Colley,male,47,0,0,25.5875,0 -3,Mr,Peju Coleff,male,36,0,0,7.4958,0 -3,Mr,Eino William Lindqvist,male,20,1,0,7.925,1 -2,Mr,Lewis Hickman,male,32,2,0,73.5,0 -2,Mr,Reginald Fenton Butler,male,25,0,0,13,0 -3,Mr,Knud Paust Rommetvedt,male,49,0,0,7.775,0 -3,Mr,Jacob Cook,male,43,0,0,8.05,0 -1,Mrs,Elmer Zebley (Juliet Cummins Wright) Taylor,female,48,1,0,52,1 -2,Mrs,Thomas William Solomon (Elizabeth Catherine Ford) Brown,female,40,1,1,39,1 -1,Mr,Thornton Davidson,male,31,1,0,52,0 -2,Mr,Henry Michael Mitchell,male,70,0,0,10.5,0 -2,Mr,Charles Wilhelms,male,31,0,0,13,1 -2,Mr,Ennis Hastings Watson,male,19,0,0,0,0 -3,Mr,Gustaf Hjalmar Edvardsson,male,18,0,0,7.775,0 -3,Mr,Frederick Charles Sawyer,male,24.5,0,0,8.05,0 -3,Miss,Anna Sofia Turja,female,18,0,0,9.8417,1 -3,Mrs,Frederick (Augusta Tyler) Goodwin,female,43,1,6,46.9,0 -1,Mr,Thomas Drake Martinez Cardeza,male,36,0,1,512.3292,1 -3,Miss,Katie Peters,female,28,0,0,8.1375,0 -1,Mr,Hammad Hassab,male,27,0,0,76.7292,1 -3,Mr,Thor Anderson Olsvigen,male,20,0,0,9.225,0 -3,Mr,Charles Edward Goodwin,male,14,5,2,46.9,0 -2,Mr,Thomas William Solomon Brown,male,60,1,1,39,0 -2,Mr,Joseph Philippe Lemercier Laroche,male,25,1,2,41.5792,0 -3,Mr,Jaako Arnold Panula,male,14,4,1,39.6875,0 -3,Mr,Branko Dakic,male,19,0,0,10.1708,0 -3,Mr,Eberhard Thelander Fischer,male,18,0,0,7.7958,0 -1,Miss,Georgette Alexandra Madill,female,15,0,1,211.3375,1 -1,Mr,Albert Adrian Dick,male,31,1,0,57,1 -3,Miss,Manca Karun,female,4,0,1,13.4167,1 -3,Mr,Ali Lam,male,37,0,0,56.4958,1 -3,Mr,Khalil Saad,male,25,0,0,7.225,0 -1,Col,John Weir,male,60,0,0,26.55,0 -2,Mr,Charles Henry Chapman,male,52,0,0,13.5,0 -3,Mr,James Kelly,male,44,0,0,8.05,0 -3,Miss,Katherine Mullens,female,19,0,0,7.7333,1 -1,Mr,John Borland Thayer,male,49,1,1,110.8833,0 -3,Mr,Adolf Mathias Nicolai Olsen Humblen,male,42,0,0,7.65,0 -1,Mrs,John Jacob (Madeleine Talmadge Force) Astor,female,18,1,0,227.525,1 -1,Mr,Spencer Victor Silverthorne,male,35,0,0,26.2875,1 -3,Miss,Saiide Barbara,female,18,0,1,14.4542,0 -3,Mr,Martin Gallagher,male,25,0,0,7.7417,0 -3,Mr,Henrik Juul Hansen,male,26,1,0,7.8542,0 -2,Mr,Henry Samuel Morley,male,39,0,0,26,0 -2,Mrs,Florence Kelly,female,45,0,0,13.5,1 -1,Mr,Edward Pennington Calderhead,male,42,0,0,26.2875,1 -1,Miss,Alice Cleaver,female,22,0,0,151.55,1 -3,Master,Halim Gonios Moubarek,male,4,1,1,15.2458,1 -1,Mlle,Berthe Antonine Mayne,female,24,0,0,49.5042,1 -1,Mr,Herman Klaber,male,41,0,0,26.55,0 -1,Mr,Elmer Zebley Taylor,male,48,1,0,52,1 -3,Mr,August Viktor Larsson,male,29,0,0,9.4833,0 -2,Mr,Samuel Greenberg,male,52,0,0,13,0 -3,Mr,Peter Andreas Lauritz Andersen Soholt,male,19,0,0,7.65,0 -1,Miss,Caroline Louise Endres,female,38,0,0,227.525,1 -2,Miss,Edwina Celia Troutt,female,27,0,0,10.5,1 -3,Mr,Malkolm Joackim Johnson,male,33,0,0,7.775,0 -2,Miss,Annie Jessie Harper,female,6,0,1,33,1 -3,Mr,Svend Lauritz Jensen,male,17,1,0,7.0542,0 -2,Mr,William Henry Gillespie,male,34,0,0,13,0 -2,Mr,Henry Price Hodges,male,50,0,0,13,0 -1,Mr,Norman Campbell Chambers,male,27,1,0,53.1,1 -3,Mr,Luka Oreskovic,male,20,0,0,8.6625,0 -2,Mrs,Peter Henry (Lillian Jefferys) Renouf,female,30,3,0,21,1 -3,Miss,Margareth Mannion,female,28,0,0,7.7375,1 -2,Mr,Kurt Arnold Gottfrid Bryhl,male,25,1,0,26,0 -3,Miss,Pieta Sofia Ilmakangas,female,25,1,0,7.925,0 -1,Miss,Elisabeth Walton Allen,female,29,0,0,211.3375,1 -3,Mr,Houssein G N Hassan,male,11,0,0,18.7875,0 -2,Mr,Robert J Knight,male,41,0,0,0,0 -2,Mr,William John Berriman,male,23,0,0,13,0 -2,Mr,Moses Aaron Troupiansky,male,23,0,0,13,0 -3,Mr,Leslie Williams,male,28.5,0,0,16.1,0 -3,Mrs,Edward (Margaret Ann Watson) Ford,female,48,1,3,34.375,0 -1,Mr,Gustave J Lesurer,male,35,0,0,512.3292,1 -3,Mr,Kanio Ivanoff,male,20,0,0,7.8958,0 -3,Mr,Minko Nankoff,male,32,0,0,7.8958,0 -1,Mr,Walter James Hawksford,male,45,0,0,30,1 -1,Mr,Tyrell William Cavendish,male,36,1,0,78.85,0 -1,Miss,Susan Parker Ryerson,female,21,2,2,262.375,1 -3,Mr,Neal McNamee,male,24,1,0,16.1,0 -3,Mr,Juho Stranden,male,31,0,0,7.925,1 -1,Capt,Edward Gifford Crosby,male,70,1,1,71,0 -3,Mr,Rossmore Edward Abbott,male,16,1,1,20.25,0 -2,Miss,Anna Sinkkonen,female,30,0,0,13,1 -1,Mr,Daniel Warner Marvin,male,19,1,0,53.1,0 -3,Mr,Michael Connaghton,male,31,0,0,7.75,0 -2,Miss,Joan Wells,female,4,1,1,23,1 -3,Master,Meier Moor,male,6,0,1,12.475,1 -3,Mr,Johannes Joseph Vande Velde,male,33,0,0,9.5,0 -3,Mr,Lalio Jonkoff,male,23,0,0,7.8958,0 -2,Mrs,Samuel (Jane Laver) Herman,female,48,1,2,65,1 -2,Master,Viljo Hamalainen,male,0.67,1,1,14.5,1 -3,Mr,August Sigfrid Carlsson,male,28,0,0,7.7958,0 -2,Mr,Percy Andrew Bailey,male,18,0,0,11.5,0 -3,Mr,Thomas Leonard Theobald,male,34,0,0,8.05,0 -1,the,ountess. of (Lucy Noel Martha Dyer-Edwards) Rothes,female,33,0,0,86.5,1 -3,Mr,John Garfirth,male,23,0,0,14.5,0 -3,Mr,Iisakki Antino Aijo Nirva,male,41,0,0,7.125,0 -3,Mr,Hanna Assi Barah,male,20,0,0,7.2292,1 -1,Mrs,William Ernest (Lucile Polk) Carter,female,36,1,2,120,1 -3,Mr,Hans Linus Eklund,male,16,0,0,7.775,0 -1,Mrs,John C (Anna Andrews) Hogeboom,female,51,1,0,77.9583,1 -1,Dr,Arthur Jackson Brewe,male,46,0,0,39.6,0 -3,Miss,Mary Mangan,female,30.5,0,0,7.75,0 -3,Mr,Daniel J Moran,male,28,1,0,24.15,0 -3,Mr,Daniel Danielsen Gronnestad,male,32,0,0,8.3625,0 -3,Mr,Rene Aime Lievens,male,24,0,0,9.5,0 -3,Mr,Niels Peder Jensen,male,48,0,0,7.8542,0 -2,Mrs,(Mary) Mack,female,57,0,0,10.5,0 -3,Mr,Dibo Elias,male,29,0,0,7.225,0 -2,Mrs,Elizabeth (Eliza Needs) Hocking,female,54,1,3,23,1 -3,Mr,Pehr Fabian Oliver Malkolm Myhrman,male,18,0,0,7.75,0 -3,Mr,Roger Tobin,male,20,0,0,7.75,0 -3,Miss,Virginia Ethel Emanuel,female,5,0,0,12.475,1 -3,Mr,Thomas J Kilgannon,male,22,0,0,7.7375,0 -1,Mrs,Edward Scott (Elisabeth Walton McMillan) Robert,female,43,0,1,211.3375,1 -3,Miss,Banoura Ayoub,female,13,0,0,7.2292,1 -1,Mrs,Albert Adrian (Vera Gillespie) Dick,female,17,1,0,57,1 -1,Mr,Milton Clyde Long,male,29,0,0,30,0 -3,Mr,Andrew G Johnston,male,35,1,2,23.45,0 -3,Mr,William Ali,male,25,0,0,7.05,0 -3,Mr,Abraham (David Lishin) Harmer,male,25,0,0,7.25,0 -3,Miss,Anna Sofia Sjoblom,female,18,0,0,7.4958,1 -3,Master,George Hugh Rice,male,8,4,1,29.125,0 -3,Master,Bertram Vere Dean,male,1,1,2,20.575,1 -1,Mr,Benjamin Guggenheim,male,46,0,0,79.2,0 -3,Mr,Andrew Keane,male,20,0,0,7.75,0 -2,Mr,Alfred Gaskell,male,16,0,0,26,0 -3,Miss,Stella Anna Sage,female,21,8,2,69.55,0 -1,Mr,William Fisher Hoyt,male,43,0,0,30.6958,0 -3,Mr,Ristiu Dantcheff,male,25,0,0,7.8958,0 -2,Mr,Richard Otter,male,39,0,0,13,0 -1,Dr,Alice (Farnham) Leader,female,49,0,0,25.9292,1 -3,Mrs,Mara Osman,female,31,0,0,8.6833,1 -3,Mr,Yousseff Ibrahim Shawah,male,30,0,0,7.2292,0 -3,Mrs,Jean Baptiste (Rosalie Paula Govaert) Van Impe,female,30,1,1,24.15,0 -2,Mr,Martin Ponesell,male,34,0,0,13,0 -2,Mrs,Harvey (Charlotte Annie Tate) Collyer,female,31,1,1,26.25,1 -1,Master,William Thornton II Carter,male,11,1,2,120,1 -3,Master,Assad Alexander Thomas,male,0.42,0,1,8.5167,1 -3,Mr,Oskar Arvid Hedman,male,27,0,0,6.975,1 -3,Mr,Karl Johan Johansson,male,31,0,0,7.775,0 -1,Mr,Thomas Jr Andrews,male,39,0,0,0,0 -3,Miss,Ellen Natalia Pettersson,female,18,0,0,7.775,0 -2,Mr,August Meyer,male,39,0,0,13,0 -1,Mrs,Norman Campbell (Bertha Griggs) Chambers,female,33,1,0,53.1,1 -3,Mr,William Alexander,male,26,0,0,7.8875,0 -3,Mr,James Lester,male,39,0,0,24.15,0 -2,Mr,Richard James Slemen,male,35,0,0,10.5,0 -3,Miss,Ebba Iris Alfrida Andersson,female,6,4,2,31.275,0 -3,Mr,Ernest Portage Tomlin,male,30.5,0,0,8.05,0 -1,Mr,Richard Fry,male,39,0,0,0,0 -3,Miss,Wendla Maria Heininen,female,23,0,0,7.925,0 -2,Mr,Albert Mallet,male,31,1,1,37.0042,0 -3,Mr,John Fredrik Alexander Holm,male,43,0,0,6.45,0 -3,Master,Karl Thorsten Skoog,male,10,3,2,27.9,0 -1,Mrs,Charles Melville (Clara Jennings Gregg) Hays,female,52,1,1,93.5,1 -3,Mr,Nikola Lulic,male,27,0,0,8.6625,1 -1,Jonkheer,John George Reuchlin,male,38,0,0,0,0 -3,Mrs,(Beila) Moor,female,27,0,1,12.475,1 -3,Master,Urho Abraham Panula,male,2,4,1,39.6875,0 -3,Mr,John Flynn,male,36,0,0,6.95,0 -3,Mr,Len Lam,male,23,0,0,56.4958,0 -2,Master,Andre Mallet,male,1,0,2,37.0042,1 -3,Mr,Thomas Joseph McCormack,male,19,0,0,7.75,1 -1,Mrs,George Nelson (Martha Evelyn) Stone,female,62,0,0,80,1 -3,Mrs,Antoni (Selini Alexander) Yasbeck,female,15,1,0,14.4542,1 -2,Master,George Sibley Richards,male,0.83,1,1,18.75,1 -3,Mr,Amin Saad,male,30,0,0,7.2292,0 -3,Mr,Albert Augustsson,male,23,0,0,7.8542,0 -3,Mr,Owen George Allum,male,18,0,0,8.3,0 -1,Miss,Sara Rebecca Compton,female,39,1,1,83.1583,1 -3,Mr,Jakob Pasic,male,21,0,0,8.6625,0 -3,Mr,Maurice Sirota,male,20,0,0,8.05,0 -3,Mr,Chang Chip,male,32,0,0,56.4958,1 -1,Mr,Pierre Marechal,male,29,0,0,29.7,1 -3,Mr,Ilmari Rudolf Alhomaki,male,20,0,0,7.925,0 -2,Mr,Thomas Charles Mudd,male,16,0,0,10.5,0 -1,Miss,Augusta Serepeca,female,30,0,0,31,1 -3,Mr,Peter L Lemberopolous,male,34.5,0,0,6.4375,0 -3,Mr,Jeso Culumovic,male,17,0,0,8.6625,0 -3,Mr,Anthony Abbing,male,42,0,0,7.55,0 -3,Mr,Douglas Bullen Sage,male,18,8,2,69.55,0 -3,Mr,Marin Markoff,male,35,0,0,7.8958,0 -2,Rev,John Harper,male,28,0,1,33,0 -1,Mrs,Samuel L (Edwiga Grabowska) Goldenberg,female,40,1,0,89.1042,1 -3,Master,Sigvard Harald Elias Andersson,male,4,4,2,31.275,0 -3,Mr,Johan Svensson,male,74,0,0,7.775,0 -3,Miss,Nourelain Boulos,female,9,1,1,15.2458,0 -1,Miss,Mary Conover Lines,female,16,0,1,39.4,1 -2,Mrs,Ernest Courtenay (Lilian Hughes) Carter,female,44,1,0,26,0 -3,Mrs,Sam (Leah Rosen) Aks,female,18,0,1,9.35,1 -1,Mrs,George Dennick (Mary Hitchcock) Wick,female,45,1,1,164.8667,1 -1,Mr,Peter Denis Daly,male,51,0,0,26.55,1 -3,Mrs,Solomon (Latifa Qurban) Baclini,female,24,0,3,19.2583,1 -3,Mr,Raihed Razi,male,30,0,0,7.2292,0 -3,Mr,Claus Peter Hansen,male,41,2,0,14.1083,0 -2,Mr,Frederick Edward Giles,male,21,1,0,11.5,0 -1,Mrs,Frederick Joel (Margaret Welles Barron) Swift,female,48,0,0,25.9292,1 -3,Miss,Dorothy Edith Sage,female,14,8,2,69.55,0 -2,Mr,John William Gill,male,24,0,0,13,0 -2,Mrs,(Karolina) Bystrom,female,42,0,0,13,1 -2,Miss,Asuncion Duran y More,female,27,1,0,13.8583,1 -1,Mr,Washington Augustus II Roebling,male,31,0,0,50.4958,0 -3,Mr,Philemon van Melkebeke,male,23,0,0,9.5,0 -3,Master,Harold Theodor Johnson,male,4,1,1,11.1333,1 -3,Mr,Cerin Balkic,male,26,0,0,7.8958,0 -1,Mrs,Richard Leonard (Sallie Monypeny) Beckwith,female,47,1,1,52.5542,1 -1,Mr,Frans Olof Carlsson,male,33,0,0,5,0 -3,Mr,Victor Vander Cruyssen,male,47,0,0,9,0 -2,Mrs,Samuel (Hannah Wizosky) Abelson,female,28,1,0,24,1 -3,Miss,Adele Kiamie Najib,female,15,0,0,7.225,1 -3,Mr,Alfred Ossian Gustafsson,male,20,0,0,9.8458,0 -3,Mr,Nedelio Petroff,male,19,0,0,7.8958,0 -3,Mr,Kristo Laleff,male,23,0,0,7.8958,0 -1,Mrs,Thomas Jr (Lily Alexenia Wilson) Potter,female,56,0,1,83.1583,1 -2,Mrs,William (Imanita Parrish Hall) Shelley,female,25,0,1,26,1 -3,Mr,Johann Markun,male,33,0,0,7.8958,0 -3,Miss,Gerda Ulrika Dahlberg,female,22,0,0,10.5167,0 -2,Mr,Frederick James Banfield,male,28,0,0,10.5,0 -3,Mr,Henry Jr Sutehall,male,25,0,0,7.05,0 -3,Mrs,William (Margaret Norton) Rice,female,39,0,5,29.125,0 -2,Rev,Juozas Montvila,male,27,0,0,13,0 -1,Miss,Margaret Edith Graham,female,19,0,0,30,1 -3,Miss,Catherine Helen Johnston,female,7,1,2,23.45,0 -1,Mr,Karl Howell Behr,male,26,0,0,30,1 -3,Mr,Patrick Dooley,male,32,0,0,7.75,0 \ No newline at end of file diff --git a/public/models/01-regression/auto-mpg/0/lr-model-0.json b/public/models/01-regression/auto-mpg/0/lr-model-0.json deleted file mode 100644 index f631ca3..0000000 --- a/public/models/01-regression/auto-mpg/0/lr-model-0.json +++ /dev/null @@ -1 +0,0 @@ -{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_13","layers":[{"class_name":"Dense","config":{"units":64,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense1","trainable":true,"batch_input_shape":[null,6],"dtype":"float32"}},{"class_name":"Dense","config":{"units":64,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense2","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense3","trainable":true}}]},"keras_version":"tfjs-layers 4.21.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.21.0","convertedBy":null,"weightsManifest":[{"paths":["./lr-model-0.weights.bin"],"weights":[{"name":"dense_Dense1/kernel","shape":[6,64],"dtype":"float32"},{"name":"dense_Dense1/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense2/kernel","shape":[64,64],"dtype":"float32"},{"name":"dense_Dense2/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense3/kernel","shape":[64,1],"dtype":"float32"},{"name":"dense_Dense3/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/01-regression/auto-mpg/0/lr-model-0.weights.bin b/public/models/01-regression/auto-mpg/0/lr-model-0.weights.bin deleted file mode 100644 index 35b8381..0000000 Binary files a/public/models/01-regression/auto-mpg/0/lr-model-0.weights.bin and /dev/null differ diff --git a/public/models/01-regression/boston-housing/0/lr-model-0.json b/public/models/01-regression/boston-housing/0/lr-model-0.json deleted file mode 100644 index 4359277..0000000 --- a/public/models/01-regression/boston-housing/0/lr-model-0.json +++ /dev/null @@ -1 +0,0 @@ -{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_28","layers":[{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense15","trainable":true,"batch_input_shape":[null,1],"dtype":"float32"}},{"class_name":"Dense","config":{"units":20,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense16","trainable":true}},{"class_name":"Dense","config":{"units":20,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense17","trainable":true}},{"class_name":"Dense","config":{"units":20,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense18","trainable":true}},{"class_name":"Dense","config":{"units":20,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense19","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense20","trainable":true}}]},"keras_version":"tfjs-layers 3.21.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v3.21.0","convertedBy":null,"weightsManifest":[{"paths":["./lr-model-0.weights.bin"],"weights":[{"name":"dense_Dense15/kernel","shape":[1,1],"dtype":"float32"},{"name":"dense_Dense15/bias","shape":[1],"dtype":"float32"},{"name":"dense_Dense16/kernel","shape":[1,20],"dtype":"float32"},{"name":"dense_Dense16/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense17/kernel","shape":[20,20],"dtype":"float32"},{"name":"dense_Dense17/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense18/kernel","shape":[20,20],"dtype":"float32"},{"name":"dense_Dense18/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense19/kernel","shape":[20,20],"dtype":"float32"},{"name":"dense_Dense19/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense20/kernel","shape":[20,1],"dtype":"float32"},{"name":"dense_Dense20/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/01-regression/boston-housing/0/lr-model-0.weights.bin b/public/models/01-regression/boston-housing/0/lr-model-0.weights.bin deleted file mode 100644 index 9293a03..0000000 Binary files a/public/models/01-regression/boston-housing/0/lr-model-0.weights.bin and /dev/null differ diff --git a/public/models/01-regression/breast-cancer/0/lr-model-0.json b/public/models/01-regression/breast-cancer/0/lr-model-0.json deleted file mode 100644 index 693ae6b..0000000 --- a/public/models/01-regression/breast-cancer/0/lr-model-0.json +++ /dev/null @@ -1 +0,0 @@ -{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_13","layers":[{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense1","trainable":true,"batch_input_shape":[null,1],"dtype":"float32"}},{"class_name":"Dense","config":{"units":10,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense2","trainable":true}},{"class_name":"Dense","config":{"units":20,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense3","trainable":true}},{"class_name":"Dense","config":{"units":20,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense4","trainable":true}},{"class_name":"Dense","config":{"units":20,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense5","trainable":true}},{"class_name":"Dense","config":{"units":20,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense6","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense7","trainable":true}}]},"keras_version":"tfjs-layers 3.21.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v3.21.0","convertedBy":null,"weightsManifest":[{"paths":["./lr-model-0.weights.bin"],"weights":[{"name":"dense_Dense1/kernel","shape":[1,1],"dtype":"float32"},{"name":"dense_Dense1/bias","shape":[1],"dtype":"float32"},{"name":"dense_Dense2/kernel","shape":[1,10],"dtype":"float32"},{"name":"dense_Dense2/bias","shape":[10],"dtype":"float32"},{"name":"dense_Dense3/kernel","shape":[10,20],"dtype":"float32"},{"name":"dense_Dense3/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense4/kernel","shape":[20,20],"dtype":"float32"},{"name":"dense_Dense4/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense5/kernel","shape":[20,20],"dtype":"float32"},{"name":"dense_Dense5/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense6/kernel","shape":[20,20],"dtype":"float32"},{"name":"dense_Dense6/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense7/kernel","shape":[20,1],"dtype":"float32"},{"name":"dense_Dense7/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/01-regression/breast-cancer/0/lr-model-0.weights.bin b/public/models/01-regression/breast-cancer/0/lr-model-0.weights.bin deleted file mode 100644 index a1f6e5c..0000000 Binary files a/public/models/01-regression/breast-cancer/0/lr-model-0.weights.bin and /dev/null differ diff --git a/public/models/01-regression/housing-dataset/0/lr-model-0.json b/public/models/01-regression/housing-dataset/0/lr-model-0.json deleted file mode 100644 index 91c5450..0000000 --- a/public/models/01-regression/housing-dataset/0/lr-model-0.json +++ /dev/null @@ -1 +0,0 @@ -{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_11","layers":[{"class_name":"Dense","config":{"units":64,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense1","trainable":true,"batch_input_shape":[null,12],"dtype":"float32"}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense2","trainable":true}}]},"keras_version":"tfjs-layers 4.21.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.21.0","convertedBy":null,"weightsManifest":[{"paths":["./lr-model-0.weights.bin"],"weights":[{"name":"dense_Dense1/kernel","shape":[12,64],"dtype":"float32"},{"name":"dense_Dense1/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense2/kernel","shape":[64,1],"dtype":"float32"},{"name":"dense_Dense2/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/01-regression/housing-dataset/0/lr-model-0.weights.bin b/public/models/01-regression/housing-dataset/0/lr-model-0.weights.bin deleted file mode 100644 index 7281d53..0000000 Binary files a/public/models/01-regression/housing-dataset/0/lr-model-0.weights.bin and /dev/null differ diff --git a/public/models/01-regression/salary/0/lr-model-0.json b/public/models/01-regression/salary/0/lr-model-0.json deleted file mode 100644 index a868875..0000000 --- a/public/models/01-regression/salary/0/lr-model-0.json +++ /dev/null @@ -1 +0,0 @@ -{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_10","layers":[{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense1","trainable":true,"batch_input_shape":[null,1],"dtype":"float32"}},{"class_name":"Dense","config":{"units":10,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense2","trainable":true}},{"class_name":"Dense","config":{"units":20,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense3","trainable":true}},{"class_name":"Dense","config":{"units":20,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense4","trainable":true}},{"class_name":"Dense","config":{"units":20,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense5","trainable":true}},{"class_name":"Dense","config":{"units":20,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense6","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense7","trainable":true}}]},"keras_version":"tfjs-layers 3.21.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v3.21.0","convertedBy":null,"weightsManifest":[{"paths":["./lr-model-0.weights.bin"],"weights":[{"name":"dense_Dense1/kernel","shape":[1,1],"dtype":"float32"},{"name":"dense_Dense1/bias","shape":[1],"dtype":"float32"},{"name":"dense_Dense2/kernel","shape":[1,10],"dtype":"float32"},{"name":"dense_Dense2/bias","shape":[10],"dtype":"float32"},{"name":"dense_Dense3/kernel","shape":[10,20],"dtype":"float32"},{"name":"dense_Dense3/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense4/kernel","shape":[20,20],"dtype":"float32"},{"name":"dense_Dense4/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense5/kernel","shape":[20,20],"dtype":"float32"},{"name":"dense_Dense5/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense6/kernel","shape":[20,20],"dtype":"float32"},{"name":"dense_Dense6/bias","shape":[20],"dtype":"float32"},{"name":"dense_Dense7/kernel","shape":[20,1],"dtype":"float32"},{"name":"dense_Dense7/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/01-regression/salary/0/lr-model-0.weights.bin b/public/models/01-regression/salary/0/lr-model-0.weights.bin deleted file mode 100644 index 55e8ae1..0000000 Binary files a/public/models/01-regression/salary/0/lr-model-0.weights.bin and /dev/null differ diff --git a/public/models/01-regression/salary/2/lr-model-2.json b/public/models/01-regression/salary/2/lr-model-2.json deleted file mode 100644 index af5c128..0000000 --- a/public/models/01-regression/salary/2/lr-model-2.json +++ /dev/null @@ -1 +0,0 @@ -{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_148","layers":[{"class_name":"Dense","config":{"units":32,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense12","trainable":true,"batch_input_shape":[null,1],"dtype":"float32"}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense13","trainable":true}}]},"keras_version":"tfjs-layers 4.21.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.21.0","convertedBy":null,"weightsManifest":[{"paths":["./lr-model-2.weights.bin"],"weights":[{"name":"dense_Dense12/kernel","shape":[1,32],"dtype":"float32"},{"name":"dense_Dense12/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense13/kernel","shape":[32,1],"dtype":"float32"},{"name":"dense_Dense13/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/01-regression/salary/2/lr-model-2.weights.bin b/public/models/01-regression/salary/2/lr-model-2.weights.bin deleted file mode 100644 index 2c6fe14..0000000 Binary files a/public/models/01-regression/salary/2/lr-model-2.weights.bin and /dev/null differ diff --git a/public/models/01-regression/student-performance/0/lr-model-mat.json b/public/models/01-regression/student-performance/0/lr-model-mat.json deleted file mode 100644 index 70d2224..0000000 --- a/public/models/01-regression/student-performance/0/lr-model-mat.json +++ /dev/null @@ -1 +0,0 @@ -{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_143","layers":[{"class_name":"Dense","config":{"units":64,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense34","trainable":true,"batch_input_shape":[null,30],"dtype":"float32"}},{"class_name":"Dense","config":{"units":64,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense35","trainable":true}},{"class_name":"Dense","config":{"units":64,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense36","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense37","trainable":true}}]},"keras_version":"tfjs-layers 4.21.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.21.0","convertedBy":null,"weightsManifest":[{"paths":["./lr-model-mat.weights.bin"],"weights":[{"name":"dense_Dense34/kernel","shape":[30,64],"dtype":"float32"},{"name":"dense_Dense34/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense35/kernel","shape":[64,64],"dtype":"float32"},{"name":"dense_Dense35/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense36/kernel","shape":[64,64],"dtype":"float32"},{"name":"dense_Dense36/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense37/kernel","shape":[64,1],"dtype":"float32"},{"name":"dense_Dense37/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/01-regression/student-performance/0/lr-model-mat.weights.bin b/public/models/01-regression/student-performance/0/lr-model-mat.weights.bin deleted file mode 100644 index 84ff287..0000000 Binary files a/public/models/01-regression/student-performance/0/lr-model-mat.weights.bin and /dev/null differ diff --git a/public/models/01-regression/student-performance/0/lr-model-por.json b/public/models/01-regression/student-performance/0/lr-model-por.json deleted file mode 100644 index 7bde47a..0000000 --- a/public/models/01-regression/student-performance/0/lr-model-por.json +++ /dev/null @@ -1 +0,0 @@ -{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_30","layers":[{"class_name":"Dense","config":{"units":64,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense1","trainable":true,"batch_input_shape":[null,30],"dtype":"float32"}},{"class_name":"Dense","config":{"units":64,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense2","trainable":true}},{"class_name":"Dense","config":{"units":64,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense3","trainable":true}},{"class_name":"Dense","config":{"units":64,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense4","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense5","trainable":true}}]},"keras_version":"tfjs-layers 4.21.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.21.0","convertedBy":null,"weightsManifest":[{"paths":["./lr-model-por.weights.bin"],"weights":[{"name":"dense_Dense1/kernel","shape":[30,64],"dtype":"float32"},{"name":"dense_Dense1/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense2/kernel","shape":[64,64],"dtype":"float32"},{"name":"dense_Dense2/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense3/kernel","shape":[64,64],"dtype":"float32"},{"name":"dense_Dense3/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense4/kernel","shape":[64,64],"dtype":"float32"},{"name":"dense_Dense4/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense5/kernel","shape":[64,1],"dtype":"float32"},{"name":"dense_Dense5/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/01-regression/student-performance/0/lr-model-por.weights.bin b/public/models/01-regression/student-performance/0/lr-model-por.weights.bin deleted file mode 100644 index e97bdf0..0000000 Binary files a/public/models/01-regression/student-performance/0/lr-model-por.weights.bin and /dev/null differ diff --git a/public/models/01-regression/wine/0/lr-model-red.json b/public/models/01-regression/wine/0/lr-model-red.json deleted file mode 100644 index 6490c4b..0000000 --- a/public/models/01-regression/wine/0/lr-model-red.json +++ /dev/null @@ -1 +0,0 @@ -{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_16","layers":[{"class_name":"Dense","config":{"units":32,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense5","trainable":true,"batch_input_shape":[null,11],"dtype":"float32"}},{"class_name":"Dense","config":{"units":32,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense6","trainable":true}},{"class_name":"Dense","config":{"units":16,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense7","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense8","trainable":true}}]},"keras_version":"tfjs-layers 4.21.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.21.0","convertedBy":null,"weightsManifest":[{"paths":["./lr-model-red.weights.bin"],"weights":[{"name":"dense_Dense5/kernel","shape":[11,32],"dtype":"float32"},{"name":"dense_Dense5/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense6/kernel","shape":[32,32],"dtype":"float32"},{"name":"dense_Dense6/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense7/kernel","shape":[32,16],"dtype":"float32"},{"name":"dense_Dense7/bias","shape":[16],"dtype":"float32"},{"name":"dense_Dense8/kernel","shape":[16,1],"dtype":"float32"},{"name":"dense_Dense8/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/01-regression/wine/0/lr-model-red.weights.bin b/public/models/01-regression/wine/0/lr-model-red.weights.bin deleted file mode 100644 index aa8e919..0000000 Binary files a/public/models/01-regression/wine/0/lr-model-red.weights.bin and /dev/null differ diff --git a/public/models/01-regression/wine/0/lr-model-white.json b/public/models/01-regression/wine/0/lr-model-white.json deleted file mode 100644 index ec95953..0000000 --- a/public/models/01-regression/wine/0/lr-model-white.json +++ /dev/null @@ -1 +0,0 @@ -{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_17","layers":[{"class_name":"Dense","config":{"units":64,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense1","trainable":true,"batch_input_shape":[null,11],"dtype":"float32"}},{"class_name":"Dense","config":{"units":32,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense2","trainable":true}},{"class_name":"Dense","config":{"units":16,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense3","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense4","trainable":true}}]},"keras_version":"tfjs-layers 4.21.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.21.0","convertedBy":null,"weightsManifest":[{"paths":["./lr-model-white.weights.bin"],"weights":[{"name":"dense_Dense1/kernel","shape":[11,64],"dtype":"float32"},{"name":"dense_Dense1/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense2/kernel","shape":[64,32],"dtype":"float32"},{"name":"dense_Dense2/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense3/kernel","shape":[32,16],"dtype":"float32"},{"name":"dense_Dense3/bias","shape":[16],"dtype":"float32"},{"name":"dense_Dense4/kernel","shape":[16,1],"dtype":"float32"},{"name":"dense_Dense4/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/01-regression/wine/0/lr-model-white.weights.bin b/public/models/01-regression/wine/0/lr-model-white.weights.bin deleted file mode 100644 index 11d0f7f..0000000 Binary files a/public/models/01-regression/wine/0/lr-model-white.weights.bin and /dev/null differ diff --git a/public/models/03-image-classification/mnist/mymodel.json b/public/models/03-image-classification/mnist/mymodel.json deleted file mode 100644 index 9d06621..0000000 --- a/public/models/03-image-classification/mnist/mymodel.json +++ /dev/null @@ -1,233 +0,0 @@ -{ - "modelTopology": { - "class_name": "Sequential", - "config": { - "name": "sequential_4", - "layers": [ - { - "class_name": "Conv2D", - "config": { - "filters": 10, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1, - "mode": "fan_in", - "distribution": "normal", - "seed": null - } - }, - "kernel_regularizer": null, - "kernel_constraint": null, - "kernel_size": [ - 5, - 5 - ], - "strides": [ - 1, - 1 - ], - "padding": "valid", - "data_format": "channels_last", - "dilation_rate": [ - 1, - 1 - ], - "activation": "sigmoid", - "use_bias": true, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "bias_regularizer": null, - "activity_regularizer": null, - "bias_constraint": null, - "name": "conv2d_Conv2D7", - "trainable": true, - "batch_input_shape": [ - null, - 28, - 28, - 1 - ], - "dtype": "float32" - } - }, - { - "class_name": "MaxPooling2D", - "config": { - "pool_size": [ - 2, - 2 - ], - "padding": "valid", - "strides": [ - 2, - 2 - ], - "data_format": "channels_last", - "name": "max_pooling2d_MaxPooling2D7", - "trainable": true - } - }, - { - "class_name": "Conv2D", - "config": { - "filters": 16, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1, - "mode": "fan_in", - "distribution": "normal", - "seed": null - } - }, - "kernel_regularizer": null, - "kernel_constraint": null, - "kernel_size": [ - 5, - 5 - ], - "strides": [ - 1, - 1 - ], - "padding": "valid", - "data_format": "channels_last", - "dilation_rate": [ - 1, - 1 - ], - "activation": "sigmoid", - "use_bias": true, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "bias_regularizer": null, - "activity_regularizer": null, - "bias_constraint": null, - "name": "conv2d_Conv2D8", - "trainable": true - } - }, - { - "class_name": "MaxPooling2D", - "config": { - "pool_size": [ - 2, - 2 - ], - "padding": "valid", - "strides": [ - 2, - 2 - ], - "data_format": "channels_last", - "name": "max_pooling2d_MaxPooling2D8", - "trainable": true - } - }, - { - "class_name": "Flatten", - "config": { - "name": "flatten_Flatten4", - "trainable": true - } - }, - { - "class_name": "Dense", - "config": { - "units": 10, - "activation": "softmax", - "use_bias": true, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1, - "mode": "fan_in", - "distribution": "normal", - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null, - "name": "dense_Dense4", - "trainable": true - } - } - ] - }, - "keras_version": "tfjs-layers 3.19.0", - "backend": "tensor_flow.js" - }, - "format": "layers-model", - "generatedBy": "TensorFlow.js tfjs-layers v3.19.0", - "convertedBy": null, - "weightsManifest": [ - { - "paths": [ - "./mymodel.weights.bin" - ], - "weights": [ - { - "name": "conv2d_Conv2D7/kernel", - "shape": [ - 5, - 5, - 1, - 10 - ], - "dtype": "float32" - }, - { - "name": "conv2d_Conv2D7/bias", - "shape": [ - 10 - ], - "dtype": "float32" - }, - { - "name": "conv2d_Conv2D8/kernel", - "shape": [ - 5, - 5, - 10, - 16 - ], - "dtype": "float32" - }, - { - "name": "conv2d_Conv2D8/bias", - "shape": [ - 16 - ], - "dtype": "float32" - }, - { - "name": "dense_Dense4/kernel", - "shape": [ - 256, - 10 - ], - "dtype": "float32" - }, - { - "name": "dense_Dense4/bias", - "shape": [ - 10 - ], - "dtype": "float32" - } - ] - } - ] -} diff --git a/public/models/03-image-classification/mnist/mymodel.weights.bin b/public/models/03-image-classification/mnist/mymodel.weights.bin deleted file mode 100644 index 632c79c..0000000 Binary files a/public/models/03-image-classification/mnist/mymodel.weights.bin and /dev/null differ diff --git a/public/models/03-image-classification/mnist/mymodel2.json b/public/models/03-image-classification/mnist/mymodel2.json deleted file mode 100644 index 7dfb9d0..0000000 --- a/public/models/03-image-classification/mnist/mymodel2.json +++ /dev/null @@ -1 +0,0 @@ -{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_1","layers":[{"class_name":"Conv2D","config":{"filters":10,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_in","distribution":"normal","seed":null}},"kernel_regularizer":null,"kernel_constraint":null,"kernel_size":[5,5],"strides":[1,1],"padding":"valid","data_format":"channels_last","dilation_rate":[1,1],"activation":"sigmoid","use_bias":true,"bias_initializer":{"class_name":"Zeros","config":{}},"bias_regularizer":null,"activity_regularizer":null,"bias_constraint":null,"name":"conv2d_Conv2D1","trainable":true,"batch_input_shape":[null,28,28,1],"dtype":"float32"}},{"class_name":"MaxPooling2D","config":{"pool_size":[2,2],"padding":"valid","strides":[2,2],"data_format":"channels_last","name":"max_pooling2d_MaxPooling2D1","trainable":true}},{"class_name":"Conv2D","config":{"filters":16,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_in","distribution":"normal","seed":null}},"kernel_regularizer":null,"kernel_constraint":null,"kernel_size":[5,5],"strides":[1,1],"padding":"valid","data_format":"channels_last","dilation_rate":[1,1],"activation":"relu","use_bias":true,"bias_initializer":{"class_name":"Zeros","config":{}},"bias_regularizer":null,"activity_regularizer":null,"bias_constraint":null,"name":"conv2d_Conv2D2","trainable":true}},{"class_name":"MaxPooling2D","config":{"pool_size":[2,2],"padding":"valid","strides":[2,2],"data_format":"channels_last","name":"max_pooling2d_MaxPooling2D2","trainable":true}},{"class_name":"Flatten","config":{"name":"flatten_Flatten1","trainable":true}},{"class_name":"Dense","config":{"units":10,"activation":"softmax","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_in","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense1","trainable":true}}]},"keras_version":"tfjs-layers 3.14.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v3.14.0","convertedBy":null,"weightsManifest":[{"paths":["./mymodel.weights.bin"],"weights":[{"name":"conv2d_Conv2D1/kernel","shape":[5,5,1,10],"dtype":"float32"},{"name":"conv2d_Conv2D1/bias","shape":[10],"dtype":"float32"},{"name":"conv2d_Conv2D2/kernel","shape":[5,5,10,16],"dtype":"float32"},{"name":"conv2d_Conv2D2/bias","shape":[16],"dtype":"float32"},{"name":"dense_Dense1/kernel","shape":[256,10],"dtype":"float32"},{"name":"dense_Dense1/bias","shape":[10],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/03-image-classification/model-mnist/EcKX-group4-shard1of1.weights.bin b/public/models/03-image-classification/model-mnist/EcKX-group4-shard1of1.weights.bin deleted file mode 100644 index 901ede8..0000000 Binary files a/public/models/03-image-classification/model-mnist/EcKX-group4-shard1of1.weights.bin and /dev/null differ diff --git a/public/models/03-image-classification/model-mnist/RaxT-group3-shard1of1.weights.bin b/public/models/03-image-classification/model-mnist/RaxT-group3-shard1of1.weights.bin deleted file mode 100644 index 5334568..0000000 Binary files a/public/models/03-image-classification/model-mnist/RaxT-group3-shard1of1.weights.bin and /dev/null differ diff --git a/public/models/03-image-classification/model-mnist/TpCA-group2-shard1of1.weights.bin b/public/models/03-image-classification/model-mnist/TpCA-group2-shard1of1.weights.bin deleted file mode 100644 index 78ef885..0000000 Binary files a/public/models/03-image-classification/model-mnist/TpCA-group2-shard1of1.weights.bin and /dev/null differ diff --git a/public/models/03-image-classification/model-mnist/incs-group1-shard1of1.weights.bin b/public/models/03-image-classification/model-mnist/incs-group1-shard1of1.weights.bin deleted file mode 100644 index 003c3d3..0000000 Binary files a/public/models/03-image-classification/model-mnist/incs-group1-shard1of1.weights.bin and /dev/null differ diff --git a/public/models/03-image-classification/model-mnist/model.json b/public/models/03-image-classification/model-mnist/model.json deleted file mode 100644 index 527d618..0000000 --- a/public/models/03-image-classification/model-mnist/model.json +++ /dev/null @@ -1,322 +0,0 @@ -{ - "modelTopology": { - "keras_version": "2.1.4", - "backend": "tensorflow", - "model_config": { - "class_name": "Sequential", - "config": [ - { - "class_name": "Conv2D", - "config": { - "name": "conv2d_1", - "trainable": true, - "batch_input_shape": [ - null, - 28, - 28, - 1 - ], - "dtype": "float32", - "filters": 32, - "kernel_size": [ - 5, - 5 - ], - "strides": [ - 1, - 1 - ], - "padding": "valid", - "data_format": "channels_last", - "dilation_rate": [ - 1, - 1 - ], - "activation": "relu", - "use_bias": true, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1.0, - "mode": "fan_avg", - "distribution": "uniform", - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null - } - }, - { - "class_name": "MaxPooling2D", - "config": { - "name": "max_pooling2d_1", - "trainable": true, - "pool_size": [ - 2, - 2 - ], - "padding": "valid", - "strides": [ - 2, - 2 - ], - "data_format": "channels_last" - } - }, - { - "class_name": "Conv2D", - "config": { - "name": "conv2d_2", - "trainable": true, - "filters": 32, - "kernel_size": [ - 3, - 3 - ], - "strides": [ - 1, - 1 - ], - "padding": "valid", - "data_format": "channels_last", - "dilation_rate": [ - 1, - 1 - ], - "activation": "relu", - "use_bias": true, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1.0, - "mode": "fan_avg", - "distribution": "uniform", - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null - } - }, - { - "class_name": "MaxPooling2D", - "config": { - "name": "max_pooling2d_2", - "trainable": true, - "pool_size": [ - 2, - 2 - ], - "padding": "valid", - "strides": [ - 2, - 2 - ], - "data_format": "channels_last" - } - }, - { - "class_name": "Dropout", - "config": { - "name": "dropout_1", - "trainable": true, - "rate": 0.2, - "noise_shape": null, - "seed": null - } - }, - { - "class_name": "Flatten", - "config": { - "name": "flatten_1", - "trainable": true - } - }, - { - "class_name": "Dense", - "config": { - "name": "dense_1", - "trainable": true, - "units": 128, - "activation": "relu", - "use_bias": true, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1.0, - "mode": "fan_avg", - "distribution": "uniform", - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null - } - }, - { - "class_name": "Dense", - "config": { - "name": "dense_2", - "trainable": true, - "units": 10, - "activation": "softmax", - "use_bias": true, - "kernel_initializer": { - "class_name": "VarianceScaling", - "config": { - "scale": 1.0, - "mode": "fan_avg", - "distribution": "uniform", - "seed": null - } - }, - "bias_initializer": { - "class_name": "Zeros", - "config": {} - }, - "kernel_regularizer": null, - "bias_regularizer": null, - "activity_regularizer": null, - "kernel_constraint": null, - "bias_constraint": null - } - } - ] - }, - "training_config": { - "optimizer_config": { - "class_name": "Adam", - "config": { - "lr": 0.0010000000474974513, - "beta_1": 0.8999999761581421, - "beta_2": 0.9990000128746033, - "decay": 0.0, - "epsilon": 1e-07, - "amsgrad": false - } - }, - "loss": "categorical_crossentropy", - "metrics": [ - "accuracy" - ], - "sample_weight_mode": null, - "loss_weights": null - } - }, - "weightsManifest": [ - { - "paths": [ - "./incs-group1-shard1of1.weights.bin" - ], - "weights": [ - { - "name": "conv2d_1/kernel", - "shape": [ - 5, - 5, - 1, - 32 - ], - "dtype": "float32" - }, - { - "name": "conv2d_1/bias", - "shape": [ - 32 - ], - "dtype": "float32" - } - ] - }, - { - "paths": [ - "./TpCA-group2-shard1of1.weights.bin" - ], - "weights": [ - { - "name": "conv2d_2/kernel", - "shape": [ - 3, - 3, - 32, - 32 - ], - "dtype": "float32" - }, - { - "name": "conv2d_2/bias", - "shape": [ - 32 - ], - "dtype": "float32" - } - ] - }, - { - "paths": [ - "./RaxT-group3-shard1of1.weights.bin" - ], - "weights": [ - { - "name": "dense_1/kernel", - "shape": [ - 800, - 128 - ], - "dtype": "float32" - }, - { - "name": "dense_1/bias", - "shape": [ - 128 - ], - "dtype": "float32" - } - ] - }, - { - "paths": [ - "./EcKX-group4-shard1of1.weights.bin" - ], - "weights": [ - { - "name": "dense_2/kernel", - "shape": [ - 128, - 10 - ], - "dtype": "float32" - }, - { - "name": "dense_2/bias", - "shape": [ - 10 - ], - "dtype": "float32" - } - ] - } - ] -} \ No newline at end of file diff --git a/public/n4l/airline-passengers.n4l/data/airline-passengers.csv b/public/n4l/airline-passengers.n4l/data/airline-passengers.csv new file mode 100644 index 0000000..0ba6bd0 --- /dev/null +++ b/public/n4l/airline-passengers.n4l/data/airline-passengers.csv @@ -0,0 +1,145 @@ +Month,Passengers +1949-01,112 +1949-02,118 +1949-03,132 +1949-04,129 +1949-05,121 +1949-06,135 +1949-07,148 +1949-08,148 +1949-09,136 +1949-10,119 +1949-11,104 +1949-12,118 +1950-01,115 +1950-02,126 +1950-03,141 +1950-04,135 +1950-05,125 +1950-06,149 +1950-07,170 +1950-08,170 +1950-09,158 +1950-10,133 +1950-11,114 +1950-12,140 +1951-01,145 +1951-02,150 +1951-03,178 +1951-04,163 +1951-05,172 +1951-06,178 +1951-07,199 +1951-08,199 +1951-09,184 +1951-10,162 +1951-11,146 +1951-12,166 +1952-01,171 +1952-02,180 +1952-03,193 +1952-04,181 +1952-05,183 +1952-06,218 +1952-07,230 +1952-08,242 +1952-09,209 +1952-10,191 +1952-11,172 +1952-12,194 +1953-01,196 +1953-02,196 +1953-03,236 +1953-04,235 +1953-05,229 +1953-06,243 +1953-07,264 +1953-08,272 +1953-09,237 +1953-10,211 +1953-11,180 +1953-12,201 +1954-01,204 +1954-02,188 +1954-03,235 +1954-04,227 +1954-05,234 +1954-06,264 +1954-07,302 +1954-08,293 +1954-09,259 +1954-10,229 +1954-11,203 +1954-12,229 +1955-01,242 +1955-02,233 +1955-03,267 +1955-04,269 +1955-05,270 +1955-06,315 +1955-07,364 +1955-08,347 +1955-09,312 +1955-10,274 +1955-11,237 +1955-12,278 +1956-01,284 +1956-02,277 +1956-03,317 +1956-04,313 +1956-05,318 +1956-06,374 +1956-07,413 +1956-08,405 +1956-09,355 +1956-10,306 +1956-11,271 +1956-12,306 +1957-01,315 +1957-02,301 +1957-03,356 +1957-04,348 +1957-05,355 +1957-06,422 +1957-07,465 +1957-08,467 +1957-09,404 +1957-10,347 +1957-11,305 +1957-12,336 +1958-01,340 +1958-02,318 +1958-03,362 +1958-04,348 +1958-05,363 +1958-06,435 +1958-07,491 +1958-08,505 +1958-09,404 +1958-10,359 +1958-11,310 +1958-12,337 +1959-01,360 +1959-02,342 +1959-03,406 +1959-04,396 +1959-05,420 +1959-06,472 +1959-07,548 +1959-08,559 +1959-09,463 +1959-10,407 +1959-11,362 +1959-12,405 +1960-01,417 +1960-02,391 +1960-03,419 +1960-04,461 +1960-05,472 +1960-06,535 +1960-07,622 +1960-08,606 +1960-09,508 +1960-10,461 +1960-11,390 +1960-12,432 diff --git a/public/n4l/airline-passengers.n4l/locales/en.json b/public/n4l/airline-passengers.n4l/locales/en.json new file mode 100644 index 0000000..6a4f325 --- /dev/null +++ b/public/n4l/airline-passengers.n4l/locales/en.json @@ -0,0 +1,40 @@ +{ + "columns": { + "Month": "Month", + "Passengers": "Passengers" + }, + "tasks": { + "time-series": { + "name": "Airline passengers", + "summary": "International airline passengers each month, from 1949 to 1960: more every year, and even more in summer.", + "description": { + "text": [ + "The classic Box and Jenkins series: total international airline passengers each month, in thousands, from January 1949 to December 1960 (144 months). Almost every time series forecasting method is explained with it.", + "It has a trend, because more people fly every year (in 1960, almost four times as many as in 1949), and a 12-month seasonality: the peaks are in July and August and the quietest months are in winter. The peaks also grow with the series (the seasonality is multiplicative), which is why its logarithm is often forecast instead." + ], + "sections": [ + { + "title": "Variables", + "items": [ + "Month: the month (year-month).", + "Passengers: the passengers that month, in thousands. This is what is forecast." + ] + }, + { + "title": "Pre-trained model", + "items": [ + "A network with one Dense layer of 32 neurons that sees the previous 24 months. On the test part (August 1958 to December 1960, which it did not see while training) it is off by {{test_mae, number(maximumFractionDigits: 1)}} thousand passengers on average one step ahead and by {{test_recursive_mae, number(maximumFractionDigits: 1)}} forecasting the whole test part at once; repeating the value one year earlier is off by {{test_seasonal_mae, number(maximumFractionDigits: 1)}}." + ] + }, + { + "title": "References", + "items": [ + "AirPassengers in the R documentation, with its original source.", + "The CSV, from the jbrownlee/Datasets repository." + ] + } + ] + } + } + } +} diff --git a/public/n4l/airline-passengers.n4l/locales/es.json b/public/n4l/airline-passengers.n4l/locales/es.json new file mode 100644 index 0000000..ab9a5ea --- /dev/null +++ b/public/n4l/airline-passengers.n4l/locales/es.json @@ -0,0 +1,40 @@ +{ + "columns": { + "Month": "Mes", + "Passengers": "Pasajeros" + }, + "tasks": { + "time-series": { + "name": "Pasajeros de avión", + "summary": "Los pasajeros de líneas aéreas internacionales de cada mes, de 1949 a 1960: cada año hay más, y en verano más todavía.", + "description": { + "text": [ + "La serie clásica de Box y Jenkins: el total de pasajeros de líneas aéreas internacionales de cada mes, en miles, de enero de 1949 a diciembre de 1960 (144 meses). Con ella se explican casi todos los métodos de predicción de series temporales.", + "Tiene tendencia, porque cada año vuela más gente (en 1960, casi cuatro veces más que en 1949), y estacionalidad de 12 meses: los picos son en julio y agosto, y los meses más flojos, en invierno. Además, los picos crecen con la serie (la estacionalidad es multiplicativa), y por eso a menudo se predice su logaritmo." + ], + "sections": [ + { + "title": "Variables", + "items": [ + "Month: el mes (año-mes).", + "Passengers: los pasajeros de ese mes, en miles. Es lo que se predice." + ] + }, + { + "title": "Modelo ya entrenado", + "items": [ + "Una red con una capa Dense de 32 neuronas que ve los 24 meses anteriores. Con la prueba (de agosto de 1958 a diciembre de 1960, que no vio al entrenar) se equivoca {{test_mae, number(maximumFractionDigits: 1)}} miles de pasajeros de media a un paso y {{test_recursive_mae, number(maximumFractionDigits: 1)}} prediciendo toda la prueba seguida; repetir el valor de hace un año se equivoca {{test_seasonal_mae, number(maximumFractionDigits: 1)}}." + ] + }, + { + "title": "Referencias", + "items": [ + "AirPassengers en la documentación de R, con su fuente original.", + "El CSV, del repositorio jbrownlee/Datasets." + ] + } + ] + } + } + } +} diff --git a/public/n4l/airline-passengers.n4l/locales/ja.json b/public/n4l/airline-passengers.n4l/locales/ja.json new file mode 100644 index 0000000..ce5421a --- /dev/null +++ b/public/n4l/airline-passengers.n4l/locales/ja.json @@ -0,0 +1,40 @@ +{ + "columns": { + "Month": "月", + "Passengers": "乗客数" + }, + "tasks": { + "time-series": { + "name": "航空旅客数", + "summary": "1949 年から 1960 年までの国際線の月ごとの旅客数です。毎年増え、夏はさらに多くなります。", + "description": { + "text": [ + "Box と Jenkins による古典的な系列で、1949 年 1 月から 1960 年 12 月までの国際線の月ごとの旅客数の合計(単位は千人、144 か月)です。時系列予測のほとんどの手法がこのデータで説明されます。", + "毎年飛行機に乗る人が増えるためトレンドがあり(1960 年は 1949 年のほぼ 4 倍)、12 か月の季節性もあります。ピークは 7 月と 8 月で、少ないのは冬です。さらにピークは系列とともに大きくなる(乗法的な季節性)ため、対数を予測することがよくあります。" + ], + "sections": [ + { + "title": "変数", + "items": [ + "Month:月(年-月)。", + "Passengers:その月の旅客数(千人)。予測する値です。" + ] + }, + { + "title": "学習済みモデル", + "items": [ + "32 ニューロンの Dense 層 1 つで、直前の 24 か月を見るネットワークです。学習で見ていないテスト部分(1958 年 8 月〜1960 年 12 月)での誤差は、1 ステップ先で平均 {{test_mae, number(maximumFractionDigits: 1)}} 千人、テスト部分全体を続けて予測すると {{test_recursive_mae, number(maximumFractionDigits: 1)}} です。1 年前の値を繰り返すと {{test_seasonal_mae, number(maximumFractionDigits: 1)}} です。" + ] + }, + { + "title": "参考文献", + "items": [ + "R のドキュメントの AirPassengers(元の出典つき)。", + "CSV ファイル(jbrownlee/Datasets リポジトリ)。" + ] + } + ] + } + } + } +} diff --git a/public/n4l/airline-passengers.n4l/manifest.json b/public/n4l/airline-passengers.n4l/manifest.json new file mode 100644 index 0000000..2a78937 --- /dev/null +++ b/public/n4l/airline-passengers.n4l/manifest.json @@ -0,0 +1,95 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "airline-passengers", + "version": "1.1.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/AirPassengers.html", + "links": { + "link2": "https://github.com/jbrownlee/Datasets/blob/master/airline-passengers.csv" + }, + "citation": "@book{box1994time,\n author = {Box, George E. P. and Jenkins, Gwilym M. and Reinsel, Gregory C.},\n title = {Time Series Analysis: Forecasting and Control},\n edition = {3},\n publisher = {Prentice Hall},\n year = {1994},\n isbn = {978-0130607744}\n}" + }, + "datasets": [ + { + "id": "airline-passengers", + "file": "data/airline-passengers.csv", + "rows": 144, + "frequency": "month", + "columns": [ + { + "name": "Month", + "role": "ID", + "type": "Date", + "missing": 0, + "description": "month (YYYY-MM)" + }, + { + "name": "Passengers", + "role": "Target", + "type": "Integer", + "missing": 0, + "units": "thousands", + "description": "total international airline passengers in the month" + } + ] + } + ], + "tasks": [ + { + "task": "time-series", + "key": "AIRLINE-PASSENGERS", + "runtime": "time-series", + "datasets": [ + "airline-passengers" + ], + "order": 1, + "preprocessing": [], + "models": [ + { + "id": "forecast", + "format": "tfjs-layers", + "path": "models/forecast/model.json", + "dataset": "airline-passengers", + "input": "scaled", + "metrics": { + "test_mae": 12.1231, + "test_rmse": 15.2024, + "test_recursive_mae": 14.8255, + "test_naive_mae": 44.7241, + "test_seasonal_mae": 41.3103 + } + } + ], + "training": { + "layers": [ + { + "class": "dense", + "units": 32, + "activation": "relu" + }, + { + "class": "dense", + "units": 1, + "activation": "linear", + "locked": true + } + ], + "learningRate": 0.01, + "epochs": 100 + }, + "forecast": { + "window": 24, + "season": 12, + "difference": false, + "testSize": 20 + } + } + ] +} diff --git a/public/n4l/airline-passengers.n4l/models/forecast/model.json b/public/n4l/airline-passengers.n4l/models/forecast/model.json new file mode 100644 index 0000000..83b78d6 --- /dev/null +++ b/public/n4l/airline-passengers.n4l/models/forecast/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_4","layers":[{"class_name":"Dense","config":{"units":32,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense7","trainable":true,"batch_input_shape":[null,24],"dtype":"float32"}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense8","trainable":true}}]},"keras_version":"tfjs-layers 4.22.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.22.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense7/kernel","shape":[24,32],"dtype":"float32"},{"name":"dense_Dense7/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense8/kernel","shape":[32,1],"dtype":"float32"},{"name":"dense_Dense8/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/n4l/airline-passengers.n4l/models/forecast/model.weights.bin b/public/n4l/airline-passengers.n4l/models/forecast/model.weights.bin new file mode 100644 index 0000000..c7219f5 Binary files /dev/null and b/public/n4l/airline-passengers.n4l/models/forecast/model.weights.bin differ diff --git a/public/datasets/01-regression/auto-mpg/auto-mpg.csv b/public/n4l/auto-mpg.n4l/data/auto-mpg.csv similarity index 100% rename from public/datasets/01-regression/auto-mpg/auto-mpg.csv rename to public/n4l/auto-mpg.n4l/data/auto-mpg.csv diff --git a/public/datasets/01-regression/auto-mpg/auto-mpg.names b/public/n4l/auto-mpg.n4l/data/auto-mpg.names similarity index 100% rename from public/datasets/01-regression/auto-mpg/auto-mpg.names rename to public/n4l/auto-mpg.n4l/data/auto-mpg.names diff --git a/public/n4l/auto-mpg.n4l/locales/en.json b/public/n4l/auto-mpg.n4l/locales/en.json new file mode 100644 index 0000000..05cff0d --- /dev/null +++ b/public/n4l/auto-mpg.n4l/locales/en.json @@ -0,0 +1,67 @@ +{ + "columns": { + "cylinders": "cylinders", + "displacement": "displacement", + "horsepower": "horsepower", + "weight": "weight", + "acceleration": "acceleration", + "model-year": "model-year", + "mpg": "mpg" + }, + "tasks": { + "regression": { + "title": "Auto MPG", + "name": "Auto MPG", + "summary": "The fuel consumption of 70s and 80s cars, in miles per gallon, from their engine, weight and year.", + "description": { + "text": [ + "The AUTO MPG dataset was taken from the StatLib library maintained at Carnegie Mellon University. The dataset was used at the 1983 American Statistical Association Exposition.", + "The term \"Auto MPG\" refers to miles per gallon, a unit of fuel efficiency measurement commonly used in the United States. This measure indicates how many miles a vehicle can travel on one gallon of fuel. However, \"Auto MPG\" is an English term and there is no direct translation in Spanish.\n\nIn Spanish, terms such as \"consumo de combustible\" or \"rendimiento de combustible\" are often used to refer to the fuel efficiency of a car. These terms indicate how many kilometres or miles a vehicle can travel on one litre or gallon of fuel, respectively.\n\nIt is important to note that different countries use different units of measurement for fuel consumption. For example, in some places the litre per 100 kilometres travelled (L/100 km) is used to indicate fuel efficiency.", + "For more information about this dataset, visit the ICS.UCI.edu repository." + ], + "sections": [ + { + "title": "Information", + "items": [ + "MPG: MPG is Miles Per Gallon. This is the amount of fuel consumed by the particular vehicle of an instance. This variable can also be used as the variable to be predicted for any car", + "cylinders: This attribute describes the number of cylinders of each car. This is a discrete valued attribute", + "displacement: This is another attribute of the vehicle which has a quantitative continuous value describing the engine displacement", + "horsepower: This attribute tells about the horsepower of a car and is a continuous valued variable", + "weight: This refers to the weight of each car which is a continuous valued quantitative variable", + "acceleration: The acceleration of the car", + "model year: The year the model was released is mentioned in this attribute", + "origin: The origin attribute has 3 discrete values. 1 refers to cars made in USA, 2 for Europe and 3 for Asia", + "car name: This is the name of the car in string" + ] + }, + { + "title": "Input data", + "items": [ + "MPG: continuous", + "cylinders: multi-valued discrete, 4, 6, 8", + "displacement: continuous", + "horsepower: continuous", + "weight: continuous", + "acceleration: continuous", + "model Year: multi-valued discrete", + "origin: multi-valued discrete, 1 refers to cars made in USA, 2 for Europe and 3 for Asia", + "car name: string (unique for each instance)" + ] + }, + { + "title": "Output data", + "items": [ + "Calculated regression (MPG/b>)" + ] + }, + { + "title": "References", + "items": [ + "Auto MPG" + ] + } + ] + } + } + } +} diff --git a/public/n4l/auto-mpg.n4l/locales/es.json b/public/n4l/auto-mpg.n4l/locales/es.json new file mode 100644 index 0000000..425ffb9 --- /dev/null +++ b/public/n4l/auto-mpg.n4l/locales/es.json @@ -0,0 +1,67 @@ +{ + "columns": { + "cylinders": "cylinders", + "displacement": "displacement", + "horsepower": "horsepower", + "weight": "weight", + "acceleration": "acceleration", + "model-year": "model-year", + "mpg": "mpg" + }, + "tasks": { + "regression": { + "title": "Rendimiento de combustible", + "name": "Auto MPG", + "summary": "El consumo de coches de los años 70 y 80, en millas por galón, a partir de su motor, su peso y su año.", + "description": { + "text": [ + "El conjunto de datos AUTO MPG se tomó de la biblioteca StatLib que se mantiene en la Universidad Carnegie Mellon. El conjunto de datos se utilizó en la Exposición de la Asociación Estadounidense de Estadística de 1983.", + "El término \"Auto MPG\" se refiere a las millas por galón, una unidad de medida de eficiencia de combustible utilizada comúnmente en los Estados Unidos. Esta medida indica cuántas millas puede recorrer un vehículo con un galón de combustible. Sin embargo, \"Auto MPG\" es un término en inglés y no hay una traducción directa en español.\n\nEn español, para referirse a la eficiencia de combustible de un automóvil, se suelen utilizar términos como \"consumo de combustible\" o \"rendimiento de combustible\". Estos términos indican cuántos kilómetros o millas puede recorrer un vehículo con un litro o galón de combustible, respectivamente.\n\nEs importante tener en cuenta que en diferentes países se utilizan unidades de medida distintas para el consumo de combustible. Por ejemplo, en algunos lugares se utiliza el litro por cada 100 kilómetros recorridos (L/100 km) para indicar la eficiencia de combustible.", + "Para obtener más información acerca de este conjunto de datos visita el repositorio ics.uci.edu." + ], + "sections": [ + { + "title": "Información", + "items": [ + "MPG: MPG son las siglas en inglés de Millas por Galón. Es la cantidad de combustible consumido por el vehículo particular de una instancia. Esta variable también se puede utilizar como la variable a predecir para cualquier coche.", + "cylinders: Este atributo describe el número de cilindros de cada coche. Se trata de un atributo de valor discreto", + "displacement: Este es otro atributo del vehículo que tiene un valor cuantitativo continuo que describe el desplazamiento del motor", + "horsepower: Este atributo informa sobre los caballos de un coche y es una variable de valor continuo", + "weight: Se refiere al peso de cada coche que es una variable cuantitativa de valor continuo", + "acceleration: La aceleración del coche", + "model year: El año de lanzamiento del modelo", + "origin: El atributo origen tiene 3 valores discretos. 1 se refiere a coches fabricados en EE.UU., 2 para Europa y 3 para Asia", + "car name: Es el nombre del coche en cadena." + ] + }, + { + "title": "Datos de entrada", + "items": [ + "MPG: continuo", + "cylinders: discreto multivalor, 4, 6, 8", + "displacement: continuo", + "horsepower: continua", + "weight: continuo", + "acceleration: continua", + "model Year: discreto de varios valores", + "origin: discreto multivalor, 1 se refiere a automóviles fabricados en EE. UU., 2 para Europa y 3 para Asia", + "car name: texto (única para cada instancia)" + ] + }, + { + "title": "Datos de salida", + "items": [ + "Regresión calculada (MPG)" + ] + }, + { + "title": "Referencias", + "items": [ + "Auto MPG" + ] + } + ] + } + } + } +} diff --git a/public/n4l/auto-mpg.n4l/locales/ja.json b/public/n4l/auto-mpg.n4l/locales/ja.json new file mode 100644 index 0000000..5e9039b --- /dev/null +++ b/public/n4l/auto-mpg.n4l/locales/ja.json @@ -0,0 +1,67 @@ +{ + "columns": { + "cylinders": "cylinders", + "displacement": "displacement", + "horsepower": "horsepower", + "weight": "weight", + "acceleration": "acceleration", + "model-year": "model-year", + "mpg": "mpg" + }, + "tasks": { + "regression": { + "title": "燃費性能", + "name": "燃費性能", + "summary": "70〜80年代の車の燃費(マイル/ガロン)を、エンジン、重量、年式から予測します。", + "description": { + "text": [ + "AUTO MPG データセットは、カーネギーメロン大学で管理されているStatLibライブラリから取得されました。このデータセットは、1983年の米国統計学会の展示会で使用されました。", + "「Auto MPG」(ガロンあたりのマイル)という用語は、一般的に米国で使用される燃費効率の測定単位を指します。この尺度は、車両が1ガロンの燃料で走行できるマイル数を示します。スペイン語では、通常、「consumo de combustible」(燃料消費量)または「rendimiento de combustible」(燃費性能)という用語が使用されます。国によって測定単位が異なることに注意することが重要です。", + "このデータセットの詳細はICS.UCI.edu リポジトリをご覧ください。" + ], + "sections": [ + { + "title": "情報", + "items": [ + "MPG: MPG は Miles Per Gallon(1ガロンあたりの走行マイル)の略で、各インスタンスの車両の燃費を表します。任意の車について予測対象の変数としても使用できます", + "cylinders: 各車のシリンダー数を表す属性です。離散値の属性です", + "displacement: エンジンの排気量を表す、連続値の量的属性です", + "horsepower: 車の馬力を表す連続値の変数です", + "weight: 各車の重量を表す連続値の量的変数です", + "acceleration: 車の加速性能です", + "model year: そのモデルが発売された年です", + "origin: 3つの離散値をとる属性で、1 は米国製、2 は欧州製、3 はアジア製の車を表します", + "car name: 車名を表す文字列です" + ] + }, + { + "title": "入力データ", + "items": [ + "MPG: 連続値", + "cylinders: 多値の離散値(4, 6, 8)", + "displacement: 連続値", + "horsepower: 連続値", + "weight: 連続値", + "acceleration: 連続値", + "model year: 多値の離散値", + "origin: 多値の離散値。1 は米国製、2 は欧州製、3 はアジア製の車を表します", + "car name: 文字列(インスタンスごとに一意)" + ] + }, + { + "title": "出力データ", + "items": [ + "回帰による計算値(MPG)" + ] + }, + { + "title": "参考文献", + "items": [ + "Auto MPG" + ] + } + ] + } + } + } +} diff --git a/public/n4l/auto-mpg.n4l/manifest.json b/public/n4l/auto-mpg.n4l/manifest.json new file mode 100644 index 0000000..a777684 --- /dev/null +++ b/public/n4l/auto-mpg.n4l/manifest.json @@ -0,0 +1,125 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "auto-mpg", + "version": "1.1.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://archive.ics.uci.edu/dataset/9/auto+mpg", + "citation": "@misc{misc_auto_mpg_9,\n author = {Quinlan,R.},\n title = {{Auto MPG}},\n year = {1993},\n howpublished = {UCI Machine Learning Repository},\n note = {{DOI}: https://doi.org/10.24432/C5859H}\n}" + }, + "datasets": [ + { + "id": "auto-mpg", + "file": "data/auto-mpg.csv", + "info": "data/auto-mpg.names", + "rows": 396, + "columns": [ + { + "name": "cylinders", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "number of cylinders (multi-valued discrete)" + }, + { + "name": "displacement", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "engine displacement" + }, + { + "name": "horsepower", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "engine horsepower" + }, + { + "name": "weight", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "vehicle weight" + }, + { + "name": "acceleration", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "acceleration" + }, + { + "name": "model-year", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "model year (multi-valued discrete)" + }, + { + "name": "mpg", + "role": "Target", + "type": "Continuous", + "missing": 0, + "description": "fuel consumption in miles per gallon" + } + ] + } + ], + "tasks": [ + { + "task": "regression", + "key": "AUTO_MPG", + "runtime": "regression", + "datasets": [ + "auto-mpg" + ], + "preprocessing": [ + { + "op": "min-max", + "columns": "features" + } + ], + "models": [ + { + "id": "mlp", + "format": "tfjs-layers", + "path": "models/mlp/model.json", + "dataset": "auto-mpg", + "input": "scaled", + "metrics": { + "test_r2": 0.831, + "test_mae": 2.0889, + "test_baseline_mae": 5.6724 + } + } + ], + "training": { + "layers": [ + { + "class": "dense", + "units": 64, + "activation": "relu" + }, + { + "class": "dense", + "units": 64, + "activation": "relu" + }, + { + "class": "dense", + "units": 1, + "activation": "linear", + "locked": true + } + ] + } + } + ] +} diff --git a/public/n4l/auto-mpg.n4l/models/mlp/model.json b/public/n4l/auto-mpg.n4l/models/mlp/model.json new file mode 100644 index 0000000..8fac953 --- /dev/null +++ b/public/n4l/auto-mpg.n4l/models/mlp/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_4","layers":[{"class_name":"Dense","config":{"units":32,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1030}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense11","trainable":true,"batch_input_shape":[null,6],"dtype":"float32"}},{"class_name":"Dense","config":{"units":16,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1031}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense12","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1129}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense13","trainable":true}}]},"keras_version":"tfjs-layers 4.22.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.22.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense11/kernel","shape":[6,32],"dtype":"float32"},{"name":"dense_Dense11/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense12/kernel","shape":[32,16],"dtype":"float32"},{"name":"dense_Dense12/bias","shape":[16],"dtype":"float32"},{"name":"dense_Dense13/kernel","shape":[16,1],"dtype":"float32"},{"name":"dense_Dense13/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/n4l/auto-mpg.n4l/models/mlp/model.weights.bin b/public/n4l/auto-mpg.n4l/models/mlp/model.weights.bin new file mode 100644 index 0000000..cc6feca Binary files /dev/null and b/public/n4l/auto-mpg.n4l/models/mlp/model.weights.bin differ diff --git a/public/datasets/01-regression/housing-prices/boston-housing-2020.csv b/public/n4l/boston-housing.n4l/data/boston-housing-2020.csv similarity index 100% rename from public/datasets/01-regression/housing-prices/boston-housing-2020.csv rename to public/n4l/boston-housing.n4l/data/boston-housing-2020.csv diff --git a/public/datasets/01-regression/housing-prices/boston-housing.names b/public/n4l/boston-housing.n4l/data/boston-housing.names similarity index 100% rename from public/datasets/01-regression/housing-prices/boston-housing.names rename to public/n4l/boston-housing.n4l/data/boston-housing.names diff --git a/public/n4l/boston-housing.n4l/locales/en.json b/public/n4l/boston-housing.n4l/locales/en.json new file mode 100644 index 0000000..4d81094 --- /dev/null +++ b/public/n4l/boston-housing.n4l/locales/en.json @@ -0,0 +1,65 @@ +{ + "columns": { + "CRIM": "CRIM", + "ZN": "ZN", + "INDUS": "INDUS", + "CHAS": "CHAS", + "NOX": "NOX", + "RM": "RM", + "AGE": "AGE", + "DIS": "DIS", + "RAD": "RAD", + "TAX": "TAX", + "PTRATIO": "PTRATIO", + "LSTAT": "LSTAT", + "MEDV": "MEDV" + }, + "tasks": { + "regression": { + "title": "The Housing prices", + "name": "Housing Prices", + "summary": "The median house price in Boston neighbourhoods by crime rate, rooms or distance to the centre.", + "description": { + "text": [ + "The Boston housing data set is derived from information collected by the U.S. Census Service concerning housing in the Boston area.", + "The data set is designed to address house price modeling and regression problems in different neighborhoods in Boston, Massachusetts, United States. This data set is commonly used for examples and practices in education and research.", + "UCI data set info" + ], + "sections": [ + { + "title": "Input", + "items": [ + "CRIM per capita crime rate by town", + "ZN proportion of residential land zoned for lots over 25,000 sq.ft.", + "INDUS proportion of non-retail business acres per town", + "CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)", + "NOX nitric oxides concentration (parts per 10 million)", + "RM average number of rooms per dwelling", + "AGE proportion of owner-occupied units built prior to 1940", + "DIS weighted distances to five Boston employment centres", + "RAD index of accessibility to radial highways", + "TAX full-value property-tax rate per $10,000", + "PTRATIO pupil-teacher ratio by town", + "B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town", + "LSTAT % lower status of the population", + "MEDV Median value of owner-occupied homes in $1000's" + ] + }, + { + "title": "Output", + "items": [ + "Calculated regression" + ] + }, + { + "title": "References", + "items": [ + "UCI data set info", + "Boston housing dataset controversy" + ] + } + ] + } + } + } +} diff --git a/public/n4l/boston-housing.n4l/locales/es.json b/public/n4l/boston-housing.n4l/locales/es.json new file mode 100644 index 0000000..539bbd7 --- /dev/null +++ b/public/n4l/boston-housing.n4l/locales/es.json @@ -0,0 +1,65 @@ +{ + "columns": { + "CRIM": "CRIM", + "ZN": "ZN", + "INDUS": "INDUS", + "CHAS": "CHAS", + "NOX": "NOX", + "RM": "RM", + "AGE": "AGE", + "DIS": "DIS", + "RAD": "RAD", + "TAX": "TAX", + "PTRATIO": "PTRATIO", + "LSTAT": "LSTAT", + "MEDV": "MEDV" + }, + "tasks": { + "regression": { + "title": "Precio de las viviendas", + "name": "Housing Prices", + "summary": "El precio medio de la vivienda en los barrios de Boston según la criminalidad, las habitaciones o la distancia al centro.", + "description": { + "text": [ + "El conjunto de datos de viviendas de Boston se deriva de la información recopilada por el Servicio del Censo de EE. UU. sobre viviendas en el área de Boston.", + "El conjunto de datos está diseñado para abordar problemas de regresión y modelado de precios de viviendas en diferentes vecindarios de Boston, Massachusetts, Estados Unidos. Este conjunto de datos es comúnmente utilizado para ejemplos y prácticas en la educación y la investigación.", + "Entrada del conjunto de datos UCI" + ], + "sections": [ + { + "title": "Datos de entrada", + "items": [ + "CRIM Tasa de criminalidad del crimen per cápita por ciudad", + "Zn Proporción de tierras residenciales zonas por lotes de más de 25,000 pies cuadrados.", + "INDUS Proporción de acres comerciales no reales por ciudad", + "CHAS Charles River Variable Dummy (= 1 if tract bounds river; 0 en otro caso)", + "NOX Concentración de óxidos nítricos (partes por 10 millones)", + "RM Número promedio de habitaciones por vivienda", + "AGE Proporción de unidades ocupadas por los propietarios construidas antes de 1940", + "DIS Distancias ponderadas a cinco centros de empleo de Boston", + "RAD Índice de accesibilidad a carreteras radiales", + "TAX Impuesto a la propiedad de la propiedad de valor completo por cada $ 10,000", + "PRATIO Ratio alumnos-profesor por ciudad", + "B 1000 (BK - 0.63)^2 donde BK es la proporción de negros por ciudad", + "LSTAT LSTAT % más bajo estado de la población", + "MEDVValor mediano de las casas ocupadas por el propietario en $ 1000" + ] + }, + { + "title": "Datos de salida", + "items": [ + "Regresión calculada" + ] + }, + { + "title": "Referencias", + "items": [ + "Entrada del conjunto de datos UCI", + "Controversia sobre el conjunto de datos de vivienda de Boston" + ] + } + ] + } + } + } +} diff --git a/public/n4l/boston-housing.n4l/locales/ja.json b/public/n4l/boston-housing.n4l/locales/ja.json new file mode 100644 index 0000000..4774fa1 --- /dev/null +++ b/public/n4l/boston-housing.n4l/locales/ja.json @@ -0,0 +1,65 @@ +{ + "columns": { + "CRIM": "CRIM", + "ZN": "ZN", + "INDUS": "INDUS", + "CHAS": "CHAS", + "NOX": "NOX", + "RM": "RM", + "AGE": "AGE", + "DIS": "DIS", + "RAD": "RAD", + "TAX": "TAX", + "PTRATIO": "PTRATIO", + "LSTAT": "LSTAT", + "MEDV": "MEDV" + }, + "tasks": { + "regression": { + "title": "住宅価格", + "name": "住宅価格", + "summary": "ボストンの地区ごとの住宅価格の中央値を、犯罪率、部屋数、中心部までの距離などから予測します。", + "description": { + "text": [ + "ボストン住宅データセットは、米国国勢調査局がボストン地域の住宅について収集した情報から派生しています。", + "このデータセットは、米国マサチューセッツ州ボストン地域のさまざまな近隣地域の住宅価格の回帰およびモデリングの問題に対処するように設計されています。このデータセットは、教育および研究の例や実践に一般的に使用されています。", + "UCIデータセットエントリ" + ], + "sections": [ + { + "title": "入力データ", + "items": [ + "CRIM 市内の一人当たりの犯罪率", + "ZN 25,000平方フィート以上の区画の住宅地の割合。", + "INDUS 市内の一人当たりの非小売業の割合", + "CHAS チャールズ川ダミー変数(トラクトが川と接している場合は1、それ以外の場合は0)", + "NOX 窒素酸化物濃度(1000万分の1)", + "RM 住宅あたりの平均部屋数", + "AGE 1940年より前に建てられた所有者居住ユニットの割合", + "DIS 5つのボストン雇用センターまでの加重距離", + "RAD ラジアル高速道路へのアクセス指数", + "TAX 10,000ドルあたりの固定資産税", + "PTRATIO 生徒と教師の比率", + "B 1000 (Bk - 0.63)^2 (Bkは市内の一人当たりの黒人の割合)", + "LSTAT 人口の低所得者層の割合", + "MEDV 所有者居住住宅の平均価値(1000ドル)" + ] + }, + { + "title": "出力データ", + "items": [ + "計算された回帰" + ] + }, + { + "title": "参照元", + "items": [ + "UCIデータセット情報", + "ボストン住宅データセットに関する論争" + ] + } + ] + } + } + } +} diff --git a/public/n4l/boston-housing.n4l/manifest.json b/public/n4l/boston-housing.n4l/manifest.json new file mode 100644 index 0000000..1944513 --- /dev/null +++ b/public/n4l/boston-housing.n4l/manifest.json @@ -0,0 +1,174 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "boston-housing", + "version": "1.1.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html" + }, + "datasets": [ + { + "id": "boston-housing", + "file": "data/boston-housing-2020.csv", + "info": "data/boston-housing.names", + "rows": 506, + "columns": [ + { + "name": "CRIM", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "per capita crime rate by town" + }, + { + "name": "ZN", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "proportion of residential land zoned for lots over 25,000 sq.ft." + }, + { + "name": "INDUS", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "proportion of non-retail business acres per town" + }, + { + "name": "CHAS", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "Charles River dummy variable (1 if tract bounds river; 0 otherwise)" + }, + { + "name": "NOX", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "units": "parts per 10 million", + "description": "nitric oxides concentration" + }, + { + "name": "RM", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "average number of rooms per dwelling" + }, + { + "name": "AGE", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "proportion of owner-occupied units built prior to 1940" + }, + { + "name": "DIS", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "weighted distances to five Boston employment centres" + }, + { + "name": "RAD", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "index of accessibility to radial highways" + }, + { + "name": "TAX", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "full-value property-tax rate per $10,000" + }, + { + "name": "PTRATIO", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "pupil-teacher ratio by town" + }, + { + "name": "LSTAT", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "% lower status of the population" + }, + { + "name": "MEDV", + "role": "Target", + "type": "Continuous", + "missing": 0, + "units": "$1000's", + "description": "median value of owner-occupied homes" + } + ] + } + ], + "tasks": [ + { + "task": "regression", + "key": "HOUSING_PRICES", + "runtime": "regression", + "datasets": [ + "boston-housing" + ], + "preprocessing": [ + { + "op": "label-encoder", + "columns": [ + "CHAS" + ] + }, + { + "op": "min-max", + "columns": "features" + } + ], + "models": [ + { + "id": "mlp", + "format": "tfjs-layers", + "path": "models/mlp/model.json", + "dataset": "boston-housing", + "input": "scaled", + "metrics": { + "test_r2": 0.7666, + "test_mae": 3.4892, + "test_baseline_mae": 7.0247 + } + } + ], + "training": { + "layers": [ + { + "class": "dense", + "units": 32, + "activation": "sigmoid" + }, + { + "class": "dense", + "units": 16, + "activation": "sigmoid" + }, + { + "class": "dense", + "units": 1, + "activation": "linear", + "locked": true + } + ] + } + } + ] +} diff --git a/public/n4l/boston-housing.n4l/models/mlp/model.json b/public/n4l/boston-housing.n4l/models/mlp/model.json new file mode 100644 index 0000000..cbf7651 --- /dev/null +++ b/public/n4l/boston-housing.n4l/models/mlp/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_4","layers":[{"class_name":"Dense","config":{"units":32,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1030}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense11","trainable":true,"batch_input_shape":[null,12],"dtype":"float32"}},{"class_name":"Dense","config":{"units":16,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1031}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense12","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1129}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense13","trainable":true}}]},"keras_version":"tfjs-layers 4.22.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.22.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense11/kernel","shape":[12,32],"dtype":"float32"},{"name":"dense_Dense11/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense12/kernel","shape":[32,16],"dtype":"float32"},{"name":"dense_Dense12/bias","shape":[16],"dtype":"float32"},{"name":"dense_Dense13/kernel","shape":[16,1],"dtype":"float32"},{"name":"dense_Dense13/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/n4l/boston-housing.n4l/models/mlp/model.weights.bin b/public/n4l/boston-housing.n4l/models/mlp/model.weights.bin new file mode 100644 index 0000000..283e257 Binary files /dev/null and b/public/n4l/boston-housing.n4l/models/mlp/model.weights.bin differ diff --git a/public/datasets/01-regression/breast-cancer/breast-cancer-wisconsin.csv b/public/n4l/breast-cancer.n4l/data/breast-cancer-wisconsin.csv similarity index 100% rename from public/datasets/01-regression/breast-cancer/breast-cancer-wisconsin.csv rename to public/n4l/breast-cancer.n4l/data/breast-cancer-wisconsin.csv diff --git a/public/datasets/01-regression/breast-cancer/breast-cancer-wisconsin.names b/public/n4l/breast-cancer.n4l/data/breast-cancer-wisconsin.names similarity index 100% rename from public/datasets/01-regression/breast-cancer/breast-cancer-wisconsin.names rename to public/n4l/breast-cancer.n4l/data/breast-cancer-wisconsin.names diff --git a/public/datasets/01-regression/breast-cancer/wdbc.csv b/public/n4l/breast-cancer.n4l/data/wdbc.csv similarity index 100% rename from public/datasets/01-regression/breast-cancer/wdbc.csv rename to public/n4l/breast-cancer.n4l/data/wdbc.csv diff --git a/public/datasets/01-regression/breast-cancer/wdbc.names b/public/n4l/breast-cancer.n4l/data/wdbc.names similarity index 100% rename from public/datasets/01-regression/breast-cancer/wdbc.names rename to public/n4l/breast-cancer.n4l/data/wdbc.names diff --git a/public/datasets/01-regression/breast-cancer/wpbc.csv b/public/n4l/breast-cancer.n4l/data/wpbc.csv similarity index 100% rename from public/datasets/01-regression/breast-cancer/wpbc.csv rename to public/n4l/breast-cancer.n4l/data/wpbc.csv diff --git a/public/datasets/01-regression/breast-cancer/wpbc.names b/public/n4l/breast-cancer.n4l/data/wpbc.names similarity index 100% rename from public/datasets/01-regression/breast-cancer/wpbc.names rename to public/n4l/breast-cancer.n4l/data/wpbc.names diff --git a/public/n4l/breast-cancer.n4l/locales/en.json b/public/n4l/breast-cancer.n4l/locales/en.json new file mode 100644 index 0000000..d61dbc2 --- /dev/null +++ b/public/n4l/breast-cancer.n4l/locales/en.json @@ -0,0 +1,102 @@ +{ + "columns": { + "Sample_code_number": "Sample_code_number", + "Clump_Thickness": "Clump_Thickness", + "Uniformity_of_Cell_Size": "Uniformity_of_Cell_Size", + "Uniformity_of_Cell_Shape": "Uniformity_of_Cell_Shape", + "Marginal_Adhesion": "Marginal_Adhesion", + "Single_Epithelial_Cell_Size": "Single_Epithelial_Cell_Size", + "Bare_Nuclei": "Bare_Nuclei", + "Bland_Chromatin": "Bland_Chromatin", + "Normal_Nucleoli": "Normal_Nucleoli", + "Mitoses": "Mitoses", + "Class": "Class", + "ID": "ID", + "radius1": "radius1", + "texture1": "texture1", + "perimeter1": "perimeter1", + "area1": "area1", + "smoothness1": "smoothness1", + "compactness1": "compactness1", + "concavity1": "concavity1", + "concave_points1": "concave_points1", + "symmetry1": "symmetry1", + "fractal_dimension1": "fractal_dimension1", + "radius2": "radius2", + "texture2": "texture2", + "perimeter2": "perimeter2", + "area2": "area2", + "smoothness2": "smoothness2", + "compactness2": "compactness2", + "concavity2": "concavity2", + "concave_points2": "concave_points2", + "symmetry2": "symmetry2", + "fractal_dimension2": "fractal_dimension2", + "radius3": "radius3", + "texture3": "texture3", + "perimeter3": "perimeter3", + "area3": "area3", + "smoothness3": "smoothness3", + "compactness3": "compactness3", + "concavity3": "concavity3", + "concave_points3": "concave_points3", + "symmetry3": "symmetry3", + "fractal_dimension3": "fractal_dimension3", + "Diagnosis": "Diagnosis", + "Time": "Time", + "tumor_size": "tumor_size", + "lymph_node_status": "lymph_node_status", + "Outcome": "Outcome" + }, + "tasks": { + "regression": { + "title": "Breast Cancer Wisconsin (Diagnostic and prognostic)", + "name": "Breast cancer", + "summary": "Three Wisconsin datasets about breast tumours: the original, the diagnostic one (WDBC) and the prognostic one (WPBC).", + "description": { + "text": [ + "These are data from the University of Wisconsin Hospital about breast cancer. They are used to predict whether a breast tumour is benign or malignant.", + "Each record represents follow-up data for a breast cancer case. These are cases treated since 1984 by Dr. Wolberg, he only includes those cases that present invasive breast cancer and without evidence of metastasis.", + "The first 30 characteristics are calculated from a digitized image of a fine needle aspiration (FNAB) of the breast mass, these data describe the characteristics of the cell nuclei present in the image, some images can be found in cs wisc", + "The file wdbc.csv corresponds to the diagnostic data set and wpbc.csv corresponds to the prognostic data set.", + "UCI data set input " + ], + "sections": [ + { + "title": "Input", + "items": [ + "ID number", + "Outcome (R = recur, N = nonrecur)", + "Time (recurrence time if field 2 = R, disease-free time if field 2 = N)", + "4-33 Ten real-valued features are computed for each cell nucleus:", + "radius (mean of distances from center to points on the perimeter)", + "texture (standard deviation of gray-scale values)", + "perimeter", + "area", + "smoothness (local variation in radius lengths)", + "compactness (perimeter^2 / area - 1.0)", + "concavity (severity of concave portions of the contour)", + "concave points (number of concave portions of the contour)", + "symmetry", + "fractal dimension (\"coastline approximation\" - 1)" + ] + }, + { + "title": "Output", + "items": [ + "Calculated regression (Salary)" + ] + }, + { + "title": "References", + "items": [ + "Breast Cancer Wisconsin", + "Breast Cancer Wisconsin (Prognostic)", + "Breast Cancer Wisconsin (Diagnostic)" + ] + } + ] + } + } + } +} diff --git a/public/n4l/breast-cancer.n4l/locales/es.json b/public/n4l/breast-cancer.n4l/locales/es.json new file mode 100644 index 0000000..0d5e04f --- /dev/null +++ b/public/n4l/breast-cancer.n4l/locales/es.json @@ -0,0 +1,102 @@ +{ + "columns": { + "Sample_code_number": "Sample_code_number", + "Clump_Thickness": "Clump_Thickness", + "Uniformity_of_Cell_Size": "Uniformity_of_Cell_Size", + "Uniformity_of_Cell_Shape": "Uniformity_of_Cell_Shape", + "Marginal_Adhesion": "Marginal_Adhesion", + "Single_Epithelial_Cell_Size": "Single_Epithelial_Cell_Size", + "Bare_Nuclei": "Bare_Nuclei", + "Bland_Chromatin": "Bland_Chromatin", + "Normal_Nucleoli": "Normal_Nucleoli", + "Mitoses": "Mitoses", + "Class": "Class", + "ID": "ID", + "radius1": "radius1", + "texture1": "texture1", + "perimeter1": "perimeter1", + "area1": "area1", + "smoothness1": "smoothness1", + "compactness1": "compactness1", + "concavity1": "concavity1", + "concave_points1": "concave_points1", + "symmetry1": "symmetry1", + "fractal_dimension1": "fractal_dimension1", + "radius2": "radius2", + "texture2": "texture2", + "perimeter2": "perimeter2", + "area2": "area2", + "smoothness2": "smoothness2", + "compactness2": "compactness2", + "concavity2": "concavity2", + "concave_points2": "concave_points2", + "symmetry2": "symmetry2", + "fractal_dimension2": "fractal_dimension2", + "radius3": "radius3", + "texture3": "texture3", + "perimeter3": "perimeter3", + "area3": "area3", + "smoothness3": "smoothness3", + "compactness3": "compactness3", + "concavity3": "concavity3", + "concave_points3": "concave_points3", + "symmetry3": "symmetry3", + "fractal_dimension3": "fractal_dimension3", + "Diagnosis": "Diagnosis", + "Time": "Time", + "tumor_size": "tumor_size", + "lymph_node_status": "lymph_node_status", + "Outcome": "Outcome" + }, + "tasks": { + "regression": { + "title": "Cáncer de mama Wisconsin (diagnóstico y pronóstico)", + "name": "Breast cancer", + "summary": "Tres conjuntos de Wisconsin sobre tumores de mama: el original, el de diagnóstico (WDBC) y el de pronóstico (WPBC).", + "description": { + "text": [ + "Son datos del Hospital de la Universidad de Wisconsin sobre cáncer de mama. Sirven para predecir si un tumor de mama es benigno o maligno.", + "Cada registro representa los datos de seguimiento de un caso de cáncer de mama. Estos son casos atendidos desde 1984 por el Dr. Wolberg, solo incluye aquellos casos que presentan cáncer de mama invasivo y sin evidencia de metástasis.", + "Las primeras 30 características se calculan a partir de una imagen digitalizada de una aspiración con aguja fina (PAAF) de la masa mamaria, dichos datos describen las características de los núcleos celulares presentes en la imagen, algunas imágenes se pueden encontrar en cs wisc.", + "El fichero wdbc.csv corresponde al conjunto de datos de diagnóstico y wpbc.csv corresponde al conjunto de datos de pronóstico.", + "Entrada del conjunto de datos UCI" + ], + "sections": [ + { + "title": "Datos de entrada", + "items": [ + "Número de identificación", + "Resultado (R = recurrente, N = no recurrente)", + "Tiempo (tiempo de recurrencia si el campo 2 = R, tiempo libre de enfermedad si el campo 2 = N)", + "4-33 Se calculan diez características de valor real para cada núcleo celular:", + "radio (media de distancias desde el centro a puntos del perímetro)", + "textura (desviación estándar de los valores de escala de grises)", + "perímetro", + "área", + "suavidad (variación local en la longitud del radio)", + "compacidad (perímetro^2 / área - 1,0)", + "concavidad (severidad de las porciones cóncavas del contorno)", + "puntos cóncavos (número de porciones cóncavas del contorno)", + "simetría", + "dimensión fractal (\"aproximación de la línea costera\" - 1)" + ] + }, + { + "title": "Datos de salida", + "items": [ + "Regresión calculada" + ] + }, + { + "title": "Referencias", + "items": [ + "Breast Cancer Wisconsin", + "Breast Cancer Wisconsin (Prognostic)", + "Breast Cancer Wisconsin (Diagnostic)" + ] + } + ] + } + } + } +} diff --git a/public/n4l/breast-cancer.n4l/locales/ja.json b/public/n4l/breast-cancer.n4l/locales/ja.json new file mode 100644 index 0000000..b18695b --- /dev/null +++ b/public/n4l/breast-cancer.n4l/locales/ja.json @@ -0,0 +1,102 @@ +{ + "columns": { + "Sample_code_number": "Sample_code_number", + "Clump_Thickness": "Clump_Thickness", + "Uniformity_of_Cell_Size": "Uniformity_of_Cell_Size", + "Uniformity_of_Cell_Shape": "Uniformity_of_Cell_Shape", + "Marginal_Adhesion": "Marginal_Adhesion", + "Single_Epithelial_Cell_Size": "Single_Epithelial_Cell_Size", + "Bare_Nuclei": "Bare_Nuclei", + "Bland_Chromatin": "Bland_Chromatin", + "Normal_Nucleoli": "Normal_Nucleoli", + "Mitoses": "Mitoses", + "Class": "Class", + "ID": "ID", + "radius1": "radius1", + "texture1": "texture1", + "perimeter1": "perimeter1", + "area1": "area1", + "smoothness1": "smoothness1", + "compactness1": "compactness1", + "concavity1": "concavity1", + "concave_points1": "concave_points1", + "symmetry1": "symmetry1", + "fractal_dimension1": "fractal_dimension1", + "radius2": "radius2", + "texture2": "texture2", + "perimeter2": "perimeter2", + "area2": "area2", + "smoothness2": "smoothness2", + "compactness2": "compactness2", + "concavity2": "concavity2", + "concave_points2": "concave_points2", + "symmetry2": "symmetry2", + "fractal_dimension2": "fractal_dimension2", + "radius3": "radius3", + "texture3": "texture3", + "perimeter3": "perimeter3", + "area3": "area3", + "smoothness3": "smoothness3", + "compactness3": "compactness3", + "concavity3": "concavity3", + "concave_points3": "concave_points3", + "symmetry3": "symmetry3", + "fractal_dimension3": "fractal_dimension3", + "Diagnosis": "Diagnosis", + "Time": "Time", + "tumor_size": "tumor_size", + "lymph_node_status": "lymph_node_status", + "Outcome": "Outcome" + }, + "tasks": { + "regression": { + "title": "ウィスコンシン乳がん (診断と予後)", + "name": "乳がん", + "summary": "乳腺腫瘍に関するウィスコンシンの 3 つのデータセット:オリジナル、診断(WDBC)、予後(WPBC)。", + "description": { + "text": [ + "ウィスコンシン大学病院の乳がん関連データセットです。良性か悪性かを区別し、乳がん腫瘍の予測と識別に役立ちます。", + "各レコードは、1984年以来Dr. Wolbergによって治療された浸潤性乳がんの症例追跡データであり、転移の証拠がない症例のみが含まれます。", + "最初の30の特徴量は、乳腺腫瘤の穿刺吸引細胞診(FNAB)のデジタル画像から計算され、画像に存在する細胞核の特徴を記述しています。いくつかの画像はcs wiscで見つけることができます。", + "ファイル wdbc.csv は診断データセットに対応し、wpbc.csv は予後データセットに対応します。", + "UCIデータセット入力" + ], + "sections": [ + { + "title": "入力データ", + "items": [ + "ID番号", + "結果 (R = 再発, N = 非再発)", + "時間 (フィールド 2 = R の場合は再発までの時間、フィールド 2 = N の場合は無病期間)", + "4-33 各細胞核について10個の実数値特徴量が計算されます:", + "半径 (中心から周囲までの距離の平均)", + "テクスチャ (グレースケール値の標準偏差)", + "周囲長", + "面積", + "平滑性 (半径の長さの局所的な変動)", + "コンパクトさ (周囲長^2 / 面積 - 1.0)", + "凹面 (輪郭の凹状部分の重症度)", + "凹点 (輪郭の凹状部分の数)", + "対称性", + "フラクタル次元 (「海岸線近似」 - 1)" + ] + }, + { + "title": "出力データ", + "items": [ + "計算された回帰 (給与)" + ] + }, + { + "title": "参照元", + "items": [ + "Breast Cancer Wisconsin", + "Breast Cancer Wisconsin (Prognostic)", + "Breast Cancer Wisconsin (Diagnostic)" + ] + } + ] + } + } + } +} diff --git a/public/n4l/breast-cancer.n4l/manifest.json b/public/n4l/breast-cancer.n4l/manifest.json new file mode 100644 index 0000000..e433df2 --- /dev/null +++ b/public/n4l/breast-cancer.n4l/manifest.json @@ -0,0 +1,645 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "breast-cancer", + "version": "1.0.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://archive.ics.uci.edu/dataset/15/breast+cancer+wisconsin+original", + "links": { + "link2": "https://www.cs.wisc.edu/~street/images/", + "link3": "https://archive.ics.uci.edu/dataset/16/breast+cancer+wisconsin+prognostic", + "link4": "https://archive.ics.uci.edu/dataset/17/breast+cancer+wisconsin+diagnostic" + }, + "citation": "@misc{misc_breast_cancer_wisconsin_(prognostic)_16,\n author = {Wolberg,William, Street,W., and Mangasarian,Olvi},\n title = {{Breast Cancer Wisconsin (Prognostic)}},\n year = {1995},\n howpublished = {UCI Machine Learning Repository},\n note = {{DOI}: https://doi.org/10.24432/C5GK50}\n}" + }, + "datasets": [ + { + "id": "breast-cancer-wisconsin", + "file": "data/breast-cancer-wisconsin.csv", + "info": "data/breast-cancer-wisconsin.names", + "rows": 699, + "columns": [ + { + "name": "Sample_code_number", + "role": "ID", + "type": "Categorical", + "missing": 0, + "description": "id number" + }, + { + "name": "Clump_Thickness", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 - 10" + }, + { + "name": "Uniformity_of_Cell_Size", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 - 10" + }, + { + "name": "Uniformity_of_Cell_Shape", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 - 10" + }, + { + "name": "Marginal_Adhesion", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 - 10" + }, + { + "name": "Single_Epithelial_Cell_Size", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 - 10" + }, + { + "name": "Bare_Nuclei", + "role": "Feature", + "type": "Integer", + "missing": 16, + "description": "1 - 10" + }, + { + "name": "Bland_Chromatin", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 - 10" + }, + { + "name": "Normal_Nucleoli", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 - 10" + }, + { + "name": "Mitoses", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 - 10" + }, + { + "name": "Class", + "role": "Target", + "type": "Binary", + "missing": 0, + "description": "2 = benign, 4 = malignant" + } + ] + }, + { + "id": "wdbc", + "file": "data/wdbc.csv", + "info": "data/wdbc.names", + "rows": 569, + "columns": [ + { + "name": "ID", + "role": "ID", + "type": "Categorical", + "missing": 0, + "description": "ID number" + }, + { + "name": "radius1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "radius (mean of distances from center to points on the perimeter), mean" + }, + { + "name": "texture1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "texture (standard deviation of gray-scale values), mean" + }, + { + "name": "perimeter1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "perimeter, mean" + }, + { + "name": "area1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "area, mean" + }, + { + "name": "smoothness1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "smoothness (local variation in radius lengths), mean" + }, + { + "name": "compactness1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "compactness (perimeter^2 / area - 1.0), mean" + }, + { + "name": "concavity1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "concavity (severity of concave portions of the contour), mean" + }, + { + "name": "concave_points1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "concave points (number of concave portions of the contour), mean" + }, + { + "name": "symmetry1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "symmetry, mean" + }, + { + "name": "fractal_dimension1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "fractal dimension (\"coastline approximation\" - 1), mean" + }, + { + "name": "radius2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "radius (mean of distances from center to points on the perimeter), standard error" + }, + { + "name": "texture2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "texture (standard deviation of gray-scale values), standard error" + }, + { + "name": "perimeter2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "perimeter, standard error" + }, + { + "name": "area2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "area, standard error" + }, + { + "name": "smoothness2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "smoothness (local variation in radius lengths), standard error" + }, + { + "name": "compactness2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "compactness (perimeter^2 / area - 1.0), standard error" + }, + { + "name": "concavity2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "concavity (severity of concave portions of the contour), standard error" + }, + { + "name": "concave_points2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "concave points (number of concave portions of the contour), standard error" + }, + { + "name": "symmetry2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "symmetry, standard error" + }, + { + "name": "fractal_dimension2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "fractal dimension (\"coastline approximation\" - 1), standard error" + }, + { + "name": "radius3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "radius (mean of distances from center to points on the perimeter), worst (mean of the three largest values)" + }, + { + "name": "texture3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "texture (standard deviation of gray-scale values), worst (mean of the three largest values)" + }, + { + "name": "perimeter3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "perimeter, worst (mean of the three largest values)" + }, + { + "name": "area3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "area, worst (mean of the three largest values)" + }, + { + "name": "smoothness3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "smoothness (local variation in radius lengths), worst (mean of the three largest values)" + }, + { + "name": "compactness3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "compactness (perimeter^2 / area - 1.0), worst (mean of the three largest values)" + }, + { + "name": "concavity3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "concavity (severity of concave portions of the contour), worst (mean of the three largest values)" + }, + { + "name": "concave_points3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "concave points (number of concave portions of the contour), worst (mean of the three largest values)" + }, + { + "name": "symmetry3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "symmetry, worst (mean of the three largest values)" + }, + { + "name": "fractal_dimension3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "fractal dimension (\"coastline approximation\" - 1), worst (mean of the three largest values)" + }, + { + "name": "Diagnosis", + "role": "Target", + "type": "Categorical", + "missing": 0, + "description": "M = malignant, B = benign" + } + ] + }, + { + "id": "wpbc", + "file": "data/wpbc.csv", + "info": "data/wpbc.names", + "rows": 198, + "columns": [ + { + "name": "ID", + "role": "ID", + "type": "Integer", + "missing": 0, + "description": "ID number" + }, + { + "name": "Time", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "recurrence time if Outcome = R, disease-free time if Outcome = N" + }, + { + "name": "radius1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "radius (mean of distances from center to points on the perimeter), mean" + }, + { + "name": "texture1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "texture (standard deviation of gray-scale values), mean" + }, + { + "name": "perimeter1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "perimeter, mean" + }, + { + "name": "area1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "area, mean" + }, + { + "name": "smoothness1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "smoothness (local variation in radius lengths), mean" + }, + { + "name": "compactness1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "compactness (perimeter^2 / area - 1.0), mean" + }, + { + "name": "concavity1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "concavity (severity of concave portions of the contour), mean" + }, + { + "name": "concave_points1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "concave points (number of concave portions of the contour), mean" + }, + { + "name": "symmetry1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "symmetry, mean" + }, + { + "name": "fractal_dimension1", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "fractal dimension (\"coastline approximation\" - 1), mean" + }, + { + "name": "radius2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "radius (mean of distances from center to points on the perimeter), standard error" + }, + { + "name": "texture2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "texture (standard deviation of gray-scale values), standard error" + }, + { + "name": "perimeter2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "perimeter, standard error" + }, + { + "name": "area2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "area, standard error" + }, + { + "name": "smoothness2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "smoothness (local variation in radius lengths), standard error" + }, + { + "name": "compactness2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "compactness (perimeter^2 / area - 1.0), standard error" + }, + { + "name": "concavity2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "concavity (severity of concave portions of the contour), standard error" + }, + { + "name": "concave_points2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "concave points (number of concave portions of the contour), standard error" + }, + { + "name": "symmetry2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "symmetry, standard error" + }, + { + "name": "fractal_dimension2", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "fractal dimension (\"coastline approximation\" - 1), standard error" + }, + { + "name": "radius3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "radius (mean of distances from center to points on the perimeter), worst (mean of the three largest values)" + }, + { + "name": "texture3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "texture (standard deviation of gray-scale values), worst (mean of the three largest values)" + }, + { + "name": "perimeter3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "perimeter, worst (mean of the three largest values)" + }, + { + "name": "area3", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "area, worst (mean of the three largest values)" + }, + { + "name": "smoothness3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "smoothness (local variation in radius lengths), worst (mean of the three largest values)" + }, + { + "name": "compactness3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "compactness (perimeter^2 / area - 1.0), worst (mean of the three largest values)" + }, + { + "name": "concavity3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "concavity (severity of concave portions of the contour), worst (mean of the three largest values)" + }, + { + "name": "concave_points3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "concave points (number of concave portions of the contour), worst (mean of the three largest values)" + }, + { + "name": "symmetry3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "symmetry, worst (mean of the three largest values)" + }, + { + "name": "fractal_dimension3", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "fractal dimension (\"coastline approximation\" - 1), worst (mean of the three largest values)" + }, + { + "name": "tumor_size", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "units": "cm", + "description": "diameter of the excised tumor" + }, + { + "name": "lymph_node_status", + "role": "Feature", + "type": "Integer", + "missing": 4, + "description": "number of positive axillary lymph nodes observed at time of surgery" + }, + { + "name": "Outcome", + "role": "Target", + "type": "Categorical", + "missing": 0, + "description": "R = recur, N = nonrecur" + } + ] + } + ], + "tasks": [ + { + "task": "regression", + "key": "BREAST_CANCER", + "runtime": "regression", + "datasets": [ + "breast-cancer-wisconsin", + "wdbc", + "wpbc" + ], + "listed": false, + "preprocessing": [ + { + "op": "label-encoder", + "columns": "categorical" + }, + { + "op": "drop", + "columns": [ + "Bare_Nuclei", + "lymph_node_status" + ] + }, + { + "op": "min-max", + "columns": "features" + } + ], + "models": [], + "training": { + "layers": [ + { + "class": "dense", + "units": 32, + "activation": "relu" + }, + { + "class": "dense", + "units": 16, + "activation": "relu" + }, + { + "class": "dense", + "units": 1, + "activation": "linear", + "locked": true + } + ] + } + } + ] +} diff --git a/public/models/00-tabular-classification/car/car.csv b/public/n4l/car.n4l/data/car.csv similarity index 100% rename from public/models/00-tabular-classification/car/car.csv rename to public/n4l/car.n4l/data/car.csv diff --git a/public/models/00-tabular-classification/car/car.names b/public/n4l/car.n4l/data/car.names similarity index 100% rename from public/models/00-tabular-classification/car/car.names rename to public/n4l/car.n4l/data/car.names diff --git a/public/n4l/car.n4l/locales/en.json b/public/n4l/car.n4l/locales/en.json new file mode 100644 index 0000000..3adfbec --- /dev/null +++ b/public/n4l/car.n4l/locales/en.json @@ -0,0 +1,80 @@ +{ + "columns": { + "Buying": "Buying price", + "Maint": "Price of the maintenance", + "Doors": "number of doors", + "Persons": "Capacity in terms of persons to carry", + "Lug_boot": "The size of luggage boot", + "Safety": "Estimated safety of the car", + "Result": "Result" + }, + "classes": { + "unacc": "Unacceptable", + "acc": "Acceptable", + "vgood": "Very good", + "good": "Good" + }, + "tasks": { + "tabular-classification": { + "title": "CAR - Car classification", + "name": "Car classification", + "summary": "Whether a car is acceptable given its price, maintenance, seats, boot and safety: everything is a category.", + "description": { + "text": [ + "The dataset car evaluation allows to evaluate vehicles through the following structure", + "For more information about this dataset, visit the ICS.UCI.edu repository." + ], + "sections": [ + { + "title": "Information", + "items": [ + "buying: Purchase price.", + "maint: Maintenance cost.", + "doors: Number of doors.", + "persons: Number of places.", + "lug_boot: Trunk size.", + "safety: Estimated vehicle security." + ] + }, + { + "title": "Input data", + "text": [ + "Characteristics of the car" + ], + "items": [ + "buying: vhigh, high, med, low.", + "maint: vhigh, high, med, low.", + "doors: 2, 3, 4, 5more.", + "persons: 2, 4, more.", + "lug_boot: small, med, big.", + "safety: low, med, high." + ] + }, + { + "title": "Output data", + "text": [ + "Vehicle acceptance" + ], + "items": [ + "unacc : Inaccessible", + "acc : Accessible", + "good : Good", + "vgood : Very good" + ] + }, + { + "title": "References", + "items": [ + "Data set" + ] + } + ] + }, + "example": { + "text": "Enter the values corresponding to the car to be evaluated:", + "items": "(Buying; Maint; Doors; Persons; Lug_boot; Safety)", + "examples": "Examples:" + } + } + } +} diff --git a/public/n4l/car.n4l/locales/es.json b/public/n4l/car.n4l/locales/es.json new file mode 100644 index 0000000..7151c8e --- /dev/null +++ b/public/n4l/car.n4l/locales/es.json @@ -0,0 +1,80 @@ +{ + "columns": { + "Buying": "Precio de compra", + "Maint": "Precio del mantenimiento", + "Doors": "Número de puertas", + "Persons": "Capacidad de personas", + "Lug_boot": "Tamaño del maletero", + "Safety": "Seguridad estimada del coche.", + "Result": "Resultado" + }, + "classes": { + "unacc": "Inaceptable", + "acc": "Aceptable", + "vgood": "Muy bueno", + "good": "Bueno" + }, + "tasks": { + "tabular-classification": { + "title": "CAR - Clasificación de coches", + "name": "Clasificación de coches", + "summary": "Si un coche es aceptable según su precio, su mantenimiento, sus plazas, su maletero y su seguridad: todo son categorías.", + "description": { + "text": [ + "El conjunto de datos Car Evaluation permite evaluar vehículos a través de la siguiente estructura", + "Para obtener más información acerca de este conjunto de datos visita el repositorio ics.uci.edu." + ], + "sections": [ + { + "title": "Información", + "items": [ + "buying: Precio de compra.", + "maint: Costo del mantenimiento.", + "doors: Número de puertas.", + "persons: Número de plazas.", + "lug_boot: Tamaño del maletero.", + "safety: Seguridad estimada del vehículo." + ] + }, + { + "title": "Datos de entrada", + "text": [ + "Características del coche" + ], + "items": [ + "buying: vhigh, high, med, low.", + "maint: vhigh, high, med, low.", + "doors: 2, 3, 4, 5more.", + "persons: 2, 4, more.", + "lug_boot: small, med, big.", + "safety: low, med, high." + ] + }, + { + "title": "Datos de salida", + "text": [ + "Aceptación del vehículo" + ], + "items": [ + "UNACC: Inaccesible", + "ACC: Accesible", + "GOOD: Bien", + "VGOOD: Muy bien" + ] + }, + { + "title": "Referencias", + "items": [ + "Conjunto de datos" + ] + } + ] + }, + "example": { + "text": "Introduce los valores correspondientes a el coche que se va a evaluar:", + "items": "(buying; maint; doors; persons; lug_boot; safety)", + "examples": "Ejemplos:" + } + } + } +} diff --git a/public/n4l/car.n4l/locales/ja.json b/public/n4l/car.n4l/locales/ja.json new file mode 100644 index 0000000..8bfe148 --- /dev/null +++ b/public/n4l/car.n4l/locales/ja.json @@ -0,0 +1,80 @@ +{ + "columns": { + "Buying": "購入価格", + "Maint": "メンテナンス費用", + "Doors": "ドアの数", + "Persons": "乗車定員", + "Lug_boot": "トランクの大きさ", + "Safety": "車の推定安全性", + "Result": "結果" + }, + "classes": { + "unacc": "不可", + "acc": "可", + "vgood": "優", + "good": "良" + }, + "tasks": { + "tabular-classification": { + "title": "CAR - 車両評価分類", + "name": "車両評価分類", + "summary": "価格、維持費、定員、荷室、安全性から、車が受け入れられるかどうかを判定します。すべてカテゴリ値です。", + "description": { + "text": [ + "Car Evaluation データセットは、次の構造を通じて車両を評価できます", + "このデータセットの詳細については、ics.uci.eduリポジトリをご覧ください。" + ], + "sections": [ + { + "title": "情報", + "items": [ + "buying: 購入価格。", + "maint: 維持費。", + "doors: ドア数。", + "persons: 乗車定員。", + "lug_boot: トランクのサイズ。", + "safety: 車両の推定安全性。" + ] + }, + { + "title": "入力データ", + "text": [ + "車両の特徴" + ], + "items": [ + "buying: vhigh (非常に高い), high (高い), med (中), low (低い)。", + "maint: vhigh, high, med, low。", + "doors: 2, 3, 4, 5more (5以上)。", + "persons: 2, 4, more (それ以上)。", + "lug_boot: small (小), med (中), big (大)。", + "safety: low, med, high (高)。" + ] + }, + { + "title": "出力データ", + "text": [ + "車両の受容性" + ], + "items": [ + "unacc: 受け入れられない", + "acc: 受け入れられる", + "good: 良い", + "vgood: 非常に良い" + ] + }, + { + "title": "参照元", + "items": [ + "データセット" + ] + } + ] + }, + "example": { + "text": "評価する車両の対応する値を入力してください:", + "items": "(buying; maint; doors; persons; lug_boot; safety)", + "examples": "例:" + } + } + } +} diff --git a/public/n4l/car.n4l/manifest.json b/public/n4l/car.n4l/manifest.json new file mode 100644 index 0000000..15b602b --- /dev/null +++ b/public/n4l/car.n4l/manifest.json @@ -0,0 +1,225 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "car", + "version": "1.0.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://archive.ics.uci.edu/dataset/19/car+evaluation", + "citation": "@misc{misc_car_evaluation_19,\n author = {Bohanec,Marko},\n title = {{Car Evaluation}},\n year = {1997},\n howpublished = {UCI Machine Learning Repository},\n note = {{DOI}: https://doi.org/10.24432/C5JP48}\n}" + }, + "datasets": [ + { + "id": "car", + "file": "data/car.csv", + "info": "data/car.names", + "rows": 1728, + "columns": [ + { + "name": "Buying", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "buying price (vhigh, high, med, low)", + "options": [ + "vhigh", + "high", + "med", + "low" + ] + }, + { + "name": "Maint", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "price of the maintenance (vhigh, high, med, low)", + "options": [ + "vhigh", + "high", + "med", + "low" + ] + }, + { + "name": "Doors", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "number of doors (2, 3, 4, 5more)", + "options": [ + "2", + "3", + "4", + "5more" + ] + }, + { + "name": "Persons", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "capacity in terms of persons to carry (2, 4, more)", + "options": [ + "2", + "4", + "more" + ] + }, + { + "name": "Lug_boot", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "the size of luggage boot (small, med, big)", + "options": [ + "small", + "med", + "big" + ] + }, + { + "name": "Safety", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "estimated safety of the car (low, med, high)", + "options": [ + "low", + "med", + "high" + ] + }, + { + "name": "Result", + "role": "Target", + "type": "Categorical", + "missing": 0, + "description": "evaluation level (unacc, acc, good, vgood)", + "options": [ + "unacc", + "acc", + "vgood", + "good" + ] + } + ] + } + ], + "tasks": [ + { + "task": "tabular-classification", + "key": "CAR", + "runtime": "tabular-classification", + "datasets": [ + "car" + ], + "preprocessing": [ + { + "op": "label-encoder", + "columns": "categorical" + }, + { + "op": "min-max", + "columns": "features" + } + ], + "classes": [ + { + "id": "unacc" + }, + { + "id": "acc" + }, + { + "id": "vgood" + }, + { + "id": "good" + } + ], + "models": [ + { + "id": "mlp", + "format": "tfjs-layers", + "path": "models/mlp/model.json", + "dataset": "car" + } + ], + "prediction": { + "defaults": { + "Buying": "vhigh", + "Maint": "vhigh", + "Doors": "2", + "Persons": "2", + "Lug_boot": "small", + "Safety": "low" + }, + "examples": [ + { + "values": { + "Buying": "low", + "Maint": "vhigh", + "Doors": "4", + "Persons": "2", + "Lug_boot": "small", + "Safety": "low" + }, + "expected": "unacc" + }, + { + "values": { + "Buying": "med", + "Maint": "low", + "Doors": "5more", + "Persons": "more", + "Lug_boot": "med", + "Safety": "med" + }, + "expected": "acc" + }, + { + "values": { + "Buying": "low", + "Maint": "low", + "Doors": "5more", + "Persons": "more", + "Lug_boot": "big", + "Safety": "high" + }, + "expected": "vgood" + } + ] + }, + "training": { + "layers": [ + { + "class": "dense", + "units": 128, + "activation": "relu" + }, + { + "class": "dense", + "units": 64, + "activation": "relu" + }, + { + "class": "dense", + "units": 32, + "activation": "relu" + }, + { + "class": "dense", + "units": 4, + "activation": "softmax" + } + ] + } + } + ] +} diff --git a/public/n4l/car.n4l/models/mlp/model.json b/public/n4l/car.n4l/models/mlp/model.json new file mode 100644 index 0000000..b716d6d --- /dev/null +++ b/public/n4l/car.n4l/models/mlp/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_1","layers":[{"class_name":"Dense","config":{"units":10,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense1","trainable":true,"batch_input_shape":[null,6],"dtype":"float32"}},{"class_name":"Dense","config":{"units":3,"activation":"softmax","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense2","trainable":true,"batch_input_shape":[null,6],"dtype":"float32"}}]},"keras_version":"tfjs-layers 3.14.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v3.14.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense1/kernel","shape":[6,10],"dtype":"float32"},{"name":"dense_Dense1/bias","shape":[10],"dtype":"float32"},{"name":"dense_Dense2/kernel","shape":[10,3],"dtype":"float32"},{"name":"dense_Dense2/bias","shape":[3],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/00-tabular-classification/car/my-model-car.weights.bin b/public/n4l/car.n4l/models/mlp/model.weights.bin similarity index 100% rename from public/models/00-tabular-classification/car/my-model-car.weights.bin rename to public/n4l/car.n4l/models/mlp/model.weights.bin diff --git a/public/n4l/cifar10.n4l/data/cifar10_images.png b/public/n4l/cifar10.n4l/data/cifar10_images.png new file mode 100644 index 0000000..c03971c Binary files /dev/null and b/public/n4l/cifar10.n4l/data/cifar10_images.png differ diff --git a/public/n4l/cifar10.n4l/data/cifar10_labels_uint8 b/public/n4l/cifar10.n4l/data/cifar10_labels_uint8 new file mode 100644 index 0000000..e28136c Binary files /dev/null and b/public/n4l/cifar10.n4l/data/cifar10_labels_uint8 differ diff --git a/public/n4l/cifar10.n4l/examples/airplane.png b/public/n4l/cifar10.n4l/examples/airplane.png new file mode 100644 index 0000000..bac6aef Binary files /dev/null and b/public/n4l/cifar10.n4l/examples/airplane.png differ diff --git a/public/n4l/cifar10.n4l/examples/automobile.png b/public/n4l/cifar10.n4l/examples/automobile.png new file mode 100644 index 0000000..d40da3c Binary files /dev/null and b/public/n4l/cifar10.n4l/examples/automobile.png differ diff --git a/public/n4l/cifar10.n4l/examples/bird.png b/public/n4l/cifar10.n4l/examples/bird.png new file mode 100644 index 0000000..47b97a7 Binary files /dev/null and b/public/n4l/cifar10.n4l/examples/bird.png differ diff --git a/public/n4l/cifar10.n4l/examples/cat.png b/public/n4l/cifar10.n4l/examples/cat.png new file mode 100644 index 0000000..b7ac068 Binary files /dev/null and b/public/n4l/cifar10.n4l/examples/cat.png differ diff --git a/public/n4l/cifar10.n4l/examples/deer.png b/public/n4l/cifar10.n4l/examples/deer.png new file mode 100644 index 0000000..196ac8e Binary files /dev/null and b/public/n4l/cifar10.n4l/examples/deer.png differ diff --git a/public/n4l/cifar10.n4l/examples/dog.png b/public/n4l/cifar10.n4l/examples/dog.png new file mode 100644 index 0000000..31f5395 Binary files /dev/null and b/public/n4l/cifar10.n4l/examples/dog.png differ diff --git a/public/n4l/cifar10.n4l/examples/frog.png b/public/n4l/cifar10.n4l/examples/frog.png new file mode 100644 index 0000000..2db78bb Binary files /dev/null and b/public/n4l/cifar10.n4l/examples/frog.png differ diff --git a/public/n4l/cifar10.n4l/examples/horse.png b/public/n4l/cifar10.n4l/examples/horse.png new file mode 100644 index 0000000..d539bcf Binary files /dev/null and b/public/n4l/cifar10.n4l/examples/horse.png differ diff --git a/public/n4l/cifar10.n4l/examples/ship.png b/public/n4l/cifar10.n4l/examples/ship.png new file mode 100644 index 0000000..8f24d02 Binary files /dev/null and b/public/n4l/cifar10.n4l/examples/ship.png differ diff --git a/public/n4l/cifar10.n4l/examples/truck.png b/public/n4l/cifar10.n4l/examples/truck.png new file mode 100644 index 0000000..5f5a801 Binary files /dev/null and b/public/n4l/cifar10.n4l/examples/truck.png differ diff --git a/public/n4l/cifar10.n4l/locales/en.json b/public/n4l/cifar10.n4l/locales/en.json new file mode 100644 index 0000000..7c44eaf --- /dev/null +++ b/public/n4l/cifar10.n4l/locales/en.json @@ -0,0 +1,54 @@ +{ + "classes": { + "airplane": "airplane", + "automobile": "automobile", + "bird": "bird", + "cat": "cat", + "deer": "deer", + "dog": "dog", + "frog": "frog", + "horse": "horse", + "ship": "ship", + "truck": "truck" + }, + "tasks": { + "image-classification": { + "title": "CIFAR-10 - Photo classification", + "name": "CIFAR-10 - Photo classification", + "summary": "32×32 color photos of ten classes, from airplanes to trucks: the step from digits to real photos.", + "description": { + "text": [ + "CIFAR-10 is a set of 60,000 color photos of 32 x 32 pixels in 10 classes: airplane, automobile, bird, cat, deer, dog, frog, horse, ship and truck. Alex Krizhevsky, Vinod Nair and Geoffrey Hinton prepared it in 2009 from the 80 million tiny images collection.", + "Unlike MNIST, each image has three channels (red, green and blue) and the object can appear in any position, size, color or background. With so few pixels, it is sometimes hard even for a person: a cat and a dog, or an automobile and a truck, are easily confused." + ], + "sections": [ + { + "title": "Input data", + "items": [ + "Color (RGB) photo of 32 x 32 pixels, each value between 0 and 1" + ] + }, + { + "title": "Output data", + "items": [ + "One of the 10 classes: airplane, automobile, bird, cat, deer, dog, frog, horse, ship or truck" + ] + }, + { + "title": "Models", + "items": [ + "Pre-trained model: convolutional network (three blocks of two convolutional layers and two dense layers) trained with the 50,000 training images, randomly flipped and shifted so that it learns more. It gets {{test_accuracy, number(style: percent; minimumFractionDigits: 1)}} of the {{test_images, number}} test images of the dataset right, which it did not see during training.", + "Training in the browser: a balanced subset is used, with 500 training images and 200 test images per class. With so few photos and few epochs, a small network stays far from the pre-trained model." + ] + }, + { + "title": "References", + "items": [ + "Dataset" + ] + } + ] + } + } + } +} diff --git a/public/n4l/cifar10.n4l/locales/es.json b/public/n4l/cifar10.n4l/locales/es.json new file mode 100644 index 0000000..6d1c7c7 --- /dev/null +++ b/public/n4l/cifar10.n4l/locales/es.json @@ -0,0 +1,54 @@ +{ + "classes": { + "airplane": "avión", + "automobile": "automóvil", + "bird": "pájaro", + "cat": "gato", + "deer": "ciervo", + "dog": "perro", + "frog": "rana", + "horse": "caballo", + "ship": "barco", + "truck": "camión" + }, + "tasks": { + "image-classification": { + "title": "CIFAR-10 - Clasificación de fotos", + "name": "CIFAR-10 - Clasificación de fotos", + "summary": "Fotos en color de 32×32 de diez clases, de aviones a camiones: el paso de los dígitos a las fotos de verdad.", + "description": { + "text": [ + "CIFAR-10 es un conjunto de 60.000 fotos en color de 32 x 32 píxeles repartidas en 10 clases: avión, automóvil, pájaro, gato, ciervo, perro, rana, caballo, barco y camión. Lo prepararon Alex Krizhevsky, Vinod Nair y Geoffrey Hinton en 2009 a partir de la colección de 80 millones de imágenes pequeñas.", + "A diferencia de MNIST, cada imagen tiene tres canales (rojo, verde y azul) y el objeto puede aparecer en cualquier posición, tamaño, color o fondo. Con tan pocos píxeles, a veces cuesta incluso a una persona: un gato y un perro, o un automóvil y un camión, se confunden con facilidad." + ], + "sections": [ + { + "title": "Datos de entrada", + "items": [ + "Foto en color (RGB) de 32 x 32 píxeles, cada valor entre 0 y 1" + ] + }, + { + "title": "Datos de salida", + "items": [ + "Una de las 10 clases: avión, automóvil, pájaro, gato, ciervo, perro, rana, caballo, barco o camión" + ] + }, + { + "title": "Modelos", + "items": [ + "Modelo ya entrenado: red convolucional (tres bloques de dos capas convolucionales y dos capas densas) entrenada con las 50.000 imágenes de entrenamiento, volteadas y desplazadas al azar para que aprenda más. Acierta el {{test_accuracy, number(style: percent; minimumFractionDigits: 1)}} de las {{test_images, number}} imágenes de prueba del conjunto, que no vio al entrenar.", + "Entrenamiento en el navegador: se usa un subconjunto equilibrado, con 500 imágenes de entrenamiento y 200 de prueba por clase. Con tan pocas fotos y pocas épocas, una red pequeña se queda lejos del modelo ya entrenado." + ] + }, + { + "title": "Referencias", + "items": [ + "Conjunto de datos" + ] + } + ] + } + } + } +} diff --git a/public/n4l/cifar10.n4l/locales/ja.json b/public/n4l/cifar10.n4l/locales/ja.json new file mode 100644 index 0000000..1af5f8f --- /dev/null +++ b/public/n4l/cifar10.n4l/locales/ja.json @@ -0,0 +1,54 @@ +{ + "classes": { + "airplane": "飛行機", + "automobile": "自動車", + "bird": "鳥", + "cat": "猫", + "deer": "鹿", + "dog": "犬", + "frog": "カエル", + "horse": "馬", + "ship": "船", + "truck": "トラック" + }, + "tasks": { + "image-classification": { + "title": "CIFAR-10 - 写真の分類", + "name": "CIFAR-10 - 写真の分類", + "summary": "飛行機からトラックまで、10 クラスの 32×32 のカラー写真。数字から本物の写真への一歩です。", + "description": { + "text": [ + "CIFAR-10 は、32 x 32 ピクセルのカラー写真 60,000 枚を 10 クラス(飛行機、自動車、鳥、猫、鹿、犬、カエル、馬、船、トラック)に分けたデータセットです。2009 年に Alex Krizhevsky、Vinod Nair、Geoffrey Hinton が、8,000 万枚の小さな画像のコレクションから作成しました。", + "MNIST と違い、各画像には 3 つのチャンネル(赤、緑、青)があり、物はどんな位置、大きさ、色、背景でも現れます。ピクセルがとても少ないため、人間でも難しいことがあります。猫と犬、自動車とトラックはよく間違えられます。" + ], + "sections": [ + { + "title": "入力データ", + "items": [ + "32 x 32 ピクセルのカラー(RGB)写真。各値は 0 から 1 の間" + ] + }, + { + "title": "出力データ", + "items": [ + "10 クラスのいずれか:飛行機、自動車、鳥、猫、鹿、犬、カエル、馬、船、トラック" + ] + }, + { + "title": "モデル", + "items": [ + "学習済みモデル:畳み込みニューラルネットワーク(畳み込み層 2 つのブロック 3 つと全結合層 2 つ)で、学習用画像 50,000 枚を、より多く学べるようにランダムに反転・移動させて学習しました。学習で見ていないこのデータセットのテスト画像 {{test_images, number}} 枚での正解率は {{test_accuracy, number(style: percent; minimumFractionDigits: 1)}} です。", + "ブラウザでの学習:各クラスについて学習用 500 枚、テスト用 200 枚のバランスの取れたサブセットを使用します。写真もエポックも少ないので、小さなネットワークは学習済みモデルにはなかなか届きません。" + ] + }, + { + "title": "参照元", + "items": [ + "データセット" + ] + } + ] + } + } + } +} diff --git a/public/n4l/cifar10.n4l/manifest.json b/public/n4l/cifar10.n4l/manifest.json new file mode 100644 index 0000000..3f9111d --- /dev/null +++ b/public/n4l/cifar10.n4l/manifest.json @@ -0,0 +1,179 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "cifar10", + "version": "1.0.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://www.cs.toronto.edu/~kriz/cifar.html", + "citation": "@techreport{krizhevsky2009learning,\n title = {Learning Multiple Layers of Features from Tiny Images},\n author = {Krizhevsky, Alex},\n institution = {University of Toronto},\n year = {2009}\n}" + }, + "datasets": [ + { + "id": "cifar10", + "kind": "image-sprite", + "file": "data/cifar10_images.png", + "labels": "data/cifar10_labels_uint8", + "rows": 7000, + "train": 5000, + "image": { + "width": 32, + "height": 32, + "channels": 3 + } + } + ], + "tasks": [ + { + "task": "image-classification", + "key": "IMAGE-CIFAR10", + "runtime": "image-classification", + "datasets": [ + "cifar10" + ], + "order": 3, + "preprocessing": [], + "classes": [ + { + "id": "airplane" + }, + { + "id": "automobile" + }, + { + "id": "bird" + }, + { + "id": "cat" + }, + { + "id": "deer" + }, + { + "id": "dog" + }, + { + "id": "frog" + }, + { + "id": "horse" + }, + { + "id": "ship" + }, + { + "id": "truck" + } + ], + "models": [ + { + "id": "cnn", + "format": "tfjs-layers", + "path": "models/cnn/model.json", + "dataset": "cifar10", + "metrics": { + "test_accuracy": 0.888, + "test_images": 2000 + } + } + ], + "prediction": { + "images": [ + { + "file": "examples/airplane.png", + "expected": "airplane" + }, + { + "file": "examples/automobile.png", + "expected": "automobile" + }, + { + "file": "examples/bird.png", + "expected": "bird" + }, + { + "file": "examples/cat.png", + "expected": "cat" + }, + { + "file": "examples/deer.png", + "expected": "deer" + }, + { + "file": "examples/dog.png", + "expected": "dog" + }, + { + "file": "examples/frog.png", + "expected": "frog" + }, + { + "file": "examples/horse.png", + "expected": "horse" + }, + { + "file": "examples/ship.png", + "expected": "ship" + }, + { + "file": "examples/truck.png", + "expected": "truck" + } + ] + }, + "training": { + "layers": [ + { + "class": "conv2d", + "filters": 32, + "kernelSize": 3, + "activation": "relu", + "locked": true + }, + { + "class": "maxPooling2d", + "poolSize": 2, + "strides": 2 + }, + { + "class": "conv2d", + "filters": 64, + "kernelSize": 3, + "activation": "relu" + }, + { + "class": "maxPooling2d", + "poolSize": 2, + "strides": 2 + }, + { + "class": "conv2d", + "filters": 64, + "kernelSize": 3, + "activation": "relu" + }, + { + "class": "flatten" + }, + { + "class": "dense", + "units": 64, + "activation": "relu" + }, + { + "class": "dense", + "units": 10, + "activation": "softmax" + } + ], + "learningRate": 0.001, + "epochs": 20 + } + } + ] +} diff --git a/public/n4l/cifar10.n4l/models/cnn/model.json b/public/n4l/cifar10.n4l/models/cnn/model.json new file mode 100644 index 0000000..fb6cc32 --- /dev/null +++ b/public/n4l/cifar10.n4l/models/cnn/model.json @@ -0,0 +1 @@ +{"modelTopology": {"class_name": "Sequential", "config": {"name": "sequential_1", "layers": [{"class_name": "Conv2D", "config": {"filters": 32, "kernel_size": [3, 3], "strides": [1, 1], "padding": "same", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1, "mode": "fan_avg", "distribution": "normal", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "kernel_constraint": null, "bias_regularizer": null, "activity_regularizer": null, "bias_constraint": null, "batch_input_shape": [null, 32, 32, 3], "dtype": "float32", "name": "conv2d_Conv2D1", "trainable": true}}, {"class_name": "Conv2D", "config": {"filters": 32, "kernel_size": [3, 3], "strides": [1, 1], "padding": "same", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1, "mode": "fan_avg", "distribution": "normal", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "kernel_constraint": null, "bias_regularizer": null, "activity_regularizer": null, "bias_constraint": null, "name": "conv2d_Conv2D2", "trainable": true}}, {"class_name": "MaxPooling2D", "config": {"pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last", "name": "max_pooling2d_MaxPooling2D1", "trainable": true}}, {"class_name": "Dropout", "config": {"rate": 0.2, "noise_shape": null, "seed": null, "name": "dropout_Dropout1", "trainable": true}}, {"class_name": "Conv2D", "config": {"filters": 64, "kernel_size": [3, 3], "strides": [1, 1], "padding": "same", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1, "mode": "fan_avg", "distribution": "normal", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "kernel_constraint": null, "bias_regularizer": null, "activity_regularizer": null, "bias_constraint": null, "name": "conv2d_Conv2D3", "trainable": true}}, {"class_name": "Conv2D", "config": {"filters": 64, "kernel_size": [3, 3], "strides": [1, 1], "padding": "same", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1, "mode": "fan_avg", "distribution": "normal", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "kernel_constraint": null, "bias_regularizer": null, "activity_regularizer": null, "bias_constraint": null, "name": "conv2d_Conv2D4", "trainable": true}}, {"class_name": "MaxPooling2D", "config": {"pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last", "name": "max_pooling2d_MaxPooling2D2", "trainable": true}}, {"class_name": "Dropout", "config": {"rate": 0.3, "noise_shape": null, "seed": null, "name": "dropout_Dropout2", "trainable": true}}, {"class_name": "Conv2D", "config": {"filters": 128, "kernel_size": [3, 3], "strides": [1, 1], "padding": "same", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1, "mode": "fan_avg", "distribution": "normal", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "kernel_constraint": null, "bias_regularizer": null, "activity_regularizer": null, "bias_constraint": null, "name": "conv2d_Conv2D5", "trainable": true}}, {"class_name": "Conv2D", "config": {"filters": 128, "kernel_size": [3, 3], "strides": [1, 1], "padding": "same", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1, "mode": "fan_avg", "distribution": "normal", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "kernel_constraint": null, "bias_regularizer": null, "activity_regularizer": null, "bias_constraint": null, "name": "conv2d_Conv2D6", "trainable": true}}, {"class_name": "MaxPooling2D", "config": {"pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last", "name": "max_pooling2d_MaxPooling2D3", "trainable": true}}, {"class_name": "Dropout", "config": {"rate": 0.4, "noise_shape": null, "seed": null, "name": "dropout_Dropout3", "trainable": true}}, {"class_name": "Flatten", "config": {"data_format": "channels_last", "name": "flatten_Flatten1", "trainable": true}}, {"class_name": "Dense", "config": {"units": 256, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1, "mode": "fan_avg", "distribution": "normal", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "kernel_constraint": null, "bias_regularizer": null, "activity_regularizer": null, "bias_constraint": null, "name": "dense_Dense1", "trainable": true}}, {"class_name": "Dropout", "config": {"rate": 0.5, "noise_shape": null, "seed": null, "name": "dropout_Dropout4", "trainable": true}}, {"class_name": "Dense", "config": {"units": 10, "activation": "softmax", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1, "mode": "fan_avg", "distribution": "normal", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "kernel_constraint": null, "bias_regularizer": null, "activity_regularizer": null, "bias_constraint": null, "name": "dense_Dense2", "trainable": true}}]}, "keras_version": "tfjs-layers 4.22.0", "backend": "tensor_flow.js"}, "weightsManifest": [{"paths": ["weights.bin"], "weights": [{"name": "conv2d_Conv2D1/kernel", "shape": [3, 3, 3, 32], "dtype": "float32"}, {"name": "conv2d_Conv2D1/bias", "shape": [32], "dtype": "float32"}, {"name": "conv2d_Conv2D2/kernel", "shape": [3, 3, 32, 32], "dtype": "float32"}, {"name": "conv2d_Conv2D2/bias", "shape": [32], "dtype": "float32"}, {"name": "conv2d_Conv2D3/kernel", "shape": [3, 3, 32, 64], "dtype": "float32"}, {"name": "conv2d_Conv2D3/bias", "shape": [64], "dtype": "float32"}, {"name": "conv2d_Conv2D4/kernel", "shape": [3, 3, 64, 64], "dtype": "float32"}, {"name": "conv2d_Conv2D4/bias", "shape": [64], "dtype": "float32"}, {"name": "conv2d_Conv2D5/kernel", "shape": [3, 3, 64, 128], "dtype": "float32"}, {"name": "conv2d_Conv2D5/bias", "shape": [128], "dtype": "float32"}, {"name": "conv2d_Conv2D6/kernel", "shape": [3, 3, 128, 128], "dtype": "float32"}, {"name": "conv2d_Conv2D6/bias", "shape": [128], "dtype": "float32"}, {"name": "dense_Dense1/kernel", "shape": [2048, 256], "dtype": "float32"}, {"name": "dense_Dense1/bias", "shape": [256], "dtype": "float32"}, {"name": "dense_Dense2/kernel", "shape": [256, 10], "dtype": "float32"}, {"name": "dense_Dense2/bias", "shape": [10], "dtype": "float32"}]}], "format": "layers-model", "generatedBy": "Scripts/train_cifar10_model.py (PyTorch)", "convertedBy": null, "userDefinedMetadata": {"dataset": "CIFAR-10", "classLabels": ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"], "trainImages": 50000, "testImages": 10000, "testAccuracy": 0.8967, "epochs": 50}} \ No newline at end of file diff --git a/public/n4l/cifar10.n4l/models/cnn/weights.bin b/public/n4l/cifar10.n4l/models/cnn/weights.bin new file mode 100644 index 0000000..6f34762 Binary files /dev/null and b/public/n4l/cifar10.n4l/models/cnn/weights.bin differ diff --git a/public/n4l/imagenet.n4l/examples/beef-burger.jpg b/public/n4l/imagenet.n4l/examples/beef-burger.jpg new file mode 100644 index 0000000..587f073 Binary files /dev/null and b/public/n4l/imagenet.n4l/examples/beef-burger.jpg differ diff --git a/public/n4l/imagenet.n4l/examples/bulldog.jpg b/public/n4l/imagenet.n4l/examples/bulldog.jpg new file mode 100644 index 0000000..c1fc860 Binary files /dev/null and b/public/n4l/imagenet.n4l/examples/bulldog.jpg differ diff --git a/public/n4l/imagenet.n4l/examples/butterfly.jpg b/public/n4l/imagenet.n4l/examples/butterfly.jpg new file mode 100644 index 0000000..39412e5 Binary files /dev/null and b/public/n4l/imagenet.n4l/examples/butterfly.jpg differ diff --git a/public/n4l/imagenet.n4l/examples/cat.jpg b/public/n4l/imagenet.n4l/examples/cat.jpg new file mode 100644 index 0000000..1ea7b0b Binary files /dev/null and b/public/n4l/imagenet.n4l/examples/cat.jpg differ diff --git a/public/n4l/imagenet.n4l/examples/cheetah.jpg b/public/n4l/imagenet.n4l/examples/cheetah.jpg new file mode 100644 index 0000000..1a07651 Binary files /dev/null and b/public/n4l/imagenet.n4l/examples/cheetah.jpg differ diff --git a/public/n4l/imagenet.n4l/examples/cruise.jpg b/public/n4l/imagenet.n4l/examples/cruise.jpg new file mode 100644 index 0000000..f88e654 Binary files /dev/null and b/public/n4l/imagenet.n4l/examples/cruise.jpg differ diff --git a/public/n4l/imagenet.n4l/examples/duck.jpg b/public/n4l/imagenet.n4l/examples/duck.jpg new file mode 100644 index 0000000..05ded51 Binary files /dev/null and b/public/n4l/imagenet.n4l/examples/duck.jpg differ diff --git a/public/n4l/imagenet.n4l/examples/elephant.jpg b/public/n4l/imagenet.n4l/examples/elephant.jpg new file mode 100644 index 0000000..e71caee Binary files /dev/null and b/public/n4l/imagenet.n4l/examples/elephant.jpg differ diff --git a/public/n4l/imagenet.n4l/examples/lion.jpg b/public/n4l/imagenet.n4l/examples/lion.jpg new file mode 100644 index 0000000..a5b47c6 Binary files /dev/null and b/public/n4l/imagenet.n4l/examples/lion.jpg differ diff --git a/public/n4l/imagenet.n4l/locales/en.json b/public/n4l/imagenet.n4l/locales/en.json new file mode 100644 index 0000000..0d0f3c9 --- /dev/null +++ b/public/n4l/imagenet.n4l/locales/en.json @@ -0,0 +1,39 @@ +{ + "tasks": { + "image-classification": { + "title": "MobileNet - Image classification", + "name": "MobileNet - Image Classifier", + "summary": "All kinds of photos: MobileNet V2, pre-trained on ImageNet, recognises a thousand categories of animals, objects and food.", + "description": { + "text": [ + "MobileNet V2 is a family of neural networks for the classification of similar images and tasks.", + "This model is able to differentiate between 1001 categories, identifying the main context of the image." + ], + "sections": [ + { + "title": "Input data", + "items": [ + "Image with color values between [0, 1] of 224 x 224 pixels." + ] + }, + { + "title": "Output data", + "items": [ + "A number of 0 to 1001 that are each of the categories of this list " + ] + }, + { + "title": "References", + "text": [ + "Originally it was published by Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen:" + ], + "items": [ + "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation 2018", + "ImageNet: the dataset it was trained with. It is not in the package: it has over a million photos." + ] + } + ] + } + } + } +} diff --git a/public/n4l/imagenet.n4l/locales/es.json b/public/n4l/imagenet.n4l/locales/es.json new file mode 100644 index 0000000..e8361c3 --- /dev/null +++ b/public/n4l/imagenet.n4l/locales/es.json @@ -0,0 +1,39 @@ +{ + "tasks": { + "image-classification": { + "title": "MobileNet - Clasificación de imágenes", + "name": "MobileNet - Clasificación de imágenes", + "summary": "Fotos de todo tipo: MobileNet V2, ya entrenado con ImageNet, reconoce mil categorías de animales, objetos y comida.", + "description": { + "text": [ + "MobileNet V2 es una familia de arquitecturas de redes neuronales para la clasificación de imágenes y tareas similares.", + "Este modelo es capaz de diferenciar entre 1001 categorías, identificando el contexto principal de la imagen." + ], + "sections": [ + { + "title": "Datos de entrada", + "items": [ + "Imagen con valores de color entre [0, 1] de 224 x 224 píxeles." + ] + }, + { + "title": "Datos de salida", + "items": [ + "Un número de 0 a 1001 que son cada una de las categorías de esta lista" + ] + }, + { + "title": "Referencias", + "text": [ + "Originalmente, fue publicado por Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen:" + ], + "items": [ + "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation 2018", + "ImageNet: el conjunto con el que se entrenó. No va en el paquete: son más de un millón de fotos." + ] + } + ] + } + } + } +} diff --git a/public/n4l/imagenet.n4l/locales/ja.json b/public/n4l/imagenet.n4l/locales/ja.json new file mode 100644 index 0000000..eb319e8 --- /dev/null +++ b/public/n4l/imagenet.n4l/locales/ja.json @@ -0,0 +1,39 @@ +{ + "tasks": { + "image-classification": { + "title": "MobileNet - 画像分類", + "name": "MobileNet - 画像分類器", + "summary": "あらゆる写真:ImageNet で学習済みの MobileNet V2 が、動物・物・食べ物など 1,000 のカテゴリを認識します。", + "description": { + "text": [ + "MobileNet V2は、画像分類などに使用されるニューラルネットワークアーキテクチャのファミリーです。", + "このモデルは、画像の主要なコンテキストを識別することで、1001のカテゴリを区別できます。" + ], + "sections": [ + { + "title": "入力データ", + "items": [ + "224 x 224ピクセルサイズで、[0, 1]の色の値を持つ画像。" + ] + }, + { + "title": "出力データ", + "items": [ + "このリストの各カテゴリに対応する0から1001までの数字" + ] + }, + { + "title": "参照元", + "text": [ + "Mark Sandler、Andrew Howard、Menglong Zhu、Andrey Zhmoginov、Liang-Chieh Chenによって最初に公開されました:" + ], + "items": [ + "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation 2018", + "ImageNet:学習に使われたデータセットです。100 万枚を超える写真があるため、パッケージには含まれていません。" + ] + } + ] + } + } + } +} diff --git a/public/n4l/imagenet.n4l/manifest.json b/public/n4l/imagenet.n4l/manifest.json new file mode 100644 index 0000000..864df84 --- /dev/null +++ b/public/n4l/imagenet.n4l/manifest.json @@ -0,0 +1,80 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "imagenet", + "version": "1.0.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://www.image-net.org/", + "links": { + "link2": "https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt", + "link3": "https://arxiv.org/abs/1801.04381" + }, + "citation": "@inproceedings{deng2009imagenet,\n title={ImageNet: A large-scale hierarchical image database},\n author={Deng, Jia and Dong, Wei and Socher, Richard and Li, Li-Jia and Li, Kai and Fei-Fei, Li},\n booktitle={2009 IEEE Conference on Computer Vision and Pattern Recognition},\n pages={248--255},\n year={2009},\n organization={IEEE}\n}\n\n@inproceedings{sandler2018mobilenetv2,\n title={MobileNetV2: Inverted Residuals and Linear Bottlenecks},\n author={Sandler, Mark and Howard, Andrew and Zhu, Menglong and Zhmoginov, Andrey and Chen, Liang-Chieh},\n booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},\n pages={4510--4520},\n year={2018}\n}" + }, + "datasets": [ + { + "id": "imagenet", + "kind": "external", + "url": "https://www.image-net.org/", + "rows": 1281167 + } + ], + "tasks": [ + { + "task": "image-classification", + "key": "IMAGE-MOBILENET", + "runtime": "image-classification", + "datasets": [ + "imagenet" + ], + "order": 4, + "preprocessing": [], + "models": [ + { + "id": "mobilenet-v2", + "format": "tfjs-mobilenet", + "dataset": "imagenet", + "version": 2, + "alpha": 1 + } + ], + "prediction": { + "images": [ + { + "file": "examples/beef-burger.jpg" + }, + { + "file": "examples/bulldog.jpg" + }, + { + "file": "examples/butterfly.jpg" + }, + { + "file": "examples/cat.jpg" + }, + { + "file": "examples/cheetah.jpg" + }, + { + "file": "examples/cruise.jpg" + }, + { + "file": "examples/duck.jpg" + }, + { + "file": "examples/elephant.jpg" + }, + { + "file": "examples/lion.jpg" + } + ] + } + } + ] +} diff --git a/public/models/00-tabular-classification/iris/iris.csv b/public/n4l/iris.n4l/data/iris.csv similarity index 100% rename from public/models/00-tabular-classification/iris/iris.csv rename to public/n4l/iris.n4l/data/iris.csv diff --git a/public/models/00-tabular-classification/iris/iris.names b/public/n4l/iris.n4l/data/iris.names similarity index 100% rename from public/models/00-tabular-classification/iris/iris.names rename to public/n4l/iris.n4l/data/iris.names diff --git a/public/n4l/iris.n4l/locales/en.json b/public/n4l/iris.n4l/locales/en.json new file mode 100644 index 0000000..dfaca4e --- /dev/null +++ b/public/n4l/iris.n4l/locales/en.json @@ -0,0 +1,60 @@ +{ + "columns": { + "sepal_length": "Sepal length", + "sepal_width": "Sepal width", + "petal_length": "Petal length", + "petal_width": "Petal width", + "class": "Class" + }, + "classes": { + "Setosa": "Iris setosa", + "Versicolor": "Iris versicolor", + "Virginica": "Iris virginica" + }, + "tasks": { + "tabular-classification": { + "title": "IRIS - Iris classification", + "name": "Iris classification", + "summary": "The classic to start with: the species of a flower from the measurements of its petals and sepals.", + "description": { + "text": [ + "The Iris-Data dataset allows to detect what type of iris plant is from the altitude and length of its petal and sepalo." + ], + "sections": [ + { + "title": "Input data", + "items": [ + "Sepal length: continuous", + "Sepal width: continuous", + "Petal length: continuous", + "Petal width: continuous" + ] + }, + { + "title": "Output data", + "items": [ + "0: Setosa", + "1: Versicolor", + "2: Virginica" + ] + }, + { + "title": "References", + "items": [ + "Data set" + ] + } + ] + }, + "example": { + "text": "Enter the values corresponding to the plant to be evaluated:", + "items": "(sepal length; sepalo width; petal length; petal width).", + "examples": "Examples:" + } + }, + "clustering": { + "name": "Iris flowers (without the species)", + "summary": "The measurements of 150 flowers, without the species: one species separates on its own and the other two touch." + } + } +} diff --git a/public/n4l/iris.n4l/locales/es.json b/public/n4l/iris.n4l/locales/es.json new file mode 100644 index 0000000..8b6593e --- /dev/null +++ b/public/n4l/iris.n4l/locales/es.json @@ -0,0 +1,60 @@ +{ + "columns": { + "sepal_length": "Longitud sépalo", + "sepal_width": "Anchura sépalo", + "petal_length": "Longitud pétalo", + "petal_width": "Anchura pétalo", + "class": "Clase" + }, + "classes": { + "Setosa": "Iris setosa", + "Versicolor": "Iris versicolor", + "Virginica": "Iris virginica" + }, + "tasks": { + "tabular-classification": { + "title": "IRIS - Clasificación de iris", + "name": "Clasificación de flor iris", + "summary": "El clásico para empezar: la especie de una flor a partir de las medidas de sus pétalos y sus sépalos.", + "description": { + "text": [ + "El conjunto de datos de Iris-Data permite detectar que tipo de planta iris es a partir de altitud y longitud de su pétalo y sépalo." + ], + "sections": [ + { + "title": "Datos de entrada", + "items": [ + "Longitud del sépalo: continuo", + "Anchura del sépalo: continuo", + "Longitud del pétalo: continuo", + "Anchura del pétalo: continuo" + ] + }, + { + "title": "Datos de salida", + "items": [ + "0: Iris Setosa", + "1: Iris Versicolor", + "2: Iris Virginica" + ] + }, + { + "title": "Referencias", + "items": [ + "Conjunto de datos" + ] + } + ] + }, + "example": { + "text": "Introduce los valores correspondientes a la flor que se va a evaluar:", + "items": "(longitud sépalo; anchura sépalo; longitud pétalo; anchura pétalo).", + "examples": "Ejemplos:" + } + }, + "clustering": { + "name": "Flores iris (sin la especie)", + "summary": "Las medidas de 150 flores, sin decirle la especie: una especie se separa sola y las otras dos se tocan." + } + } +} diff --git a/public/n4l/iris.n4l/locales/ja.json b/public/n4l/iris.n4l/locales/ja.json new file mode 100644 index 0000000..f4c248e --- /dev/null +++ b/public/n4l/iris.n4l/locales/ja.json @@ -0,0 +1,60 @@ +{ + "columns": { + "sepal_length": "がく片の長さ", + "sepal_width": "がく片の幅", + "petal_length": "花弁の長さ", + "petal_width": "花弁の幅", + "class": "クラス" + }, + "classes": { + "Setosa": "ヒオウギアヤメ (setosa)", + "Versicolor": "ブルーフラッグ (versicolor)", + "Virginica": "バージニカ (virginica)" + }, + "tasks": { + "tabular-classification": { + "title": "IRIS - アヤメ分類", + "name": "アヤメ分類", + "summary": "最初に試す定番:花びらとがく片の大きさから花の種類を当てます。", + "description": { + "text": [ + "Iris-Data データセットは、花弁と萼の長さと幅から、アヤメのどのタイプかを検出できます。" + ], + "sections": [ + { + "title": "入力データ", + "items": [ + "Sepal length (萼の長さ): 連続値", + "Sepal width (萼の幅): 連続値", + "Petal length (花弁の長さ): 連続値", + "Petal width (花弁の幅): 連続値" + ] + }, + { + "title": "出力データ", + "items": [ + "0: Iris Setosa", + "1: Iris Versicolor", + "2: Iris Virginica" + ] + }, + { + "title": "参照元", + "items": [ + "データセット" + ] + } + ] + }, + "example": { + "text": "評価する植物に対応する値を入力してください:", + "items": "(萼の長さ; 萼の幅; 花弁の長さ; 花弁の幅)。", + "examples": "例:" + } + }, + "clustering": { + "name": "アヤメ(種類なし)", + "summary": "150本の花の測定値(種類なし):1つの種類は自然に分かれ、残りの2つは接しています。" + } + } +} diff --git a/public/n4l/iris.n4l/manifest.json b/public/n4l/iris.n4l/manifest.json new file mode 100644 index 0000000..0eb78eb --- /dev/null +++ b/public/n4l/iris.n4l/manifest.json @@ -0,0 +1,180 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "iris", + "version": "1.0.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://archive.ics.uci.edu/dataset/53/iris", + "citation": "@misc{misc_iris_53,\n author = {Fisher,R. A.},\n title = {{Iris}},\n year = {1988},\n howpublished = {UCI Machine Learning Repository},\n note = {{DOI}: https://doi.org/10.24432/C56C76}\n}" + }, + "datasets": [ + { + "id": "iris", + "file": "data/iris.csv", + "info": "data/iris.names", + "rows": 150, + "columns": [ + { + "name": "sepal_length", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "units": "cm" + }, + { + "name": "sepal_width", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "units": "cm" + }, + { + "name": "petal_length", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "units": "cm" + }, + { + "name": "petal_width", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "units": "cm" + }, + { + "name": "class", + "role": "Target", + "type": "Categorical", + "missing": 0, + "description": "class of iris plant: Iris Setosa, Iris Versicolour or Iris Virginica", + "options": [ + "Setosa", + "Versicolor", + "Virginica" + ] + } + ] + } + ], + "tasks": [ + { + "task": "tabular-classification", + "key": "IRIS", + "runtime": "tabular-classification", + "datasets": [ + "iris" + ], + "preprocessing": [ + { + "op": "label-encoder", + "columns": "categorical" + }, + { + "op": "min-max", + "columns": "features" + } + ], + "classes": [ + { + "id": "Setosa", + "aliases": [ + "Iris-setosa" + ] + }, + { + "id": "Versicolor", + "aliases": [ + "Iris-versicolor" + ] + }, + { + "id": "Virginica", + "aliases": [ + "Iris-virginica" + ] + } + ], + "models": [ + { + "id": "mlp", + "format": "tfjs-layers", + "path": "models/mlp/model.json", + "dataset": "iris" + } + ], + "prediction": { + "defaults": { + "sepal_length": 5.1, + "sepal_width": 3.5, + "petal_length": 1.4, + "petal_width": 0.2 + }, + "examples": [ + { + "values": { + "sepal_length": 5.1, + "sepal_width": 3.5, + "petal_length": 1.4, + "petal_width": 0.2 + }, + "expected": "Setosa" + }, + { + "values": { + "sepal_length": 6.1, + "sepal_width": 3, + "petal_length": 4.6, + "petal_width": 1.4 + }, + "expected": "Versicolor" + }, + { + "values": { + "sepal_length": 5.8, + "sepal_width": 2.7, + "petal_length": 5.1, + "petal_width": 1.9 + }, + "expected": "Virginica" + } + ] + }, + "training": { + "layers": [ + { + "class": "dense", + "units": 10, + "activation": "relu" + }, + { + "class": "dense", + "units": 10, + "activation": "relu" + }, + { + "class": "dense", + "units": 3, + "activation": "softmax" + } + ] + } + }, + { + "task": "clustering", + "key": "IRIS", + "runtime": "clustering", + "datasets": [ + "iris" + ], + "preprocessing": [], + "models": [] + } + ] +} diff --git a/public/n4l/iris.n4l/models/mlp/model.json b/public/n4l/iris.n4l/models/mlp/model.json new file mode 100644 index 0000000..d91ce64 --- /dev/null +++ b/public/n4l/iris.n4l/models/mlp/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_1","layers":[{"class_name":"Dense","config":{"units":10,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense1","trainable":true,"batch_input_shape":[null,4],"dtype":"float32"}},{"class_name":"Dense","config":{"units":3,"activation":"softmax","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense2","trainable":true}}]},"keras_version":"tfjs-layers 3.14.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v3.14.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense1/kernel","shape":[4,10],"dtype":"float32"},{"name":"dense_Dense1/bias","shape":[10],"dtype":"float32"},{"name":"dense_Dense2/kernel","shape":[10,3],"dtype":"float32"},{"name":"dense_Dense2/bias","shape":[3],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/00-tabular-classification/iris/my-model-iris.weights.bin b/public/n4l/iris.n4l/models/mlp/model.weights.bin similarity index 100% rename from public/models/00-tabular-classification/iris/my-model-iris.weights.bin rename to public/n4l/iris.n4l/models/mlp/model.weights.bin diff --git a/public/datasets/03-image-classification/kmnist/kmnist_classmap.csv b/public/n4l/kmnist.n4l/data/kmnist_classmap.csv similarity index 100% rename from public/datasets/03-image-classification/kmnist/kmnist_classmap.csv rename to public/n4l/kmnist.n4l/data/kmnist_classmap.csv diff --git a/public/datasets/03-image-classification/kmnist/kmnist_images.png b/public/n4l/kmnist.n4l/data/kmnist_images.png similarity index 100% rename from public/datasets/03-image-classification/kmnist/kmnist_images.png rename to public/n4l/kmnist.n4l/data/kmnist_images.png diff --git a/public/datasets/03-image-classification/kmnist/kmnist_labels_uint8 b/public/n4l/kmnist.n4l/data/kmnist_labels_uint8 similarity index 100% rename from public/datasets/03-image-classification/kmnist/kmnist_labels_uint8 rename to public/n4l/kmnist.n4l/data/kmnist_labels_uint8 diff --git a/public/assets/kmnist/0.png b/public/n4l/kmnist.n4l/examples/0.png similarity index 100% rename from public/assets/kmnist/0.png rename to public/n4l/kmnist.n4l/examples/0.png diff --git a/public/assets/kmnist/1.png b/public/n4l/kmnist.n4l/examples/1.png similarity index 100% rename from public/assets/kmnist/1.png rename to public/n4l/kmnist.n4l/examples/1.png diff --git a/public/assets/kmnist/2.png b/public/n4l/kmnist.n4l/examples/2.png similarity index 100% rename from public/assets/kmnist/2.png rename to public/n4l/kmnist.n4l/examples/2.png diff --git a/public/assets/kmnist/3.png b/public/n4l/kmnist.n4l/examples/3.png similarity index 100% rename from public/assets/kmnist/3.png rename to public/n4l/kmnist.n4l/examples/3.png diff --git a/public/assets/kmnist/4.png b/public/n4l/kmnist.n4l/examples/4.png similarity index 100% rename from public/assets/kmnist/4.png rename to public/n4l/kmnist.n4l/examples/4.png diff --git a/public/assets/kmnist/5.png b/public/n4l/kmnist.n4l/examples/5.png similarity index 100% rename from public/assets/kmnist/5.png rename to public/n4l/kmnist.n4l/examples/5.png diff --git a/public/assets/kmnist/6.png b/public/n4l/kmnist.n4l/examples/6.png similarity index 100% rename from public/assets/kmnist/6.png rename to public/n4l/kmnist.n4l/examples/6.png diff --git a/public/assets/kmnist/7.png b/public/n4l/kmnist.n4l/examples/7.png similarity index 100% rename from public/assets/kmnist/7.png rename to public/n4l/kmnist.n4l/examples/7.png diff --git a/public/assets/kmnist/8.png b/public/n4l/kmnist.n4l/examples/8.png similarity index 100% rename from public/assets/kmnist/8.png rename to public/n4l/kmnist.n4l/examples/8.png diff --git a/public/assets/kmnist/9.png b/public/n4l/kmnist.n4l/examples/9.png similarity index 100% rename from public/assets/kmnist/9.png rename to public/n4l/kmnist.n4l/examples/9.png diff --git a/public/n4l/kmnist.n4l/examples/forms/1B014.png b/public/n4l/kmnist.n4l/examples/forms/1B014.png new file mode 100644 index 0000000..5af7455 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B014.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B015.png b/public/n4l/kmnist.n4l/examples/forms/1B015.png new file mode 100644 index 0000000..8970add Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B015.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B016.png b/public/n4l/kmnist.n4l/examples/forms/1B016.png new file mode 100644 index 0000000..b27420b Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B016.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B023.png b/public/n4l/kmnist.n4l/examples/forms/1B023.png new file mode 100644 index 0000000..23a9081 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B023.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B024.png b/public/n4l/kmnist.n4l/examples/forms/1B024.png new file mode 100644 index 0000000..6aa379b Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B024.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B025.png b/public/n4l/kmnist.n4l/examples/forms/1B025.png new file mode 100644 index 0000000..23072a0 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B025.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B026.png b/public/n4l/kmnist.n4l/examples/forms/1B026.png new file mode 100644 index 0000000..67bd197 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B026.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B027.png b/public/n4l/kmnist.n4l/examples/forms/1B027.png new file mode 100644 index 0000000..b4dc753 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B027.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B028.png b/public/n4l/kmnist.n4l/examples/forms/1B028.png new file mode 100644 index 0000000..86072e4 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B028.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B029.png b/public/n4l/kmnist.n4l/examples/forms/1B029.png new file mode 100644 index 0000000..76864a1 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B029.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B02A.png b/public/n4l/kmnist.n4l/examples/forms/1B02A.png new file mode 100644 index 0000000..549316b Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B02A.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B04A.png b/public/n4l/kmnist.n4l/examples/forms/1B04A.png new file mode 100644 index 0000000..23bd1f7 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B04A.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B04B.png b/public/n4l/kmnist.n4l/examples/forms/1B04B.png new file mode 100644 index 0000000..1e1786c Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B04B.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B04C.png b/public/n4l/kmnist.n4l/examples/forms/1B04C.png new file mode 100644 index 0000000..a26fe02 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B04C.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B04D.png b/public/n4l/kmnist.n4l/examples/forms/1B04D.png new file mode 100644 index 0000000..223423a Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B04D.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B04E.png b/public/n4l/kmnist.n4l/examples/forms/1B04E.png new file mode 100644 index 0000000..fba3385 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B04E.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B04F.png b/public/n4l/kmnist.n4l/examples/forms/1B04F.png new file mode 100644 index 0000000..7c23c6d Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B04F.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B050.png b/public/n4l/kmnist.n4l/examples/forms/1B050.png new file mode 100644 index 0000000..d14468e Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B050.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B051.png b/public/n4l/kmnist.n4l/examples/forms/1B051.png new file mode 100644 index 0000000..d34e18a Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B051.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B069.png b/public/n4l/kmnist.n4l/examples/forms/1B069.png new file mode 100644 index 0000000..c702850 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B069.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B06A.png b/public/n4l/kmnist.n4l/examples/forms/1B06A.png new file mode 100644 index 0000000..e465649 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B06A.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B06B.png b/public/n4l/kmnist.n4l/examples/forms/1B06B.png new file mode 100644 index 0000000..ff1e979 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B06B.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B06C.png b/public/n4l/kmnist.n4l/examples/forms/1B06C.png new file mode 100644 index 0000000..2536783 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B06C.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B06D.png b/public/n4l/kmnist.n4l/examples/forms/1B06D.png new file mode 100644 index 0000000..d604b59 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B06D.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B07E.png b/public/n4l/kmnist.n4l/examples/forms/1B07E.png new file mode 100644 index 0000000..c964512 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B07E.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B07F.png b/public/n4l/kmnist.n4l/examples/forms/1B07F.png new file mode 100644 index 0000000..4b0af46 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B07F.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B080.png b/public/n4l/kmnist.n4l/examples/forms/1B080.png new file mode 100644 index 0000000..cdb29f2 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B080.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B081.png b/public/n4l/kmnist.n4l/examples/forms/1B081.png new file mode 100644 index 0000000..51be60d Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B081.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B082.png b/public/n4l/kmnist.n4l/examples/forms/1B082.png new file mode 100644 index 0000000..cea416f Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B082.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B083.png b/public/n4l/kmnist.n4l/examples/forms/1B083.png new file mode 100644 index 0000000..9e5c878 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B083.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B084.png b/public/n4l/kmnist.n4l/examples/forms/1B084.png new file mode 100644 index 0000000..1f3c604 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B084.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B085.png b/public/n4l/kmnist.n4l/examples/forms/1B085.png new file mode 100644 index 0000000..a19845a Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B085.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B086.png b/public/n4l/kmnist.n4l/examples/forms/1B086.png new file mode 100644 index 0000000..a50971f Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B086.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B09E.png b/public/n4l/kmnist.n4l/examples/forms/1B09E.png new file mode 100644 index 0000000..7d6122e Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B09E.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B09F.png b/public/n4l/kmnist.n4l/examples/forms/1B09F.png new file mode 100644 index 0000000..4439df4 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B09F.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0A0.png b/public/n4l/kmnist.n4l/examples/forms/1B0A0.png new file mode 100644 index 0000000..48f58c9 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0A0.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0A1.png b/public/n4l/kmnist.n4l/examples/forms/1B0A1.png new file mode 100644 index 0000000..6cb1b9a Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0A1.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0A2.png b/public/n4l/kmnist.n4l/examples/forms/1B0A2.png new file mode 100644 index 0000000..da1c076 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0A2.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0A3.png b/public/n4l/kmnist.n4l/examples/forms/1B0A3.png new file mode 100644 index 0000000..e005ce0 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0A3.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0A4.png b/public/n4l/kmnist.n4l/examples/forms/1B0A4.png new file mode 100644 index 0000000..8426f7a Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0A4.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0A5.png b/public/n4l/kmnist.n4l/examples/forms/1B0A5.png new file mode 100644 index 0000000..fc02863 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0A5.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0A6.png b/public/n4l/kmnist.n4l/examples/forms/1B0A6.png new file mode 100644 index 0000000..36505ab Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0A6.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0A7.png b/public/n4l/kmnist.n4l/examples/forms/1B0A7.png new file mode 100644 index 0000000..4c09e98 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0A7.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0A8.png b/public/n4l/kmnist.n4l/examples/forms/1B0A8.png new file mode 100644 index 0000000..b0ce6fe Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0A8.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0C2.png b/public/n4l/kmnist.n4l/examples/forms/1B0C2.png new file mode 100644 index 0000000..7dfd173 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0C2.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0C3.png b/public/n4l/kmnist.n4l/examples/forms/1B0C3.png new file mode 100644 index 0000000..956b9a2 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0C3.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0C4.png b/public/n4l/kmnist.n4l/examples/forms/1B0C4.png new file mode 100644 index 0000000..9cdd982 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0C4.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0C5.png b/public/n4l/kmnist.n4l/examples/forms/1B0C5.png new file mode 100644 index 0000000..11d0d2f Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0C5.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0C6.png b/public/n4l/kmnist.n4l/examples/forms/1B0C6.png new file mode 100644 index 0000000..6a818cf Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0C6.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0C7.png b/public/n4l/kmnist.n4l/examples/forms/1B0C7.png new file mode 100644 index 0000000..7f146cf Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0C7.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0C8.png b/public/n4l/kmnist.n4l/examples/forms/1B0C8.png new file mode 100644 index 0000000..ac58e72 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0C8.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0DD.png b/public/n4l/kmnist.n4l/examples/forms/1B0DD.png new file mode 100644 index 0000000..fdd1d05 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0DD.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0DE.png b/public/n4l/kmnist.n4l/examples/forms/1B0DE.png new file mode 100644 index 0000000..c891703 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0DE.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0DF.png b/public/n4l/kmnist.n4l/examples/forms/1B0DF.png new file mode 100644 index 0000000..8b05951 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0DF.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0E0.png b/public/n4l/kmnist.n4l/examples/forms/1B0E0.png new file mode 100644 index 0000000..aac3715 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0E0.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0E1.png b/public/n4l/kmnist.n4l/examples/forms/1B0E1.png new file mode 100644 index 0000000..13a3178 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0E1.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0E2.png b/public/n4l/kmnist.n4l/examples/forms/1B0E2.png new file mode 100644 index 0000000..488e303 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0E2.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0FE.png b/public/n4l/kmnist.n4l/examples/forms/1B0FE.png new file mode 100644 index 0000000..c163782 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0FE.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B0FF.png b/public/n4l/kmnist.n4l/examples/forms/1B0FF.png new file mode 100644 index 0000000..3dd2ec9 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B0FF.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B100.png b/public/n4l/kmnist.n4l/examples/forms/1B100.png new file mode 100644 index 0000000..f4e4a11 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B100.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B101.png b/public/n4l/kmnist.n4l/examples/forms/1B101.png new file mode 100644 index 0000000..21df21a Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B101.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B116.png b/public/n4l/kmnist.n4l/examples/forms/1B116.png new file mode 100644 index 0000000..705c07a Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B116.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B117.png b/public/n4l/kmnist.n4l/examples/forms/1B117.png new file mode 100644 index 0000000..047028f Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B117.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B118.png b/public/n4l/kmnist.n4l/examples/forms/1B118.png new file mode 100644 index 0000000..533cc39 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B118.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B119.png b/public/n4l/kmnist.n4l/examples/forms/1B119.png new file mode 100644 index 0000000..bff408d Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B119.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B11A.png b/public/n4l/kmnist.n4l/examples/forms/1B11A.png new file mode 100644 index 0000000..f0dbaea Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B11A.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B11B.png b/public/n4l/kmnist.n4l/examples/forms/1B11B.png new file mode 100644 index 0000000..edf2ab0 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B11B.png differ diff --git a/public/n4l/kmnist.n4l/examples/forms/1B11C.png b/public/n4l/kmnist.n4l/examples/forms/1B11C.png new file mode 100644 index 0000000..1e145d8 Binary files /dev/null and b/public/n4l/kmnist.n4l/examples/forms/1B11C.png differ diff --git a/public/n4l/kmnist.n4l/locales/en.json b/public/n4l/kmnist.n4l/locales/en.json new file mode 100644 index 0000000..ad7c666 --- /dev/null +++ b/public/n4l/kmnist.n4l/locales/en.json @@ -0,0 +1,44 @@ +{ + "tasks": { + "image-classification": { + "title": "KMNIST - Japanese character classification", + "name": "KMNIST - Japanese character classification", + "summary": "Ten handwritten hiragana characters from classical Japanese: like MNIST, but harder.", + "description": { + "text": [ + "Kuzushiji-MNIST (KMNIST) is a drop-in replacement for MNIST: grayscale images of 28 x 28 pixels and 10 classes, but instead of digits it contains handwritten Japanese characters written in kuzushiji (cursive script).", + "Kuzushiji was the usual way of writing Japanese for over a thousand years, but it stopped being taught after the writing reform of the early 20th century and today very few people can read it. The images come from classical books digitised by the National Institute of Japanese Literature and were prepared by the ROIS-DS Center for Open Data in the Humanities (CODH).", + "Each class is a modern hiragana character, but in the dataset it appears handwritten as it used to be. Until 1900 the same syllable could be written in many ways: with the kanji today's form comes from, drawn differently, or starting from another kanji. These are the hentaigana; that year only one form was kept, today's. That is why one class gathers strokes that look little like each other or like the modern character, and it is harder than MNIST." + ], + "sections": [ + { + "title": "Input data", + "items": [ + "Grayscale image of 28 x 28 pixels" + ] + }, + { + "title": "Output data", + "items": [ + "One of the 10 hiragana characters: お, き, す, つ, な, は, ま, や, れ, を" + ] + }, + { + "title": "Models", + "items": [ + "Pre-trained model: convolutional network trained with the 55,000 KMNIST training images (and 5,000 more for validation). It gets {{test_accuracy, number(style: percent; minimumFractionDigits: 1)}} of the {{test_images, number}} test images of the dataset right, which it did not see during training.", + "Training in the browser: a balanced subset is used, with 2,000 training images and 500 test images per character." + ] + } + ] + }, + "forms": { + "title": "The 10 characters, today and before", + "modern": "Today", + "old": "Before: other forms (hentaigana), with their kanji", + "old-alt": "old {{char}}, from {{origin}}", + "note": "Under each modern character, how it is read and the kanji it comes from; under each old form, its own. The old forms are the Unicode hentaigana, drawn with the Noto Serif Hentaigana font. In the dataset they appear handwritten: to see them like that, load the test images on the model page." + } + } + } +} diff --git a/public/n4l/kmnist.n4l/locales/es.json b/public/n4l/kmnist.n4l/locales/es.json new file mode 100644 index 0000000..22aa2e9 --- /dev/null +++ b/public/n4l/kmnist.n4l/locales/es.json @@ -0,0 +1,44 @@ +{ + "tasks": { + "image-classification": { + "title": "KMNIST - Clasificación de caracteres japoneses", + "name": "KMNIST - Clasificación de caracteres japoneses", + "summary": "Diez caracteres hiragana del japonés clásico escritos a mano: como MNIST, pero más difícil.", + "description": { + "text": [ + "Kuzushiji-MNIST (KMNIST) es un sustituto directo de MNIST: imágenes en escala de grises de 28 x 28 píxeles y 10 clases, pero en lugar de dígitos contiene caracteres japoneses manuscritos en kuzushiji (escritura cursiva).", + "El kuzushiji fue la forma habitual de escribir japonés durante más de mil años, pero dejó de enseñarse tras la reforma de la escritura de principios del siglo XX y hoy muy poca gente sabe leerlo. Las imágenes proceden de libros clásicos digitalizados por el Instituto Nacional de Literatura Japonesa y las preparó el ROIS-DS Center for Open Data in the Humanities (CODH).", + "Cada clase es un carácter hiragana de hoy, pero en el conjunto aparece escrito a mano como se hacía antes. Hasta 1900 una misma sílaba se podía escribir de muchas formas: con el kanji del que viene la de hoy, trazado de otra manera, o partiendo de otro kanji. Son las hentaigana; ese año se dejó una sola forma, la de hoy. Por eso una misma clase junta trazos que se parecen poco entre sí o al carácter de hoy, y es más difícil que MNIST." + ], + "sections": [ + { + "title": "Datos de entrada", + "items": [ + "Imagen en escala de grises de 28 x 28 píxeles" + ] + }, + { + "title": "Datos de salida", + "items": [ + "Uno de los 10 caracteres hiragana: お, き, す, つ, な, は, ま, や, れ, を" + ] + }, + { + "title": "Modelos", + "items": [ + "Modelo ya entrenado: red convolucional entrenada con las 55.000 imágenes de entrenamiento de KMNIST (y otras 5.000 para validar). Acierta el {{test_accuracy, number(style: percent; minimumFractionDigits: 1)}} de las {{test_images, number}} imágenes de prueba del conjunto, que no vio al entrenar.", + "Entrenamiento en el navegador: se usa un subconjunto equilibrado, con 2.000 imágenes de entrenamiento y 500 de test por carácter." + ] + } + ] + }, + "forms": { + "title": "Los 10 caracteres, hoy y antes", + "modern": "Hoy", + "old": "Antes: otras formas (hentaigana), con su kanji", + "old-alt": "{{char}} antiguo, que viene de {{origin}}", + "note": "Debajo de cada carácter de hoy, cómo se lee y el kanji del que viene; debajo de cada forma antigua, el suyo. Las formas antiguas son las hentaigana de Unicode, dibujadas con la fuente Noto Serif Hentaigana. En el conjunto de datos aparecen escritas a mano: para verlas así, carga las imágenes de test en la página del modelo." + } + } + } +} diff --git a/public/n4l/kmnist.n4l/locales/ja.json b/public/n4l/kmnist.n4l/locales/ja.json new file mode 100644 index 0000000..d1fd923 --- /dev/null +++ b/public/n4l/kmnist.n4l/locales/ja.json @@ -0,0 +1,44 @@ +{ + "tasks": { + "image-classification": { + "title": "KMNIST - くずし字の分類", + "name": "KMNIST - くずし字の分類", + "summary": "古典日本語の手書きひらがな10文字:MNISTに似ていますが、より難しいデータです。", + "description": { + "text": [ + "Kuzushiji-MNIST(KMNIST)は MNIST と同じ形式のデータセットです。28 x 28 ピクセルのグレースケール画像で 10 クラスですが、数字の代わりにくずし字で書かれた手書きの日本語の文字が含まれています。", + "くずし字は千年以上にわたって日本語の一般的な書き方でしたが、20 世紀初めの表記改革以降は学校で教えられなくなり、現在読める人はごくわずかです。画像は国文学研究資料館がデジタル化した古典籍から取られ、ROIS-DS 人文学オープンデータ共同利用センター(CODH)が作成しました。", + "各クラスは現代のひらがな 1 文字ですが、データセットでは昔のように手書きで現れます。1900 年までは同じ音をさまざまな形で書くことができました。今の形のもとになった漢字を別のくずし方で書いたり、別の漢字から書いたりしたもので、これが変体仮名です。この年に 1 つの形だけが残され、それが今の形です。そのため 1 つのクラスに、互いにも今の文字にもあまり似ていない字形が集まり、MNIST より難しくなります。" + ], + "sections": [ + { + "title": "入力データ", + "items": [ + "28 x 28 ピクセルのグレースケール画像" + ] + }, + { + "title": "出力データ", + "items": [ + "10 種類のひらがなのいずれか:お、き、す、つ、な、は、ま、や、れ、を" + ] + }, + { + "title": "モデル", + "items": [ + "学習済みモデル:KMNIST の学習用画像 55,000 枚(ほかに検証用 5,000 枚)で学習した畳み込みニューラルネットワークです。学習で見ていないこのデータセットのテスト画像 {{test_images, number}} 枚での正解率は {{test_accuracy, number(style: percent; minimumFractionDigits: 1)}} です。", + "ブラウザでの学習:各文字について学習用 2,000 枚、テスト用 500 枚のバランスの取れたサブセットを使用します。" + ] + } + ] + }, + "forms": { + "title": "10 文字の今と昔", + "modern": "今", + "old": "昔:ほかの字形(変体仮名)と字母", + "old-alt": "{{origin}}から生まれた昔の{{char}}", + "note": "今の文字の下に読み方と字母(もとになった漢字)を、昔の字形の下にそれぞれの字母を示します。昔の字形は Unicode の変体仮名で、Noto Serif Hentaigana フォントで描いています。データセットでは手書きで現れます。そのように見るには、モデルのページでテスト画像を読み込んでください。" + } + } + } +} diff --git a/public/n4l/kmnist.n4l/manifest.json b/public/n4l/kmnist.n4l/manifest.json new file mode 100644 index 0000000..6d5718e --- /dev/null +++ b/public/n4l/kmnist.n4l/manifest.json @@ -0,0 +1,606 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "kmnist", + "version": "1.0.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://github.com/rois-codh/kmnist", + "citation": "@online{clanuwat2018deep,\n author = {Tarin Clanuwat and Mikel Bober-Irizar and Asanobu Kitamoto and Alex Lamb and Kazuaki Yamamoto and David Ha},\n title = {Deep Learning for Classical Japanese Literature},\n date = {2018-12-03},\n year = {2018},\n eprintclass = {cs.CV},\n eprinttype = {arXiv},\n eprint = {cs.CV/1812.01718},\n}" + }, + "datasets": [ + { + "id": "kmnist", + "kind": "image-sprite", + "file": "data/kmnist_images.png", + "labels": "data/kmnist_labels_uint8", + "info": "data/kmnist_classmap.csv", + "rows": 25000, + "train": 20000, + "image": { + "width": 28, + "height": 28, + "channels": 1 + } + } + ], + "tasks": [ + { + "task": "image-classification", + "key": "IMAGE-KMNIST", + "runtime": "image-classification", + "datasets": [ + "kmnist" + ], + "order": 2, + "preprocessing": [], + "classes": [ + { + "id": "お", + "reading": "o", + "origin": "於" + }, + { + "id": "き", + "reading": "ki", + "origin": "幾" + }, + { + "id": "す", + "reading": "su", + "origin": "寸" + }, + { + "id": "つ", + "reading": "tsu", + "origin": "川" + }, + { + "id": "な", + "reading": "na", + "origin": "奈" + }, + { + "id": "は", + "reading": "ha", + "origin": "波" + }, + { + "id": "ま", + "reading": "ma", + "origin": "末" + }, + { + "id": "や", + "reading": "ya", + "origin": "也" + }, + { + "id": "れ", + "reading": "re", + "origin": "礼" + }, + { + "id": "を", + "reading": "wo", + "origin": "遠" + } + ], + "models": [ + { + "id": "cnn", + "format": "tfjs-layers", + "path": "models/cnn/model.json", + "dataset": "kmnist", + "metrics": { + "test_accuracy": 0.983, + "test_images": 5000 + } + } + ], + "prediction": { + "images": [ + { + "file": "examples/0.png", + "expected": "お" + }, + { + "file": "examples/forms/1B014.png", + "expected": "お", + "old": true, + "origin": "於" + }, + { + "file": "examples/forms/1B015.png", + "expected": "お", + "old": true, + "origin": "於" + }, + { + "file": "examples/forms/1B016.png", + "expected": "お", + "old": true, + "origin": "隱" + }, + { + "file": "examples/1.png", + "expected": "き" + }, + { + "file": "examples/forms/1B025.png", + "expected": "き", + "old": true, + "origin": "幾" + }, + { + "file": "examples/forms/1B02A.png", + "expected": "き", + "old": true, + "origin": "起" + }, + { + "file": "examples/forms/1B026.png", + "expected": "き", + "old": true, + "origin": "支" + }, + { + "file": "examples/forms/1B023.png", + "expected": "き", + "old": true, + "origin": "喜" + }, + { + "file": "examples/forms/1B024.png", + "expected": "き", + "old": true, + "origin": "幾" + }, + { + "file": "examples/forms/1B027.png", + "expected": "き", + "old": true, + "origin": "木" + }, + { + "file": "examples/forms/1B028.png", + "expected": "き", + "old": true, + "origin": "祈" + }, + { + "file": "examples/forms/1B029.png", + "expected": "き", + "old": true, + "origin": "貴" + }, + { + "file": "examples/2.png", + "expected": "す" + }, + { + "file": "examples/forms/1B051.png", + "expected": "す", + "old": true, + "origin": "須" + }, + { + "file": "examples/forms/1B04F.png", + "expected": "す", + "old": true, + "origin": "春" + }, + { + "file": "examples/forms/1B04B.png", + "expected": "す", + "old": true, + "origin": "壽" + }, + { + "file": "examples/forms/1B04A.png", + "expected": "す", + "old": true, + "origin": "受" + }, + { + "file": "examples/forms/1B04C.png", + "expected": "す", + "old": true, + "origin": "數" + }, + { + "file": "examples/forms/1B04D.png", + "expected": "す", + "old": true, + "origin": "數" + }, + { + "file": "examples/forms/1B04E.png", + "expected": "す", + "old": true, + "origin": "春" + }, + { + "file": "examples/forms/1B050.png", + "expected": "す", + "old": true, + "origin": "須" + }, + { + "file": "examples/3.png", + "expected": "つ" + }, + { + "file": "examples/forms/1B06A.png", + "expected": "つ", + "old": true, + "origin": "川" + }, + { + "file": "examples/forms/1B06B.png", + "expected": "つ", + "old": true, + "origin": "津" + }, + { + "file": "examples/forms/1B06D.png", + "expected": "つ", + "old": true, + "origin": "徒" + }, + { + "file": "examples/forms/1B069.png", + "expected": "つ", + "old": true, + "origin": "川" + }, + { + "file": "examples/forms/1B06C.png", + "expected": "つ", + "old": true, + "origin": "都" + }, + { + "file": "examples/4.png", + "expected": "な" + }, + { + "file": "examples/forms/1B081.png", + "expected": "な", + "old": true, + "origin": "奈" + }, + { + "file": "examples/forms/1B085.png", + "expected": "な", + "old": true, + "origin": "那" + }, + { + "file": "examples/forms/1B07E.png", + "expected": "な", + "old": true, + "origin": "南" + }, + { + "file": "examples/forms/1B07F.png", + "expected": "な", + "old": true, + "origin": "名" + }, + { + "file": "examples/forms/1B080.png", + "expected": "な", + "old": true, + "origin": "奈" + }, + { + "file": "examples/forms/1B082.png", + "expected": "な", + "old": true, + "origin": "奈" + }, + { + "file": "examples/forms/1B083.png", + "expected": "な", + "old": true, + "origin": "菜" + }, + { + "file": "examples/forms/1B084.png", + "expected": "な", + "old": true, + "origin": "那" + }, + { + "file": "examples/forms/1B086.png", + "expected": "な", + "old": true, + "origin": "難" + }, + { + "file": "examples/5.png", + "expected": "は" + }, + { + "file": "examples/forms/1B09E.png", + "expected": "は", + "old": true, + "origin": "八" + }, + { + "file": "examples/forms/1B0A6.png", + "expected": "は", + "old": true, + "origin": "者" + }, + { + "file": "examples/forms/1B0A1.png", + "expected": "は", + "old": true, + "origin": "波" + }, + { + "file": "examples/forms/1B09F.png", + "expected": "は", + "old": true, + "origin": "半" + }, + { + "file": "examples/forms/1B0A0.png", + "expected": "は", + "old": true, + "origin": "婆" + }, + { + "file": "examples/forms/1B0A2.png", + "expected": "は", + "old": true, + "origin": "盤" + }, + { + "file": "examples/forms/1B0A3.png", + "expected": "は", + "old": true, + "origin": "盤" + }, + { + "file": "examples/forms/1B0A4.png", + "expected": "は", + "old": true, + "origin": "破" + }, + { + "file": "examples/forms/1B0A5.png", + "expected": "は", + "old": true, + "origin": "者" + }, + { + "file": "examples/forms/1B0A7.png", + "expected": "は", + "old": true, + "origin": "葉" + }, + { + "file": "examples/forms/1B0A8.png", + "expected": "は", + "old": true, + "origin": "頗" + }, + { + "file": "examples/6.png", + "expected": "ま" + }, + { + "file": "examples/forms/1B0C2.png", + "expected": "ま", + "old": true, + "origin": "万" + }, + { + "file": "examples/forms/1B0C5.png", + "expected": "ま", + "old": true, + "origin": "滿" + }, + { + "file": "examples/forms/1B0C4.png", + "expected": "ま", + "old": true, + "origin": "末" + }, + { + "file": "examples/forms/1B0C3.png", + "expected": "ま", + "old": true, + "origin": "末" + }, + { + "file": "examples/forms/1B0C6.png", + "expected": "ま", + "old": true, + "origin": "滿" + }, + { + "file": "examples/forms/1B0C7.png", + "expected": "ま", + "old": true, + "origin": "萬" + }, + { + "file": "examples/forms/1B0C8.png", + "expected": "ま", + "old": true, + "origin": "麻" + }, + { + "file": "examples/7.png", + "expected": "や" + }, + { + "file": "examples/forms/1B0DE.png", + "expected": "や", + "old": true, + "origin": "也" + }, + { + "file": "examples/forms/1B0DF.png", + "expected": "や", + "old": true, + "origin": "屋" + }, + { + "file": "examples/forms/1B0E2.png", + "expected": "や", + "old": true, + "origin": "夜" + }, + { + "file": "examples/forms/1B0DD.png", + "expected": "や", + "old": true, + "origin": "也" + }, + { + "file": "examples/forms/1B0E0.png", + "expected": "や", + "old": true, + "origin": "耶" + }, + { + "file": "examples/forms/1B0E1.png", + "expected": "や", + "old": true, + "origin": "耶" + }, + { + "file": "examples/8.png", + "expected": "れ" + }, + { + "file": "examples/forms/1B100.png", + "expected": "れ", + "old": true, + "origin": "連" + }, + { + "file": "examples/forms/1B0FF.png", + "expected": "れ", + "old": true, + "origin": "禮" + }, + { + "file": "examples/forms/1B101.png", + "expected": "れ", + "old": true, + "origin": "麗" + }, + { + "file": "examples/forms/1B0FE.png", + "expected": "れ", + "old": true, + "origin": "禮" + }, + { + "file": "examples/9.png", + "expected": "を" + }, + { + "file": "examples/forms/1B11A.png", + "expected": "を", + "old": true, + "origin": "越" + }, + { + "file": "examples/forms/1B11C.png", + "expected": "を", + "old": true, + "origin": "遠" + }, + { + "file": "examples/forms/1B116.png", + "expected": "を", + "old": true, + "origin": "乎" + }, + { + "file": "examples/forms/1B117.png", + "expected": "を", + "old": true, + "origin": "乎" + }, + { + "file": "examples/forms/1B118.png", + "expected": "を", + "old": true, + "origin": "尾" + }, + { + "file": "examples/forms/1B119.png", + "expected": "を", + "old": true, + "origin": "緒" + }, + { + "file": "examples/forms/1B11B.png", + "expected": "を", + "old": true, + "origin": "遠" + } + ] + }, + "training": { + "layers": [ + { + "class": "conv2d", + "filters": 16, + "kernelSize": 3, + "activation": "relu", + "locked": true + }, + { + "class": "maxPooling2d", + "poolSize": 2, + "strides": 2 + }, + { + "class": "conv2d", + "filters": 32, + "kernelSize": 3, + "activation": "relu" + }, + { + "class": "maxPooling2d", + "poolSize": 2, + "strides": 2 + }, + { + "class": "conv2d", + "filters": 32, + "kernelSize": 3, + "activation": "relu" + }, + { + "class": "flatten" + }, + { + "class": "dense", + "units": 64, + "activation": "relu" + }, + { + "class": "dense", + "units": 10, + "activation": "softmax" + } + ] + } + } + ] +} diff --git a/public/models/03-image-classification/kmnist/model.json b/public/n4l/kmnist.n4l/models/cnn/model.json similarity index 100% rename from public/models/03-image-classification/kmnist/model.json rename to public/n4l/kmnist.n4l/models/cnn/model.json diff --git a/public/models/03-image-classification/kmnist/weights.bin b/public/n4l/kmnist.n4l/models/cnn/weights.bin similarity index 100% rename from public/models/03-image-classification/kmnist/weights.bin rename to public/n4l/kmnist.n4l/models/cnn/weights.bin diff --git a/public/models/00-tabular-classification/lymphography/lymphography.csv b/public/n4l/lymphography.n4l/data/lymphography.csv similarity index 100% rename from public/models/00-tabular-classification/lymphography/lymphography.csv rename to public/n4l/lymphography.n4l/data/lymphography.csv diff --git a/public/models/00-tabular-classification/lymphography/lymphography.names b/public/n4l/lymphography.n4l/data/lymphography.names similarity index 100% rename from public/models/00-tabular-classification/lymphography/lymphography.names rename to public/n4l/lymphography.n4l/data/lymphography.names diff --git a/public/n4l/lymphography.n4l/locales/en.json b/public/n4l/lymphography.n4l/locales/en.json new file mode 100644 index 0000000..c459cd9 --- /dev/null +++ b/public/n4l/lymphography.n4l/locales/en.json @@ -0,0 +1,172 @@ +{ + "columns": { + "lymphatics": "Lymphatics", + "block of affere": "Block of afferent vessels", + "bl_ of lymph_ c": "Block of lymphatics (c)", + "bl_ of lymph_ s": "Block of lymphatics (s)", + "by pass": "Bypass", + "extravasates": "Extravasates", + "regeneration of": "Regeneration", + "early uptake in": "Early uptake", + "lym_nodes dimin": "Diminished lymph nodes", + "lym_nodes enlar": "Enlarged lymph nodes", + "changes in lym_": "Changes in lymphatics", + "defect in node": "Defect in node", + "changes in node": "Changes in node", + "changes in stru": "Changes in structure", + "special forms": "Special forms", + "dislocation of": "Dislocation", + "exclusion of no": "Exclusion of nodes", + "no_ of nodes in": "Number of nodes", + "class": "Diagnosis" + }, + "classes": { + "1": "Normal find", + "2": "Metastases", + "3": "Malignant lymphoma", + "4": "Fibrosis" + }, + "options": { + "lymphatics": { + "1": "normal", + "2": "arched", + "3": "deformed", + "4": "displaced" + }, + "block of affere": { + "1": "No", + "2": "Yes" + }, + "bl_ of lymph_ c": { + "1": "No", + "2": "Yes" + }, + "bl_ of lymph_ s": { + "1": "No", + "2": "Yes" + }, + "by pass": { + "1": "No", + "2": "Yes" + }, + "extravasates": { + "1": "No", + "2": "Yes" + }, + "regeneration of": { + "1": "No", + "2": "Yes" + }, + "early uptake in": { + "1": "No", + "2": "Yes" + }, + "changes in lym_": { + "1": "bean", + "2": "oval", + "3": "round" + }, + "defect in node": { + "1": "no", + "2": "lacunar", + "3": "lacunar marginal", + "4": "lacunar central" + }, + "changes in node": { + "1": "no", + "2": "lacunar", + "3": "lacunar marginal", + "4": "lacunar central" + }, + "changes in stru": { + "1": "no", + "2": "grainy", + "3": "drop-like", + "4": "coarse", + "5": "diluted", + "6": "reticular", + "7": "stripped", + "8": "faint" + }, + "special forms": { + "1": "no", + "2": "chalices", + "3": "vesicles" + }, + "dislocation of": { + "1": "No", + "2": "Yes" + }, + "exclusion of no": { + "1": "No", + "2": "Yes" + }, + "no_ of nodes in": { + "1": "0-9", + "2": "10-19", + "3": "20-29", + "4": "30-39", + "5": "40-49", + "6": "50-59", + "7": "60-69", + "8": "≥ 70" + } + }, + "tasks": { + "tabular-classification": { + "title": "LYMPHOGRAPHY - Lymphoma data classification", + "name": "Lymphomas classification", + "summary": "The diagnosis of a lymphoma from the features of a lymphography: few rows and very unbalanced classes.", + "description": { + "text": [ + "The Lymphography dataset gathers the features of the lymphography of 148 patients and their diagnosis: normal find, metastases, malignant lymphoma or fibrosis." + ], + "sections": [ + { + "title": "Input data", + "items": [ + "Lymphatics: normal, arched, deformed, displaced", + "Block of afferent vessels: No, Yes", + "Block of lymphatics (c): No, Yes", + "Block of lymphatics (s): No, Yes", + "Bypass: No, Yes", + "Extravasates: No, Yes", + "Regeneration: No, Yes", + "Early uptake: No, Yes", + "Diminished lymph nodes: 0-3", + "Enlarged lymph nodes: 1-4", + "Changes in lymphatics: bean, oval, round", + "Defect in node: no, lacunar, lacunar marginal, lacunar central", + "Changes in node: no, lacunar, lacunar marginal, lacunar central", + "Changes in structure: no, grainy, drop-like, coarse, diluted, reticular, stripped, faint", + "Special forms: no, chalices, vesicles", + "Dislocation: No, Yes", + "Exclusion of nodes: No, Yes", + "Number of nodes: 0-9, 10-19, 20-29, 30-39, 40-49, 50-59, 60-69, ≥ 70" + ] + }, + { + "title": "Output data", + "items": [ + "Normal find", + "Metastases", + "Malignant lymphoma", + "Fibrosis" + ] + }, + { + "title": "References", + "items": [ + "Data set" + ] + } + ] + }, + "example": { + "text": "Enter the corresponding values of the patient to be evaluated:", + "items": "(Lymphatics, Block of afferent vessels, Block of lymphatics (c), Block of lymphatics (s), Bypass, Extravasates, Regeneration, Early uptake, Diminished lymph nodes, Enlarged lymph nodes, Changes in lymphatics, Defect in node, Changes in node, Changes in structure, Special forms, Dislocation, Exclusion of nodes, Number of nodes).", + "examples": "Examples:" + } + } + } +} diff --git a/public/n4l/lymphography.n4l/locales/es.json b/public/n4l/lymphography.n4l/locales/es.json new file mode 100644 index 0000000..2ff542f --- /dev/null +++ b/public/n4l/lymphography.n4l/locales/es.json @@ -0,0 +1,172 @@ +{ + "columns": { + "lymphatics": "Vasos linfáticos", + "block of affere": "Bloqueo de los vasos aferentes", + "bl_ of lymph_ c": "Bloqueo linfático (c)", + "bl_ of lymph_ s": "Bloqueo linfático (s)", + "by pass": "Derivación (bypass)", + "extravasates": "Extravasación", + "regeneration of": "Regeneración", + "early uptake in": "Captación temprana", + "lym_nodes dimin": "Ganglios disminuidos", + "lym_nodes enlar": "Ganglios agrandados", + "changes in lym_": "Forma de los vasos linfáticos", + "defect in node": "Defecto en el ganglio", + "changes in node": "Cambios en el ganglio", + "changes in stru": "Cambios en la estructura", + "special forms": "Formas especiales", + "dislocation of": "Desplazamiento", + "exclusion of no": "Exclusión de ganglios", + "no_ of nodes in": "Número de ganglios", + "class": "Diagnóstico" + }, + "classes": { + "1": "Hallazgo normal", + "2": "Metástasis", + "3": "Linfoma maligno", + "4": "Fibrosis" + }, + "options": { + "lymphatics": { + "1": "normales", + "2": "arqueados", + "3": "deformados", + "4": "desplazados" + }, + "block of affere": { + "1": "No", + "2": "Sí" + }, + "bl_ of lymph_ c": { + "1": "No", + "2": "Sí" + }, + "bl_ of lymph_ s": { + "1": "No", + "2": "Sí" + }, + "by pass": { + "1": "No", + "2": "Sí" + }, + "extravasates": { + "1": "No", + "2": "Sí" + }, + "regeneration of": { + "1": "No", + "2": "Sí" + }, + "early uptake in": { + "1": "No", + "2": "Sí" + }, + "changes in lym_": { + "1": "de judía", + "2": "ovalada", + "3": "redonda" + }, + "defect in node": { + "1": "no", + "2": "lacunar", + "3": "lacunar marginal", + "4": "lacunar central" + }, + "changes in node": { + "1": "no", + "2": "lacunar", + "3": "lacunar marginal", + "4": "lacunar central" + }, + "changes in stru": { + "1": "no", + "2": "granular", + "3": "en gotas", + "4": "grueso", + "5": "diluido", + "6": "reticular", + "7": "estriado", + "8": "tenue" + }, + "special forms": { + "1": "no", + "2": "cálices", + "3": "vesículas" + }, + "dislocation of": { + "1": "No", + "2": "Sí" + }, + "exclusion of no": { + "1": "No", + "2": "Sí" + }, + "no_ of nodes in": { + "1": "0-9", + "2": "10-19", + "3": "20-29", + "4": "30-39", + "5": "40-49", + "6": "50-59", + "7": "60-69", + "8": "≥ 70" + } + }, + "tasks": { + "tabular-classification": { + "title": "LYMPHOGRAPHY - Clasificación por datos de linfomas", + "name": "Clasificación de linfomas", + "summary": "El diagnóstico de un linfoma a partir de los rasgos de una linfografía: pocas filas y clases muy desequilibradas.", + "description": { + "text": [ + "El conjunto de datos Lymphography recoge los rasgos de la linfografía de 148 pacientes y su diagnóstico: hallazgo normal, metástasis, linfoma maligno o fibrosis." + ], + "sections": [ + { + "title": "Datos de entrada", + "items": [ + "Vasos linfáticos: normales, arqueados, deformados, desplazados", + "Bloqueo de los vasos aferentes: No, Sí", + "Bloqueo linfático (c): No, Sí", + "Bloqueo linfático (s): No, Sí", + "Derivación (bypass): No, Sí", + "Extravasación: No, Sí", + "Regeneración: No, Sí", + "Captación temprana: No, Sí", + "Ganglios disminuidos: 0-3", + "Ganglios agrandados: 1-4", + "Forma de los vasos linfáticos: de judía, ovalada, redonda", + "Defecto en el ganglio: no, lacunar, lacunar marginal, lacunar central", + "Cambios en el ganglio: no, lacunar, lacunar marginal, lacunar central", + "Cambios en la estructura: no, granular, en gotas, grueso, diluido, reticular, estriado, tenue", + "Formas especiales: no, cálices, vesículas", + "Desplazamiento: No, Sí", + "Exclusión de ganglios: No, Sí", + "Número de ganglios: 0-9, 10-19, 20-29, 30-39, 40-49, 50-59, 60-69, ≥ 70" + ] + }, + { + "title": "Datos de salida", + "items": [ + "Hallazgo normal", + "Metástasis", + "Linfoma maligno", + "Fibrosis" + ] + }, + { + "title": "Referencias", + "items": [ + "Conjunto de datos" + ] + } + ] + }, + "example": { + "text": "Introduce los valores correspondientes del paciente que se va a evaluar:", + "items": "(Vasos linfáticos, Bloqueo de los vasos aferentes, Bloqueo linfático (c), Bloqueo linfático (s), Derivación (bypass), Extravasación, Regeneración, Captación temprana, Ganglios disminuidos, Ganglios agrandados, Forma de los vasos linfáticos, Defecto en el ganglio, Cambios en el ganglio, Cambios en la estructura, Formas especiales, Desplazamiento, Exclusión de ganglios, Número de ganglios).", + "examples": "Ejemplos:" + } + } + } +} diff --git a/public/n4l/lymphography.n4l/locales/ja.json b/public/n4l/lymphography.n4l/locales/ja.json new file mode 100644 index 0000000..b8b7b88 --- /dev/null +++ b/public/n4l/lymphography.n4l/locales/ja.json @@ -0,0 +1,172 @@ +{ + "columns": { + "lymphatics": "リンパ管", + "block of affere": "輸入リンパ管の閉塞", + "bl_ of lymph_ c": "リンパ管の閉塞(c)", + "bl_ of lymph_ s": "リンパ管の閉塞(s)", + "by pass": "バイパス", + "extravasates": "血管外漏出", + "regeneration of": "再生", + "early uptake in": "早期取り込み", + "lym_nodes dimin": "リンパ節の縮小", + "lym_nodes enlar": "リンパ節の腫大", + "changes in lym_": "リンパ管の変化", + "defect in node": "リンパ節の欠損", + "changes in node": "リンパ節の変化", + "changes in stru": "構造の変化", + "special forms": "特殊な形態", + "dislocation of": "転位", + "exclusion of no": "リンパ節の除外", + "no_ of nodes in": "リンパ節の数", + "class": "診断" + }, + "classes": { + "1": "正常所見", + "2": "転移", + "3": "悪性リンパ腫", + "4": "線維症" + }, + "options": { + "lymphatics": { + "1": "正常", + "2": "アーチ状", + "3": "変形", + "4": "変位" + }, + "block of affere": { + "1": "なし", + "2": "あり" + }, + "bl_ of lymph_ c": { + "1": "なし", + "2": "あり" + }, + "bl_ of lymph_ s": { + "1": "なし", + "2": "あり" + }, + "by pass": { + "1": "なし", + "2": "あり" + }, + "extravasates": { + "1": "なし", + "2": "あり" + }, + "regeneration of": { + "1": "なし", + "2": "あり" + }, + "early uptake in": { + "1": "なし", + "2": "あり" + }, + "changes in lym_": { + "1": "豆形", + "2": "楕円形", + "3": "円形" + }, + "defect in node": { + "1": "なし", + "2": "裂孔状", + "3": "辺縁裂孔", + "4": "中心裂孔" + }, + "changes in node": { + "1": "なし", + "2": "裂孔状", + "3": "辺縁裂孔", + "4": "中心裂孔" + }, + "changes in stru": { + "1": "なし", + "2": "顆粒状", + "3": "滴状", + "4": "粗い", + "5": "希薄", + "6": "網状", + "7": "線状", + "8": "淡い" + }, + "special forms": { + "1": "なし", + "2": "杯状", + "3": "小胞" + }, + "dislocation of": { + "1": "なし", + "2": "あり" + }, + "exclusion of no": { + "1": "なし", + "2": "あり" + }, + "no_ of nodes in": { + "1": "0-9", + "2": "10-19", + "3": "20-29", + "4": "30-39", + "5": "40-49", + "6": "50-59", + "7": "60-69", + "8": "≥ 70" + } + }, + "tasks": { + "tabular-classification": { + "title": "LYMPHOGRAPHY - リンパ腫データ分類", + "name": "リンパ腫分類", + "summary": "リンパ管造影の特徴からリンパ腫を診断します。行数が少なく、クラスの偏りが大きいデータです。", + "description": { + "text": [ + "Lymphography データセットは、148 人の患者のリンパ管造影の所見と診断(正常所見、転移、悪性リンパ腫、線維症)をまとめたものです。" + ], + "sections": [ + { + "title": "入力データ", + "items": [ + "リンパ管: 正常、アーチ状、変形、変位", + "輸入リンパ管の閉塞: なし、あり", + "リンパ管の閉塞(c): なし、あり", + "リンパ管の閉塞(s): なし、あり", + "バイパス: なし、あり", + "血管外漏出: なし、あり", + "再生: なし、あり", + "早期取り込み: なし、あり", + "リンパ節の縮小: 0-3", + "リンパ節の腫大: 1-4", + "リンパ管の変化: 豆形、楕円形、円形", + "リンパ節の欠損: なし、裂孔状、辺縁裂孔、中心裂孔", + "リンパ節の変化: なし、裂孔状、辺縁裂孔、中心裂孔", + "構造の変化: なし、顆粒状、滴状、粗い、希薄、網状、線状、淡い", + "特殊な形態: なし、杯状、小胞", + "転位: なし、あり", + "リンパ節の除外: なし、あり", + "リンパ節の数: 0-9、10-19、20-29、30-39、40-49、50-59、60-69、≥ 70" + ] + }, + { + "title": "出力データ", + "items": [ + "正常所見", + "転移", + "悪性リンパ腫", + "線維症" + ] + }, + { + "title": "参照元", + "items": [ + "データセット" + ] + } + ] + }, + "example": { + "text": "評価する患者の対応する値を入力してください:", + "items": "(リンパ管、輸入リンパ管の閉塞、リンパ管の閉塞(c)、リンパ管の閉塞(s)、バイパス、血管外漏出、再生、早期取り込み、リンパ節の縮小、リンパ節の腫大、リンパ管の変化、リンパ節の欠損、リンパ節の変化、構造の変化、特殊な形態、転位、リンパ節の除外、リンパ節の数).", + "examples": "例:" + } + } + } +} diff --git a/public/n4l/lymphography.n4l/manifest.json b/public/n4l/lymphography.n4l/manifest.json new file mode 100644 index 0000000..ff9b3e4 --- /dev/null +++ b/public/n4l/lymphography.n4l/manifest.json @@ -0,0 +1,476 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "lymphography", + "version": "1.0.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://archive.ics.uci.edu/dataset/63/lymphography", + "citation": "@misc{misc_lymphography_63,\n author = {Zwitter,M. and Soklic,M.},\n title = {{Lymphography}},\n year = {1988},\n howpublished = {UCI Machine Learning Repository},\n note = {{DOI}: https://doi.org/10.24432/C54598}\n}" + }, + "datasets": [ + { + "id": "lymphography", + "file": "data/lymphography.csv", + "info": "data/lymphography.names", + "rows": 148, + "columns": [ + { + "name": "lymphatics", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = normal, 2 = arched, 3 = deformed, 4 = displaced", + "options": [ + "1", + "2", + "3", + "4" + ] + }, + { + "name": "block of affere", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = yes", + "options": [ + "1", + "2" + ] + }, + { + "name": "bl. of lymph. c", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = yes", + "options": [ + "1", + "2" + ] + }, + { + "name": "bl. of lymph. s", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = yes", + "options": [ + "1", + "2" + ] + }, + { + "name": "by pass", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = yes", + "options": [ + "1", + "2" + ] + }, + { + "name": "extravasates", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = yes", + "options": [ + "1", + "2" + ] + }, + { + "name": "regeneration of", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = yes", + "options": [ + "1", + "2" + ] + }, + { + "name": "early uptake in", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = yes", + "options": [ + "1", + "2" + ] + }, + { + "name": "lym.nodes dimin", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "0-3", + "options": [ + "1", + "2", + "3" + ] + }, + { + "name": "lym.nodes enlar", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1-4", + "options": [ + "1", + "2", + "3", + "4" + ] + }, + { + "name": "changes in lym.", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = bean, 2 = oval, 3 = round", + "options": [ + "1", + "2", + "3" + ] + }, + { + "name": "defect in node", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = lacunar, 3 = lac. marginal, 4 = lac. central", + "options": [ + "1", + "2", + "3", + "4" + ] + }, + { + "name": "changes in node", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = lacunar, 3 = lac. margin, 4 = lac. central", + "options": [ + "1", + "2", + "3", + "4" + ] + }, + { + "name": "changes in stru", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = grainy, 3 = drop-like, 4 = coarse, 5 = diluted, 6 = reticular, 7 = stripped, 8 = faint", + "options": [ + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8" + ] + }, + { + "name": "special forms", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = chalices, 3 = vesicles", + "options": [ + "1", + "2", + "3" + ] + }, + { + "name": "dislocation of", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = yes", + "options": [ + "1", + "2" + ] + }, + { + "name": "exclusion of no", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "1 = no, 2 = yes", + "options": [ + "1", + "2" + ] + }, + { + "name": "no. of nodes in", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "1 = 0-9, 2 = 10-19, 3 = 20-29, 4 = 30-39, 5 = 40-49, 6 = 50-59, 7 = 60-69, 8 = >=70", + "options": [ + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8" + ] + }, + { + "name": "class", + "role": "Target", + "type": "Integer", + "missing": 0, + "description": "1 = normal find, 2 = metastases, 3 = malign lymph, 4 = fibrosis", + "options": [ + "3", + "2", + "4", + "1" + ] + } + ] + } + ], + "tasks": [ + { + "task": "tabular-classification", + "key": "LYMPHOGRAPHY", + "runtime": "tabular-classification", + "datasets": [ + "lymphography" + ], + "preprocessing": [ + { + "op": "label-encoder", + "columns": [ + "lymphatics", + "block of affere", + "bl. of lymph. c", + "bl. of lymph. s", + "by pass", + "extravasates", + "regeneration of", + "early uptake in", + "lym.nodes dimin", + "lym.nodes enlar", + "changes in lym.", + "defect in node", + "changes in node", + "changes in stru", + "special forms", + "dislocation of", + "exclusion of no", + "no. of nodes in", + "class" + ] + }, + { + "op": "min-max", + "columns": "features" + } + ], + "classes": [ + { + "id": "3", + "aliases": [ + "malign lymph" + ] + }, + { + "id": "2", + "aliases": [ + "metastases", + "metastasis" + ] + }, + { + "id": "4", + "aliases": [ + "fibrosis" + ] + }, + { + "id": "1", + "aliases": [ + "normal find", + "normal" + ] + } + ], + "models": [ + { + "id": "mlp", + "format": "tfjs-layers", + "path": "models/mlp/model.json", + "dataset": "lymphography" + } + ], + "prediction": { + "defaults": { + "lymphatics": "3", + "block of affere": "1", + "bl. of lymph. c": "1", + "bl. of lymph. s": "1", + "by pass": "1", + "extravasates": "2", + "regeneration of": "2", + "early uptake in": "1", + "lym.nodes dimin": "3", + "lym.nodes enlar": "1", + "changes in lym.": "1", + "defect in node": "2", + "changes in node": "1", + "changes in stru": "4", + "special forms": "2", + "dislocation of": "1", + "exclusion of no": "1", + "no. of nodes in": "7" + }, + "examples": [ + { + "values": { + "lymphatics": "1", + "block of affere": "1", + "bl. of lymph. c": "1", + "bl. of lymph. s": "1", + "by pass": "1", + "extravasates": "2", + "regeneration of": "1", + "early uptake in": "2", + "lym.nodes dimin": "1", + "lym.nodes enlar": "2", + "changes in lym.": "2", + "defect in node": "1", + "changes in node": "1", + "changes in stru": "1", + "special forms": "1", + "dislocation of": "1", + "exclusion of no": "1", + "no. of nodes in": "2" + }, + "expected": "1" + }, + { + "values": { + "lymphatics": "2", + "block of affere": "2", + "bl. of lymph. c": "2", + "bl. of lymph. s": "1", + "by pass": "2", + "extravasates": "2", + "regeneration of": "1", + "early uptake in": "1", + "lym.nodes dimin": "1", + "lym.nodes enlar": "2", + "changes in lym.": "2", + "defect in node": "3", + "changes in node": "3", + "changes in stru": "4", + "special forms": "2", + "dislocation of": "1", + "exclusion of no": "2", + "no. of nodes in": "1" + }, + "expected": "2" + }, + { + "values": { + "lymphatics": "2", + "block of affere": "1", + "bl. of lymph. c": "1", + "bl. of lymph. s": "1", + "by pass": "1", + "extravasates": "2", + "regeneration of": "1", + "early uptake in": "2", + "lym.nodes dimin": "1", + "lym.nodes enlar": "3", + "changes in lym.": "3", + "defect in node": "4", + "changes in node": "2", + "changes in stru": "7", + "special forms": "3", + "dislocation of": "2", + "exclusion of no": "2", + "no. of nodes in": "3" + }, + "expected": "3" + }, + { + "values": { + "lymphatics": "3", + "block of affere": "1", + "bl. of lymph. c": "1", + "bl. of lymph. s": "1", + "by pass": "1", + "extravasates": "2", + "regeneration of": "2", + "early uptake in": "1", + "lym.nodes dimin": "3", + "lym.nodes enlar": "1", + "changes in lym.": "1", + "defect in node": "2", + "changes in node": "1", + "changes in stru": "4", + "special forms": "2", + "dislocation of": "1", + "exclusion of no": "1", + "no. of nodes in": "7" + }, + "expected": "4" + } + ] + }, + "training": { + "layers": [ + { + "class": "dense", + "units": 18, + "activation": "sigmoid" + }, + { + "class": "dense", + "units": 10, + "activation": "relu" + }, + { + "class": "dense", + "units": 10, + "activation": "relu" + }, + { + "class": "dense", + "units": 4, + "activation": "softmax" + } + ] + } + } + ] +} diff --git a/public/n4l/lymphography.n4l/models/mlp/model.json b/public/n4l/lymphography.n4l/models/mlp/model.json new file mode 100644 index 0000000..3c3214e --- /dev/null +++ b/public/n4l/lymphography.n4l/models/mlp/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_1","layers":[{"class_name":"Dense","config":{"units":18,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense1","trainable":true,"batch_input_shape":[null,18],"dtype":"float32"}},{"class_name":"Dense","config":{"units":10,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense2","trainable":true}},{"class_name":"Dense","config":{"units":4,"activation":"softmax","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense3","trainable":true}}]},"keras_version":"tfjs-layers 3.21.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v3.21.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense1/kernel","shape":[18,18],"dtype":"float32"},{"name":"dense_Dense1/bias","shape":[18],"dtype":"float32"},{"name":"dense_Dense2/kernel","shape":[18,10],"dtype":"float32"},{"name":"dense_Dense2/bias","shape":[10],"dtype":"float32"},{"name":"dense_Dense3/kernel","shape":[10,4],"dtype":"float32"},{"name":"dense_Dense3/bias","shape":[4],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/models/00-tabular-classification/lymphography/my-model-lymphography.weights.bin b/public/n4l/lymphography.n4l/models/mlp/model.weights.bin similarity index 100% rename from public/models/00-tabular-classification/lymphography/my-model-lymphography.weights.bin rename to public/n4l/lymphography.n4l/models/mlp/model.weights.bin diff --git a/public/n4l/melbourne-temperatures.n4l/data/daily-min-temperatures.csv b/public/n4l/melbourne-temperatures.n4l/data/daily-min-temperatures.csv new file mode 100644 index 0000000..b685185 --- /dev/null +++ b/public/n4l/melbourne-temperatures.n4l/data/daily-min-temperatures.csv @@ -0,0 +1,3651 @@ +Date,Temp +1981-01-01,20.7 +1981-01-02,17.9 +1981-01-03,18.8 +1981-01-04,14.6 +1981-01-05,15.8 +1981-01-06,15.8 +1981-01-07,15.8 +1981-01-08,17.4 +1981-01-09,21.8 +1981-01-10,20.0 +1981-01-11,16.2 +1981-01-12,13.3 +1981-01-13,16.7 +1981-01-14,21.5 +1981-01-15,25.0 +1981-01-16,20.7 +1981-01-17,20.6 +1981-01-18,24.8 +1981-01-19,17.7 +1981-01-20,15.5 +1981-01-21,18.2 +1981-01-22,12.1 +1981-01-23,14.4 +1981-01-24,16.0 +1981-01-25,16.5 +1981-01-26,18.7 +1981-01-27,19.4 +1981-01-28,17.2 +1981-01-29,15.5 +1981-01-30,15.1 +1981-01-31,15.4 +1981-02-01,15.3 +1981-02-02,18.8 +1981-02-03,21.9 +1981-02-04,19.9 +1981-02-05,16.6 +1981-02-06,16.8 +1981-02-07,14.6 +1981-02-08,17.1 +1981-02-09,25.0 +1981-02-10,15.0 +1981-02-11,13.7 +1981-02-12,13.9 +1981-02-13,18.3 +1981-02-14,22.0 +1981-02-15,22.1 +1981-02-16,21.2 +1981-02-17,18.4 +1981-02-18,16.6 +1981-02-19,16.1 +1981-02-20,15.7 +1981-02-21,16.6 +1981-02-22,16.5 +1981-02-23,14.4 +1981-02-24,14.4 +1981-02-25,18.5 +1981-02-26,16.9 +1981-02-27,17.5 +1981-02-28,21.2 +1981-03-01,17.8 +1981-03-02,18.6 +1981-03-03,17.0 +1981-03-04,16.0 +1981-03-05,13.3 +1981-03-06,14.3 +1981-03-07,11.4 +1981-03-08,16.3 +1981-03-09,16.1 +1981-03-10,11.8 +1981-03-11,12.2 +1981-03-12,14.7 +1981-03-13,11.8 +1981-03-14,11.3 +1981-03-15,10.6 +1981-03-16,11.7 +1981-03-17,14.2 +1981-03-18,11.2 +1981-03-19,16.9 +1981-03-20,16.7 +1981-03-21,8.1 +1981-03-22,8.0 +1981-03-23,8.8 +1981-03-24,13.4 +1981-03-25,10.9 +1981-03-26,13.4 +1981-03-27,11.0 +1981-03-28,15.0 +1981-03-29,15.7 +1981-03-30,14.5 +1981-03-31,15.8 +1981-04-01,16.7 +1981-04-02,16.8 +1981-04-03,17.5 +1981-04-04,17.1 +1981-04-05,18.1 +1981-04-06,16.6 +1981-04-07,10.0 +1981-04-08,14.9 +1981-04-09,15.9 +1981-04-10,13.0 +1981-04-11,7.6 +1981-04-12,11.5 +1981-04-13,13.5 +1981-04-14,13.0 +1981-04-15,13.3 +1981-04-16,12.1 +1981-04-17,12.4 +1981-04-18,13.2 +1981-04-19,13.8 +1981-04-20,10.6 +1981-04-21,9.0 +1981-04-22,10.0 +1981-04-23,9.8 +1981-04-24,11.5 +1981-04-25,8.9 +1981-04-26,7.4 +1981-04-27,9.9 +1981-04-28,9.3 +1981-04-29,9.9 +1981-04-30,7.4 +1981-05-01,8.6 +1981-05-02,11.9 +1981-05-03,14.0 +1981-05-04,8.6 +1981-05-05,10.0 +1981-05-06,13.5 +1981-05-07,12.0 +1981-05-08,10.5 +1981-05-09,10.7 +1981-05-10,8.1 +1981-05-11,10.1 +1981-05-12,10.6 +1981-05-13,5.3 +1981-05-14,6.6 +1981-05-15,8.5 +1981-05-16,11.2 +1981-05-17,9.8 +1981-05-18,5.9 +1981-05-19,3.2 +1981-05-20,2.1 +1981-05-21,3.4 +1981-05-22,5.4 +1981-05-23,9.6 +1981-05-24,11.5 +1981-05-25,12.3 +1981-05-26,12.6 +1981-05-27,11.0 +1981-05-28,11.2 +1981-05-29,11.4 +1981-05-30,11.8 +1981-05-31,12.8 +1981-06-01,11.6 +1981-06-02,10.6 +1981-06-03,9.8 +1981-06-04,11.2 +1981-06-05,5.7 +1981-06-06,7.1 +1981-06-07,2.5 +1981-06-08,3.5 +1981-06-09,4.6 +1981-06-10,11.0 +1981-06-11,5.7 +1981-06-12,7.7 +1981-06-13,10.4 +1981-06-14,11.4 +1981-06-15,9.2 +1981-06-16,6.1 +1981-06-17,2.7 +1981-06-18,4.3 +1981-06-19,6.3 +1981-06-20,3.8 +1981-06-21,4.4 +1981-06-22,7.1 +1981-06-23,4.8 +1981-06-24,5.8 +1981-06-25,6.2 +1981-06-26,7.3 +1981-06-27,9.2 +1981-06-28,10.2 +1981-06-29,9.5 +1981-06-30,9.5 +1981-07-01,10.7 +1981-07-02,10.0 +1981-07-03,6.5 +1981-07-04,7.0 +1981-07-05,7.4 +1981-07-06,8.1 +1981-07-07,6.6 +1981-07-08,8.3 +1981-07-09,8.9 +1981-07-10,4.6 +1981-07-11,6.8 +1981-07-12,5.7 +1981-07-13,6.1 +1981-07-14,7.0 +1981-07-15,7.2 +1981-07-16,6.3 +1981-07-17,8.8 +1981-07-18,5.0 +1981-07-19,7.4 +1981-07-20,10.1 +1981-07-21,12.0 +1981-07-22,9.0 +1981-07-23,8.9 +1981-07-24,9.8 +1981-07-25,9.0 +1981-07-26,9.2 +1981-07-27,7.7 +1981-07-28,8.0 +1981-07-29,6.1 +1981-07-30,3.5 +1981-07-31,3.2 +1981-08-01,5.7 +1981-08-02,7.7 +1981-08-03,9.0 +1981-08-04,10.0 +1981-08-05,6.2 +1981-08-06,6.9 +1981-08-07,6.5 +1981-08-08,6.8 +1981-08-09,7.0 +1981-08-10,5.2 +1981-08-11,3.0 +1981-08-12,5.6 +1981-08-13,7.9 +1981-08-14,9.0 +1981-08-15,8.6 +1981-08-16,10.3 +1981-08-17,10.5 +1981-08-18,7.6 +1981-08-19,9.7 +1981-08-20,12.5 +1981-08-21,7.4 +1981-08-22,7.9 +1981-08-23,3.9 +1981-08-24,6.6 +1981-08-25,4.6 +1981-08-26,7.0 +1981-08-27,6.0 +1981-08-28,5.5 +1981-08-29,8.1 +1981-08-30,5.5 +1981-08-31,6.2 +1981-09-01,8.0 +1981-09-02,10.3 +1981-09-03,9.8 +1981-09-04,9.6 +1981-09-05,8.5 +1981-09-06,7.5 +1981-09-07,11.2 +1981-09-08,14.6 +1981-09-09,11.7 +1981-09-10,7.8 +1981-09-11,12.3 +1981-09-12,10.1 +1981-09-13,11.5 +1981-09-14,7.3 +1981-09-15,10.9 +1981-09-16,14.1 +1981-09-17,10.7 +1981-09-18,16.9 +1981-09-19,10.5 +1981-09-20,6.5 +1981-09-21,11.0 +1981-09-22,6.3 +1981-09-23,10.5 +1981-09-24,7.2 +1981-09-25,7.6 +1981-09-26,10.7 +1981-09-27,7.8 +1981-09-28,9.6 +1981-09-29,11.4 +1981-09-30,12.4 +1981-10-01,8.9 +1981-10-02,13.2 +1981-10-03,8.6 +1981-10-04,6.2 +1981-10-05,11.4 +1981-10-06,13.2 +1981-10-07,14.3 +1981-10-08,7.3 +1981-10-09,12.9 +1981-10-10,7.8 +1981-10-11,6.2 +1981-10-12,5.6 +1981-10-13,10.0 +1981-10-14,13.3 +1981-10-15,8.3 +1981-10-16,10.2 +1981-10-17,8.6 +1981-10-18,7.3 +1981-10-19,10.4 +1981-10-20,11.2 +1981-10-21,13.2 +1981-10-22,11.4 +1981-10-23,9.1 +1981-10-24,6.6 +1981-10-25,8.4 +1981-10-26,9.7 +1981-10-27,13.2 +1981-10-28,12.5 +1981-10-29,11.0 +1981-10-30,11.0 +1981-10-31,11.7 +1981-11-01,9.2 +1981-11-02,11.5 +1981-11-03,13.6 +1981-11-04,13.7 +1981-11-05,10.4 +1981-11-06,11.5 +1981-11-07,7.6 +1981-11-08,9.6 +1981-11-09,14.2 +1981-11-10,15.7 +1981-11-11,10.5 +1981-11-12,10.5 +1981-11-13,9.7 +1981-11-14,9.5 +1981-11-15,11.3 +1981-11-16,8.9 +1981-11-17,9.4 +1981-11-18,11.9 +1981-11-19,11.7 +1981-11-20,13.4 +1981-11-21,12.6 +1981-11-22,10.1 +1981-11-23,15.8 +1981-11-24,13.6 +1981-11-25,11.9 +1981-11-26,9.9 +1981-11-27,12.6 +1981-11-28,17.8 +1981-11-29,15.0 +1981-11-30,13.6 +1981-12-01,13.4 +1981-12-02,10.5 +1981-12-03,14.2 +1981-12-04,11.5 +1981-12-05,13.0 +1981-12-06,15.0 +1981-12-07,14.7 +1981-12-08,12.6 +1981-12-09,12.5 +1981-12-10,13.5 +1981-12-11,14.8 +1981-12-12,17.2 +1981-12-13,9.7 +1981-12-14,12.1 +1981-12-15,12.8 +1981-12-16,11.2 +1981-12-17,16.4 +1981-12-18,15.6 +1981-12-19,13.3 +1981-12-20,11.0 +1981-12-21,11.1 +1981-12-22,15.0 +1981-12-23,12.8 +1981-12-24,15.0 +1981-12-25,14.2 +1981-12-26,14.0 +1981-12-27,15.5 +1981-12-28,13.3 +1981-12-29,15.6 +1981-12-30,15.2 +1981-12-31,17.4 +1982-01-01,17.0 +1982-01-02,15.0 +1982-01-03,13.5 +1982-01-04,15.2 +1982-01-05,13.0 +1982-01-06,12.5 +1982-01-07,14.1 +1982-01-08,14.8 +1982-01-09,16.2 +1982-01-10,15.8 +1982-01-11,19.1 +1982-01-12,22.2 +1982-01-13,15.9 +1982-01-14,13.0 +1982-01-15,14.1 +1982-01-16,15.8 +1982-01-17,24.0 +1982-01-18,18.0 +1982-01-19,19.7 +1982-01-20,25.2 +1982-01-21,20.5 +1982-01-22,19.3 +1982-01-23,15.8 +1982-01-24,17.0 +1982-01-25,18.4 +1982-01-26,13.3 +1982-01-27,14.6 +1982-01-28,12.5 +1982-01-29,17.0 +1982-01-30,17.1 +1982-01-31,14.0 +1982-02-01,14.6 +1982-02-02,13.3 +1982-02-03,14.8 +1982-02-04,15.1 +1982-02-05,13.1 +1982-02-06,13.6 +1982-02-07,19.5 +1982-02-08,22.7 +1982-02-09,17.2 +1982-02-10,13.5 +1982-02-11,15.4 +1982-02-12,17.0 +1982-02-13,19.2 +1982-02-14,22.8 +1982-02-15,26.3 +1982-02-16,18.2 +1982-02-17,17.0 +1982-02-18,14.8 +1982-02-19,12.8 +1982-02-20,15.5 +1982-02-21,15.6 +1982-02-22,13.1 +1982-02-23,15.2 +1982-02-24,14.1 +1982-02-25,12.5 +1982-02-26,14.6 +1982-02-27,10.4 +1982-02-28,13.9 +1982-03-01,11.9 +1982-03-02,13.5 +1982-03-03,9.8 +1982-03-04,14.0 +1982-03-05,21.5 +1982-03-06,19.5 +1982-03-07,16.7 +1982-03-08,19.1 +1982-03-09,11.0 +1982-03-10,9.0 +1982-03-11,10.0 +1982-03-12,14.6 +1982-03-13,12.5 +1982-03-14,17.2 +1982-03-15,19.2 +1982-03-16,22.2 +1982-03-17,15.7 +1982-03-18,14.2 +1982-03-19,9.8 +1982-03-20,14.0 +1982-03-21,17.5 +1982-03-22,20.7 +1982-03-23,15.6 +1982-03-24,13.2 +1982-03-25,14.5 +1982-03-26,16.8 +1982-03-27,17.2 +1982-03-28,13.4 +1982-03-29,14.2 +1982-03-30,14.3 +1982-03-31,10.2 +1982-04-01,10.4 +1982-04-02,12.3 +1982-04-03,11.9 +1982-04-04,11.2 +1982-04-05,8.5 +1982-04-06,12.0 +1982-04-07,12.4 +1982-04-08,12.9 +1982-04-09,10.1 +1982-04-10,15.0 +1982-04-11,13.6 +1982-04-12,12.4 +1982-04-13,13.6 +1982-04-14,16.1 +1982-04-15,19.5 +1982-04-16,14.2 +1982-04-17,9.3 +1982-04-18,10.1 +1982-04-19,7.4 +1982-04-20,8.6 +1982-04-21,7.8 +1982-04-22,9.1 +1982-04-23,13.0 +1982-04-24,16.5 +1982-04-25,12.9 +1982-04-26,6.9 +1982-04-27,6.9 +1982-04-28,8.7 +1982-04-29,10.0 +1982-04-30,10.8 +1982-05-01,7.5 +1982-05-02,6.3 +1982-05-03,11.9 +1982-05-04,13.8 +1982-05-05,11.8 +1982-05-06,11.0 +1982-05-07,10.1 +1982-05-08,8.5 +1982-05-09,5.5 +1982-05-10,7.6 +1982-05-11,8.7 +1982-05-12,10.8 +1982-05-13,11.2 +1982-05-14,9.1 +1982-05-15,3.7 +1982-05-16,4.6 +1982-05-17,6.6 +1982-05-18,13.2 +1982-05-19,15.2 +1982-05-20,7.6 +1982-05-21,8.4 +1982-05-22,6.0 +1982-05-23,8.3 +1982-05-24,8.6 +1982-05-25,11.1 +1982-05-26,12.1 +1982-05-27,12.9 +1982-05-28,14.0 +1982-05-29,12.5 +1982-05-30,11.5 +1982-05-31,7.0 +1982-06-01,7.1 +1982-06-02,9.0 +1982-06-03,3.1 +1982-06-04,2.5 +1982-06-05,0.0 +1982-06-06,1.6 +1982-06-07,2.6 +1982-06-08,5.7 +1982-06-09,2.3 +1982-06-10,4.5 +1982-06-11,8.2 +1982-06-12,6.9 +1982-06-13,7.3 +1982-06-14,6.0 +1982-06-15,7.3 +1982-06-16,7.6 +1982-06-17,8.0 +1982-06-18,8.0 +1982-06-19,6.8 +1982-06-20,7.3 +1982-06-21,6.2 +1982-06-22,6.9 +1982-06-23,8.9 +1982-06-24,4.0 +1982-06-25,1.3 +1982-06-26,0.8 +1982-06-27,4.3 +1982-06-28,7.3 +1982-06-29,7.7 +1982-06-30,9.0 +1982-07-01,4.2 +1982-07-02,1.6 +1982-07-03,2.6 +1982-07-04,3.4 +1982-07-05,3.9 +1982-07-06,7.0 +1982-07-07,7.8 +1982-07-08,5.3 +1982-07-09,2.4 +1982-07-10,2.8 +1982-07-11,4.0 +1982-07-12,7.5 +1982-07-13,7.8 +1982-07-14,5.6 +1982-07-15,3.3 +1982-07-16,5.0 +1982-07-17,3.7 +1982-07-18,3.9 +1982-07-19,5.2 +1982-07-20,0.2 +1982-07-21,0.8 +1982-07-22,0.9 +1982-07-23,3.5 +1982-07-24,6.6 +1982-07-25,9.5 +1982-07-26,9.0 +1982-07-27,3.5 +1982-07-28,4.5 +1982-07-29,5.7 +1982-07-30,5.6 +1982-07-31,7.1 +1982-08-01,9.7 +1982-08-02,8.3 +1982-08-03,9.1 +1982-08-04,2.8 +1982-08-05,2.2 +1982-08-06,4.5 +1982-08-07,3.8 +1982-08-08,3.8 +1982-08-09,6.2 +1982-08-10,11.5 +1982-08-11,10.2 +1982-08-12,7.9 +1982-08-13,9.0 +1982-08-14,9.5 +1982-08-15,6.0 +1982-08-16,8.2 +1982-08-17,9.2 +1982-08-18,4.3 +1982-08-19,6.6 +1982-08-20,9.4 +1982-08-21,13.2 +1982-08-22,6.6 +1982-08-23,5.1 +1982-08-24,12.1 +1982-08-25,11.2 +1982-08-26,8.5 +1982-08-27,4.6 +1982-08-28,7.0 +1982-08-29,14.2 +1982-08-30,12.7 +1982-08-31,7.6 +1982-09-01,4.0 +1982-09-02,10.0 +1982-09-03,10.5 +1982-09-04,5.0 +1982-09-05,4.5 +1982-09-06,8.2 +1982-09-07,4.3 +1982-09-08,9.8 +1982-09-09,5.8 +1982-09-10,5.0 +1982-09-11,8.5 +1982-09-12,9.0 +1982-09-13,3.6 +1982-09-14,6.7 +1982-09-15,6.7 +1982-09-16,10.1 +1982-09-17,15.0 +1982-09-18,8.9 +1982-09-19,5.7 +1982-09-20,4.2 +1982-09-21,4.0 +1982-09-22,5.3 +1982-09-23,6.3 +1982-09-24,8.5 +1982-09-25,11.5 +1982-09-26,7.7 +1982-09-27,9.2 +1982-09-28,7.8 +1982-09-29,6.3 +1982-09-30,6.3 +1982-10-01,8.6 +1982-10-02,6.1 +1982-10-03,13.2 +1982-10-04,9.9 +1982-10-05,4.7 +1982-10-06,5.8 +1982-10-07,14.9 +1982-10-08,10.7 +1982-10-09,8.6 +1982-10-10,9.4 +1982-10-11,5.7 +1982-10-12,10.9 +1982-10-13,13.1 +1982-10-14,10.4 +1982-10-15,8.2 +1982-10-16,9.8 +1982-10-17,7.5 +1982-10-18,5.8 +1982-10-19,9.8 +1982-10-20,7.9 +1982-10-21,8.7 +1982-10-22,10.0 +1982-10-23,10.6 +1982-10-24,8.0 +1982-10-25,10.2 +1982-10-26,15.1 +1982-10-27,13.9 +1982-10-28,9.2 +1982-10-29,9.0 +1982-10-30,13.2 +1982-10-31,7.0 +1982-11-01,10.6 +1982-11-02,6.9 +1982-11-03,9.5 +1982-11-04,12.5 +1982-11-05,13.6 +1982-11-06,17.7 +1982-11-07,16.0 +1982-11-08,11.3 +1982-11-09,10.5 +1982-11-10,14.4 +1982-11-11,10.3 +1982-11-12,9.0 +1982-11-13,11.1 +1982-11-14,14.5 +1982-11-15,18.0 +1982-11-16,12.8 +1982-11-17,10.7 +1982-11-18,9.1 +1982-11-19,8.7 +1982-11-20,12.4 +1982-11-21,12.6 +1982-11-22,10.3 +1982-11-23,13.7 +1982-11-24,16.0 +1982-11-25,15.8 +1982-11-26,12.1 +1982-11-27,12.5 +1982-11-28,12.2 +1982-11-29,13.7 +1982-11-30,16.1 +1982-12-01,15.5 +1982-12-02,10.3 +1982-12-03,10.5 +1982-12-04,11.0 +1982-12-05,11.9 +1982-12-06,13.0 +1982-12-07,12.2 +1982-12-08,10.6 +1982-12-09,13.0 +1982-12-10,13.0 +1982-12-11,12.2 +1982-12-12,12.6 +1982-12-13,18.7 +1982-12-14,15.2 +1982-12-15,15.3 +1982-12-16,13.9 +1982-12-17,15.8 +1982-12-18,13.0 +1982-12-19,13.0 +1982-12-20,13.7 +1982-12-21,12.0 +1982-12-22,10.8 +1982-12-23,15.6 +1982-12-24,15.3 +1982-12-25,13.9 +1982-12-26,13.0 +1982-12-27,15.3 +1982-12-28,16.3 +1982-12-29,15.8 +1982-12-30,17.7 +1982-12-31,16.3 +1983-01-01,18.4 +1983-01-02,15.0 +1983-01-03,10.9 +1983-01-04,11.4 +1983-01-05,14.8 +1983-01-06,12.1 +1983-01-07,12.8 +1983-01-08,16.2 +1983-01-09,15.5 +1983-01-10,13.0 +1983-01-11,10.5 +1983-01-12,9.1 +1983-01-13,10.5 +1983-01-14,11.8 +1983-01-15,12.7 +1983-01-16,12.7 +1983-01-17,11.5 +1983-01-18,13.8 +1983-01-19,13.3 +1983-01-20,11.6 +1983-01-21,15.4 +1983-01-22,12.4 +1983-01-23,16.9 +1983-01-24,14.7 +1983-01-25,10.6 +1983-01-26,15.6 +1983-01-27,10.7 +1983-01-28,12.6 +1983-01-29,13.8 +1983-01-30,14.3 +1983-01-31,14.0 +1983-02-01,18.1 +1983-02-02,17.3 +1983-02-03,13.0 +1983-02-04,16.0 +1983-02-05,14.9 +1983-02-06,16.2 +1983-02-07,20.3 +1983-02-08,22.5 +1983-02-09,17.2 +1983-02-10,15.9 +1983-02-11,16.8 +1983-02-12,13.8 +1983-02-13,12.8 +1983-02-14,14.0 +1983-02-15,17.5 +1983-02-16,21.5 +1983-02-17,16.8 +1983-02-18,13.6 +1983-02-19,14.5 +1983-02-20,14.2 +1983-02-21,15.7 +1983-02-22,19.7 +1983-02-23,17.4 +1983-02-24,14.4 +1983-02-25,16.9 +1983-02-26,19.1 +1983-02-27,20.4 +1983-02-28,20.1 +1983-03-01,19.9 +1983-03-02,22.0 +1983-03-03,20.5 +1983-03-04,22.1 +1983-03-05,20.6 +1983-03-06,15.0 +1983-03-07,20.6 +1983-03-08,21.5 +1983-03-09,16.2 +1983-03-10,14.1 +1983-03-11,14.5 +1983-03-12,21.1 +1983-03-13,15.9 +1983-03-14,15.2 +1983-03-15,13.1 +1983-03-16,13.2 +1983-03-17,12.5 +1983-03-18,15.2 +1983-03-19,17.6 +1983-03-20,15.5 +1983-03-21,16.7 +1983-03-22,16.3 +1983-03-23,15.1 +1983-03-24,12.7 +1983-03-25,10.0 +1983-03-26,11.4 +1983-03-27,12.6 +1983-03-28,10.7 +1983-03-29,10.0 +1983-03-30,13.9 +1983-03-31,13.4 +1983-04-01,12.5 +1983-04-02,12.8 +1983-04-03,7.8 +1983-04-04,11.1 +1983-04-05,10.7 +1983-04-06,7.1 +1983-04-07,6.7 +1983-04-08,5.7 +1983-04-09,9.1 +1983-04-10,15.2 +1983-04-11,15.5 +1983-04-12,11.1 +1983-04-13,11.7 +1983-04-14,11.5 +1983-04-15,9.8 +1983-04-16,6.2 +1983-04-17,6.7 +1983-04-18,7.5 +1983-04-19,8.8 +1983-04-20,8.0 +1983-04-21,10.4 +1983-04-22,14.5 +1983-04-23,16.5 +1983-04-24,14.1 +1983-04-25,10.5 +1983-04-26,12.6 +1983-04-27,13.0 +1983-04-28,8.7 +1983-04-29,10.1 +1983-04-30,12.0 +1983-05-01,12.5 +1983-05-02,13.5 +1983-05-03,13.7 +1983-05-04,13.5 +1983-05-05,10.7 +1983-05-06,13.0 +1983-05-07,11.6 +1983-05-08,13.0 +1983-05-09,11.2 +1983-05-10,13.5 +1983-05-11,12.9 +1983-05-12,6.8 +1983-05-13,10.0 +1983-05-14,14.5 +1983-05-15,11.7 +1983-05-16,6.7 +1983-05-17,4.6 +1983-05-18,4.9 +1983-05-19,7.4 +1983-05-20,8.3 +1983-05-21,7.5 +1983-05-22,6.2 +1983-05-23,7.8 +1983-05-24,13.2 +1983-05-25,11.9 +1983-05-26,6.5 +1983-05-27,8.3 +1983-05-28,12.1 +1983-05-29,9.3 +1983-05-30,7.5 +1983-05-31,9.3 +1983-06-01,11.0 +1983-06-02,10.8 +1983-06-03,5.3 +1983-06-04,7.6 +1983-06-05,5.6 +1983-06-06,7.2 +1983-06-07,9.6 +1983-06-08,7.0 +1983-06-09,8.3 +1983-06-10,7.8 +1983-06-11,4.7 +1983-06-12,6.8 +1983-06-13,7.2 +1983-06-14,8.3 +1983-06-15,9.5 +1983-06-16,4.7 +1983-06-17,3.0 +1983-06-18,1.5 +1983-06-19,2.5 +1983-06-20,6.2 +1983-06-21,11.6 +1983-06-22,6.6 +1983-06-23,6.6 +1983-06-24,8.0 +1983-06-25,7.9 +1983-06-26,3.3 +1983-06-27,3.9 +1983-06-28,6.0 +1983-06-29,4.0 +1983-06-30,5.5 +1983-07-01,8.5 +1983-07-02,9.8 +1983-07-03,9.5 +1983-07-04,7.2 +1983-07-05,8.1 +1983-07-06,8.0 +1983-07-07,8.5 +1983-07-08,8.8 +1983-07-09,8.3 +1983-07-10,2.4 +1983-07-11,4.9 +1983-07-12,5.9 +1983-07-13,6.7 +1983-07-14,8.4 +1983-07-15,6.5 +1983-07-16,7.9 +1983-07-17,4.1 +1983-07-18,5.4 +1983-07-19,7.5 +1983-07-20,3.9 +1983-07-21,2.5 +1983-07-22,5.3 +1983-07-23,6.6 +1983-07-24,0.0 +1983-07-25,0.7 +1983-07-26,7.6 +1983-07-27,12.3 +1983-07-28,9.2 +1983-07-29,9.6 +1983-07-30,9.5 +1983-07-31,10.0 +1983-08-01,7.7 +1983-08-02,8.0 +1983-08-03,8.3 +1983-08-04,8.3 +1983-08-05,4.5 +1983-08-06,6.5 +1983-08-07,9.4 +1983-08-08,9.4 +1983-08-09,10.5 +1983-08-10,10.7 +1983-08-11,9.9 +1983-08-12,7.6 +1983-08-13,5.8 +1983-08-14,8.5 +1983-08-15,13.8 +1983-08-16,14.3 +1983-08-17,8.3 +1983-08-18,5.3 +1983-08-19,3.0 +1983-08-20,5.2 +1983-08-21,10.3 +1983-08-22,11.1 +1983-08-23,10.5 +1983-08-24,9.0 +1983-08-25,13.0 +1983-08-26,6.4 +1983-08-27,8.4 +1983-08-28,6.7 +1983-08-29,8.3 +1983-08-30,11.2 +1983-08-31,10.0 +1983-09-01,10.1 +1983-09-02,10.6 +1983-09-03,10.9 +1983-09-04,5.7 +1983-09-05,9.5 +1983-09-06,10.4 +1983-09-07,11.1 +1983-09-08,12.2 +1983-09-09,10.6 +1983-09-10,8.8 +1983-09-11,9.2 +1983-09-12,5.5 +1983-09-13,7.1 +1983-09-14,6.5 +1983-09-15,4.3 +1983-09-16,5.0 +1983-09-17,11.2 +1983-09-18,7.5 +1983-09-19,12.0 +1983-09-20,13.6 +1983-09-21,8.3 +1983-09-22,8.5 +1983-09-23,12.9 +1983-09-24,7.7 +1983-09-25,7.6 +1983-09-26,3.5 +1983-09-27,10.4 +1983-09-28,15.4 +1983-09-29,10.6 +1983-09-30,9.6 +1983-10-01,9.3 +1983-10-02,13.9 +1983-10-03,7.7 +1983-10-04,9.5 +1983-10-05,7.6 +1983-10-06,6.9 +1983-10-07,6.8 +1983-10-08,5.8 +1983-10-09,6.0 +1983-10-10,8.3 +1983-10-11,9.1 +1983-10-12,12.5 +1983-10-13,13.2 +1983-10-14,16.2 +1983-10-15,12.5 +1983-10-16,11.8 +1983-10-17,10.6 +1983-10-18,10.0 +1983-10-19,12.2 +1983-10-20,8.9 +1983-10-21,10.3 +1983-10-22,7.5 +1983-10-23,11.6 +1983-10-24,12.6 +1983-10-25,12.9 +1983-10-26,11.7 +1983-10-27,14.0 +1983-10-28,12.3 +1983-10-29,9.0 +1983-10-30,9.2 +1983-10-31,9.8 +1983-11-01,11.8 +1983-11-02,10.6 +1983-11-03,12.6 +1983-11-04,11.0 +1983-11-05,8.2 +1983-11-06,7.5 +1983-11-07,13.6 +1983-11-08,14.8 +1983-11-09,10.9 +1983-11-10,7.7 +1983-11-11,10.2 +1983-11-12,10.8 +1983-11-13,10.8 +1983-11-14,12.5 +1983-11-15,13.2 +1983-11-16,8.7 +1983-11-17,5.7 +1983-11-18,9.8 +1983-11-19,7.3 +1983-11-20,10.8 +1983-11-21,10.0 +1983-11-22,16.2 +1983-11-23,15.0 +1983-11-24,14.5 +1983-11-25,15.9 +1983-11-26,14.9 +1983-11-27,14.2 +1983-11-28,15.8 +1983-11-29,17.2 +1983-11-30,17.6 +1983-12-01,12.1 +1983-12-02,11.4 +1983-12-03,13.0 +1983-12-04,13.2 +1983-12-05,12.0 +1983-12-06,15.3 +1983-12-07,12.7 +1983-12-08,12.1 +1983-12-09,13.8 +1983-12-10,10.9 +1983-12-11,12.0 +1983-12-12,16.5 +1983-12-13,15.0 +1983-12-14,11.2 +1983-12-15,13.9 +1983-12-16,15.0 +1983-12-17,14.8 +1983-12-18,15.0 +1983-12-19,13.3 +1983-12-20,20.4 +1983-12-21,18.0 +1983-12-22,12.2 +1983-12-23,16.7 +1983-12-24,13.8 +1983-12-25,17.5 +1983-12-26,15.0 +1983-12-27,13.9 +1983-12-28,11.1 +1983-12-29,16.1 +1983-12-30,20.4 +1983-12-31,18.0 +1984-01-01,19.5 +1984-01-02,17.1 +1984-01-03,17.1 +1984-01-04,12.0 +1984-01-05,11.0 +1984-01-06,16.3 +1984-01-07,16.1 +1984-01-08,13.0 +1984-01-09,13.4 +1984-01-10,15.2 +1984-01-11,12.5 +1984-01-12,14.3 +1984-01-13,16.5 +1984-01-14,18.6 +1984-01-15,18.0 +1984-01-16,18.2 +1984-01-17,11.4 +1984-01-18,11.9 +1984-01-19,12.2 +1984-01-20,14.8 +1984-01-21,13.1 +1984-01-22,12.7 +1984-01-23,10.5 +1984-01-24,13.8 +1984-01-25,18.8 +1984-01-26,13.9 +1984-01-27,11.2 +1984-01-28,10.6 +1984-01-29,14.7 +1984-01-30,13.1 +1984-01-31,12.1 +1984-02-01,14.7 +1984-02-02,11.1 +1984-02-03,13.0 +1984-02-04,15.6 +1984-02-05,14.2 +1984-02-06,15.5 +1984-02-07,18.0 +1984-02-08,15.0 +1984-02-09,15.9 +1984-02-10,15.5 +1984-02-11,15.8 +1984-02-12,16.6 +1984-02-13,13.6 +1984-02-14,13.8 +1984-02-15,14.6 +1984-02-16,15.6 +1984-02-17,16.6 +1984-02-18,14.3 +1984-02-19,16.3 +1984-02-20,18.9 +1984-02-21,18.7 +1984-02-22,14.5 +1984-02-23,16.5 +1984-02-24,14.1 +1984-02-25,13.5 +1984-02-26,11.7 +1984-02-27,15.1 +1984-02-28,11.2 +1984-02-29,13.5 +1984-03-01,12.6 +1984-03-02,8.8 +1984-03-03,10.5 +1984-03-04,12.1 +1984-03-05,14.5 +1984-03-06,19.5 +1984-03-07,14.0 +1984-03-08,13.8 +1984-03-09,10.5 +1984-03-10,13.8 +1984-03-11,11.4 +1984-03-12,15.6 +1984-03-13,11.1 +1984-03-14,12.1 +1984-03-15,14.2 +1984-03-16,10.9 +1984-03-17,14.2 +1984-03-18,13.8 +1984-03-19,15.1 +1984-03-20,14.0 +1984-03-21,12.1 +1984-03-22,13.8 +1984-03-23,16.6 +1984-03-24,17.8 +1984-03-25,9.4 +1984-03-26,10.2 +1984-03-27,7.4 +1984-03-28,8.7 +1984-03-29,14.0 +1984-03-30,15.3 +1984-03-31,11.1 +1984-04-01,9.7 +1984-04-02,10.3 +1984-04-03,9.2 +1984-04-04,8.2 +1984-04-05,9.7 +1984-04-06,12.4 +1984-04-07,12.5 +1984-04-08,9.0 +1984-04-09,9.7 +1984-04-10,10.1 +1984-04-11,11.2 +1984-04-12,12.0 +1984-04-13,11.1 +1984-04-14,10.8 +1984-04-15,12.8 +1984-04-16,9.8 +1984-04-17,13.7 +1984-04-18,11.0 +1984-04-19,13.2 +1984-04-20,13.0 +1984-04-21,10.2 +1984-04-22,13.2 +1984-04-23,9.3 +1984-04-24,11.1 +1984-04-25,10.3 +1984-04-26,8.7 +1984-04-27,11.7 +1984-04-28,12.5 +1984-04-29,6.5 +1984-04-30,9.6 +1984-05-01,13.8 +1984-05-02,14.7 +1984-05-03,9.1 +1984-05-04,4.8 +1984-05-05,3.3 +1984-05-06,3.5 +1984-05-07,5.7 +1984-05-08,5.5 +1984-05-09,7.0 +1984-05-10,9.5 +1984-05-11,9.9 +1984-05-12,4.9 +1984-05-13,6.3 +1984-05-14,4.8 +1984-05-15,6.2 +1984-05-16,7.1 +1984-05-17,7.5 +1984-05-18,9.4 +1984-05-19,8.7 +1984-05-20,9.5 +1984-05-21,12.1 +1984-05-22,9.5 +1984-05-23,9.3 +1984-05-24,8.5 +1984-05-25,8.0 +1984-05-26,9.8 +1984-05-27,6.2 +1984-05-28,7.3 +1984-05-29,10.9 +1984-05-30,10.0 +1984-05-31,8.7 +1984-06-01,9.0 +1984-06-02,10.8 +1984-06-03,12.4 +1984-06-04,7.2 +1984-06-05,7.2 +1984-06-06,11.1 +1984-06-07,9.3 +1984-06-08,10.1 +1984-06-09,3.9 +1984-06-10,5.0 +1984-06-11,8.2 +1984-06-12,2.8 +1984-06-13,4.3 +1984-06-14,8.1 +1984-06-15,11.1 +1984-06-16,4.7 +1984-06-17,5.3 +1984-06-18,10.0 +1984-06-19,5.6 +1984-06-20,2.2 +1984-06-21,7.1 +1984-06-22,8.3 +1984-06-23,8.6 +1984-06-24,10.1 +1984-06-25,8.3 +1984-06-26,7.2 +1984-06-27,7.7 +1984-06-28,7.8 +1984-06-29,9.1 +1984-06-30,9.4 +1984-07-01,7.8 +1984-07-02,2.6 +1984-07-03,2.4 +1984-07-04,3.9 +1984-07-05,1.3 +1984-07-06,2.1 +1984-07-07,7.4 +1984-07-08,7.2 +1984-07-09,8.8 +1984-07-10,8.9 +1984-07-11,8.8 +1984-07-12,8.0 +1984-07-13,0.7 +1984-07-14,0.1 +1984-07-15,0.9 +1984-07-16,7.8 +1984-07-17,7.2 +1984-07-18,8.0 +1984-07-19,4.6 +1984-07-20,5.2 +1984-07-21,5.8 +1984-07-22,6.8 +1984-07-23,8.1 +1984-07-24,7.5 +1984-07-25,5.4 +1984-07-26,4.6 +1984-07-27,6.4 +1984-07-28,9.7 +1984-07-29,7.0 +1984-07-30,10.0 +1984-07-31,10.6 +1984-08-01,11.5 +1984-08-02,10.2 +1984-08-03,11.1 +1984-08-04,11.0 +1984-08-05,8.9 +1984-08-06,9.9 +1984-08-07,11.7 +1984-08-08,11.6 +1984-08-09,9.0 +1984-08-10,6.3 +1984-08-11,8.7 +1984-08-12,8.5 +1984-08-13,8.5 +1984-08-14,8.0 +1984-08-15,6.0 +1984-08-16,8.0 +1984-08-17,8.5 +1984-08-18,7.7 +1984-08-19,8.4 +1984-08-20,9.0 +1984-08-21,8.3 +1984-08-22,6.8 +1984-08-23,9.3 +1984-08-24,6.7 +1984-08-25,9.0 +1984-08-26,7.3 +1984-08-27,6.3 +1984-08-28,7.9 +1984-08-29,5.2 +1984-08-30,9.0 +1984-08-31,11.3 +1984-09-01,9.2 +1984-09-02,11.3 +1984-09-03,7.0 +1984-09-04,8.0 +1984-09-05,4.6 +1984-09-06,8.5 +1984-09-07,9.5 +1984-09-08,9.4 +1984-09-09,10.5 +1984-09-10,9.7 +1984-09-11,4.9 +1984-09-12,8.0 +1984-09-13,5.8 +1984-09-14,5.5 +1984-09-15,10.9 +1984-09-16,11.7 +1984-09-17,9.2 +1984-09-18,8.9 +1984-09-19,11.3 +1984-09-20,8.6 +1984-09-21,6.2 +1984-09-22,6.6 +1984-09-23,9.1 +1984-09-24,6.1 +1984-09-25,7.5 +1984-09-26,10.7 +1984-09-27,6.3 +1984-09-28,5.5 +1984-09-29,6.7 +1984-09-30,4.2 +1984-10-01,11.3 +1984-10-02,16.3 +1984-10-03,10.5 +1984-10-04,10.3 +1984-10-05,7.9 +1984-10-06,7.7 +1984-10-07,16.0 +1984-10-08,14.6 +1984-10-09,12.5 +1984-10-10,8.1 +1984-10-11,12.2 +1984-10-12,17.2 +1984-10-13,9.4 +1984-10-14,8.7 +1984-10-15,5.9 +1984-10-16,4.8 +1984-10-17,7.4 +1984-10-18,9.4 +1984-10-19,9.7 +1984-10-20,9.9 +1984-10-21,6.5 +1984-10-22,9.8 +1984-10-23,18.2 +1984-10-24,11.3 +1984-10-25,9.1 +1984-10-26,9.6 +1984-10-27,13.5 +1984-10-28,10.7 +1984-10-29,10.0 +1984-10-30,8.5 +1984-10-31,12.6 +1984-11-01,16.6 +1984-11-02,11.6 +1984-11-03,12.2 +1984-11-04,11.2 +1984-11-05,9.2 +1984-11-06,9.9 +1984-11-07,11.9 +1984-11-08,15.6 +1984-11-09,19.0 +1984-11-10,12.8 +1984-11-11,12.2 +1984-11-12,12.0 +1984-11-13,11.1 +1984-11-14,11.8 +1984-11-15,7.6 +1984-11-16,13.0 +1984-11-17,12.7 +1984-11-18,16.0 +1984-11-19,14.8 +1984-11-20,14.2 +1984-11-21,10.0 +1984-11-22,8.8 +1984-11-23,11.6 +1984-11-24,8.6 +1984-11-25,14.6 +1984-11-26,24.3 +1984-11-27,11.6 +1984-11-28,10.8 +1984-11-29,12.0 +1984-11-30,11.0 +1984-12-01,12.6 +1984-12-02,10.8 +1984-12-03,9.1 +1984-12-04,11.0 +1984-12-05,13.0 +1984-12-06,12.8 +1984-12-07,9.9 +1984-12-08,11.6 +1984-12-09,10.5 +1984-12-10,15.9 +1984-12-11,12.2 +1984-12-12,13.0 +1984-12-13,12.5 +1984-12-14,12.5 +1984-12-15,11.4 +1984-12-16,12.1 +1984-12-17,16.8 +1984-12-18,12.1 +1984-12-19,11.3 +1984-12-20,10.4 +1984-12-21,14.2 +1984-12-22,11.4 +1984-12-23,13.7 +1984-12-24,16.5 +1984-12-25,12.8 +1984-12-26,12.2 +1984-12-27,12.0 +1984-12-28,12.6 +1984-12-29,16.0 +1984-12-30,16.4 +1985-01-01,13.3 +1985-01-02,15.2 +1985-01-03,13.1 +1985-01-04,12.7 +1985-01-05,14.6 +1985-01-06,11.0 +1985-01-07,13.2 +1985-01-08,12.2 +1985-01-09,14.4 +1985-01-10,13.7 +1985-01-11,14.5 +1985-01-12,14.1 +1985-01-13,14.4 +1985-01-14,19.7 +1985-01-15,16.5 +1985-01-16,15.9 +1985-01-17,11.8 +1985-01-18,12.0 +1985-01-19,11.4 +1985-01-20,14.4 +1985-01-21,12.4 +1985-01-22,15.1 +1985-01-23,15.6 +1985-01-24,15.2 +1985-01-25,12.8 +1985-01-26,13.3 +1985-01-27,17.5 +1985-01-28,15.4 +1985-01-29,13.5 +1985-01-30,16.7 +1985-01-31,15.2 +1985-02-01,14.9 +1985-02-02,10.2 +1985-02-03,13.6 +1985-02-04,19.0 +1985-02-05,15.7 +1985-02-06,18.0 +1985-02-07,14.8 +1985-02-08,13.9 +1985-02-09,13.0 +1985-02-10,15.3 +1985-02-11,14.3 +1985-02-12,15.6 +1985-02-13,16.0 +1985-02-14,14.9 +1985-02-15,11.1 +1985-02-16,14.8 +1985-02-17,13.0 +1985-02-18,12.2 +1985-02-19,10.9 +1985-02-20,14.6 +1985-02-21,16.6 +1985-02-22,18.1 +1985-02-23,13.4 +1985-02-24,10.3 +1985-02-25,13.6 +1985-02-26,13.8 +1985-02-27,10.3 +1985-02-28,11.0 +1985-03-01,14.3 +1985-03-02,15.5 +1985-03-03,14.7 +1985-03-04,12.7 +1985-03-05,10.7 +1985-03-06,12.6 +1985-03-07,9.8 +1985-03-08,13.2 +1985-03-09,15.2 +1985-03-10,16.6 +1985-03-11,21.0 +1985-03-12,22.4 +1985-03-13,17.0 +1985-03-14,21.7 +1985-03-15,21.4 +1985-03-16,18.6 +1985-03-17,16.2 +1985-03-18,16.8 +1985-03-19,17.0 +1985-03-20,18.4 +1985-03-21,17.2 +1985-03-22,18.4 +1985-03-23,18.8 +1985-03-24,16.5 +1985-03-25,13.3 +1985-03-26,12.2 +1985-03-27,11.3 +1985-03-28,13.8 +1985-03-29,16.6 +1985-03-30,14.0 +1985-03-31,14.3 +1985-04-01,16.4 +1985-04-02,11.9 +1985-04-03,15.7 +1985-04-04,17.6 +1985-04-05,17.5 +1985-04-06,15.9 +1985-04-07,16.2 +1985-04-08,16.0 +1985-04-09,15.9 +1985-04-10,16.2 +1985-04-11,16.2 +1985-04-12,19.5 +1985-04-13,18.2 +1985-04-14,21.8 +1985-04-15,15.1 +1985-04-16,11.0 +1985-04-17,8.1 +1985-04-18,9.5 +1985-04-19,9.3 +1985-04-20,10.6 +1985-04-21,6.3 +1985-04-22,8.6 +1985-04-23,6.8 +1985-04-24,8.7 +1985-04-25,8.4 +1985-04-26,9.3 +1985-04-27,10.0 +1985-04-28,10.5 +1985-04-29,12.0 +1985-04-30,10.1 +1985-05-01,9.4 +1985-05-02,10.1 +1985-05-03,8.0 +1985-05-04,10.6 +1985-05-05,13.6 +1985-05-06,15.4 +1985-05-07,9.0 +1985-05-08,10.4 +1985-05-09,11.0 +1985-05-10,12.1 +1985-05-11,13.4 +1985-05-12,11.3 +1985-05-13,6.7 +1985-05-14,9.8 +1985-05-15,10.8 +1985-05-16,7.8 +1985-05-17,4.5 +1985-05-18,7.6 +1985-05-19,6.9 +1985-05-20,7.5 +1985-05-21,8.5 +1985-05-22,5.5 +1985-05-23,9.5 +1985-05-24,7.3 +1985-05-25,5.4 +1985-05-26,5.5 +1985-05-27,8.1 +1985-05-28,11.2 +1985-05-29,13.4 +1985-05-30,11.6 +1985-05-31,10.1 +1985-06-01,4.3 +1985-06-02,5.5 +1985-06-03,4.4 +1985-06-04,5.9 +1985-06-05,5.7 +1985-06-06,8.2 +1985-06-07,8.2 +1985-06-08,4.2 +1985-06-09,6.5 +1985-06-10,10.0 +1985-06-11,8.8 +1985-06-12,6.6 +1985-06-13,7.8 +1985-06-14,10.1 +1985-06-15,7.1 +1985-06-16,7.7 +1985-06-17,8.5 +1985-06-18,7.3 +1985-06-19,6.9 +1985-06-20,8.4 +1985-06-21,7.1 +1985-06-22,6.3 +1985-06-23,0.6 +1985-06-24,1.6 +1985-06-25,7.0 +1985-06-26,8.3 +1985-06-27,8.0 +1985-06-28,10.2 +1985-06-29,10.6 +1985-06-30,10.4 +1985-07-01,11.6 +1985-07-02,11.0 +1985-07-03,10.7 +1985-07-04,7.3 +1985-07-05,4.2 +1985-07-06,4.7 +1985-07-07,5.6 +1985-07-08,7.7 +1985-07-09,7.5 +1985-07-10,4.9 +1985-07-11,5.9 +1985-07-12,7.8 +1985-07-13,5.8 +1985-07-14,7.0 +1985-07-15,8.4 +1985-07-16,6.2 +1985-07-17,7.5 +1985-07-18,4.8 +1985-07-19,3.3 +1985-07-20,3.2 +1985-07-21,7.0 +1985-07-22,8.4 +1985-07-23,0.3 +1985-07-24,0.3 +1985-07-25,2.1 +1985-07-26,8.5 +1985-07-27,1.4 +1985-07-28,4.1 +1985-07-29,10.3 +1985-07-30,6.6 +1985-07-31,6.1 +1985-08-01,7.0 +1985-08-02,5.1 +1985-08-03,6.3 +1985-08-04,6.9 +1985-08-05,11.4 +1985-08-06,10.4 +1985-08-07,10.3 +1985-08-08,9.2 +1985-08-09,7.2 +1985-08-10,7.5 +1985-08-11,4.0 +1985-08-12,5.6 +1985-08-13,6.7 +1985-08-14,8.4 +1985-08-15,11.0 +1985-08-16,8.4 +1985-08-17,8.8 +1985-08-18,8.6 +1985-08-19,8.3 +1985-08-20,4.0 +1985-08-21,3.6 +1985-08-22,5.7 +1985-08-23,10.6 +1985-08-24,6.9 +1985-08-25,10.0 +1985-08-26,9.8 +1985-08-27,7.2 +1985-08-28,10.5 +1985-08-29,3.6 +1985-08-30,5.3 +1985-08-31,8.4 +1985-09-01,10.3 +1985-09-02,7.9 +1985-09-03,8.5 +1985-09-04,7.9 +1985-09-05,8.0 +1985-09-06,9.8 +1985-09-07,6.7 +1985-09-08,4.8 +1985-09-09,9.9 +1985-09-10,12.8 +1985-09-11,10.9 +1985-09-12,11.7 +1985-09-13,11.7 +1985-09-14,11.0 +1985-09-15,8.2 +1985-09-16,7.5 +1985-09-17,5.4 +1985-09-18,7.2 +1985-09-19,9.7 +1985-09-20,8.4 +1985-09-21,9.0 +1985-09-22,8.7 +1985-09-23,6.6 +1985-09-24,11.6 +1985-09-25,13.1 +1985-09-26,6.7 +1985-09-27,6.5 +1985-09-28,7.7 +1985-09-29,8.7 +1985-09-30,7.2 +1985-10-01,10.5 +1985-10-02,8.6 +1985-10-03,7.2 +1985-10-04,11.4 +1985-10-05,16.2 +1985-10-06,6.1 +1985-10-07,9.6 +1985-10-08,11.1 +1985-10-09,13.6 +1985-10-10,10.7 +1985-10-11,14.7 +1985-10-12,11.6 +1985-10-13,7.3 +1985-10-14,8.0 +1985-10-15,9.6 +1985-10-16,16.0 +1985-10-17,15.1 +1985-10-18,12.8 +1985-10-19,6.2 +1985-10-20,7.1 +1985-10-21,8.4 +1985-10-22,10.0 +1985-10-23,12.7 +1985-10-24,10.0 +1985-10-25,10.2 +1985-10-26,6.5 +1985-10-27,9.2 +1985-10-28,11.9 +1985-10-29,14.7 +1985-10-30,11.4 +1985-10-31,6.8 +1985-11-01,7.4 +1985-11-02,11.2 +1985-11-03,9.2 +1985-11-04,12.6 +1985-11-05,16.0 +1985-11-06,17.1 +1985-11-07,15.3 +1985-11-08,13.3 +1985-11-09,15.4 +1985-11-10,13.2 +1985-11-11,14.4 +1985-11-12,14.0 +1985-11-13,15.5 +1985-11-14,21.0 +1985-11-15,10.0 +1985-11-16,9.6 +1985-11-17,12.0 +1985-11-18,12.2 +1985-11-19,11.3 +1985-11-20,13.2 +1985-11-21,10.5 +1985-11-22,10.1 +1985-11-23,8.8 +1985-11-24,13.7 +1985-11-25,16.2 +1985-11-26,16.0 +1985-11-27,14.0 +1985-11-28,13.7 +1985-11-29,12.5 +1985-11-30,12.8 +1985-12-01,12.3 +1985-12-02,15.2 +1985-12-03,15.0 +1985-12-04,16.4 +1985-12-05,16.1 +1985-12-06,14.6 +1985-12-07,18.2 +1985-12-08,16.4 +1985-12-09,16.6 +1985-12-10,14.7 +1985-12-11,15.8 +1985-12-12,14.1 +1985-12-13,13.5 +1985-12-14,13.6 +1985-12-15,13.7 +1985-12-16,13.6 +1985-12-17,12.1 +1985-12-18,12.7 +1985-12-19,13.3 +1985-12-20,14.2 +1985-12-21,15.0 +1985-12-22,13.7 +1985-12-23,12.0 +1985-12-24,13.1 +1985-12-25,13.2 +1985-12-26,13.3 +1985-12-27,11.5 +1985-12-28,10.8 +1985-12-29,12.0 +1985-12-30,16.3 +1985-12-31,14.4 +1986-01-01,12.9 +1986-01-02,13.8 +1986-01-03,10.6 +1986-01-04,12.6 +1986-01-05,13.7 +1986-01-06,12.6 +1986-01-07,13.1 +1986-01-08,15.4 +1986-01-09,11.9 +1986-01-10,13.8 +1986-01-11,14.4 +1986-01-12,15.2 +1986-01-13,12.5 +1986-01-14,12.2 +1986-01-15,16.1 +1986-01-16,14.6 +1986-01-17,11.6 +1986-01-18,13.1 +1986-01-19,12.8 +1986-01-20,15.2 +1986-01-21,13.8 +1986-01-22,15.0 +1986-01-23,13.5 +1986-01-24,11.8 +1986-01-25,15.3 +1986-01-26,13.5 +1986-01-27,15.3 +1986-01-28,13.8 +1986-01-29,15.8 +1986-01-30,17.4 +1986-01-31,15.3 +1986-02-01,14.6 +1986-02-02,14.8 +1986-02-03,10.7 +1986-02-04,11.6 +1986-02-05,13.6 +1986-02-06,14.4 +1986-02-07,11.8 +1986-02-08,15.8 +1986-02-09,16.0 +1986-02-10,11.8 +1986-02-11,14.5 +1986-02-12,10.7 +1986-02-13,14.2 +1986-02-14,19.5 +1986-02-15,21.4 +1986-02-16,17.9 +1986-02-17,17.4 +1986-02-18,12.7 +1986-02-19,13.8 +1986-02-20,14.0 +1986-02-21,15.0 +1986-02-22,14.5 +1986-02-23,13.1 +1986-02-24,11.4 +1986-02-25,12.5 +1986-02-26,12.0 +1986-02-27,13.4 +1986-02-28,14.4 +1986-03-01,17.7 +1986-03-02,13.9 +1986-03-03,13.3 +1986-03-04,14.6 +1986-03-05,16.4 +1986-03-06,16.8 +1986-03-07,20.0 +1986-03-08,12.5 +1986-03-09,12.7 +1986-03-10,11.7 +1986-03-11,12.7 +1986-03-12,8.6 +1986-03-13,11.9 +1986-03-14,16.0 +1986-03-15,15.2 +1986-03-16,13.4 +1986-03-17,11.6 +1986-03-18,11.1 +1986-03-19,15.6 +1986-03-20,17.0 +1986-03-21,18.5 +1986-03-22,17.4 +1986-03-23,16.5 +1986-03-24,16.2 +1986-03-25,16.1 +1986-03-26,13.2 +1986-03-27,18.0 +1986-03-28,12.8 +1986-03-29,11.7 +1986-03-30,16.7 +1986-03-31,15.6 +1986-04-01,10.2 +1986-04-02,10.3 +1986-04-03,15.0 +1986-04-04,18.0 +1986-04-05,13.8 +1986-04-06,10.5 +1986-04-07,11.8 +1986-04-08,7.2 +1986-04-09,11.6 +1986-04-10,7.4 +1986-04-11,14.2 +1986-04-12,12.2 +1986-04-13,9.0 +1986-04-14,12.3 +1986-04-15,19.7 +1986-04-16,12.8 +1986-04-17,12.4 +1986-04-18,12.0 +1986-04-19,12.0 +1986-04-20,11.1 +1986-04-21,12.7 +1986-04-22,14.2 +1986-04-23,11.6 +1986-04-24,12.0 +1986-04-25,11.5 +1986-04-26,8.3 +1986-04-27,10.5 +1986-04-28,9.0 +1986-04-29,6.9 +1986-04-30,9.4 +1986-05-01,11.1 +1986-05-02,9.1 +1986-05-03,7.7 +1986-05-04,10.0 +1986-05-05,10.4 +1986-05-06,8.0 +1986-05-07,9.8 +1986-05-08,12.4 +1986-05-09,12.9 +1986-05-10,12.3 +1986-05-11,6.9 +1986-05-12,10.5 +1986-05-13,11.0 +1986-05-14,9.7 +1986-05-15,11.1 +1986-05-16,11.5 +1986-05-17,13.4 +1986-05-18,10.9 +1986-05-19,12.0 +1986-05-20,12.1 +1986-05-21,10.4 +1986-05-22,10.0 +1986-05-23,9.6 +1986-05-24,11.3 +1986-05-25,8.5 +1986-05-26,6.3 +1986-05-27,8.2 +1986-05-28,10.7 +1986-05-29,10.3 +1986-05-30,9.5 +1986-05-31,10.9 +1986-06-01,10.9 +1986-06-02,4.3 +1986-06-03,5.2 +1986-06-04,11.0 +1986-06-05,11.6 +1986-06-06,10.6 +1986-06-07,9.4 +1986-06-08,10.0 +1986-06-09,9.6 +1986-06-10,9.5 +1986-06-11,9.7 +1986-06-12,9.6 +1986-06-13,7.0 +1986-06-14,7.0 +1986-06-15,6.8 +1986-06-16,6.9 +1986-06-17,8.0 +1986-06-18,7.6 +1986-06-19,8.6 +1986-06-20,5.7 +1986-06-21,5.5 +1986-06-22,5.7 +1986-06-23,5.7 +1986-06-24,6.6 +1986-06-25,6.0 +1986-06-26,6.9 +1986-06-27,7.7 +1986-06-28,8.0 +1986-06-29,3.9 +1986-06-30,0.8 +1986-07-01,2.8 +1986-07-02,8.0 +1986-07-03,9.8 +1986-07-04,11.4 +1986-07-05,8.6 +1986-07-06,5.2 +1986-07-07,6.6 +1986-07-08,5.7 +1986-07-09,4.6 +1986-07-10,5.8 +1986-07-11,7.0 +1986-07-12,4.8 +1986-07-13,4.4 +1986-07-14,4.4 +1986-07-15,7.9 +1986-07-16,10.6 +1986-07-17,5.0 +1986-07-18,7.6 +1986-07-19,9.2 +1986-07-20,9.7 +1986-07-21,8.8 +1986-07-22,6.8 +1986-07-23,9.4 +1986-07-24,11.0 +1986-07-25,2.5 +1986-07-26,2.1 +1986-07-27,5.4 +1986-07-28,6.2 +1986-07-29,7.8 +1986-07-30,7.4 +1986-07-31,9.3 +1986-08-01,9.3 +1986-08-02,9.5 +1986-08-03,8.5 +1986-08-04,10.0 +1986-08-05,7.7 +1986-08-06,9.3 +1986-08-07,9.1 +1986-08-08,3.5 +1986-08-09,3.6 +1986-08-10,2.5 +1986-08-11,1.7 +1986-08-12,2.7 +1986-08-13,2.9 +1986-08-14,5.3 +1986-08-15,7.7 +1986-08-16,9.1 +1986-08-17,9.4 +1986-08-18,7.3 +1986-08-19,8.4 +1986-08-20,9.2 +1986-08-21,6.6 +1986-08-22,9.7 +1986-08-23,12.4 +1986-08-24,10.2 +1986-08-25,5.9 +1986-08-26,7.1 +1986-08-27,7.5 +1986-08-28,9.7 +1986-08-29,12.2 +1986-08-30,5.6 +1986-08-31,5.4 +1986-09-01,8.3 +1986-09-02,10.6 +1986-09-03,9.1 +1986-09-04,11.3 +1986-09-05,10.9 +1986-09-06,8.9 +1986-09-07,6.3 +1986-09-08,9.0 +1986-09-09,6.1 +1986-09-10,9.1 +1986-09-11,9.6 +1986-09-12,6.0 +1986-09-13,10.0 +1986-09-14,11.0 +1986-09-15,6.2 +1986-09-16,8.3 +1986-09-17,11.3 +1986-09-18,11.3 +1986-09-19,6.7 +1986-09-20,6.6 +1986-09-21,11.4 +1986-09-22,6.9 +1986-09-23,10.6 +1986-09-24,8.6 +1986-09-25,11.3 +1986-09-26,12.5 +1986-09-27,9.9 +1986-09-28,6.9 +1986-09-29,5.5 +1986-09-30,7.8 +1986-10-01,11.0 +1986-10-02,16.2 +1986-10-03,9.9 +1986-10-04,8.7 +1986-10-05,10.5 +1986-10-06,12.2 +1986-10-07,10.6 +1986-10-08,8.3 +1986-10-09,5.5 +1986-10-10,9.0 +1986-10-11,6.4 +1986-10-12,7.2 +1986-10-13,12.9 +1986-10-14,12.0 +1986-10-15,7.3 +1986-10-16,9.7 +1986-10-17,8.4 +1986-10-18,14.7 +1986-10-19,9.5 +1986-10-20,7.9 +1986-10-21,6.8 +1986-10-22,12.6 +1986-10-23,5.2 +1986-10-24,7.5 +1986-10-25,8.7 +1986-10-26,7.6 +1986-10-27,9.0 +1986-10-28,7.2 +1986-10-29,10.7 +1986-10-30,13.1 +1986-10-31,13.9 +1986-11-01,10.8 +1986-11-02,10.4 +1986-11-03,9.1 +1986-11-04,16.0 +1986-11-05,21.0 +1986-11-06,16.2 +1986-11-07,8.6 +1986-11-08,9.2 +1986-11-09,12.5 +1986-11-10,9.7 +1986-11-11,12.5 +1986-11-12,10.3 +1986-11-13,12.0 +1986-11-14,11.0 +1986-11-15,14.8 +1986-11-16,15.0 +1986-11-17,15.3 +1986-11-18,10.3 +1986-11-19,10.7 +1986-11-20,10.5 +1986-11-21,8.9 +1986-11-22,8.1 +1986-11-23,11.5 +1986-11-24,12.8 +1986-11-25,9.1 +1986-11-26,14.6 +1986-11-27,11.6 +1986-11-28,11.2 +1986-11-29,12.6 +1986-11-30,7.5 +1986-12-01,11.0 +1986-12-02,14.5 +1986-12-03,18.5 +1986-12-04,15.4 +1986-12-05,13.1 +1986-12-06,16.3 +1986-12-07,20.2 +1986-12-08,11.5 +1986-12-09,12.4 +1986-12-10,10.9 +1986-12-11,12.7 +1986-12-12,12.2 +1986-12-13,12.4 +1986-12-14,9.8 +1986-12-15,8.5 +1986-12-16,14.7 +1986-12-17,12.0 +1986-12-18,10.3 +1986-12-19,11.0 +1986-12-20,10.2 +1986-12-21,12.6 +1986-12-22,11.6 +1986-12-23,9.7 +1986-12-24,13.4 +1986-12-25,10.5 +1986-12-26,14.7 +1986-12-27,14.6 +1986-12-28,14.2 +1986-12-29,13.2 +1986-12-30,11.7 +1986-12-31,17.2 +1987-01-01,12.3 +1987-01-02,13.8 +1987-01-03,15.3 +1987-01-04,15.6 +1987-01-05,16.2 +1987-01-06,16.3 +1987-01-07,16.8 +1987-01-08,11.0 +1987-01-09,8.5 +1987-01-10,13.2 +1987-01-11,13.0 +1987-01-12,12.4 +1987-01-13,13.0 +1987-01-14,16.6 +1987-01-15,12.0 +1987-01-16,12.4 +1987-01-17,15.0 +1987-01-18,11.8 +1987-01-19,11.6 +1987-01-20,12.2 +1987-01-21,13.7 +1987-01-22,11.2 +1987-01-23,12.4 +1987-01-24,11.5 +1987-01-25,13.8 +1987-01-26,15.7 +1987-01-27,12.9 +1987-01-28,11.5 +1987-01-29,11.0 +1987-01-30,12.7 +1987-01-31,14.9 +1987-02-01,16.5 +1987-02-02,12.8 +1987-02-03,12.7 +1987-02-04,12.7 +1987-02-05,11.6 +1987-02-06,13.3 +1987-02-07,15.2 +1987-02-08,16.4 +1987-02-09,11.9 +1987-02-10,15.1 +1987-02-11,10.6 +1987-02-12,13.6 +1987-02-13,12.1 +1987-02-14,16.0 +1987-02-15,16.8 +1987-02-16,16.6 +1987-02-17,15.6 +1987-02-18,15.2 +1987-02-19,17.7 +1987-02-20,21.0 +1987-02-21,13.4 +1987-02-22,10.5 +1987-02-23,9.5 +1987-02-24,12.0 +1987-02-25,10.4 +1987-02-26,11.5 +1987-02-27,13.2 +1987-02-28,15.0 +1987-03-01,14.1 +1987-03-02,12.4 +1987-03-03,13.4 +1987-03-04,12.5 +1987-03-05,14.3 +1987-03-06,17.6 +1987-03-07,10.4 +1987-03-08,9.9 +1987-03-09,10.2 +1987-03-10,11.3 +1987-03-11,9.5 +1987-03-12,11.8 +1987-03-13,11.5 +1987-03-14,10.5 +1987-03-15,10.8 +1987-03-16,13.0 +1987-03-17,18.5 +1987-03-18,18.7 +1987-03-19,15.0 +1987-03-20,13.0 +1987-03-21,11.3 +1987-03-22,13.0 +1987-03-23,13.3 +1987-03-24,11.0 +1987-03-25,10.3 +1987-03-26,13.0 +1987-03-27,12.3 +1987-03-28,15.6 +1987-03-29,10.2 +1987-03-30,10.8 +1987-03-31,12.0 +1987-04-01,13.3 +1987-04-02,11.7 +1987-04-03,12.5 +1987-04-04,13.7 +1987-04-05,14.9 +1987-04-06,20.2 +1987-04-07,16.3 +1987-04-08,13.9 +1987-04-09,10.1 +1987-04-10,7.3 +1987-04-11,14.0 +1987-04-12,17.7 +1987-04-13,16.3 +1987-04-14,10.6 +1987-04-15,9.7 +1987-04-16,7.8 +1987-04-17,10.4 +1987-04-18,10.4 +1987-04-19,14.1 +1987-04-20,7.1 +1987-04-21,8.1 +1987-04-22,7.8 +1987-04-23,10.6 +1987-04-24,9.1 +1987-04-25,9.0 +1987-04-26,11.9 +1987-04-27,17.1 +1987-04-28,16.8 +1987-04-29,13.5 +1987-04-30,11.6 +1987-05-01,7.0 +1987-05-02,9.7 +1987-05-03,9.9 +1987-05-04,11.2 +1987-05-05,11.3 +1987-05-06,11.8 +1987-05-07,9.9 +1987-05-08,7.1 +1987-05-09,9.6 +1987-05-10,9.8 +1987-05-11,10.6 +1987-05-12,12.8 +1987-05-13,16.5 +1987-05-14,11.7 +1987-05-15,12.3 +1987-05-16,12.2 +1987-05-17,11.8 +1987-05-18,10.7 +1987-05-19,10.2 +1987-05-20,10.0 +1987-05-21,8.3 +1987-05-22,6.6 +1987-05-23,9.5 +1987-05-24,12.3 +1987-05-25,7.6 +1987-05-26,9.3 +1987-05-27,5.0 +1987-05-28,4.3 +1987-05-29,6.4 +1987-05-30,10.8 +1987-05-31,7.8 +1987-06-01,8.5 +1987-06-02,9.7 +1987-06-03,10.0 +1987-06-04,11.0 +1987-06-05,10.2 +1987-06-06,6.6 +1987-06-07,6.1 +1987-06-08,5.9 +1987-06-09,8.9 +1987-06-10,13.0 +1987-06-11,12.6 +1987-06-12,5.4 +1987-06-13,6.0 +1987-06-14,7.8 +1987-06-15,9.0 +1987-06-16,4.2 +1987-06-17,3.0 +1987-06-18,4.5 +1987-06-19,6.2 +1987-06-20,11.9 +1987-06-21,11.8 +1987-06-22,9.4 +1987-06-23,9.6 +1987-06-24,9.4 +1987-06-25,7.0 +1987-06-26,8.9 +1987-06-27,9.3 +1987-06-28,6.8 +1987-06-29,7.5 +1987-06-30,8.0 +1987-07-01,8.3 +1987-07-02,2.7 +1987-07-03,3.9 +1987-07-04,4.1 +1987-07-05,5.0 +1987-07-06,5.8 +1987-07-07,4.4 +1987-07-08,4.1 +1987-07-09,5.8 +1987-07-10,9.1 +1987-07-11,7.9 +1987-07-12,5.0 +1987-07-13,2.8 +1987-07-14,4.7 +1987-07-15,8.9 +1987-07-16,5.4 +1987-07-17,7.1 +1987-07-18,9.0 +1987-07-19,9.4 +1987-07-20,6.3 +1987-07-21,7.0 +1987-07-22,6.4 +1987-07-23,6.7 +1987-07-24,1.5 +1987-07-25,2.9 +1987-07-26,4.8 +1987-07-27,6.3 +1987-07-28,5.7 +1987-07-29,7.0 +1987-07-30,8.8 +1987-07-31,8.7 +1987-08-01,9.0 +1987-08-02,9.6 +1987-08-03,8.0 +1987-08-04,8.4 +1987-08-05,8.1 +1987-08-06,9.0 +1987-08-07,5.3 +1987-08-08,8.9 +1987-08-09,8.7 +1987-08-10,4.9 +1987-08-11,7.0 +1987-08-12,7.5 +1987-08-13,7.0 +1987-08-14,9.1 +1987-08-15,11.8 +1987-08-16,9.9 +1987-08-17,5.6 +1987-08-18,4.2 +1987-08-19,4.3 +1987-08-20,8.0 +1987-08-21,5.1 +1987-08-22,9.4 +1987-08-23,9.1 +1987-08-24,9.7 +1987-08-25,10.6 +1987-08-26,8.6 +1987-08-27,10.1 +1987-08-28,11.0 +1987-08-29,9.7 +1987-08-30,5.0 +1987-08-31,6.1 +1987-09-01,5.4 +1987-09-02,5.8 +1987-09-03,7.3 +1987-09-04,6.3 +1987-09-05,4.8 +1987-09-06,7.6 +1987-09-07,8.1 +1987-09-08,9.5 +1987-09-09,10.3 +1987-09-10,7.0 +1987-09-11,9.0 +1987-09-12,10.2 +1987-09-13,6.8 +1987-09-14,9.3 +1987-09-15,9.8 +1987-09-16,10.7 +1987-09-17,7.8 +1987-09-18,9.2 +1987-09-19,15.0 +1987-09-20,7.8 +1987-09-21,5.3 +1987-09-22,9.5 +1987-09-23,7.6 +1987-09-24,14.0 +1987-09-25,14.9 +1987-09-26,14.9 +1987-09-27,19.2 +1987-09-28,17.0 +1987-09-29,13.0 +1987-09-30,11.2 +1987-10-01,9.5 +1987-10-02,10.3 +1987-10-03,9.3 +1987-10-04,11.3 +1987-10-05,6.5 +1987-10-06,12.0 +1987-10-07,8.3 +1987-10-08,8.7 +1987-10-09,8.7 +1987-10-10,10.2 +1987-10-11,6.9 +1987-10-12,4.9 +1987-10-13,10.0 +1987-10-14,7.6 +1987-10-15,14.5 +1987-10-16,13.2 +1987-10-17,9.9 +1987-10-18,10.1 +1987-10-19,11.3 +1987-10-20,10.4 +1987-10-21,10.9 +1987-10-22,9.2 +1987-10-23,10.5 +1987-10-24,11.4 +1987-10-25,13.5 +1987-10-26,9.8 +1987-10-27,13.1 +1987-10-28,9.7 +1987-10-29,11.4 +1987-10-30,9.9 +1987-10-31,14.4 +1987-11-01,19.0 +1987-11-02,23.0 +1987-11-03,15.4 +1987-11-04,9.6 +1987-11-05,10.8 +1987-11-06,12.1 +1987-11-07,11.0 +1987-11-08,12.6 +1987-11-09,14.7 +1987-11-10,11.1 +1987-11-11,10.1 +1987-11-12,11.4 +1987-11-13,13.0 +1987-11-14,11.9 +1987-11-15,9.5 +1987-11-16,13.5 +1987-11-17,15.2 +1987-11-18,18.4 +1987-11-19,24.1 +1987-11-20,14.1 +1987-11-21,10.7 +1987-11-22,8.7 +1987-11-23,13.3 +1987-11-24,11.6 +1987-11-25,9.9 +1987-11-26,10.8 +1987-11-27,11.5 +1987-11-28,10.0 +1987-11-29,13.9 +1987-11-30,13.6 +1987-12-01,11.9 +1987-12-02,11.1 +1987-12-03,8.2 +1987-12-04,9.4 +1987-12-05,12.7 +1987-12-06,11.6 +1987-12-07,11.0 +1987-12-08,11.3 +1987-12-09,13.4 +1987-12-10,14.9 +1987-12-11,15.2 +1987-12-12,13.9 +1987-12-13,15.0 +1987-12-14,16.2 +1987-12-15,17.7 +1987-12-16,20.5 +1987-12-17,14.7 +1987-12-18,12.5 +1987-12-19,10.9 +1987-12-20,12.8 +1987-12-21,12.7 +1987-12-22,11.2 +1987-12-23,11.4 +1987-12-24,11.2 +1987-12-25,12.1 +1987-12-26,12.7 +1987-12-27,16.2 +1987-12-28,14.2 +1987-12-29,14.3 +1987-12-30,13.3 +1987-12-31,16.7 +1988-01-01,15.3 +1988-01-02,14.3 +1988-01-03,13.5 +1988-01-04,15.0 +1988-01-05,13.6 +1988-01-06,15.2 +1988-01-07,17.0 +1988-01-08,18.7 +1988-01-09,16.5 +1988-01-10,17.4 +1988-01-11,18.3 +1988-01-12,18.3 +1988-01-13,22.4 +1988-01-14,21.4 +1988-01-15,20.9 +1988-01-16,17.6 +1988-01-17,15.5 +1988-01-18,16.6 +1988-01-19,16.2 +1988-01-20,15.6 +1988-01-21,14.5 +1988-01-22,14.0 +1988-01-23,15.6 +1988-01-24,12.3 +1988-01-25,11.6 +1988-01-26,12.6 +1988-01-27,14.9 +1988-01-28,17.3 +1988-01-29,21.4 +1988-01-30,23.4 +1988-01-31,14.4 +1988-02-01,14.1 +1988-02-02,15.0 +1988-02-03,14.5 +1988-02-04,15.1 +1988-02-05,13.9 +1988-02-06,13.4 +1988-02-07,9.2 +1988-02-08,12.5 +1988-02-09,15.1 +1988-02-10,12.1 +1988-02-11,14.5 +1988-02-12,16.3 +1988-02-13,16.5 +1988-02-14,14.9 +1988-02-15,13.2 +1988-02-16,11.8 +1988-02-17,13.6 +1988-02-18,16.2 +1988-02-19,14.1 +1988-02-20,13.5 +1988-02-21,15.0 +1988-02-22,14.8 +1988-02-23,16.2 +1988-02-24,16.2 +1988-02-25,13.3 +1988-02-26,15.3 +1988-02-27,18.4 +1988-02-28,16.2 +1988-02-29,16.3 +1988-03-01,12.4 +1988-03-02,15.6 +1988-03-03,14.9 +1988-03-04,14.8 +1988-03-05,12.7 +1988-03-06,14.2 +1988-03-07,16.8 +1988-03-08,16.7 +1988-03-09,16.2 +1988-03-10,14.5 +1988-03-11,10.0 +1988-03-12,12.6 +1988-03-13,11.9 +1988-03-14,11.8 +1988-03-15,13.4 +1988-03-16,14.5 +1988-03-17,15.7 +1988-03-18,15.3 +1988-03-19,13.9 +1988-03-20,13.7 +1988-03-21,15.1 +1988-03-22,15.6 +1988-03-23,14.4 +1988-03-24,13.9 +1988-03-25,16.2 +1988-03-26,16.7 +1988-03-27,15.5 +1988-03-28,16.4 +1988-03-29,17.5 +1988-03-30,18.2 +1988-03-31,16.1 +1988-04-01,16.5 +1988-04-02,14.6 +1988-04-03,16.4 +1988-04-04,13.6 +1988-04-05,15.9 +1988-04-06,11.9 +1988-04-07,14.7 +1988-04-08,9.4 +1988-04-09,6.6 +1988-04-10,7.9 +1988-04-11,11.0 +1988-04-12,15.7 +1988-04-13,15.2 +1988-04-14,15.9 +1988-04-15,10.6 +1988-04-16,8.3 +1988-04-17,8.6 +1988-04-18,12.7 +1988-04-19,10.5 +1988-04-20,12.0 +1988-04-21,11.1 +1988-04-22,13.0 +1988-04-23,12.4 +1988-04-24,13.3 +1988-04-25,15.9 +1988-04-26,12.0 +1988-04-27,13.7 +1988-04-28,17.6 +1988-04-29,14.3 +1988-04-30,13.7 +1988-05-01,15.2 +1988-05-02,14.5 +1988-05-03,14.9 +1988-05-04,15.5 +1988-05-05,16.4 +1988-05-06,14.5 +1988-05-07,12.6 +1988-05-08,13.6 +1988-05-09,11.2 +1988-05-10,11.0 +1988-05-11,12.0 +1988-05-12,6.8 +1988-05-13,10.6 +1988-05-14,13.1 +1988-05-15,13.5 +1988-05-16,11.7 +1988-05-17,13.2 +1988-05-18,12.0 +1988-05-19,10.4 +1988-05-20,10.0 +1988-05-21,8.2 +1988-05-22,9.4 +1988-05-23,10.3 +1988-05-24,8.1 +1988-05-25,8.7 +1988-05-26,12.6 +1988-05-27,10.9 +1988-05-28,8.7 +1988-05-29,9.3 +1988-05-30,6.3 +1988-05-31,7.8 +1988-06-01,10.0 +1988-06-02,11.0 +1988-06-03,11.1 +1988-06-04,12.6 +1988-06-05,10.2 +1988-06-06,11.1 +1988-06-07,8.7 +1988-06-08,9.5 +1988-06-09,9.7 +1988-06-10,8.2 +1988-06-11,5.0 +1988-06-12,6.5 +1988-06-13,12.1 +1988-06-14,8.9 +1988-06-15,6.1 +1988-06-16,2.8 +1988-06-17,3.7 +1988-06-18,6.8 +1988-06-19,6.6 +1988-06-20,7.0 +1988-06-21,7.3 +1988-06-22,7.9 +1988-06-23,10.6 +1988-06-24,8.1 +1988-06-25,6.7 +1988-06-26,8.0 +1988-06-27,10.0 +1988-06-28,6.7 +1988-06-29,9.4 +1988-06-30,9.3 +1988-07-01,6.0 +1988-07-02,5.8 +1988-07-03,4.9 +1988-07-04,5.0 +1988-07-05,8.4 +1988-07-06,12.3 +1988-07-07,13.0 +1988-07-08,11.4 +1988-07-09,6.8 +1988-07-10,7.6 +1988-07-11,12.4 +1988-07-12,7.1 +1988-07-13,7.5 +1988-07-14,10.0 +1988-07-15,5.3 +1988-07-16,6.3 +1988-07-17,8.0 +1988-07-18,8.3 +1988-07-19,9.3 +1988-07-20,9.5 +1988-07-21,5.6 +1988-07-22,7.0 +1988-07-23,8.5 +1988-07-24,8.5 +1988-07-25,8.2 +1988-07-26,8.5 +1988-07-27,9.6 +1988-07-28,9.7 +1988-07-29,7.1 +1988-07-30,8.4 +1988-07-31,9.2 +1988-08-01,9.8 +1988-08-02,8.1 +1988-08-03,9.4 +1988-08-04,10.0 +1988-08-05,5.1 +1988-08-06,6.7 +1988-08-07,6.9 +1988-08-08,6.8 +1988-08-09,8.6 +1988-08-10,9.1 +1988-08-11,3.9 +1988-08-12,4.8 +1988-08-13,8.4 +1988-08-14,11.6 +1988-08-15,12.1 +1988-08-16,12.4 +1988-08-17,10.0 +1988-08-18,10.1 +1988-08-19,9.7 +1988-08-20,11.7 +1988-08-21,7.9 +1988-08-22,8.6 +1988-08-23,7.7 +1988-08-24,5.8 +1988-08-25,8.7 +1988-08-26,10.6 +1988-08-27,6.7 +1988-08-28,8.8 +1988-08-29,9.7 +1988-08-30,9.0 +1988-08-31,11.8 +1988-09-01,15.2 +1988-09-02,10.0 +1988-09-03,10.5 +1988-09-04,5.5 +1988-09-05,9.4 +1988-09-06,8.8 +1988-09-07,5.3 +1988-09-08,13.0 +1988-09-09,15.2 +1988-09-10,13.2 +1988-09-11,11.5 +1988-09-12,6.8 +1988-09-13,4.7 +1988-09-14,5.2 +1988-09-15,6.8 +1988-09-16,10.7 +1988-09-17,10.1 +1988-09-18,10.0 +1988-09-19,9.8 +1988-09-20,5.5 +1988-09-21,13.5 +1988-09-22,16.6 +1988-09-23,8.4 +1988-09-24,8.2 +1988-09-25,11.1 +1988-09-26,10.8 +1988-09-27,8.8 +1988-09-28,10.8 +1988-09-29,8.7 +1988-09-30,12.4 +1988-10-01,9.0 +1988-10-02,13.5 +1988-10-03,14.7 +1988-10-04,10.9 +1988-10-05,8.5 +1988-10-06,6.0 +1988-10-07,12.7 +1988-10-08,11.1 +1988-10-09,8.7 +1988-10-10,12.3 +1988-10-11,13.3 +1988-10-12,5.6 +1988-10-13,13.7 +1988-10-14,8.5 +1988-10-15,11.2 +1988-10-16,8.7 +1988-10-17,11.7 +1988-10-18,12.5 +1988-10-19,8.2 +1988-10-20,15.6 +1988-10-21,10.3 +1988-10-22,11.4 +1988-10-23,9.7 +1988-10-24,6.3 +1988-10-25,14.3 +1988-10-26,11.3 +1988-10-27,7.3 +1988-10-28,12.8 +1988-10-29,11.9 +1988-10-30,14.3 +1988-10-31,11.6 +1988-11-01,13.2 +1988-11-02,15.5 +1988-11-03,14.1 +1988-11-04,9.5 +1988-11-05,7.2 +1988-11-06,11.8 +1988-11-07,16.8 +1988-11-08,12.5 +1988-11-09,9.4 +1988-11-10,11.9 +1988-11-11,10.3 +1988-11-12,16.9 +1988-11-13,17.5 +1988-11-14,7.5 +1988-11-15,8.6 +1988-11-16,11.1 +1988-11-17,11.5 +1988-11-18,10.7 +1988-11-19,15.7 +1988-11-20,12.8 +1988-11-21,13.0 +1988-11-22,12.9 +1988-11-23,14.3 +1988-11-24,13.7 +1988-11-25,12.1 +1988-11-26,11.9 +1988-11-27,11.8 +1988-11-28,11.4 +1988-11-29,10.3 +1988-11-30,11.7 +1988-12-01,12.0 +1988-12-02,17.4 +1988-12-03,16.8 +1988-12-04,16.2 +1988-12-05,13.0 +1988-12-06,12.5 +1988-12-07,12.4 +1988-12-08,16.1 +1988-12-09,20.2 +1988-12-10,14.3 +1988-12-11,11.0 +1988-12-12,14.4 +1988-12-13,15.7 +1988-12-14,19.7 +1988-12-15,20.7 +1988-12-16,23.9 +1988-12-17,16.6 +1988-12-18,17.5 +1988-12-19,14.9 +1988-12-20,13.6 +1988-12-21,11.9 +1988-12-22,15.2 +1988-12-23,17.3 +1988-12-24,19.8 +1988-12-25,15.8 +1988-12-26,9.5 +1988-12-27,12.9 +1988-12-28,12.9 +1988-12-29,14.8 +1988-12-30,14.1 +1989-01-01,14.3 +1989-01-02,17.4 +1989-01-03,18.5 +1989-01-04,16.8 +1989-01-05,11.5 +1989-01-06,9.5 +1989-01-07,12.2 +1989-01-08,15.7 +1989-01-09,16.3 +1989-01-10,13.6 +1989-01-11,12.6 +1989-01-12,13.8 +1989-01-13,12.1 +1989-01-14,13.4 +1989-01-15,17.3 +1989-01-16,19.4 +1989-01-17,16.6 +1989-01-18,13.9 +1989-01-19,13.1 +1989-01-20,16.0 +1989-01-21,14.5 +1989-01-22,15.0 +1989-01-23,12.6 +1989-01-24,12.5 +1989-01-25,15.2 +1989-01-26,16.2 +1989-01-27,16.5 +1989-01-28,20.1 +1989-01-29,20.6 +1989-01-30,16.9 +1989-01-31,16.5 +1989-02-01,16.1 +1989-02-02,14.4 +1989-02-03,16.3 +1989-02-04,15.7 +1989-02-05,14.2 +1989-02-06,13.2 +1989-02-07,16.8 +1989-02-08,18.5 +1989-02-09,16.7 +1989-02-10,15.3 +1989-02-11,15.9 +1989-02-12,15.2 +1989-02-13,17.5 +1989-02-14,18.3 +1989-02-15,19.4 +1989-02-16,19.4 +1989-02-17,19.5 +1989-02-18,20.5 +1989-02-19,15.7 +1989-02-20,15.0 +1989-02-21,16.1 +1989-02-22,14.3 +1989-02-23,13.0 +1989-02-24,16.2 +1989-02-25,17.7 +1989-02-26,13.2 +1989-02-27,15.8 +1989-02-28,18.5 +1989-03-01,20.4 +1989-03-02,22.0 +1989-03-03,19.7 +1989-03-04,19.6 +1989-03-05,20.3 +1989-03-06,18.3 +1989-03-07,18.9 +1989-03-08,20.3 +1989-03-09,21.4 +1989-03-10,18.3 +1989-03-11,17.8 +1989-03-12,17.7 +1989-03-13,12.8 +1989-03-14,15.1 +1989-03-15,15.0 +1989-03-16,14.8 +1989-03-17,12.0 +1989-03-18,12.5 +1989-03-19,15.0 +1989-03-20,17.1 +1989-03-21,17.3 +1989-03-22,16.9 +1989-03-23,16.5 +1989-03-24,13.6 +1989-03-25,13.2 +1989-03-26,9.4 +1989-03-27,9.5 +1989-03-28,11.8 +1989-03-29,10.4 +1989-03-30,9.7 +1989-03-31,12.6 +1989-04-01,13.3 +1989-04-02,15.1 +1989-04-03,14.2 +1989-04-04,14.2 +1989-04-05,19.2 +1989-04-06,12.6 +1989-04-07,14.2 +1989-04-08,11.9 +1989-04-09,13.9 +1989-04-10,13.5 +1989-04-11,15.3 +1989-04-12,13.9 +1989-04-13,14.0 +1989-04-14,12.9 +1989-04-15,8.5 +1989-04-16,11.4 +1989-04-17,10.9 +1989-04-18,12.0 +1989-04-19,8.6 +1989-04-20,9.0 +1989-04-21,9.6 +1989-04-22,10.2 +1989-04-23,9.8 +1989-04-24,8.3 +1989-04-25,11.0 +1989-04-26,11.9 +1989-04-27,14.0 +1989-04-28,15.8 +1989-04-29,14.5 +1989-04-30,13.2 +1989-05-01,14.2 +1989-05-02,14.6 +1989-05-03,11.8 +1989-05-04,14.4 +1989-05-05,10.4 +1989-05-06,10.3 +1989-05-07,10.8 +1989-05-08,10.5 +1989-05-09,9.5 +1989-05-10,12.5 +1989-05-11,13.7 +1989-05-12,12.7 +1989-05-13,11.9 +1989-05-14,11.4 +1989-05-15,9.7 +1989-05-16,8.3 +1989-05-17,8.1 +1989-05-18,11.7 +1989-05-19,11.6 +1989-05-20,7.4 +1989-05-21,5.2 +1989-05-22,11.0 +1989-05-23,9.5 +1989-05-24,9.2 +1989-05-25,10.7 +1989-05-26,9.0 +1989-05-27,10.2 +1989-05-28,10.3 +1989-05-29,12.1 +1989-05-30,13.2 +1989-05-31,6.6 +1989-06-01,2.3 +1989-06-02,1.4 +1989-06-03,2.1 +1989-06-04,6.6 +1989-06-05,8.9 +1989-06-06,7.8 +1989-06-07,9.0 +1989-06-08,10.3 +1989-06-09,7.9 +1989-06-10,7.2 +1989-06-11,8.6 +1989-06-12,8.8 +1989-06-13,6.2 +1989-06-14,9.5 +1989-06-15,10.2 +1989-06-16,9.7 +1989-06-17,11.2 +1989-06-18,10.2 +1989-06-19,10.1 +1989-06-20,8.1 +1989-06-21,6.6 +1989-06-22,5.0 +1989-06-23,4.7 +1989-06-24,5.3 +1989-06-25,4.5 +1989-06-26,2.3 +1989-06-27,1.4 +1989-06-28,0.5 +1989-06-29,2.4 +1989-06-30,8.0 +1989-07-01,6.0 +1989-07-02,7.1 +1989-07-03,9.7 +1989-07-04,6.9 +1989-07-05,5.3 +1989-07-06,7.0 +1989-07-07,6.2 +1989-07-08,7.0 +1989-07-09,9.7 +1989-07-10,8.0 +1989-07-11,8.5 +1989-07-12,7.1 +1989-07-13,7.5 +1989-07-14,3.3 +1989-07-15,1.8 +1989-07-16,2.6 +1989-07-17,5.3 +1989-07-18,5.8 +1989-07-19,5.8 +1989-07-20,7.2 +1989-07-21,5.3 +1989-07-22,1.6 +1989-07-23,3.1 +1989-07-24,5.3 +1989-07-25,7.7 +1989-07-26,4.2 +1989-07-27,5.5 +1989-07-28,9.0 +1989-07-29,11.2 +1989-07-30,8.0 +1989-07-31,7.6 +1989-08-01,3.7 +1989-08-02,7.5 +1989-08-03,8.1 +1989-08-04,8.4 +1989-08-05,7.1 +1989-08-06,7.6 +1989-08-07,7.6 +1989-08-08,5.6 +1989-08-09,7.0 +1989-08-10,10.5 +1989-08-11,7.3 +1989-08-12,7.8 +1989-08-13,5.8 +1989-08-14,3.8 +1989-08-15,5.8 +1989-08-16,6.7 +1989-08-17,6.6 +1989-08-18,6.6 +1989-08-19,9.0 +1989-08-20,8.1 +1989-08-21,5.1 +1989-08-22,8.6 +1989-08-23,7.0 +1989-08-24,5.5 +1989-08-25,7.4 +1989-08-26,6.2 +1989-08-27,4.2 +1989-08-28,6.3 +1989-08-29,7.0 +1989-08-30,4.0 +1989-08-31,8.0 +1989-09-01,8.8 +1989-09-02,8.8 +1989-09-03,6.1 +1989-09-04,8.6 +1989-09-05,8.9 +1989-09-06,7.8 +1989-09-07,5.0 +1989-09-08,7.0 +1989-09-09,13.3 +1989-09-10,7.9 +1989-09-11,7.5 +1989-09-12,8.3 +1989-09-13,7.2 +1989-09-14,6.5 +1989-09-15,8.9 +1989-09-16,7.4 +1989-09-17,9.9 +1989-09-18,9.3 +1989-09-19,10.6 +1989-09-20,8.6 +1989-09-21,7.2 +1989-09-22,12.6 +1989-09-23,7.8 +1989-09-24,6.3 +1989-09-25,9.2 +1989-09-26,5.8 +1989-09-27,9.0 +1989-09-28,5.0 +1989-09-29,11.9 +1989-09-30,13.4 +1989-10-01,10.5 +1989-10-02,6.2 +1989-10-03,5.1 +1989-10-04,9.5 +1989-10-05,11.7 +1989-10-06,9.2 +1989-10-07,7.3 +1989-10-08,9.7 +1989-10-09,9.4 +1989-10-10,10.0 +1989-10-11,10.9 +1989-10-12,11.0 +1989-10-13,10.9 +1989-10-14,8.0 +1989-10-15,11.2 +1989-10-16,7.5 +1989-10-17,7.2 +1989-10-18,13.2 +1989-10-19,12.9 +1989-10-20,9.4 +1989-10-21,10.2 +1989-10-22,9.5 +1989-10-23,12.4 +1989-10-24,10.2 +1989-10-25,13.4 +1989-10-26,11.6 +1989-10-27,8.0 +1989-10-28,9.0 +1989-10-29,9.3 +1989-10-30,13.5 +1989-10-31,8.0 +1989-11-01,8.1 +1989-11-02,10.0 +1989-11-03,8.5 +1989-11-04,12.5 +1989-11-05,15.0 +1989-11-06,13.3 +1989-11-07,11.0 +1989-11-08,11.9 +1989-11-09,8.3 +1989-11-10,9.7 +1989-11-11,11.3 +1989-11-12,12.5 +1989-11-13,9.4 +1989-11-14,11.4 +1989-11-15,13.2 +1989-11-16,13.8 +1989-11-17,16.0 +1989-11-18,10.9 +1989-11-19,11.9 +1989-11-20,12.4 +1989-11-21,13.2 +1989-11-22,15.5 +1989-11-23,21.6 +1989-11-24,14.9 +1989-11-25,14.4 +1989-11-26,12.9 +1989-11-27,13.1 +1989-11-28,14.0 +1989-11-29,17.9 +1989-11-30,17.7 +1989-12-01,16.3 +1989-12-02,18.3 +1989-12-03,13.7 +1989-12-04,13.3 +1989-12-05,10.6 +1989-12-06,14.1 +1989-12-07,16.0 +1989-12-08,16.5 +1989-12-09,14.1 +1989-12-10,18.7 +1989-12-11,16.2 +1989-12-12,14.8 +1989-12-13,12.6 +1989-12-14,10.4 +1989-12-15,12.2 +1989-12-16,12.6 +1989-12-17,12.1 +1989-12-18,17.3 +1989-12-19,16.4 +1989-12-20,12.6 +1989-12-21,12.3 +1989-12-22,11.8 +1989-12-23,12.0 +1989-12-24,12.7 +1989-12-25,16.4 +1989-12-26,16.0 +1989-12-27,13.3 +1989-12-28,11.7 +1989-12-29,10.4 +1989-12-30,14.4 +1989-12-31,12.7 +1990-01-01,14.8 +1990-01-02,13.3 +1990-01-03,15.6 +1990-01-04,14.5 +1990-01-05,14.3 +1990-01-06,15.3 +1990-01-07,16.4 +1990-01-08,14.8 +1990-01-09,17.4 +1990-01-10,18.8 +1990-01-11,22.1 +1990-01-12,19.0 +1990-01-13,15.5 +1990-01-14,15.8 +1990-01-15,14.7 +1990-01-16,10.7 +1990-01-17,11.5 +1990-01-18,15.0 +1990-01-19,14.5 +1990-01-20,14.5 +1990-01-21,13.3 +1990-01-22,14.3 +1990-01-23,14.3 +1990-01-24,20.5 +1990-01-25,15.0 +1990-01-26,17.1 +1990-01-27,16.9 +1990-01-28,16.9 +1990-01-29,13.6 +1990-01-30,16.4 +1990-01-31,16.1 +1990-02-01,12.0 +1990-02-02,12.2 +1990-02-03,14.8 +1990-02-04,14.8 +1990-02-05,14.4 +1990-02-06,12.9 +1990-02-07,13.4 +1990-02-08,15.9 +1990-02-09,16.1 +1990-02-10,17.6 +1990-02-11,15.6 +1990-02-12,15.0 +1990-02-13,13.0 +1990-02-14,14.1 +1990-02-15,17.3 +1990-02-16,15.7 +1990-02-17,18.6 +1990-02-18,12.7 +1990-02-19,14.0 +1990-02-20,13.7 +1990-02-21,16.3 +1990-02-22,20.0 +1990-02-23,17.0 +1990-02-24,15.2 +1990-02-25,16.5 +1990-02-26,16.5 +1990-02-27,17.3 +1990-02-28,19.1 +1990-03-01,19.3 +1990-03-02,17.3 +1990-03-03,19.0 +1990-03-04,19.8 +1990-03-05,19.3 +1990-03-06,17.2 +1990-03-07,14.2 +1990-03-08,10.3 +1990-03-09,13.0 +1990-03-10,15.3 +1990-03-11,15.0 +1990-03-12,12.1 +1990-03-13,9.2 +1990-03-14,11.0 +1990-03-15,15.0 +1990-03-16,11.6 +1990-03-17,11.6 +1990-03-18,15.1 +1990-03-19,15.0 +1990-03-20,13.6 +1990-03-21,12.5 +1990-03-22,14.3 +1990-03-23,16.0 +1990-03-24,17.4 +1990-03-25,16.9 +1990-03-26,18.0 +1990-03-27,20.6 +1990-03-28,14.2 +1990-03-29,10.9 +1990-03-30,11.9 +1990-03-31,13.3 +1990-04-01,15.3 +1990-04-02,14.7 +1990-04-03,11.0 +1990-04-04,12.2 +1990-04-05,14.2 +1990-04-06,17.0 +1990-04-07,15.8 +1990-04-08,15.2 +1990-04-09,15.1 +1990-04-10,14.7 +1990-04-11,18.5 +1990-04-12,16.4 +1990-04-13,18.4 +1990-04-14,15.1 +1990-04-15,9.9 +1990-04-16,10.2 +1990-04-17,12.6 +1990-04-18,13.2 +1990-04-19,11.5 +1990-04-20,13.8 +1990-04-21,14.5 +1990-04-22,14.7 +1990-04-23,11.2 +1990-04-24,12.7 +1990-04-25,13.7 +1990-04-26,11.5 +1990-04-27,10.4 +1990-04-28,8.9 +1990-04-29,11.1 +1990-04-30,9.5 +1990-05-01,13.0 +1990-05-02,13.9 +1990-05-03,12.6 +1990-05-04,14.3 +1990-05-05,16.0 +1990-05-06,13.3 +1990-05-07,7.0 +1990-05-08,4.9 +1990-05-09,6.9 +1990-05-10,13.7 +1990-05-11,10.6 +1990-05-12,12.3 +1990-05-13,11.1 +1990-05-14,10.2 +1990-05-15,9.5 +1990-05-16,8.9 +1990-05-17,13.4 +1990-05-18,9.1 +1990-05-19,9.4 +1990-05-20,8.7 +1990-05-21,5.8 +1990-05-22,4.5 +1990-05-23,7.2 +1990-05-24,10.0 +1990-05-25,10.5 +1990-05-26,10.7 +1990-05-27,8.2 +1990-05-28,6.1 +1990-05-29,4.5 +1990-05-30,6.1 +1990-05-31,9.8 +1990-06-01,9.7 +1990-06-02,8.2 +1990-06-03,8.4 +1990-06-04,8.5 +1990-06-05,10.4 +1990-06-06,6.8 +1990-06-07,6.0 +1990-06-08,6.6 +1990-06-09,7.8 +1990-06-10,10.3 +1990-06-11,7.2 +1990-06-12,7.4 +1990-06-13,11.4 +1990-06-14,5.4 +1990-06-15,4.4 +1990-06-16,6.4 +1990-06-17,9.3 +1990-06-18,7.7 +1990-06-19,8.1 +1990-06-20,8.3 +1990-06-21,9.1 +1990-06-22,7.7 +1990-06-23,10.6 +1990-06-24,8.2 +1990-06-25,7.9 +1990-06-26,5.2 +1990-06-27,5.9 +1990-06-28,3.7 +1990-06-29,5.6 +1990-06-30,9.4 +1990-07-01,7.4 +1990-07-02,7.3 +1990-07-03,7.7 +1990-07-04,7.7 +1990-07-05,9.3 +1990-07-06,4.4 +1990-07-07,5.7 +1990-07-08,10.2 +1990-07-09,10.2 +1990-07-10,9.3 +1990-07-11,5.4 +1990-07-12,5.0 +1990-07-13,7.6 +1990-07-14,9.6 +1990-07-15,10.4 +1990-07-16,11.2 +1990-07-17,9.1 +1990-07-18,11.2 +1990-07-19,6.8 +1990-07-20,8.3 +1990-07-21,9.7 +1990-07-22,9.6 +1990-07-23,9.8 +1990-07-24,10.8 +1990-07-25,9.2 +1990-07-26,6.5 +1990-07-27,8.1 +1990-07-28,7.3 +1990-07-29,7.9 +1990-07-30,6.0 +1990-07-31,5.0 +1990-08-01,6.8 +1990-08-02,9.8 +1990-08-03,5.7 +1990-08-04,8.6 +1990-08-05,10.6 +1990-08-06,7.8 +1990-08-07,7.7 +1990-08-08,8.6 +1990-08-09,6.5 +1990-08-10,6.9 +1990-08-11,6.4 +1990-08-12,8.5 +1990-08-13,7.8 +1990-08-14,9.3 +1990-08-15,8.4 +1990-08-16,7.8 +1990-08-17,7.4 +1990-08-18,7.7 +1990-08-19,8.9 +1990-08-20,9.7 +1990-08-21,9.9 +1990-08-22,6.1 +1990-08-23,6.6 +1990-08-24,7.6 +1990-08-25,7.4 +1990-08-26,8.0 +1990-08-27,2.1 +1990-08-28,5.9 +1990-08-29,11.6 +1990-08-30,8.6 +1990-08-31,7.9 +1990-09-01,6.0 +1990-09-02,9.5 +1990-09-03,8.6 +1990-09-04,7.6 +1990-09-05,10.4 +1990-09-06,10.3 +1990-09-07,7.5 +1990-09-08,3.0 +1990-09-09,5.3 +1990-09-10,10.5 +1990-09-11,14.6 +1990-09-12,12.6 +1990-09-13,9.8 +1990-09-14,7.2 +1990-09-15,10.1 +1990-09-16,10.4 +1990-09-17,3.7 +1990-09-18,7.3 +1990-09-19,11.6 +1990-09-20,16.3 +1990-09-21,9.6 +1990-09-22,6.8 +1990-09-23,5.2 +1990-09-24,10.6 +1990-09-25,16.3 +1990-09-26,9.8 +1990-09-27,4.6 +1990-09-28,11.1 +1990-09-29,8.7 +1990-09-30,10.0 +1990-10-01,11.3 +1990-10-02,10.5 +1990-10-03,9.9 +1990-10-04,11.0 +1990-10-05,14.0 +1990-10-06,9.2 +1990-10-07,9.8 +1990-10-08,6.0 +1990-10-09,9.8 +1990-10-10,9.2 +1990-10-11,11.8 +1990-10-12,10.3 +1990-10-13,7.5 +1990-10-14,7.7 +1990-10-15,15.8 +1990-10-16,14.6 +1990-10-17,10.5 +1990-10-18,11.3 +1990-10-19,10.9 +1990-10-20,6.4 +1990-10-21,10.9 +1990-10-22,9.0 +1990-10-23,10.9 +1990-10-24,12.4 +1990-10-25,11.6 +1990-10-26,13.3 +1990-10-27,14.4 +1990-10-28,18.4 +1990-10-29,13.6 +1990-10-30,14.9 +1990-10-31,14.8 +1990-11-01,15.4 +1990-11-02,11.8 +1990-11-03,13.0 +1990-11-04,11.1 +1990-11-05,12.5 +1990-11-06,18.3 +1990-11-07,19.2 +1990-11-08,15.4 +1990-11-09,13.1 +1990-11-10,11.5 +1990-11-11,8.6 +1990-11-12,12.6 +1990-11-13,13.8 +1990-11-14,14.6 +1990-11-15,13.2 +1990-11-16,12.3 +1990-11-17,8.8 +1990-11-18,10.7 +1990-11-19,9.9 +1990-11-20,8.3 +1990-11-21,15.0 +1990-11-22,12.2 +1990-11-23,10.5 +1990-11-24,11.1 +1990-11-25,13.0 +1990-11-26,12.9 +1990-11-27,8.8 +1990-11-28,14.7 +1990-11-29,14.7 +1990-11-30,12.7 +1990-12-01,13.3 +1990-12-02,13.2 +1990-12-03,16.2 +1990-12-04,17.3 +1990-12-05,20.5 +1990-12-06,20.2 +1990-12-07,19.4 +1990-12-08,15.5 +1990-12-09,14.1 +1990-12-10,11.0 +1990-12-11,11.1 +1990-12-12,14.0 +1990-12-13,11.4 +1990-12-14,12.5 +1990-12-15,13.4 +1990-12-16,13.6 +1990-12-17,13.9 +1990-12-18,17.2 +1990-12-19,14.7 +1990-12-20,15.4 +1990-12-21,13.1 +1990-12-22,13.2 +1990-12-23,13.9 +1990-12-24,10.0 +1990-12-25,12.9 +1990-12-26,14.6 +1990-12-27,14.0 +1990-12-28,13.6 +1990-12-29,13.5 +1990-12-30,15.7 +1990-12-31,13.0 diff --git a/public/n4l/melbourne-temperatures.n4l/locales/en.json b/public/n4l/melbourne-temperatures.n4l/locales/en.json new file mode 100644 index 0000000..8df9988 --- /dev/null +++ b/public/n4l/melbourne-temperatures.n4l/locales/en.json @@ -0,0 +1,41 @@ +{ + "columns": { + "Date": "Date", + "Temp": "Temperature" + }, + "tasks": { + "time-series": { + "name": "Minimum temperatures in Melbourne", + "summary": "The minimum temperature of each day in Melbourne (Australia), from 1981 to 1990: it rises and falls with the seasons, with a lot of noise from one day to the next.", + "description": { + "text": [ + "The minimum temperature of each day in Melbourne (Australia), in degrees Celsius, from 1981 to 1990: 3,650 days. The data come from the Australian Bureau of Meteorology.", + "It has no trend, but a very clear yearly seasonality: in the southern hemisphere summer is in January and February, and July is the coldest month. It changes a lot from one day to the next (about 2 °C on average), so it has plenty of noise that no model can predict.", + "The two leap years (1984 and 1988) have no 31 December, so every year has 365 rows." + ], + "sections": [ + { + "title": "Variables", + "items": [ + "Date: the day (year-month-day).", + "Temp: the minimum temperature that day, in °C. This is what is forecast." + ] + }, + { + "title": "Pre-trained model", + "items": [ + "A network with one Dense layer of 16 neurons that sees the previous 14 days. On the test part (the last two years, which it did not see while training) it is off by {{test_mae, number(maximumFractionDigits: 2)}} °C on average one step ahead, less than repeating yesterday ({{test_naive_mae, number(maximumFractionDigits: 2)}} °C). Forecasting both years at once it is off by {{test_recursive_mae, number(maximumFractionDigits: 2)}} °C: with two weeks it cannot see the year, and repeating the previous year does better ({{test_seasonal_mae, number(maximumFractionDigits: 2)}} °C)." + ] + }, + { + "title": "References", + "items": [ + "The CSV, from the jbrownlee/Datasets repository.", + "Climate data from the Australian Bureau of Meteorology." + ] + } + ] + } + } + } +} diff --git a/public/n4l/melbourne-temperatures.n4l/locales/es.json b/public/n4l/melbourne-temperatures.n4l/locales/es.json new file mode 100644 index 0000000..e3a16c9 --- /dev/null +++ b/public/n4l/melbourne-temperatures.n4l/locales/es.json @@ -0,0 +1,41 @@ +{ + "columns": { + "Date": "Fecha", + "Temp": "Temperatura" + }, + "tasks": { + "time-series": { + "name": "Temperaturas mínimas en Melbourne", + "summary": "La temperatura mínima de cada día en Melbourne (Australia), de 1981 a 1990: sube y baja con las estaciones, con mucho ruido de un día a otro.", + "description": { + "text": [ + "La temperatura mínima de cada día en Melbourne (Australia), en grados Celsius, de 1981 a 1990: 3.650 días. Los datos son de la Oficina de Meteorología de Australia (Bureau of Meteorology).", + "No tiene tendencia, pero sí una estacionalidad anual muy clara: en el hemisferio sur el verano es en enero y febrero, y julio es el mes más frío. De un día a otro cambia mucho (unos 2 °C de media), así que tiene bastante ruido que ningún modelo puede predecir.", + "Los dos años bisiestos (1984 y 1988) no tienen el 31 de diciembre: así todos los años tienen 365 filas." + ], + "sections": [ + { + "title": "Variables", + "items": [ + "Date: el día (año-mes-día).", + "Temp: la temperatura mínima de ese día, en °C. Es lo que se predice." + ] + }, + { + "title": "Modelo ya entrenado", + "items": [ + "Una red con una capa Dense de 16 neuronas que ve los 14 días anteriores. Con la prueba (los dos últimos años, que no vio al entrenar) se equivoca {{test_mae, number(maximumFractionDigits: 2)}} °C de media a un paso, menos que repetir la de ayer ({{test_naive_mae, number(maximumFractionDigits: 2)}} °C). Prediciendo los dos años seguidos se equivoca {{test_recursive_mae, number(maximumFractionDigits: 2)}} °C: con dos semanas no ve el año, y repetir el del año anterior lo hace mejor ({{test_seasonal_mae, number(maximumFractionDigits: 2)}} °C)." + ] + }, + { + "title": "Referencias", + "items": [ + "El CSV, del repositorio jbrownlee/Datasets.", + "Datos climáticos de la Oficina de Meteorología de Australia." + ] + } + ] + } + } + } +} diff --git a/public/n4l/melbourne-temperatures.n4l/locales/ja.json b/public/n4l/melbourne-temperatures.n4l/locales/ja.json new file mode 100644 index 0000000..453f467 --- /dev/null +++ b/public/n4l/melbourne-temperatures.n4l/locales/ja.json @@ -0,0 +1,41 @@ +{ + "columns": { + "Date": "日付", + "Temp": "気温" + }, + "tasks": { + "time-series": { + "name": "メルボルンの最低気温", + "summary": "1981 年から 1990 年までのメルボルン(オーストラリア)の毎日の最低気温です。季節とともに上下し、日ごとの変動(ノイズ)が大きい系列です。", + "description": { + "text": [ + "1981 年から 1990 年までのメルボルン(オーストラリア)の毎日の最低気温(摂氏、3,650 日)です。データはオーストラリア気象局(Bureau of Meteorology)のものです。", + "トレンドはありませんが、1 年周期のはっきりした季節性があります。南半球なので夏は 1 月と 2 月で、いちばん寒いのは 7 月です。日ごとの変化が大きい(平均で約 2 °C)ため、どのモデルにも予測できないノイズがかなり含まれます。", + "うるう年の 2 年(1984 年と 1988 年)には 12 月 31 日がないため、どの年も 365 行です。" + ], + "sections": [ + { + "title": "変数", + "items": [ + "Date:日付(年-月-日)。", + "Temp:その日の最低気温(°C)。予測する値です。" + ] + }, + { + "title": "学習済みモデル", + "items": [ + "16 ニューロンの Dense 層 1 つで、直前の 14 日を見るネットワークです。学習で見ていないテスト部分(最後の 2 年)での誤差は、1 ステップ先で平均 {{test_mae, number(maximumFractionDigits: 2)}} °C で、前日の値を繰り返す場合({{test_naive_mae, number(maximumFractionDigits: 2)}} °C)より小さくなります。2 年分を続けて予測すると {{test_recursive_mae, number(maximumFractionDigits: 2)}} °C です。2 週間では 1 年の周期が見えず、前年の値を繰り返すほうが良い結果になります({{test_seasonal_mae, number(maximumFractionDigits: 2)}} °C)。" + ] + }, + { + "title": "参考文献", + "items": [ + "CSV ファイル(jbrownlee/Datasets リポジトリ)。", + "オーストラリア気象局の気候データ。" + ] + } + ] + } + } + } +} diff --git a/public/n4l/melbourne-temperatures.n4l/manifest.json b/public/n4l/melbourne-temperatures.n4l/manifest.json new file mode 100644 index 0000000..cee1a37 --- /dev/null +++ b/public/n4l/melbourne-temperatures.n4l/manifest.json @@ -0,0 +1,94 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "melbourne-temperatures", + "version": "1.1.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://github.com/jbrownlee/Datasets/blob/master/daily-min-temperatures.csv", + "links": { + "link2": "http://www.bom.gov.au/climate/data/" + } + }, + "datasets": [ + { + "id": "melbourne-temperatures", + "file": "data/daily-min-temperatures.csv", + "rows": 3650, + "frequency": "day", + "columns": [ + { + "name": "Date", + "role": "ID", + "type": "Date", + "missing": 0, + "description": "day (YYYY-MM-DD)" + }, + { + "name": "Temp", + "role": "Target", + "type": "Continuous", + "missing": 0, + "units": "°C", + "description": "daily minimum temperature in Melbourne, Australia" + } + ] + } + ], + "tasks": [ + { + "task": "time-series", + "key": "MELBOURNE-TEMPERATURES", + "runtime": "time-series", + "datasets": [ + "melbourne-temperatures" + ], + "order": 2, + "preprocessing": [], + "models": [ + { + "id": "forecast", + "format": "tfjs-layers", + "path": "models/forecast/model.json", + "dataset": "melbourne-temperatures", + "input": "scaled", + "metrics": { + "test_mae": 1.7514, + "test_rmse": 2.2207, + "test_recursive_mae": 3.7806, + "test_naive_mae": 1.9527, + "test_seasonal_mae": 2.9655 + } + } + ], + "training": { + "layers": [ + { + "class": "dense", + "units": 16, + "activation": "relu" + }, + { + "class": "dense", + "units": 1, + "activation": "linear", + "locked": true + } + ], + "learningRate": 0.001, + "epochs": 20 + }, + "forecast": { + "window": 14, + "season": 365, + "difference": false, + "testSize": 20 + } + } + ] +} diff --git a/public/n4l/melbourne-temperatures.n4l/models/forecast/model.json b/public/n4l/melbourne-temperatures.n4l/models/forecast/model.json new file mode 100644 index 0000000..b421820 --- /dev/null +++ b/public/n4l/melbourne-temperatures.n4l/models/forecast/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_4","layers":[{"class_name":"Dense","config":{"units":16,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense7","trainable":true,"batch_input_shape":[null,14],"dtype":"float32"}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense8","trainable":true}}]},"keras_version":"tfjs-layers 4.22.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.22.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense7/kernel","shape":[14,16],"dtype":"float32"},{"name":"dense_Dense7/bias","shape":[16],"dtype":"float32"},{"name":"dense_Dense8/kernel","shape":[16,1],"dtype":"float32"},{"name":"dense_Dense8/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/n4l/melbourne-temperatures.n4l/models/forecast/model.weights.bin b/public/n4l/melbourne-temperatures.n4l/models/forecast/model.weights.bin new file mode 100644 index 0000000..fc9bd33 Binary files /dev/null and b/public/n4l/melbourne-temperatures.n4l/models/forecast/model.weights.bin differ diff --git a/public/datasets/03-image-classification/mnist/mnist_images.png b/public/n4l/mnist.n4l/data/mnist_images.png similarity index 100% rename from public/datasets/03-image-classification/mnist/mnist_images.png rename to public/n4l/mnist.n4l/data/mnist_images.png diff --git a/public/datasets/03-image-classification/mnist/mnist_labels_uint8 b/public/n4l/mnist.n4l/data/mnist_labels_uint8 similarity index 100% rename from public/datasets/03-image-classification/mnist/mnist_labels_uint8 rename to public/n4l/mnist.n4l/data/mnist_labels_uint8 diff --git a/public/n4l/mnist.n4l/examples/0.png b/public/n4l/mnist.n4l/examples/0.png new file mode 100644 index 0000000..c41ba63 Binary files /dev/null and b/public/n4l/mnist.n4l/examples/0.png differ diff --git a/public/n4l/mnist.n4l/examples/1.png b/public/n4l/mnist.n4l/examples/1.png new file mode 100644 index 0000000..183a2f1 Binary files /dev/null and b/public/n4l/mnist.n4l/examples/1.png differ diff --git a/public/n4l/mnist.n4l/examples/2.png b/public/n4l/mnist.n4l/examples/2.png new file mode 100644 index 0000000..c956d6b Binary files /dev/null and b/public/n4l/mnist.n4l/examples/2.png differ diff --git a/public/n4l/mnist.n4l/examples/3.png b/public/n4l/mnist.n4l/examples/3.png new file mode 100644 index 0000000..404faec Binary files /dev/null and b/public/n4l/mnist.n4l/examples/3.png differ diff --git a/public/n4l/mnist.n4l/examples/4.png b/public/n4l/mnist.n4l/examples/4.png new file mode 100644 index 0000000..0fddbcf Binary files /dev/null and b/public/n4l/mnist.n4l/examples/4.png differ diff --git a/public/n4l/mnist.n4l/examples/5.png b/public/n4l/mnist.n4l/examples/5.png new file mode 100644 index 0000000..8750a59 Binary files /dev/null and b/public/n4l/mnist.n4l/examples/5.png differ diff --git a/public/n4l/mnist.n4l/examples/6.png b/public/n4l/mnist.n4l/examples/6.png new file mode 100644 index 0000000..4f820de Binary files /dev/null and b/public/n4l/mnist.n4l/examples/6.png differ diff --git a/public/n4l/mnist.n4l/examples/7.png b/public/n4l/mnist.n4l/examples/7.png new file mode 100644 index 0000000..a5157ab Binary files /dev/null and b/public/n4l/mnist.n4l/examples/7.png differ diff --git a/public/n4l/mnist.n4l/examples/8.png b/public/n4l/mnist.n4l/examples/8.png new file mode 100644 index 0000000..965b534 Binary files /dev/null and b/public/n4l/mnist.n4l/examples/8.png differ diff --git a/public/n4l/mnist.n4l/examples/9.png b/public/n4l/mnist.n4l/examples/9.png new file mode 100644 index 0000000..0b34df7 Binary files /dev/null and b/public/n4l/mnist.n4l/examples/9.png differ diff --git a/public/n4l/mnist.n4l/locales/en.json b/public/n4l/mnist.n4l/locales/en.json new file mode 100644 index 0000000..38beb51 --- /dev/null +++ b/public/n4l/mnist.n4l/locales/en.json @@ -0,0 +1,37 @@ +{ + "tasks": { + "image-classification": { + "title": "MNIST - Number classification", + "name": "MNIST - Number Classification", + "summary": "Handwritten digits from 0 to 9: the “hello world” of convolutional networks.", + "description": { + "text": [ + "The MNIST database is a large database of handwritten digits. The database is widely used for training and tests in the field of machine learning.", + "The samples of the original NIST data sets were created \"re-mixing\".", + "The NIST training dataset was taken from the United States Census Office. In addition, NIST's black and white images were normalized to fit into a 28 x 28 pixels and softened, which introduced gray scale levels." + ], + "sections": [ + { + "title": "Input data", + "items": [ + "Gray scale image and with a 28 x 28 pixels size" + ] + }, + { + "title": "Output data", + "items": [ + "A number between 0 and 9" + ] + }, + { + "title": "Models", + "items": [ + "Pre-trained model: the convolutional network of the Keras example (two convolutional and two dense layers), trained with the 60,000 MNIST training images. It gets {{test_accuracy, number(style: percent; minimumFractionDigits: 1)}} of the {{test_images, number}} test images right, which it did not see during training.", + "Training in the browser: each training run takes 11,000 random images out of the 55,000 training images and 2,000 out of the 10,000 test images." + ] + } + ] + } + } + } +} diff --git a/public/n4l/mnist.n4l/locales/es.json b/public/n4l/mnist.n4l/locales/es.json new file mode 100644 index 0000000..957fd3d --- /dev/null +++ b/public/n4l/mnist.n4l/locales/es.json @@ -0,0 +1,37 @@ +{ + "tasks": { + "image-classification": { + "title": "MNIST - Clasificación de números", + "name": "MNIST - Clasificación de números", + "summary": "Dígitos del 0 al 9 escritos a mano: el «hola mundo» de las redes convolucionales.", + "description": { + "text": [ + "La base de datos MNIST es una gran base de datos de dígitos escritos a mano. La base de datos se usa ampliamente para capacitación y pruebas en el campo del aprendizaje automático.", + "Fue creado \"re-mezclando\" las muestras de los conjuntos de datos originales del NIST.", + "El conjunto de datos de capacitación del NIST se tomó de la Oficina del Censo de los Estados Unidos. Además, las imágenes en blanco y negro del NIST se normalizaron para encajar en un cuadro delimitador de 28 x 28 píxeles y se suavizaron, lo que introdujo niveles de escala de grises." + ], + "sections": [ + { + "title": "Datos de entrada", + "items": [ + "Imagen en escala de grises y con un tamaño de 28 x 28 píxeles" + ] + }, + { + "title": "Datos de salida", + "items": [ + "Un número entre 0 y 9" + ] + }, + { + "title": "Modelos", + "items": [ + "Modelo ya entrenado: la red convolucional del ejemplo de Keras (dos capas convolucionales y dos densas), entrenada con las 60.000 imágenes de entrenamiento de MNIST. Acierta el {{test_accuracy, number(style: percent; minimumFractionDigits: 1)}} de las {{test_images, number}} imágenes de prueba, que no vio al entrenar.", + "Entrenamiento en el navegador: en cada entrenamiento se toman al azar 11.000 de las 55.000 imágenes de entrenamiento y 2.000 de las 10.000 de prueba." + ] + } + ] + } + } + } +} diff --git a/public/n4l/mnist.n4l/locales/ja.json b/public/n4l/mnist.n4l/locales/ja.json new file mode 100644 index 0000000..ca77c8c --- /dev/null +++ b/public/n4l/mnist.n4l/locales/ja.json @@ -0,0 +1,37 @@ +{ + "tasks": { + "image-classification": { + "title": "MNIST - 数字の分類", + "name": "MNIST - 数字の分類", + "summary": "0〜9の手書き数字:畳み込みネットワークの「Hello World」です。", + "description": { + "text": [ + "MNISTデータベースは、手書き数字の大規模なデータベースです。このデータベースは、機械学習の分野でのトレーニングとテストに広く使用されています。", + "元のNISTデータセットのサンプルを「再混合」して作成されました。", + "NISTトレーニングデータセットは、米国国勢調査局から取得されました。さらに、NISTの白黒画像は、28 x 28ピクセルの境界ボックスに収まるように正規化され、平滑化されました。これにより、グレースケールレベルが導入されました。" + ], + "sections": [ + { + "title": "入力データ", + "items": [ + "28 x 28ピクセルサイズのグレースケール画像" + ] + }, + { + "title": "出力データ", + "items": [ + "0から9までの数字" + ] + }, + { + "title": "モデル", + "items": [ + "学習済みモデル:Keras のサンプルの畳み込みニューラルネットワーク(畳み込み層 2 つと全結合層 2 つ)で、MNIST の学習用画像 60,000 枚で学習しました。学習で見ていないテスト画像 {{test_images, number}} 枚での正解率は {{test_accuracy, number(style: percent; minimumFractionDigits: 1)}} です。", + "ブラウザでの学習:学習のたびに、学習用画像 55,000 枚から 11,000 枚、テスト画像 10,000 枚から 2,000 枚を無作為に選びます。" + ] + } + ] + } + } + } +} diff --git a/public/n4l/mnist.n4l/manifest.json b/public/n4l/mnist.n4l/manifest.json new file mode 100644 index 0000000..2e32dde --- /dev/null +++ b/public/n4l/mnist.n4l/manifest.json @@ -0,0 +1,177 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "mnist", + "version": "1.0.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://yann.lecun.com/exdb/mnist/", + "citation": "@article{deng2012mnist,\n title={The mnist database of handwritten digit images for machine learning research},\n author={Deng, Li},\n journal={IEEE Signal Processing Magazine},\n volume={29},\n number={6},\n pages={141--142},\n year={2012},\n publisher={IEEE}\n}" + }, + "datasets": [ + { + "id": "mnist", + "kind": "image-sprite", + "file": "data/mnist_images.png", + "labels": "data/mnist_labels_uint8", + "rows": 65000, + "train": 55000, + "image": { + "width": 28, + "height": 28, + "channels": 1 + } + } + ], + "tasks": [ + { + "task": "image-classification", + "key": "IMAGE-MNIST", + "runtime": "image-classification", + "datasets": [ + "mnist" + ], + "order": 1, + "preprocessing": [], + "classes": [ + { + "id": "0" + }, + { + "id": "1" + }, + { + "id": "2" + }, + { + "id": "3" + }, + { + "id": "4" + }, + { + "id": "5" + }, + { + "id": "6" + }, + { + "id": "7" + }, + { + "id": "8" + }, + { + "id": "9" + } + ], + "models": [ + { + "id": "cnn", + "format": "tfjs-layers", + "path": "models/cnn/model.json", + "dataset": "mnist", + "metrics": { + "test_accuracy": 0.9907, + "test_images": 10000 + } + } + ], + "prediction": { + "images": [ + { + "file": "examples/0.png", + "expected": "0" + }, + { + "file": "examples/1.png", + "expected": "1" + }, + { + "file": "examples/2.png", + "expected": "2" + }, + { + "file": "examples/3.png", + "expected": "3" + }, + { + "file": "examples/4.png", + "expected": "4" + }, + { + "file": "examples/5.png", + "expected": "5" + }, + { + "file": "examples/6.png", + "expected": "6" + }, + { + "file": "examples/7.png", + "expected": "7" + }, + { + "file": "examples/8.png", + "expected": "8" + }, + { + "file": "examples/9.png", + "expected": "9" + } + ] + }, + "training": { + "layers": [ + { + "class": "conv2d", + "filters": 16, + "kernelSize": 3, + "activation": "relu", + "locked": true + }, + { + "class": "maxPooling2d", + "poolSize": 2, + "strides": 2 + }, + { + "class": "conv2d", + "filters": 32, + "kernelSize": 3, + "activation": "relu" + }, + { + "class": "maxPooling2d", + "poolSize": 2, + "strides": 2 + }, + { + "class": "conv2d", + "filters": 32, + "kernelSize": 3, + "activation": "relu" + }, + { + "class": "flatten" + }, + { + "class": "dense", + "units": 64, + "activation": "relu" + }, + { + "class": "dense", + "units": 10, + "activation": "softmax" + } + ] + } + } + ] +} diff --git a/public/models/03-image-classification/keras-mnist/group1-shard1of2.bin b/public/n4l/mnist.n4l/models/cnn/group1-shard1of2.bin similarity index 100% rename from public/models/03-image-classification/keras-mnist/group1-shard1of2.bin rename to public/n4l/mnist.n4l/models/cnn/group1-shard1of2.bin diff --git a/public/models/03-image-classification/keras-mnist/group1-shard2of2.bin b/public/n4l/mnist.n4l/models/cnn/group1-shard2of2.bin similarity index 100% rename from public/models/03-image-classification/keras-mnist/group1-shard2of2.bin rename to public/n4l/mnist.n4l/models/cnn/group1-shard2of2.bin diff --git a/public/models/03-image-classification/keras-mnist/model.json b/public/n4l/mnist.n4l/models/cnn/model.json similarity index 100% rename from public/models/03-image-classification/keras-mnist/model.json rename to public/n4l/mnist.n4l/models/cnn/model.json diff --git a/public/n4l/n4l.schema.json b/public/n4l/n4l.schema.json new file mode 100644 index 0000000..8b51d88 --- /dev/null +++ b/public/n4l/n4l.schema.json @@ -0,0 +1,732 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://simidat.ujaen.es/n4l/n4l.schema.json", + "title": "Paquete .n4l de Nets4Learning (formato 1)", + "description": "manifest.json de un paquete .n4l. Especificación: docs/n4l-format.md. La aplicación lo valida con src/core/n4l/validate.ts.", + "type": "object", + "required": [ + "format", + "formatVersion", + "id", + "version", + "locales", + "datasets", + "tasks" + ], + "properties": { + "$schema": { + "type": "string" + }, + "format": { + "const": "n4l" + }, + "formatVersion": { + "const": 1, + "description": "Versión del formato. Las anteriores se migran al cargarlas; las posteriores necesitan una aplicación más nueva." + }, + "id": { + "type": "string", + "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$", + "description": "El del conjunto: el nombre de la carpeta, sin .n4l" + }, + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$", + "description": "Versión del contenido (semver)" + }, + "locales": { + "type": "array", + "minItems": 1, + "items": { + "type": "string" + }, + "description": "Idiomas de locales/.json" + }, + "source": { + "type": "object", + "properties": { + "url": { + "type": "string", + "format": "uri" + }, + "citation": { + "type": "string", + "description": "Cita en BibTeX" + }, + "links": { + "type": "object", + "additionalProperties": { + "type": "string", + "format": "uri" + }, + "description": "Otras direcciones, por el nombre de su etiqueta en los textos (link2…)" + } + } + }, + "datasets": { + "type": "array", + "items": { + "oneOf": [ + { + "$ref": "#/$defs/tableDataset" + }, + { + "$ref": "#/$defs/imageDataset" + }, + { + "$ref": "#/$defs/externalDataset" + } + ] + } + }, + "tasks": { + "type": "array", + "minItems": 1, + "description": "Una sección por cada tarea en la que se usa el conjunto", + "items": { + "type": "object", + "required": [ + "task", + "key", + "runtime", + "datasets", + "preprocessing", + "models" + ], + "properties": { + "task": { + "enum": [ + "tabular-classification", + "regression", + "image-classification", + "object-detection", + "clustering", + "time-series" + ] + }, + "key": { + "type": "string", + "minLength": 1, + "description": "Clave en las direcciones: /playground//model/" + }, + "runtime": { + "type": "string", + "minLength": 1, + "description": "Motor de la aplicación que lo interpreta (tabular-classification…)" + }, + "datasets": { + "type": "array", + "minItems": 1, + "items": { + "type": "string" + }, + "description": "Los conjuntos que usa (sus id); el primero, el que se abre al entrar" + }, + "listed": { + "type": "boolean", + "description": "Si sale en los menús (por defecto, sí)" + }, + "order": { + "type": "integer", + "description": "Su posición en los menús de la tarea, de menor a mayor (sin ella, después de los que la tienen)" + }, + "preprocessing": { + "type": "array", + "items": { + "type": "object", + "required": [ + "op", + "columns" + ], + "properties": { + "op": { + "type": "string", + "description": "label-encoder, min-max…" + }, + "columns": { + "oneOf": [ + { + "enum": [ + "categorical", + "features" + ] + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + } + } + } + }, + "classes": { + "type": "array", + "minItems": 1, + "description": "Salidas del modelo, en orden", + "items": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string" + }, + "aliases": { + "type": "array", + "items": { + "type": "string" + } + }, + "reading": { + "type": "string", + "description": "Caracteres: cómo se lee (rōmaji)" + }, + "origin": { + "type": "string", + "description": "Caracteres: el kanji del que viene" + } + } + } + }, + "models": { + "type": "array", + "items": { + "oneOf": [ + { + "$ref": "#/$defs/layersModel" + }, + { + "$ref": "#/$defs/mobilenetModel" + } + ] + } + }, + "prediction": { + "oneOf": [ + { + "$ref": "#/$defs/tablePrediction" + }, + { + "$ref": "#/$defs/imagePrediction" + } + ] + }, + "training": { + "type": "object", + "required": [ + "layers" + ], + "properties": { + "layers": { + "type": "array", + "minItems": 1, + "items": { + "oneOf": [ + { + "type": "object", + "required": [ + "class", + "units", + "activation" + ], + "properties": { + "class": { + "const": "dense" + }, + "units": { + "type": "integer", + "minimum": 1 + }, + "activation": { + "type": "string" + }, + "locked": { + "type": "boolean", + "description": "La capa no se puede cambiar (la salida de la regresión…)" + } + } + }, + { + "type": "object", + "required": [ + "class", + "filters", + "kernelSize", + "activation" + ], + "properties": { + "class": { + "const": "conv2d" + }, + "filters": { + "type": "integer", + "minimum": 1 + }, + "kernelSize": { + "type": "integer", + "minimum": 1 + }, + "activation": { + "type": "string" + }, + "locked": { + "type": "boolean", + "description": "La capa no se puede cambiar (la salida de la regresión…)" + } + } + }, + { + "type": "object", + "required": [ + "class", + "poolSize", + "strides" + ], + "properties": { + "class": { + "const": "maxPooling2d" + }, + "poolSize": { + "type": "integer", + "minimum": 1 + }, + "strides": { + "type": "integer", + "minimum": 1 + }, + "locked": { + "type": "boolean", + "description": "La capa no se puede cambiar (la salida de la regresión…)" + } + } + }, + { + "type": "object", + "required": [ + "class" + ], + "properties": { + "class": { + "const": "flatten" + }, + "locked": { + "type": "boolean", + "description": "La capa no se puede cambiar (la salida de la regresión…)" + } + } + }, + { + "type": "object", + "required": [ + "class", + "units" + ], + "properties": { + "class": { + "enum": [ + "simpleRNN", + "lstm", + "gru" + ], + "description": "Series temporales: capa recurrente, que lee la ventana valor a valor" + }, + "units": { + "type": "integer", + "minimum": 1 + }, + "activation": { + "type": "string", + "description": "Por defecto, tanh" + }, + "locked": { + "type": "boolean" + } + } + } + ] + } + }, + "learningRate": { + "type": "number", + "exclusiveMinimum": 0, + "description": "La tasa de aprendizaje con la que se empieza a entrenar" + }, + "epochs": { + "type": "integer", + "minimum": 1, + "description": "Las épocas con las que se empieza a entrenar" + } + } + }, + "forecast": { + "type": "object", + "required": [ + "window" + ], + "description": "Series temporales: cómo se prepara la serie para la red al entrar", + "properties": { + "window": { + "type": "integer", + "minimum": 1, + "description": "Valores anteriores con los que se predice el siguiente" + }, + "season": { + "type": "integer", + "minimum": 2, + "description": "Valores que tarda en repetirse el patrón (12 meses…): con ella se compara con la predicción estacional" + }, + "difference": { + "type": "boolean", + "description": "Predecir el cambio respecto al valor anterior (por defecto, no)" + }, + "testSize": { + "type": "number", + "exclusiveMinimum": 0, + "exclusiveMaximum": 100, + "description": "Porcentaje final de la serie que se aparta para probar (por defecto, 20)" + } + } + } + } + } + } + }, + "$defs": { + "innerPath": { + "type": "string", + "pattern": "^(?!/)(?!.*(^|/)\\.\\.(/|$))[^\\\\]+$", + "description": "Ruta dentro del paquete" + }, + "tableDataset": { + "type": "object", + "required": [ + "id", + "file", + "rows", + "columns" + ], + "properties": { + "id": { + "type": "string" + }, + "kind": { + "const": "table", + "description": "Por defecto" + }, + "file": { + "$ref": "#/$defs/innerPath" + }, + "info": { + "$ref": "#/$defs/innerPath" + }, + "rows": { + "type": "integer", + "minimum": 1 + }, + "columns": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": [ + "name", + "role", + "type", + "missing" + ], + "properties": { + "name": { + "type": "string" + }, + "role": { + "enum": [ + "Feature", + "Target", + "ID", + "Other" + ] + }, + "type": { + "enum": [ + "Continuous", + "Integer", + "Categorical", + "Binary", + "Date" + ], + "description": "Date: la fecha de cada fila de una serie temporal" + }, + "missing": { + "type": "integer", + "minimum": 0 + }, + "units": { + "type": "string" + }, + "description": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Valores posibles, en el orden del formulario" + } + } + } + }, + "frequency": { + "enum": [ + "hour", + "day", + "week", + "month", + "quarter", + "year" + ], + "description": "Serie temporal: cada cuánto hay una fila (en orden, con su fecha en la columna de tipo Date)" + } + }, + "description": "Una tabla (un CSV) con la ficha de sus columnas" + }, + "imageDataset": { + "type": "object", + "description": "Imágenes en un sprite: un PNG con una imagen por fila (primero las de entrenamiento) y sus clases en one-hot, un byte por clase", + "required": [ + "id", + "kind", + "file", + "labels", + "rows", + "train", + "image" + ], + "properties": { + "id": { + "type": "string" + }, + "kind": { + "const": "image-sprite" + }, + "file": { + "$ref": "#/$defs/innerPath", + "description": "El PNG" + }, + "labels": { + "$ref": "#/$defs/innerPath", + "description": "Las clases en one-hot" + }, + "info": { + "$ref": "#/$defs/innerPath" + }, + "rows": { + "type": "integer", + "minimum": 1, + "description": "Imágenes" + }, + "train": { + "type": "integer", + "minimum": 1, + "description": "Las primeras, de entrenamiento; las demás, de prueba" + }, + "image": { + "type": "object", + "required": [ + "width", + "height", + "channels" + ], + "properties": { + "width": { + "type": "integer", + "minimum": 1 + }, + "height": { + "type": "integer", + "minimum": 1 + }, + "channels": { + "type": "integer", + "minimum": 1 + } + } + } + } + }, + "externalDataset": { + "type": "object", + "description": "Un conjunto que no va en el paquete (por su tamaño o su licencia)", + "required": [ + "id", + "kind", + "url" + ], + "properties": { + "id": { + "type": "string" + }, + "kind": { + "const": "external" + }, + "url": { + "type": "string", + "format": "uri" + }, + "info": { + "$ref": "#/$defs/innerPath" + }, + "rows": { + "type": "integer", + "minimum": 1 + } + } + }, + "layersModel": { + "type": "object", + "required": [ + "id", + "format", + "path", + "dataset" + ], + "properties": { + "id": { + "type": "string" + }, + "format": { + "const": "tfjs-layers" + }, + "path": { + "$ref": "#/$defs/innerPath" + }, + "dataset": { + "type": "string" + }, + "input": { + "enum": [ + "encoded", + "scaled" + ], + "description": "Lo que recibe: las columnas codificadas (encoded, por defecto) o, además, escaladas con el min-max del conjunto (scaled). Las imágenes las recibe como están en su conjunto" + }, + "metrics": { + "type": "object", + "additionalProperties": { + "type": "number" + }, + "description": "Medidas con datos que no vio al entrenar (test_…)" + } + }, + "description": "Un modelo de TF.js (LayersModel) del paquete" + }, + "mobilenetModel": { + "type": "object", + "description": "MobileNet (@tensorflow-models/mobilenet): no va en el paquete, lo descarga la librería", + "required": [ + "id", + "format", + "dataset", + "version", + "alpha" + ], + "properties": { + "id": { + "type": "string" + }, + "format": { + "const": "tfjs-mobilenet" + }, + "dataset": { + "type": "string" + }, + "version": { + "enum": [ + 1, + 2 + ] + }, + "alpha": { + "type": "number", + "exclusiveMinimum": 0 + }, + "metrics": { + "type": "object", + "additionalProperties": { + "type": "number" + } + } + } + }, + "tablePrediction": { + "type": "object", + "required": [ + "defaults", + "examples" + ], + "properties": { + "defaults": { + "type": "object" + }, + "examples": { + "type": "array", + "items": { + "type": "object", + "required": [ + "values", + "expected" + ], + "properties": { + "values": { + "type": "object" + }, + "expected": { + "type": "string" + } + } + } + } + }, + "description": "El formulario para predecir con una tabla" + }, + "imagePrediction": { + "type": "object", + "description": "Las imágenes de ejemplo que se pueden clasificar", + "required": [ + "images" + ], + "properties": { + "images": { + "type": "array", + "items": { + "type": "object", + "required": [ + "file" + ], + "properties": { + "file": { + "$ref": "#/$defs/innerPath" + }, + "expected": { + "type": "string", + "description": "Su clase, si se sabe" + }, + "old": { + "type": "boolean", + "description": "Una forma antigua del carácter (KMNIST)" + }, + "origin": { + "type": "string", + "description": "El kanji del que viene esa forma" + } + } + } + } + } + } + } +} diff --git a/public/datasets/new-thyroid.csv b/public/n4l/new-thyroid.n4l/data/new-thyroid.csv similarity index 100% rename from public/datasets/new-thyroid.csv rename to public/n4l/new-thyroid.n4l/data/new-thyroid.csv diff --git a/public/n4l/new-thyroid.n4l/locales/en.json b/public/n4l/new-thyroid.n4l/locales/en.json new file mode 100644 index 0000000..a239591 --- /dev/null +++ b/public/n4l/new-thyroid.n4l/locales/en.json @@ -0,0 +1,16 @@ +{ + "columns": { + "T3resin": "T3resin", + "thyroxin": "thyroxin", + "triiodothyronine": "triiodothyronine", + "thyroidstimulating": "thyroidstimulating", + "TSH_value": "TSH_value", + "class": "class" + }, + "tasks": { + "clustering": { + "name": "Thyroid (without the diagnosis)", + "summary": "Five thyroid tests: almost all are normal, so the hypo- and hyperthyroidism groups are small." + } + } +} diff --git a/public/n4l/new-thyroid.n4l/locales/es.json b/public/n4l/new-thyroid.n4l/locales/es.json new file mode 100644 index 0000000..527cfd2 --- /dev/null +++ b/public/n4l/new-thyroid.n4l/locales/es.json @@ -0,0 +1,16 @@ +{ + "columns": { + "T3resin": "T3resin", + "thyroxin": "thyroxin", + "triiodothyronine": "triiodothyronine", + "thyroidstimulating": "thyroidstimulating", + "TSH_value": "TSH_value", + "class": "class" + }, + "tasks": { + "clustering": { + "name": "Tiroides (sin el diagnóstico)", + "summary": "Cinco análisis del tiroides: casi todos son normales, así que los grupos del hipo y del hipertiroidismo son pequeños." + } + } +} diff --git a/public/n4l/new-thyroid.n4l/locales/ja.json b/public/n4l/new-thyroid.n4l/locales/ja.json new file mode 100644 index 0000000..cb2eb2b --- /dev/null +++ b/public/n4l/new-thyroid.n4l/locales/ja.json @@ -0,0 +1,16 @@ +{ + "columns": { + "T3resin": "T3resin", + "thyroxin": "thyroxin", + "triiodothyronine": "triiodothyronine", + "thyroidstimulating": "thyroidstimulating", + "TSH_value": "TSH_value", + "class": "class" + }, + "tasks": { + "clustering": { + "name": "甲状腺(診断なし)", + "summary": "甲状腺の5つの検査:ほとんどが正常なので、機能低下症と亢進症のグループは小さくなります。" + } + } +} diff --git a/public/n4l/new-thyroid.n4l/manifest.json b/public/n4l/new-thyroid.n4l/manifest.json new file mode 100644 index 0000000..b01fef8 --- /dev/null +++ b/public/n4l/new-thyroid.n4l/manifest.json @@ -0,0 +1,84 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "new-thyroid", + "version": "1.0.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://archive.ics.uci.edu/dataset/102/thyroid+disease" + }, + "datasets": [ + { + "id": "new-thyroid", + "file": "data/new-thyroid.csv", + "rows": 215, + "columns": [ + { + "name": "T3resin", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "units": "%", + "description": "T3-resin uptake test" + }, + { + "name": "thyroxin", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "total serum thyroxin as measured by the isotopic displacement method" + }, + { + "name": "triiodothyronine", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "total serum triiodothyronine as measured by radioimmuno assay" + }, + { + "name": "thyroidstimulating", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "basal thyroid-stimulating hormone (TSH) as measured by radioimmuno assay" + }, + { + "name": "TSH_value", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "maximal absolute difference of TSH value after injection of 200 micro grams of thyrotropin-releasing hormone as compared to the basal value" + }, + { + "name": "class", + "role": "Target", + "type": "Categorical", + "missing": 0, + "description": "normal, hyper, hypo", + "options": [ + "normal", + "hyper", + "hypo" + ] + } + ] + } + ], + "tasks": [ + { + "task": "clustering", + "key": "NEW-THYROID", + "runtime": "clustering", + "datasets": [ + "new-thyroid" + ], + "preprocessing": [], + "models": [] + } + ] +} diff --git a/public/datasets/01-regression/salary/salary-extra.csv b/public/n4l/salary.n4l/data/salary-extra.csv similarity index 100% rename from public/datasets/01-regression/salary/salary-extra.csv rename to public/n4l/salary.n4l/data/salary-extra.csv diff --git a/public/datasets/01-regression/salary/salary-extra.names b/public/n4l/salary.n4l/data/salary-extra.names similarity index 100% rename from public/datasets/01-regression/salary/salary-extra.names rename to public/n4l/salary.n4l/data/salary-extra.names diff --git a/public/datasets/01-regression/salary/salary.csv b/public/n4l/salary.n4l/data/salary.csv similarity index 100% rename from public/datasets/01-regression/salary/salary.csv rename to public/n4l/salary.n4l/data/salary.csv diff --git a/public/datasets/01-regression/salary/salary.names b/public/n4l/salary.n4l/data/salary.names similarity index 100% rename from public/datasets/01-regression/salary/salary.names rename to public/n4l/salary.n4l/data/salary.names diff --git a/public/n4l/salary.n4l/locales/en.json b/public/n4l/salary.n4l/locales/en.json new file mode 100644 index 0000000..b934994 --- /dev/null +++ b/public/n4l/salary.n4l/locales/en.json @@ -0,0 +1,47 @@ +{ + "columns": { + "YearsExperience": "YearsExperience", + "Salary": "Salary", + "Age": "Age", + "Gender": "Gender", + "Education Level": "Education Level", + "Job Title": "Job Title", + "Years of Experience": "Years of Experience" + }, + "tasks": { + "regression": { + "title": "Salary for years of experience", + "name": "Salary", + "summary": "The salary by years of experience (and, in the second file, also age, education and job title).", + "description": { + "text": [ + "The \"Salary\" data set is a collection of information that relates the number of years of work experience of an individual to their corresponding salary.", + "Each entry in the data set consists of two main variables: \"Years of Experience\" and \"Salary.\" The \"Years of Experience\" variable represents the number of years an employee has worked in their specific field, while the \"Salary\" variable represents the amount of money that employee earns annually.", + "For more information about this data set, visit the repository www.kaggy.com" + ], + "sections": [ + { + "title": "Input", + "items": [ + "Years of experience - Years of experience", + "Salary - Salary" + ] + }, + { + "title": "Output", + "items": [ + "Calculated regression (Salary)" + ] + }, + { + "title": "References", + "items": [ + "Data set 1", + "Data set 2" + ] + } + ] + } + } + } +} diff --git a/public/n4l/salary.n4l/locales/es.json b/public/n4l/salary.n4l/locales/es.json new file mode 100644 index 0000000..f52eb9e --- /dev/null +++ b/public/n4l/salary.n4l/locales/es.json @@ -0,0 +1,47 @@ +{ + "columns": { + "YearsExperience": "YearsExperience", + "Salary": "Salary", + "Age": "Age", + "Gender": "Gender", + "Education Level": "Education Level", + "Job Title": "Job Title", + "Years of Experience": "Years of Experience" + }, + "tasks": { + "regression": { + "title": "Salario por años de experiencia", + "name": "Salary", + "summary": "El salario según los años de experiencia (y, en el segundo fichero, también la edad, la formación y el puesto).", + "description": { + "text": [ + "El conjunto de datos \"Salary\" es una colección de información que relaciona la cantidad de años de experiencia laboral de un individuo con su salario correspondiente.", + "Cada entrada en el conjunto de datos consta de dos variables principales: \"Years of Experience\" (Años de experiencia) y \"Salary\" (Salario). La variable \"Years of Experience\" representa la cantidad de años que un empleado ha trabajado en su campo específico, mientras que la variable \"Salary\" representa la cantidad de dinero que dicho empleado gana anualmente.", + "Para obtener más información acerca de este conjunto de datos visita el repositorio www.kaggle.com." + ], + "sections": [ + { + "title": "Datos de entrada", + "items": [ + "Years of experience - Años de experiencia", + "Salary - Salario" + ] + }, + { + "title": "Datos de salida", + "items": [ + "Regresión calculada (Salary)" + ] + }, + { + "title": "Referencias", + "items": [ + "Conjunto de datos 1", + "Conjunto de datos 2" + ] + } + ] + } + } + } +} diff --git a/public/n4l/salary.n4l/locales/ja.json b/public/n4l/salary.n4l/locales/ja.json new file mode 100644 index 0000000..4992c27 --- /dev/null +++ b/public/n4l/salary.n4l/locales/ja.json @@ -0,0 +1,47 @@ +{ + "columns": { + "YearsExperience": "YearsExperience", + "Salary": "Salary", + "Age": "Age", + "Gender": "Gender", + "Education Level": "Education Level", + "Job Title": "Job Title", + "Years of Experience": "Years of Experience" + }, + "tasks": { + "regression": { + "title": "経験年数に基づく給与", + "name": "給与", + "summary": "経験年数から給与を予測します(2つ目のファイルには年齢、学歴、職種もあります)。", + "description": { + "text": [ + "「Salary」データセットは、個人の職務経験年数とそれに対応する給与の関係を関連付ける情報のコレクションです。", + "データセットの各エントリは、「Years of Experience」(経験年数)と「Salary」(給与)の2つの主要な変数で構成されています。「Years of Experience」変数は、従業員が特定の分野で働いた年数を表し、「Salary」変数は、その従業員が年間稼ぐ金額を表します。", + "このデータセットの詳細については、www.kaggle.comリポジトリをご覧ください。" + ], + "sections": [ + { + "title": "入力データ", + "items": [ + "Years of experience - 経験年数", + "Salary - 給与" + ] + }, + { + "title": "出力データ", + "items": [ + "計算された回帰 (Salary)" + ] + }, + { + "title": "参照元", + "items": [ + "データセット 1", + "データセット 2" + ] + } + ] + } + } + } +} diff --git a/public/n4l/salary.n4l/manifest.json b/public/n4l/salary.n4l/manifest.json new file mode 100644 index 0000000..ec38dac --- /dev/null +++ b/public/n4l/salary.n4l/manifest.json @@ -0,0 +1,146 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "salary", + "version": "1.1.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://www.kaggle.com/datasets/saquib7hussain/experience-salary-dataset", + "links": { + "link2": "https://www.kaggle.com/datasets/rkiattisak/salaly-prediction-for-beginer" + } + }, + "datasets": [ + { + "id": "salary", + "file": "data/salary.csv", + "info": "data/salary.names", + "rows": 1000, + "columns": [ + { + "name": "YearsExperience", + "role": "Feature", + "type": "Continuous", + "missing": 0, + "description": "years of experience" + }, + { + "name": "Salary", + "role": "Target", + "type": "Continuous", + "missing": 0, + "description": "salary" + } + ] + }, + { + "id": "salary-extra", + "file": "data/salary-extra.csv", + "info": "data/salary-extra.names", + "rows": 373, + "columns": [ + { + "name": "Age", + "role": "Feature", + "type": "Integer", + "missing": 0, + "units": "years" + }, + { + "name": "Gender", + "role": "Feature", + "type": "Binary", + "missing": 0 + }, + { + "name": "Education Level", + "role": "Feature", + "type": "Categorical", + "missing": 0 + }, + { + "name": "Job Title", + "role": "Feature", + "type": "Categorical", + "missing": 0 + }, + { + "name": "Years of Experience", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "Salary", + "role": "Target", + "type": "Integer", + "missing": 0 + } + ] + } + ], + "tasks": [ + { + "task": "regression", + "key": "SALARY", + "runtime": "regression", + "datasets": [ + "salary", + "salary-extra" + ], + "preprocessing": [ + { + "op": "label-encoder", + "columns": [ + "Gender", + "Education Level", + "Job Title" + ] + }, + { + "op": "min-max", + "columns": "features" + } + ], + "models": [ + { + "id": "mlp", + "format": "tfjs-layers", + "path": "models/mlp/model.json", + "dataset": "salary", + "input": "scaled", + "metrics": { + "test_r2": 0.5567, + "test_mae": 4.3045, + "test_baseline_mae": 6.4404 + } + } + ], + "training": { + "layers": [ + { + "class": "dense", + "units": 10, + "activation": "sigmoid" + }, + { + "class": "dense", + "units": 20, + "activation": "relu" + }, + { + "class": "dense", + "units": 1, + "activation": "linear", + "locked": true + } + ] + } + } + ] +} diff --git a/public/n4l/salary.n4l/models/mlp/model.json b/public/n4l/salary.n4l/models/mlp/model.json new file mode 100644 index 0000000..95895c2 --- /dev/null +++ b/public/n4l/salary.n4l/models/mlp/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_4","layers":[{"class_name":"Dense","config":{"units":32,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1030}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense11","trainable":true,"batch_input_shape":[null,1],"dtype":"float32"}},{"class_name":"Dense","config":{"units":16,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1031}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense12","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1129}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense13","trainable":true}}]},"keras_version":"tfjs-layers 4.22.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.22.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense11/kernel","shape":[1,32],"dtype":"float32"},{"name":"dense_Dense11/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense12/kernel","shape":[32,16],"dtype":"float32"},{"name":"dense_Dense12/bias","shape":[16],"dtype":"float32"},{"name":"dense_Dense13/kernel","shape":[16,1],"dtype":"float32"},{"name":"dense_Dense13/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/n4l/salary.n4l/models/mlp/model.weights.bin b/public/n4l/salary.n4l/models/mlp/model.weights.bin new file mode 100644 index 0000000..84ed48c Binary files /dev/null and b/public/n4l/salary.n4l/models/mlp/model.weights.bin differ diff --git a/public/datasets/01-regression/student-performance/student-mat-2024.csv b/public/n4l/student-performance.n4l/data/student-mat-2024.csv similarity index 100% rename from public/datasets/01-regression/student-performance/student-mat-2024.csv rename to public/n4l/student-performance.n4l/data/student-mat-2024.csv diff --git a/public/datasets/01-regression/student-performance/student-por-2024.csv b/public/n4l/student-performance.n4l/data/student-por-2024.csv similarity index 100% rename from public/datasets/01-regression/student-performance/student-por-2024.csv rename to public/n4l/student-performance.n4l/data/student-por-2024.csv diff --git a/public/datasets/01-regression/student-performance/student.names b/public/n4l/student-performance.n4l/data/student.names similarity index 100% rename from public/datasets/01-regression/student-performance/student.names rename to public/n4l/student-performance.n4l/data/student.names diff --git a/public/n4l/student-performance.n4l/locales/en.json b/public/n4l/student-performance.n4l/locales/en.json new file mode 100644 index 0000000..f6d20d9 --- /dev/null +++ b/public/n4l/student-performance.n4l/locales/en.json @@ -0,0 +1,100 @@ +{ + "columns": { + "school": "school", + "sex": "sex", + "age": "age", + "address": "address", + "famsize": "famsize", + "Pstatus": "Pstatus", + "Medu": "Medu", + "Fedu": "Fedu", + "Mjob": "Mjob", + "Fjob": "Fjob", + "reason": "reason", + "guardian": "guardian", + "traveltime": "traveltime", + "studytime": "studytime", + "failures": "failures", + "schoolsup": "schoolsup", + "famsup": "famsup", + "paid": "paid", + "activities": "activities", + "nursery": "nursery", + "higher": "higher", + "internet": "internet", + "romantic": "romantic", + "famrel": "famrel", + "freetime": "freetime", + "goout": "goout", + "Dalc": "Dalc", + "Walc": "Walc", + "health": "health", + "absences": "absences", + "G3": "G3" + }, + "tasks": { + "regression": { + "title": "Student Performance", + "name": "Student performance", + "summary": "The final grade of Portuguese secondary school students, in maths and Portuguese, by their background and habits.", + "description": { + "text": [ + "The data set includes data on the academic performance of students from two Portuguese schools. The data includes demographic, social characteristics, student grades, etc. Two sets of data are included, one with the performance of two different subjects: Mathematics (mat) and Portuguese language (por).", + "The data set contains multivariate type data, real type attributes, 649 instances, and 12 distinct attributes.", + "Important note: The target attribute G3 has a strong correlation with the attributes G2 and G1. This occurs because G3 is the grade for the last year (issued in the 3rd period), while G1 and G2 correspond to the grades for the 1st and 2nd period. It is more difficult to predict G3 without G2 and G1, but such a prediction is much more useful.", + "The file student-por.csv corresponds to the data set of Portuguese student grades and student-mat.csv corresponds to the data set of mathematics student grades.", + "UCI data set input" + ], + "sections": [ + { + "title": "Input", + "items": [ + "school - student's school (binary: 'GP' - Gabriel Pereira or 'MS' - Mousinho da Silveira)", + "sex - student's sex (binary: 'F' - female or 'M' - male)", + "age - student's age (numeric: from 15 to 22)", + "address - student's home address type (binary: 'U' - urban or 'R' - rural)", + "famsize - family size (binary: 'LE3' - less or equal to 3 or 'GT3' - greater than 3)", + "Pstatus - parent's cohabitation status (binary: 'T' - living together or 'A' - apart)", + "Medu - mother's education (numeric: 0 - none, 1 - primary education (4th grade), 2 – 5th to 9th grade, 3 – secondary education or 4 – higher education)", + "Fedu - father's education (numeric: 0 - none, 1 - primary education (4th grade), 2 – 5th to 9th grade, 3 – secondary education or 4 – higher education)", + "Mjob - mother's job (nominal: 'teacher', 'health' care related, civil 'services' (e.g. administrative or police), 'at_home' or 'other')", + "Fjob - father's job (nominal: 'teacher', 'health' care related, civil 'services' (e.g. administrative or police), 'at_home' or 'other')", + "reason - reason to choose this school (nominal: close to 'home', school 'reputation', 'course' preference or 'other')", + "guardian - student's guardian (nominal: 'mother', 'father' or 'other')", + "traveltime - home to school travel time (numeric: 1 - < 15 min., 2 - 15 to 30 min., 3 - 30 min. to 1 hour, or 4 - > 1 hour)", + "studytime - weekly study time (numeric: 1 - < 2 hours, 2 - 2 to 5 hours, 3 - 5 to 10 hours, or 4 - > 10 hours)", + "failures - number of past class failures (numeric: n if 1 ≶=n ≶3, else 4)", + "schoolsup - extra educational support (binary: yes or no)", + "famsup - family educational support (binary: yes or no)", + "paid - extra paid classes within the course subject (Math or Portuguese) (binary: yes or no)", + "activities - extra-curricular activities (binary: yes or no)", + "nursery - attended nursery school (binary: yes or no)", + "higher - wants to take higher education (binary: yes or no)", + "internet - Internet access at home (binary: yes or no)", + "romantic - with a romantic relationship (binary: yes or no)", + "famrel - quality of family relationships (numeric: from 1 - very bad to 5 - excellent)", + "freetime - free time after school (numeric: from 1 - very low to 5 - very high)", + "goout - going out with friends (numeric: from 1 - very low to 5 - very high)", + "Dalc - workday alcohol consumption (numeric: from 1 - very low to 5 - very high)", + "Walc - weekend alcohol consumption (numeric: from 1 - very low to 5 - very high)", + "health - current health status (numeric: from 1 - very bad to 5 - very good)", + "absences - number of school absences (numeric: from 0 to 93)" + ] + }, + { + "title": "Output", + "items": [ + "Calculated regression" + ] + }, + { + "title": "References", + "items": [ + "Student Performance" + ] + } + ] + } + } + } +} diff --git a/public/n4l/student-performance.n4l/locales/es.json b/public/n4l/student-performance.n4l/locales/es.json new file mode 100644 index 0000000..5ca8cd7 --- /dev/null +++ b/public/n4l/student-performance.n4l/locales/es.json @@ -0,0 +1,100 @@ +{ + "columns": { + "school": "school", + "sex": "sex", + "age": "age", + "address": "address", + "famsize": "famsize", + "Pstatus": "Pstatus", + "Medu": "Medu", + "Fedu": "Fedu", + "Mjob": "Mjob", + "Fjob": "Fjob", + "reason": "reason", + "guardian": "guardian", + "traveltime": "traveltime", + "studytime": "studytime", + "failures": "failures", + "schoolsup": "schoolsup", + "famsup": "famsup", + "paid": "paid", + "activities": "activities", + "nursery": "nursery", + "higher": "higher", + "internet": "internet", + "romantic": "romantic", + "famrel": "famrel", + "freetime": "freetime", + "goout": "goout", + "Dalc": "Dalc", + "Walc": "Walc", + "health": "health", + "absences": "absences", + "G3": "G3" + }, + "tasks": { + "regression": { + "title": "Rendimiento de estudiantes", + "name": "Student performance", + "summary": "La nota final de alumnos de secundaria portugueses, en matemáticas y en portugués, según su entorno y sus hábitos.", + "description": { + "text": [ + "El conjunto de datos incluye datos del rendimiento académico de alumnos de dos centros escolares portugueses. Los datos incluyen características demográficas, sociales, calificaciones de los estudiantes, etc. Se incluyen dos conjuntos de datos uno con el desempeño de dos materias distintas: Matemáticas (mat) y lengua portuguesa (por).", + "El conjunto de datos contiene datos de tipo multivariado, atributos de tipo reales, 649 instancias y 12 atributos distintos.", + "Nota importante: el atributo objetivo G3 tiene una fuerte correlación con los atributos G2 y G1. Esto ocurre porque G3 es la calificación del último año (emitida en el 3er período), mientras que G1 y G2 corresponden a las calificaciones del 1er y 2do período. Es más difícil predecir G3 sin G2 y G1, pero dicha predicción es mucho más útil.", + "El fichero student-por.csv corresponde al conjunto de datos de calificaciones de estudiantes de portugués y student-mat.csv corresponde al conjunto de datos de calificaciones de estudiantes de matemáticas.", + "Entrada del conjunto de datos UCI" + ], + "sections": [ + { + "title": "Datos de entrada", + "items": [ + "school - escuela del estudiante (binario: 'GP' - Gabriel Pereira o 'MS' - Mousinho da Silveira)", + "sex - sexo del estudiante (binario: 'F' - femenino o 'M' - masculino)", + "age - edad del estudiante (numérica: de 15 a 22)", + "address: tipo de dirección particular del estudiante (binario: 'U' - urbana o 'R' - rural)", + "famsize - tamaño de la familia (binario: 'LE3' - menor o igual a 3 o 'GT3' - mayor que 3)", + "Pstatus - estado de convivencia de los padres (binario: 'T' - viviendo juntos o 'A' - separados)", + "Medu - educación de la madre (numérica: 0 - ninguna, 1 - educación primaria (4º grado), 2 - 5º a 9º grado, 3 - educación secundaria o 4 - educación superior)", + "Fedu - educación del padre (numérica: 0 - ninguna, 1 - educación primaria (4º grado), 2 - 5º a 9º grado, 3 - educación secundaria o 4 - educación superior)", + "Mjob - trabajo de la madre (nominal: 'maestra', 'relacionado con la atención sanitaria', 'servicios' civiles (por ejemplo, administrativos o policiales), 'en_casa' u 'otros')", + "Fjob - trabajo del padre (nominal: 'maestro', 'relacionado con la atención sanitaria', 'servicios' civiles (por ejemplo, administrativos o policiales), 'en_casa' u 'otros')", + "razón: motivo para elegir esta escuela (nominal: cerca de \"casa\", \"reputación\" de la escuela, preferencia de \"curso\" u \"otro\")", + "tutor - tutor del estudiante (nominal: 'madre', 'padre' u 'otro')", + "tiempo de viaje: tiempo de viaje de casa a la escuela (numérico: 1 - <15 min., 2 - 15 a 30 min., 3 - 30 min. a 1 hora, o 4 - >1 hora)", + "tiempo de estudio: tiempo de estudio semanal (numérico: 1 - < 2 horas, 2 - 2 a 5 horas, 3 - 5 a 10 horas o 4 - > 10 horas)", + "reprobados: número de reprobados en clases anteriores (numérico: n si 1 ≶=n ≶3, en caso contrario 4)", + "schoolsup - apoyo educativo adicional (binario: sí o no)", + "famsup - apoyo educativo familiar (binario: sí o no)", + "pagado - clases extra pagadas dentro de la materia del curso (Matemáticas o Portugués) (binario: sí o no)", + "actividades - actividades extracurriculares (binario: sí o no)", + "guardería: asistió a la guardería (binario: sí o no)", + "superior - quiere cursar estudios superiores (binario: sí o no)", + "internet - Acceso a Internet en casa (binario: sí o no)", + "romántico - con una relación romántica (binario: sí o no)", + "famrel - calidad de las relaciones familiares (numérica: de 1 - muy mala a 5 - excelente)", + "tiempo libre: tiempo libre después de la escuela (numérico: de 1 - muy bajo a 5 - muy alto)", + "goout - salir con amigos (numérico: de 1 - muy bajo a 5 - muy alto)", + "Dalc - consumo de alcohol en jornada laboral (numérico: de 1 - muy bajo a 5 - muy alto)", + "Walc - consumo de alcohol durante el fin de semana (numérico: de 1 - muy bajo a 5 - muy alto)", + "salud: estado de salud actual (numérico: de 1: muy malo a 5: muy bueno)", + "ausencias - número de ausencias escolares (numérico: de 0 a 93)" + ] + }, + { + "title": "Datos de salida", + "items": [ + "Regresión calculada" + ] + }, + { + "title": "Referencias", + "items": [ + "Student Performance" + ] + } + ] + } + } + } +} diff --git a/public/n4l/student-performance.n4l/locales/ja.json b/public/n4l/student-performance.n4l/locales/ja.json new file mode 100644 index 0000000..f57e05a --- /dev/null +++ b/public/n4l/student-performance.n4l/locales/ja.json @@ -0,0 +1,100 @@ +{ + "columns": { + "school": "school", + "sex": "sex", + "age": "age", + "address": "address", + "famsize": "famsize", + "Pstatus": "Pstatus", + "Medu": "Medu", + "Fedu": "Fedu", + "Mjob": "Mjob", + "Fjob": "Fjob", + "reason": "reason", + "guardian": "guardian", + "traveltime": "traveltime", + "studytime": "studytime", + "failures": "failures", + "schoolsup": "schoolsup", + "famsup": "famsup", + "paid": "paid", + "activities": "activities", + "nursery": "nursery", + "higher": "higher", + "internet": "internet", + "romantic": "romantic", + "famrel": "famrel", + "freetime": "freetime", + "goout": "goout", + "Dalc": "Dalc", + "Walc": "Walc", + "health": "health", + "absences": "absences", + "G3": "G3" + }, + "tasks": { + "regression": { + "title": "学生の成績", + "name": "学生成績", + "summary": "ポルトガルの中等学校の生徒の最終成績(数学とポルトガル語)を、環境や習慣から予測します。", + "description": { + "text": [ + "このデータセットには、2つのポルトガル学校の生徒の学業成績データが含まれています。データには、生徒の人口統計、社会的な特徴、成績などが含まれています。数学(mat)とポルトガル語(por)の2つの異なる科目に関する成績データセットが含まれています。", + "データセットには多変量データ、実数型の属性、649インスタンス、および12個の異なる属性が含まれています。", + "重要な注意: ターゲット属性G3は、G2およびG1属性と強い相関があります。これは、G3が最終学年の成績(3学期に発行)であり、G1およびG2が1学期と2学期の成績に対応しているためです。G2とG1なしでG3を予測することはより困難ですが、そのような予測はより有用です。", + "ファイル student-por.csv はポルトガル語の学生成績データセットに対応し、student-mat.csv は数学の学生成績データセットに対応します。", + "UCIデータセット入力" + ], + "sections": [ + { + "title": "入力データ", + "items": [ + "school - 生徒の学校(バイナリ: 'GP' - Gabriel Pereira または 'MS' - Mousinho da Silveira)", + "sex - 生徒の性別(バイナリ: 'F' - 女性 または 'M' - 男性)", + "age - 生徒の年齢(数値: 15歳から22歳)", + "address - 生徒の住居の種類(バイナリ: 'U' - 都市 または 'R' - 地方)", + "famsize - 家族のサイズ(バイナリ: 'LE3' - 3人以下 または 'GT3' - 3人以上)", + "Pstatus - 両親の同居状況(バイナリ: 'T' - 同居 または 'A' - 別居)", + "Medu - 母親の学歴(数値: 0 - なし, 1 - 小学校(4年生), 2 - 5年生から9年生, 3 - 中等教育 または 4 - 高等教育)", + "Fedu - 父親の学歴(数値: 0 - なし, 1 - 小学校(4年生), 2 - 5年生から9年生, 3 - 中等教育 または 4 - 高等教育)", + "Mjob - 母親の職業(名義尺度: 'teacher' (教師), 'health' (医療関連), 'services' (サービス業) (例: 管理職や警察), 'at_home' (主婦) または 'other' (その他))", + "Fjob - 父親の職業(名義尺度: 'teacher', 'health', 'services', 'at_home' または 'other')", + "reason - 学校を選んだ理由(名義尺度: 'home'(家が近い), 'reputation'(評判), 'course'(コース) または 'other'(その他)", + "guardian - 生徒の保護者(名義尺度: 'mother' (母), 'father' (父) または 'other' (その他))", + "traveltime - 通学時間(数値: 1 - 15分未満, 2 - 15分から30分, 3 - 30分から1時間, または 4 - 1時間以上)", + "studytime - 週間の学習時間(数値: 1 - 2時間未満, 2 - 2時間から5時間, 3 - 5時間から10時間, または 4 - 10時間以上)", + "failures - 以前のクラスでの落第回数(数値: nが1 <= n <= 3の場合 n, それ以外の場合は4)", + "schoolsup - 追加の教育サポート(バイナリ: yes または no)", + "famsup - 家族の教育サポート(バイナリ: yes または no)", + "paid - 有料追加クラス(科目内)の有無(バイナリ: yes または no)", + "activities - 課外活動(バイナリ: yes または no)", + "nursery - 幼稚園に通っていたか(バイナリ: yes または no)", + "higher - 高等教育を希望するか(バイナリ: yes または no)", + "internet - 自宅でのインターネットアクセス(バイナリ: yes または no)", + "romantic - 恋愛関係にあるか(バイナリ: yes または no)", + "famrel - 家族関係の質(数値: 1 - 非常に悪い から 5 - 非常に良い)", + "freetime - 放課後の自由時間(数値: 1 - 非常に少ない から 5 - 非常に多い)", + "goout - 友達と外出(数値: 1 - 非常に少ない から 5 - 非常に多い)", + "Dalc - 平日のアルコール消費量(数値: 1 - 非常に少ない から 5 - 非常に多い)", + "Walc - 週末のアルコール消費量(数値: 1 - 非常に少ない から 5 - 非常に多い)", + "health - 現在の健康状態(数値: 1 - 非常に悪い から 5 - 非常に良い)", + "absences - 学校の欠席日数(数値: 0から93)" + ] + }, + { + "title": "出力データ", + "items": [ + "計算された回帰" + ] + }, + { + "title": "参照元", + "items": [ + "Student Performance" + ] + } + ] + } + } + } +} diff --git a/public/n4l/student-performance.n4l/manifest.json b/public/n4l/student-performance.n4l/manifest.json new file mode 100644 index 0000000..3306d99 --- /dev/null +++ b/public/n4l/student-performance.n4l/manifest.json @@ -0,0 +1,553 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "student-performance", + "version": "1.2.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://archive.ics.uci.edu/dataset/320/student+performance", + "citation": "@misc{misc_student_performance_320,\n author = {Cortez,Paulo},\n title = {{Student Performance}},\n year = {2014},\n howpublished = {UCI Machine Learning Repository},\n note = {{DOI}: https://doi.org/10.24432/C5TG7T}\n}" + }, + "datasets": [ + { + "id": "student-mat", + "file": "data/student-mat-2024.csv", + "info": "data/student.names", + "rows": 395, + "columns": [ + { + "name": "school", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "student's school (binary: 'GP' - Gabriel Pereira or 'MS' - Mousinho da Silveira)" + }, + { + "name": "sex", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "student's sex (binary: 'F' - female or 'M' - male)" + }, + { + "name": "age", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "student's age (numeric: from 15 to 22)" + }, + { + "name": "address", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "student's home address type (binary: 'U' - urban or 'R' - rural)" + }, + { + "name": "famsize", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "family size (binary: 'LE3' - less or equal to 3 or 'GT3' - greater than 3)" + }, + { + "name": "Pstatus", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "parent's cohabitation status (binary: 'T' - living together or 'A' - apart)" + }, + { + "name": "Medu", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "mother's education (numeric: 0 - none, 1 - primary education (4th grade), 2 - 5th to 9th grade, 3 - secondary education or 4 - higher education)" + }, + { + "name": "Fedu", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "father's education (numeric: 0 - none, 1 - primary education (4th grade), 2 – 5th to 9th grade, 3 – secondary education or 4 – higher education)" + }, + { + "name": "Mjob", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "mother's job (nominal: 'teacher', 'health' care related, civil 'services' (e.g. administrative or police), 'at_home' or 'other')" + }, + { + "name": "Fjob", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "father's job (nominal: 'teacher', 'health' care related, civil 'services' (e.g. administrative or police), 'at_home' or 'other')" + }, + { + "name": "reason", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "reason to choose this school (nominal: close to 'home', school 'reputation', 'course' preference or 'other')" + }, + { + "name": "guardian", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "student's guardian (nominal: 'mother', 'father' or 'other')" + }, + { + "name": "traveltime", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "home to school travel time (numeric: 1 - <15 min., 2 - 15 to 30 min., 3 - 30 min. to 1 hour, or 4 - >1 hour)" + }, + { + "name": "studytime", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "weekly study time (numeric: 1 - <2 hours, 2 - 2 to 5 hours, 3 - 5 to 10 hours, or 4 - >10 hours)" + }, + { + "name": "failures", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "number of past class failures (numeric: n if 1<=n<3, else 4)" + }, + { + "name": "schoolsup", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "extra educational support (binary: yes or no)" + }, + { + "name": "famsup", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "family educational support (binary: yes or no)" + }, + { + "name": "paid", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "extra paid classes within the course subject (Math or Portuguese) (binary: yes or no)" + }, + { + "name": "activities", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "extra-curricular activities (binary: yes or no)" + }, + { + "name": "nursery", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "attended nursery school (binary: yes or no)" + }, + { + "name": "higher", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "wants to take higher education (binary: yes or no)" + }, + { + "name": "internet", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "Internet access at home (binary: yes or no)" + }, + { + "name": "romantic", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "with a romantic relationship (binary: yes or no)" + }, + { + "name": "famrel", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "quality of family relationships (numeric: from 1 - very bad to 5 - excellent)" + }, + { + "name": "freetime", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "free time after school (numeric: from 1 - very low to 5 - very high)" + }, + { + "name": "goout", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "going out with friends (numeric: from 1 - very low to 5 - very high)" + }, + { + "name": "Dalc", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "workday alcohol consumption (numeric: from 1 - very low to 5 - very high)" + }, + { + "name": "Walc", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "weekend alcohol consumption (numeric: from 1 - very low to 5 - very high)" + }, + { + "name": "health", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "current health status (numeric: from 1 - very bad to 5 - very good)" + }, + { + "name": "absences", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "number of school absences (numeric: from 0 to 93)" + }, + { + "name": "G3", + "role": "Target", + "type": "Integer", + "missing": 0, + "description": "final grade (numeric: from 0 to 20, output target)" + } + ] + }, + { + "id": "student-por", + "file": "data/student-por-2024.csv", + "info": "data/student.names", + "rows": 649, + "columns": [ + { + "name": "school", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "student's school (binary: 'GP' - Gabriel Pereira or 'MS' - Mousinho da Silveira)" + }, + { + "name": "sex", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "student's sex (binary: 'F' - female or 'M' - male)" + }, + { + "name": "age", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "student's age (numeric: from 15 to 22)" + }, + { + "name": "address", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "student's home address type (binary: 'U' - urban or 'R' - rural)" + }, + { + "name": "famsize", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "family size (binary: 'LE3' - less or equal to 3 or 'GT3' - greater than 3)" + }, + { + "name": "Pstatus", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "parent's cohabitation status (binary: 'T' - living together or 'A' - apart)" + }, + { + "name": "Medu", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "mother's education (numeric: 0 - none, 1 - primary education (4th grade), 2 - 5th to 9th grade, 3 - secondary education or 4 - higher education)" + }, + { + "name": "Fedu", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "father's education (numeric: 0 - none, 1 - primary education (4th grade), 2 – 5th to 9th grade, 3 – secondary education or 4 – higher education)" + }, + { + "name": "Mjob", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "mother's job (nominal: 'teacher', 'health' care related, civil 'services' (e.g. administrative or police), 'at_home' or 'other')" + }, + { + "name": "Fjob", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "father's job (nominal: 'teacher', 'health' care related, civil 'services' (e.g. administrative or police), 'at_home' or 'other')" + }, + { + "name": "reason", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "reason to choose this school (nominal: close to 'home', school 'reputation', 'course' preference or 'other')" + }, + { + "name": "guardian", + "role": "Feature", + "type": "Categorical", + "missing": 0, + "description": "student's guardian (nominal: 'mother', 'father' or 'other')" + }, + { + "name": "traveltime", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "home to school travel time (numeric: 1 - <15 min., 2 - 15 to 30 min., 3 - 30 min. to 1 hour, or 4 - >1 hour)" + }, + { + "name": "studytime", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "weekly study time (numeric: 1 - <2 hours, 2 - 2 to 5 hours, 3 - 5 to 10 hours, or 4 - >10 hours)" + }, + { + "name": "failures", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "number of past class failures (numeric: n if 1<=n<3, else 4)" + }, + { + "name": "schoolsup", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "extra educational support (binary: yes or no)" + }, + { + "name": "famsup", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "family educational support (binary: yes or no)" + }, + { + "name": "paid", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "extra paid classes within the course subject (Math or Portuguese) (binary: yes or no)" + }, + { + "name": "activities", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "extra-curricular activities (binary: yes or no)" + }, + { + "name": "nursery", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "attended nursery school (binary: yes or no)" + }, + { + "name": "higher", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "wants to take higher education (binary: yes or no)" + }, + { + "name": "internet", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "Internet access at home (binary: yes or no)" + }, + { + "name": "romantic", + "role": "Feature", + "type": "Binary", + "missing": 0, + "description": "with a romantic relationship (binary: yes or no)" + }, + { + "name": "famrel", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "quality of family relationships (numeric: from 1 - very bad to 5 - excellent)" + }, + { + "name": "freetime", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "free time after school (numeric: from 1 - very low to 5 - very high)" + }, + { + "name": "goout", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "going out with friends (numeric: from 1 - very low to 5 - very high)" + }, + { + "name": "Dalc", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "workday alcohol consumption (numeric: from 1 - very low to 5 - very high)" + }, + { + "name": "Walc", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "weekend alcohol consumption (numeric: from 1 - very low to 5 - very high)" + }, + { + "name": "health", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "current health status (numeric: from 1 - very bad to 5 - very good)" + }, + { + "name": "absences", + "role": "Feature", + "type": "Integer", + "missing": 0, + "description": "number of school absences (numeric: from 0 to 93)" + }, + { + "name": "G3", + "role": "Target", + "type": "Integer", + "missing": 0, + "description": "final grade (numeric: from 0 to 20, output target)" + } + ] + } + ], + "tasks": [ + { + "task": "regression", + "key": "STUDENT_PERFORMANCE", + "runtime": "regression", + "datasets": [ + "student-mat", + "student-por" + ], + "preprocessing": [ + { + "op": "label-encoder", + "columns": [ + "school", + "sex", + "address", + "famsize", + "Pstatus", + "Mjob", + "Fjob", + "reason", + "guardian", + "schoolsup", + "famsup", + "paid", + "activities", + "nursery", + "higher", + "internet", + "romantic" + ] + }, + { + "op": "min-max", + "columns": "features" + } + ], + "models": [ + { + "id": "mat", + "format": "tfjs-layers", + "path": "models/mat/model.json", + "dataset": "student-mat", + "input": "scaled", + "metrics": { + "test_r2": -0.0438, + "test_mae": 3.7969, + "test_baseline_mae": 3.5177 + } + }, + { + "id": "por", + "format": "tfjs-layers", + "path": "models/por/model.json", + "dataset": "student-por", + "input": "scaled", + "metrics": { + "test_r2": 0.3363, + "test_mae": 1.6472, + "test_baseline_mae": 2.1751 + } + } + ], + "training": { + "layers": [ + { + "class": "dense", + "units": 32, + "activation": "sigmoid" + }, + { + "class": "dense", + "units": 16, + "activation": "sigmoid" + }, + { + "class": "dense", + "units": 1, + "activation": "linear", + "locked": true + } + ] + } + } + ] +} diff --git a/public/n4l/student-performance.n4l/models/mat/model.json b/public/n4l/student-performance.n4l/models/mat/model.json new file mode 100644 index 0000000..8eff661 --- /dev/null +++ b/public/n4l/student-performance.n4l/models/mat/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_3","layers":[{"class_name":"Dense","config":{"units":128,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1020}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense7","trainable":true,"batch_input_shape":[null,30],"dtype":"float32"}},{"class_name":"Dense","config":{"units":64,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1021}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense8","trainable":true}},{"class_name":"Dense","config":{"units":32,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1022}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense9","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1119}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense10","trainable":true}}]},"keras_version":"tfjs-layers 4.22.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.22.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense7/kernel","shape":[30,128],"dtype":"float32"},{"name":"dense_Dense7/bias","shape":[128],"dtype":"float32"},{"name":"dense_Dense8/kernel","shape":[128,64],"dtype":"float32"},{"name":"dense_Dense8/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense9/kernel","shape":[64,32],"dtype":"float32"},{"name":"dense_Dense9/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense10/kernel","shape":[32,1],"dtype":"float32"},{"name":"dense_Dense10/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/n4l/student-performance.n4l/models/mat/model.weights.bin b/public/n4l/student-performance.n4l/models/mat/model.weights.bin new file mode 100644 index 0000000..43774bf Binary files /dev/null and b/public/n4l/student-performance.n4l/models/mat/model.weights.bin differ diff --git a/public/n4l/student-performance.n4l/models/por/model.json b/public/n4l/student-performance.n4l/models/por/model.json new file mode 100644 index 0000000..dcb6e2e --- /dev/null +++ b/public/n4l/student-performance.n4l/models/por/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_4","layers":[{"class_name":"Dense","config":{"units":32,"activation":"sigmoid","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1030}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense11","trainable":true,"batch_input_shape":[null,30],"dtype":"float32"}},{"class_name":"Dense","config":{"units":16,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1031}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense12","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1129}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense13","trainable":true}}]},"keras_version":"tfjs-layers 4.22.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.22.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense11/kernel","shape":[30,32],"dtype":"float32"},{"name":"dense_Dense11/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense12/kernel","shape":[32,16],"dtype":"float32"},{"name":"dense_Dense12/bias","shape":[16],"dtype":"float32"},{"name":"dense_Dense13/kernel","shape":[16,1],"dtype":"float32"},{"name":"dense_Dense13/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/n4l/student-performance.n4l/models/por/model.weights.bin b/public/n4l/student-performance.n4l/models/por/model.weights.bin new file mode 100644 index 0000000..2cc5af3 Binary files /dev/null and b/public/n4l/student-performance.n4l/models/por/model.weights.bin differ diff --git a/public/n4l/sunspots.n4l/data/monthly-sunspots.csv b/public/n4l/sunspots.n4l/data/monthly-sunspots.csv new file mode 100644 index 0000000..a498488 --- /dev/null +++ b/public/n4l/sunspots.n4l/data/monthly-sunspots.csv @@ -0,0 +1,2821 @@ +Month,Sunspots +1749-01,58.0 +1749-02,62.6 +1749-03,70.0 +1749-04,55.7 +1749-05,85.0 +1749-06,83.5 +1749-07,94.8 +1749-08,66.3 +1749-09,75.9 +1749-10,75.5 +1749-11,158.6 +1749-12,85.2 +1750-01,73.3 +1750-02,75.9 +1750-03,89.2 +1750-04,88.3 +1750-05,90.0 +1750-06,100.0 +1750-07,85.4 +1750-08,103.0 +1750-09,91.2 +1750-10,65.7 +1750-11,63.3 +1750-12,75.4 +1751-01,70.0 +1751-02,43.5 +1751-03,45.3 +1751-04,56.4 +1751-05,60.7 +1751-06,50.7 +1751-07,66.3 +1751-08,59.8 +1751-09,23.5 +1751-10,23.2 +1751-11,28.5 +1751-12,44.0 +1752-01,35.0 +1752-02,50.0 +1752-03,71.0 +1752-04,59.3 +1752-05,59.7 +1752-06,39.6 +1752-07,78.4 +1752-08,29.3 +1752-09,27.1 +1752-10,46.6 +1752-11,37.6 +1752-12,40.0 +1753-01,44.0 +1753-02,32.0 +1753-03,45.7 +1753-04,38.0 +1753-05,36.0 +1753-06,31.7 +1753-07,22.2 +1753-08,39.0 +1753-09,28.0 +1753-10,25.0 +1753-11,20.0 +1753-12,6.7 +1754-01,0.0 +1754-02,3.0 +1754-03,1.7 +1754-04,13.7 +1754-05,20.7 +1754-06,26.7 +1754-07,18.8 +1754-08,12.3 +1754-09,8.2 +1754-10,24.1 +1754-11,13.2 +1754-12,4.2 +1755-01,10.2 +1755-02,11.2 +1755-03,6.8 +1755-04,6.5 +1755-05,0.0 +1755-06,0.0 +1755-07,8.6 +1755-08,3.2 +1755-09,17.8 +1755-10,23.7 +1755-11,6.8 +1755-12,20.0 +1756-01,12.5 +1756-02,7.1 +1756-03,5.4 +1756-04,9.4 +1756-05,12.5 +1756-06,12.9 +1756-07,3.6 +1756-08,6.4 +1756-09,11.8 +1756-10,14.3 +1756-11,17.0 +1756-12,9.4 +1757-01,14.1 +1757-02,21.2 +1757-03,26.2 +1757-04,30.0 +1757-05,38.1 +1757-06,12.8 +1757-07,25.0 +1757-08,51.3 +1757-09,39.7 +1757-10,32.5 +1757-11,64.7 +1757-12,33.5 +1758-01,37.6 +1758-02,52.0 +1758-03,49.0 +1758-04,72.3 +1758-05,46.4 +1758-06,45.0 +1758-07,44.0 +1758-08,38.7 +1758-09,62.5 +1758-10,37.7 +1758-11,43.0 +1758-12,43.0 +1759-01,48.3 +1759-02,44.0 +1759-03,46.8 +1759-04,47.0 +1759-05,49.0 +1759-06,50.0 +1759-07,51.0 +1759-08,71.3 +1759-09,77.2 +1759-10,59.7 +1759-11,46.3 +1759-12,57.0 +1760-01,67.3 +1760-02,59.5 +1760-03,74.7 +1760-04,58.3 +1760-05,72.0 +1760-06,48.3 +1760-07,66.0 +1760-08,75.6 +1760-09,61.3 +1760-10,50.6 +1760-11,59.7 +1760-12,61.0 +1761-01,70.0 +1761-02,91.0 +1761-03,80.7 +1761-04,71.7 +1761-05,107.2 +1761-06,99.3 +1761-07,94.1 +1761-08,91.1 +1761-09,100.7 +1761-10,88.7 +1761-11,89.7 +1761-12,46.0 +1762-01,43.8 +1762-02,72.8 +1762-03,45.7 +1762-04,60.2 +1762-05,39.9 +1762-06,77.1 +1762-07,33.8 +1762-08,67.7 +1762-09,68.5 +1762-10,69.3 +1762-11,77.8 +1762-12,77.2 +1763-01,56.5 +1763-02,31.9 +1763-03,34.2 +1763-04,32.9 +1763-05,32.7 +1763-06,35.8 +1763-07,54.2 +1763-08,26.5 +1763-09,68.1 +1763-10,46.3 +1763-11,60.9 +1763-12,61.4 +1764-01,59.7 +1764-02,59.7 +1764-03,40.2 +1764-04,34.4 +1764-05,44.3 +1764-06,30.0 +1764-07,30.0 +1764-08,30.0 +1764-09,28.2 +1764-10,28.0 +1764-11,26.0 +1764-12,25.7 +1765-01,24.0 +1765-02,26.0 +1765-03,25.0 +1765-04,22.0 +1765-05,20.2 +1765-06,20.0 +1765-07,27.0 +1765-08,29.7 +1765-09,16.0 +1765-10,14.0 +1765-11,14.0 +1765-12,13.0 +1766-01,12.0 +1766-02,11.0 +1766-03,36.6 +1766-04,6.0 +1766-05,26.8 +1766-06,3.0 +1766-07,3.3 +1766-08,4.0 +1766-09,4.3 +1766-10,5.0 +1766-11,5.7 +1766-12,19.2 +1767-01,27.4 +1767-02,30.0 +1767-03,43.0 +1767-04,32.9 +1767-05,29.8 +1767-06,33.3 +1767-07,21.9 +1767-08,40.8 +1767-09,42.7 +1767-10,44.1 +1767-11,54.7 +1767-12,53.3 +1768-01,53.5 +1768-02,66.1 +1768-03,46.3 +1768-04,42.7 +1768-05,77.7 +1768-06,77.4 +1768-07,52.6 +1768-08,66.8 +1768-09,74.8 +1768-10,77.8 +1768-11,90.6 +1768-12,111.8 +1769-01,73.9 +1769-02,64.2 +1769-03,64.3 +1769-04,96.7 +1769-05,73.6 +1769-06,94.4 +1769-07,118.6 +1769-08,120.3 +1769-09,148.8 +1769-10,158.2 +1769-11,148.1 +1769-12,112.0 +1770-01,104.0 +1770-02,142.5 +1770-03,80.1 +1770-04,51.0 +1770-05,70.1 +1770-06,83.3 +1770-07,109.8 +1770-08,126.3 +1770-09,104.4 +1770-10,103.6 +1770-11,132.2 +1770-12,102.3 +1771-01,36.0 +1771-02,46.2 +1771-03,46.7 +1771-04,64.9 +1771-05,152.7 +1771-06,119.5 +1771-07,67.7 +1771-08,58.5 +1771-09,101.4 +1771-10,90.0 +1771-11,99.7 +1771-12,95.7 +1772-01,100.9 +1772-02,90.8 +1772-03,31.1 +1772-04,92.2 +1772-05,38.0 +1772-06,57.0 +1772-07,77.3 +1772-08,56.2 +1772-09,50.5 +1772-10,78.6 +1772-11,61.3 +1772-12,64.0 +1773-01,54.6 +1773-02,29.0 +1773-03,51.2 +1773-04,32.9 +1773-05,41.1 +1773-06,28.4 +1773-07,27.7 +1773-08,12.7 +1773-09,29.3 +1773-10,26.3 +1773-11,40.9 +1773-12,43.2 +1774-01,46.8 +1774-02,65.4 +1774-03,55.7 +1774-04,43.8 +1774-05,51.3 +1774-06,28.5 +1774-07,17.5 +1774-08,6.6 +1774-09,7.9 +1774-10,14.0 +1774-11,17.7 +1774-12,12.2 +1775-01,4.4 +1775-02,0.0 +1775-03,11.6 +1775-04,11.2 +1775-05,3.9 +1775-06,12.3 +1775-07,1.0 +1775-08,7.9 +1775-09,3.2 +1775-10,5.6 +1775-11,15.1 +1775-12,7.9 +1776-01,21.7 +1776-02,11.6 +1776-03,6.3 +1776-04,21.8 +1776-05,11.2 +1776-06,19.0 +1776-07,1.0 +1776-08,24.2 +1776-09,16.0 +1776-10,30.0 +1776-11,35.0 +1776-12,40.0 +1777-01,45.0 +1777-02,36.5 +1777-03,39.0 +1777-04,95.5 +1777-05,80.3 +1777-06,80.7 +1777-07,95.0 +1777-08,112.0 +1777-09,116.2 +1777-10,106.5 +1777-11,146.0 +1777-12,157.3 +1778-01,177.3 +1778-02,109.3 +1778-03,134.0 +1778-04,145.0 +1778-05,238.9 +1778-06,171.6 +1778-07,153.0 +1778-08,140.0 +1778-09,171.7 +1778-10,156.3 +1778-11,150.3 +1778-12,105.0 +1779-01,114.7 +1779-02,165.7 +1779-03,118.0 +1779-04,145.0 +1779-05,140.0 +1779-06,113.7 +1779-07,143.0 +1779-08,112.0 +1779-09,111.0 +1779-10,124.0 +1779-11,114.0 +1779-12,110.0 +1780-01,70.0 +1780-02,98.0 +1780-03,98.0 +1780-04,95.0 +1780-05,107.2 +1780-06,88.0 +1780-07,86.0 +1780-08,86.0 +1780-09,93.7 +1780-10,77.0 +1780-11,60.0 +1780-12,58.7 +1781-01,98.7 +1781-02,74.7 +1781-03,53.0 +1781-04,68.3 +1781-05,104.7 +1781-06,97.7 +1781-07,73.5 +1781-08,66.0 +1781-09,51.0 +1781-10,27.3 +1781-11,67.0 +1781-12,35.2 +1782-01,54.0 +1782-02,37.5 +1782-03,37.0 +1782-04,41.0 +1782-05,54.3 +1782-06,38.0 +1782-07,37.0 +1782-08,44.0 +1782-09,34.0 +1782-10,23.2 +1782-11,31.5 +1782-12,30.0 +1783-01,28.0 +1783-02,38.7 +1783-03,26.7 +1783-04,28.3 +1783-05,23.0 +1783-06,25.2 +1783-07,32.2 +1783-08,20.0 +1783-09,18.0 +1783-10,8.0 +1783-11,15.0 +1783-12,10.5 +1784-01,13.0 +1784-02,8.0 +1784-03,11.0 +1784-04,10.0 +1784-05,6.0 +1784-06,9.0 +1784-07,6.0 +1784-08,10.0 +1784-09,10.0 +1784-10,8.0 +1784-11,17.0 +1784-12,14.0 +1785-01,6.5 +1785-02,8.0 +1785-03,9.0 +1785-04,15.7 +1785-05,20.7 +1785-06,26.3 +1785-07,36.3 +1785-08,20.0 +1785-09,32.0 +1785-10,47.2 +1785-11,40.2 +1785-12,27.3 +1786-01,37.2 +1786-02,47.6 +1786-03,47.7 +1786-04,85.4 +1786-05,92.3 +1786-06,59.0 +1786-07,83.0 +1786-08,89.7 +1786-09,111.5 +1786-10,112.3 +1786-11,116.0 +1786-12,112.7 +1787-01,134.7 +1787-02,106.0 +1787-03,87.4 +1787-04,127.2 +1787-05,134.8 +1787-06,99.2 +1787-07,128.0 +1787-08,137.2 +1787-09,157.3 +1787-10,157.0 +1787-11,141.5 +1787-12,174.0 +1788-01,138.0 +1788-02,129.2 +1788-03,143.3 +1788-04,108.5 +1788-05,113.0 +1788-06,154.2 +1788-07,141.5 +1788-08,136.0 +1788-09,141.0 +1788-10,142.0 +1788-11,94.7 +1788-12,129.5 +1789-01,114.0 +1789-02,125.3 +1789-03,120.0 +1789-04,123.3 +1789-05,123.5 +1789-06,120.0 +1789-07,117.0 +1789-08,103.0 +1789-09,112.0 +1789-10,89.7 +1789-11,134.0 +1789-12,135.5 +1790-01,103.0 +1790-02,127.5 +1790-03,96.3 +1790-04,94.0 +1790-05,93.0 +1790-06,91.0 +1790-07,69.3 +1790-08,87.0 +1790-09,77.3 +1790-10,84.3 +1790-11,82.0 +1790-12,74.0 +1791-01,72.7 +1791-02,62.0 +1791-03,74.0 +1791-04,77.2 +1791-05,73.7 +1791-06,64.2 +1791-07,71.0 +1791-08,43.0 +1791-09,66.5 +1791-10,61.7 +1791-11,67.0 +1791-12,66.0 +1792-01,58.0 +1792-02,64.0 +1792-03,63.0 +1792-04,75.7 +1792-05,62.0 +1792-06,61.0 +1792-07,45.8 +1792-08,60.0 +1792-09,59.0 +1792-10,59.0 +1792-11,57.0 +1792-12,56.0 +1793-01,56.0 +1793-02,55.0 +1793-03,55.5 +1793-04,53.0 +1793-05,52.3 +1793-06,51.0 +1793-07,50.0 +1793-08,29.3 +1793-09,24.0 +1793-10,47.0 +1793-11,44.0 +1793-12,45.7 +1794-01,45.0 +1794-02,44.0 +1794-03,38.0 +1794-04,28.4 +1794-05,55.7 +1794-06,41.5 +1794-07,41.0 +1794-08,40.0 +1794-09,11.1 +1794-10,28.5 +1794-11,67.4 +1794-12,51.4 +1795-01,21.4 +1795-02,39.9 +1795-03,12.6 +1795-04,18.6 +1795-05,31.0 +1795-06,17.1 +1795-07,12.9 +1795-08,25.7 +1795-09,13.5 +1795-10,19.5 +1795-11,25.0 +1795-12,18.0 +1796-01,22.0 +1796-02,23.8 +1796-03,15.7 +1796-04,31.7 +1796-05,21.0 +1796-06,6.7 +1796-07,26.9 +1796-08,1.5 +1796-09,18.4 +1796-10,11.0 +1796-11,8.4 +1796-12,5.1 +1797-01,14.4 +1797-02,4.2 +1797-03,4.0 +1797-04,4.0 +1797-05,7.3 +1797-06,11.1 +1797-07,4.3 +1797-08,6.0 +1797-09,5.7 +1797-10,6.9 +1797-11,5.8 +1797-12,3.0 +1798-01,2.0 +1798-02,4.0 +1798-03,12.4 +1798-04,1.1 +1798-05,0.0 +1798-06,0.0 +1798-07,0.0 +1798-08,3.0 +1798-09,2.4 +1798-10,1.5 +1798-11,12.5 +1798-12,9.9 +1799-01,1.6 +1799-02,12.6 +1799-03,21.7 +1799-04,8.4 +1799-05,8.2 +1799-06,10.6 +1799-07,2.1 +1799-08,0.0 +1799-09,0.0 +1799-10,4.6 +1799-11,2.7 +1799-12,8.6 +1800-01,6.9 +1800-02,9.3 +1800-03,13.9 +1800-04,0.0 +1800-05,5.0 +1800-06,23.7 +1800-07,21.0 +1800-08,19.5 +1800-09,11.5 +1800-10,12.3 +1800-11,10.5 +1800-12,40.1 +1801-01,27.0 +1801-02,29.0 +1801-03,30.0 +1801-04,31.0 +1801-05,32.0 +1801-06,31.2 +1801-07,35.0 +1801-08,38.7 +1801-09,33.5 +1801-10,32.6 +1801-11,39.8 +1801-12,48.2 +1802-01,47.8 +1802-02,47.0 +1802-03,40.8 +1802-04,42.0 +1802-05,44.0 +1802-06,46.0 +1802-07,48.0 +1802-08,50.0 +1802-09,51.8 +1802-10,38.5 +1802-11,34.5 +1802-12,50.0 +1803-01,50.0 +1803-02,50.8 +1803-03,29.5 +1803-04,25.0 +1803-05,44.3 +1803-06,36.0 +1803-07,48.3 +1803-08,34.1 +1803-09,45.3 +1803-10,54.3 +1803-11,51.0 +1803-12,48.0 +1804-01,45.3 +1804-02,48.3 +1804-03,48.0 +1804-04,50.6 +1804-05,33.4 +1804-06,34.8 +1804-07,29.8 +1804-08,43.1 +1804-09,53.0 +1804-10,62.3 +1804-11,61.0 +1804-12,60.0 +1805-01,61.0 +1805-02,44.1 +1805-03,51.4 +1805-04,37.5 +1805-05,39.0 +1805-06,40.5 +1805-07,37.6 +1805-08,42.7 +1805-09,44.4 +1805-10,29.4 +1805-11,41.0 +1805-12,38.3 +1806-01,39.0 +1806-02,29.6 +1806-03,32.7 +1806-04,27.7 +1806-05,26.4 +1806-06,25.6 +1806-07,30.0 +1806-08,26.3 +1806-09,24.0 +1806-10,27.0 +1806-11,25.0 +1806-12,24.0 +1807-01,12.0 +1807-02,12.2 +1807-03,9.6 +1807-04,23.8 +1807-05,10.0 +1807-06,12.0 +1807-07,12.7 +1807-08,12.0 +1807-09,5.7 +1807-10,8.0 +1807-11,2.6 +1807-12,0.0 +1808-01,0.0 +1808-02,4.5 +1808-03,0.0 +1808-04,12.3 +1808-05,13.5 +1808-06,13.5 +1808-07,6.7 +1808-08,8.0 +1808-09,11.7 +1808-10,4.7 +1808-11,10.5 +1808-12,12.3 +1809-01,7.2 +1809-02,9.2 +1809-03,0.9 +1809-04,2.5 +1809-05,2.0 +1809-06,7.7 +1809-07,0.3 +1809-08,0.2 +1809-09,0.4 +1809-10,0.0 +1809-11,0.0 +1809-12,0.0 +1810-01,0.0 +1810-02,0.0 +1810-03,0.0 +1810-04,0.0 +1810-05,0.0 +1810-06,0.0 +1810-07,0.0 +1810-08,0.0 +1810-09,0.0 +1810-10,0.0 +1810-11,0.0 +1810-12,0.0 +1811-01,0.0 +1811-02,0.0 +1811-03,0.0 +1811-04,0.0 +1811-05,0.0 +1811-06,0.0 +1811-07,6.6 +1811-08,0.0 +1811-09,2.4 +1811-10,6.1 +1811-11,0.8 +1811-12,1.1 +1812-01,11.3 +1812-02,1.9 +1812-03,0.7 +1812-04,0.0 +1812-05,1.0 +1812-06,1.3 +1812-07,0.5 +1812-08,15.6 +1812-09,5.2 +1812-10,3.9 +1812-11,7.9 +1812-12,10.1 +1813-01,0.0 +1813-02,10.3 +1813-03,1.9 +1813-04,16.6 +1813-05,5.5 +1813-06,11.2 +1813-07,18.3 +1813-08,8.4 +1813-09,15.3 +1813-10,27.8 +1813-11,16.7 +1813-12,14.3 +1814-01,22.2 +1814-02,12.0 +1814-03,5.7 +1814-04,23.8 +1814-05,5.8 +1814-06,14.9 +1814-07,18.5 +1814-08,2.3 +1814-09,8.1 +1814-10,19.3 +1814-11,14.5 +1814-12,20.1 +1815-01,19.2 +1815-02,32.2 +1815-03,26.2 +1815-04,31.6 +1815-05,9.8 +1815-06,55.9 +1815-07,35.5 +1815-08,47.2 +1815-09,31.5 +1815-10,33.5 +1815-11,37.2 +1815-12,65.0 +1816-01,26.3 +1816-02,68.8 +1816-03,73.7 +1816-04,58.8 +1816-05,44.3 +1816-06,43.6 +1816-07,38.8 +1816-08,23.2 +1816-09,47.8 +1816-10,56.4 +1816-11,38.1 +1816-12,29.9 +1817-01,36.4 +1817-02,57.9 +1817-03,96.2 +1817-04,26.4 +1817-05,21.2 +1817-06,40.0 +1817-07,50.0 +1817-08,45.0 +1817-09,36.7 +1817-10,25.6 +1817-11,28.9 +1817-12,28.4 +1818-01,34.9 +1818-02,22.4 +1818-03,25.4 +1818-04,34.5 +1818-05,53.1 +1818-06,36.4 +1818-07,28.0 +1818-08,31.5 +1818-09,26.1 +1818-10,31.7 +1818-11,10.9 +1818-12,25.8 +1819-01,32.5 +1819-02,20.7 +1819-03,3.7 +1819-04,20.2 +1819-05,19.6 +1819-06,35.0 +1819-07,31.4 +1819-08,26.1 +1819-09,14.9 +1819-10,27.5 +1819-11,25.1 +1819-12,30.6 +1820-01,19.2 +1820-02,26.6 +1820-03,4.5 +1820-04,19.4 +1820-05,29.3 +1820-06,10.8 +1820-07,20.6 +1820-08,25.9 +1820-09,5.2 +1820-10,9.0 +1820-11,7.9 +1820-12,9.7 +1821-01,21.5 +1821-02,4.3 +1821-03,5.7 +1821-04,9.2 +1821-05,1.7 +1821-06,1.8 +1821-07,2.5 +1821-08,4.8 +1821-09,4.4 +1821-10,18.8 +1821-11,4.4 +1821-12,0.0 +1822-01,0.0 +1822-02,0.9 +1822-03,16.1 +1822-04,13.5 +1822-05,1.5 +1822-06,5.6 +1822-07,7.9 +1822-08,2.1 +1822-09,0.0 +1822-10,0.4 +1822-11,0.0 +1822-12,0.0 +1823-01,0.0 +1823-02,0.0 +1823-03,0.6 +1823-04,0.0 +1823-05,0.0 +1823-06,0.0 +1823-07,0.5 +1823-08,0.0 +1823-09,0.0 +1823-10,0.0 +1823-11,0.0 +1823-12,20.4 +1824-01,21.6 +1824-02,10.8 +1824-03,0.0 +1824-04,19.4 +1824-05,2.8 +1824-06,0.0 +1824-07,0.0 +1824-08,1.4 +1824-09,20.5 +1824-10,25.2 +1824-11,0.0 +1824-12,0.8 +1825-01,5.0 +1825-02,15.5 +1825-03,22.4 +1825-04,3.8 +1825-05,15.4 +1825-06,15.4 +1825-07,30.9 +1825-08,25.4 +1825-09,15.7 +1825-10,15.6 +1825-11,11.7 +1825-12,22.0 +1826-01,17.7 +1826-02,18.2 +1826-03,36.7 +1826-04,24.0 +1826-05,32.4 +1826-06,37.1 +1826-07,52.5 +1826-08,39.6 +1826-09,18.9 +1826-10,50.6 +1826-11,39.5 +1826-12,68.1 +1827-01,34.6 +1827-02,47.4 +1827-03,57.8 +1827-04,46.0 +1827-05,56.3 +1827-06,56.7 +1827-07,42.9 +1827-08,53.7 +1827-09,49.6 +1827-10,57.2 +1827-11,48.2 +1827-12,46.1 +1828-01,52.8 +1828-02,64.4 +1828-03,65.0 +1828-04,61.1 +1828-05,89.1 +1828-06,98.0 +1828-07,54.3 +1828-08,76.4 +1828-09,50.4 +1828-10,54.7 +1828-11,57.0 +1828-12,46.6 +1829-01,43.0 +1829-02,49.4 +1829-03,72.3 +1829-04,95.0 +1829-05,67.5 +1829-06,73.9 +1829-07,90.8 +1829-08,78.3 +1829-09,52.8 +1829-10,57.2 +1829-11,67.6 +1829-12,56.5 +1830-01,52.2 +1830-02,72.1 +1830-03,84.6 +1830-04,107.1 +1830-05,66.3 +1830-06,65.1 +1830-07,43.9 +1830-08,50.7 +1830-09,62.1 +1830-10,84.4 +1830-11,81.2 +1830-12,82.1 +1831-01,47.5 +1831-02,50.1 +1831-03,93.4 +1831-04,54.6 +1831-05,38.1 +1831-06,33.4 +1831-07,45.2 +1831-08,54.9 +1831-09,37.9 +1831-10,46.2 +1831-11,43.5 +1831-12,28.9 +1832-01,30.9 +1832-02,55.5 +1832-03,55.1 +1832-04,26.9 +1832-05,41.3 +1832-06,26.7 +1832-07,13.9 +1832-08,8.9 +1832-09,8.2 +1832-10,21.1 +1832-11,14.3 +1832-12,27.5 +1833-01,11.3 +1833-02,14.9 +1833-03,11.8 +1833-04,2.8 +1833-05,12.9 +1833-06,1.0 +1833-07,7.0 +1833-08,5.7 +1833-09,11.6 +1833-10,7.5 +1833-11,5.9 +1833-12,9.9 +1834-01,4.9 +1834-02,18.1 +1834-03,3.9 +1834-04,1.4 +1834-05,8.8 +1834-06,7.8 +1834-07,8.7 +1834-08,4.0 +1834-09,11.5 +1834-10,24.8 +1834-11,30.5 +1834-12,34.5 +1835-01,7.5 +1835-02,24.5 +1835-03,19.7 +1835-04,61.5 +1835-05,43.6 +1835-06,33.2 +1835-07,59.8 +1835-08,59.0 +1835-09,100.8 +1835-10,95.2 +1835-11,100.0 +1835-12,77.5 +1836-01,88.6 +1836-02,107.6 +1836-03,98.1 +1836-04,142.9 +1836-05,111.4 +1836-06,124.7 +1836-07,116.7 +1836-08,107.8 +1836-09,95.1 +1836-10,137.4 +1836-11,120.9 +1836-12,206.2 +1837-01,188.0 +1837-02,175.6 +1837-03,134.6 +1837-04,138.2 +1837-05,111.3 +1837-06,158.0 +1837-07,162.8 +1837-08,134.0 +1837-09,96.3 +1837-10,123.7 +1837-11,107.0 +1837-12,129.8 +1838-01,144.9 +1838-02,84.8 +1838-03,140.8 +1838-04,126.6 +1838-05,137.6 +1838-06,94.5 +1838-07,108.2 +1838-08,78.8 +1838-09,73.6 +1838-10,90.8 +1838-11,77.4 +1838-12,79.8 +1839-01,107.6 +1839-02,102.5 +1839-03,77.7 +1839-04,61.8 +1839-05,53.8 +1839-06,54.6 +1839-07,84.7 +1839-08,131.2 +1839-09,132.7 +1839-10,90.8 +1839-11,68.8 +1839-12,63.6 +1840-01,81.2 +1840-02,87.7 +1840-03,55.5 +1840-04,65.9 +1840-05,69.2 +1840-06,48.5 +1840-07,60.7 +1840-08,57.8 +1840-09,74.0 +1840-10,49.8 +1840-11,54.3 +1840-12,53.7 +1841-01,24.0 +1841-02,29.9 +1841-03,29.7 +1841-04,42.6 +1841-05,67.4 +1841-06,55.7 +1841-07,30.8 +1841-08,39.3 +1841-09,35.1 +1841-10,28.5 +1841-11,19.8 +1841-12,38.8 +1842-01,20.4 +1842-02,22.1 +1842-03,21.7 +1842-04,26.9 +1842-05,24.9 +1842-06,20.5 +1842-07,12.6 +1842-08,26.5 +1842-09,18.5 +1842-10,38.1 +1842-11,40.5 +1842-12,17.6 +1843-01,13.3 +1843-02,3.5 +1843-03,8.3 +1843-04,8.8 +1843-05,21.1 +1843-06,10.5 +1843-07,9.5 +1843-08,11.8 +1843-09,4.2 +1843-10,5.3 +1843-11,19.1 +1843-12,12.7 +1844-01,9.4 +1844-02,14.7 +1844-03,13.6 +1844-04,20.8 +1844-05,12.0 +1844-06,3.7 +1844-07,21.2 +1844-08,23.9 +1844-09,6.9 +1844-10,21.5 +1844-11,10.7 +1844-12,21.6 +1845-01,25.7 +1845-02,43.6 +1845-03,43.3 +1845-04,56.9 +1845-05,47.8 +1845-06,31.1 +1845-07,30.6 +1845-08,32.3 +1845-09,29.6 +1845-10,40.7 +1845-11,39.4 +1845-12,59.7 +1846-01,38.7 +1846-02,51.0 +1846-03,63.9 +1846-04,69.2 +1846-05,59.9 +1846-06,65.1 +1846-07,46.5 +1846-08,54.8 +1846-09,107.1 +1846-10,55.9 +1846-11,60.4 +1846-12,65.5 +1847-01,62.6 +1847-02,44.9 +1847-03,85.7 +1847-04,44.7 +1847-05,75.4 +1847-06,85.3 +1847-07,52.2 +1847-08,140.6 +1847-09,161.2 +1847-10,180.4 +1847-11,138.9 +1847-12,109.6 +1848-01,159.1 +1848-02,111.8 +1848-03,108.9 +1848-04,107.1 +1848-05,102.2 +1848-06,123.8 +1848-07,139.2 +1848-08,132.5 +1848-09,100.3 +1848-10,132.4 +1848-11,114.6 +1848-12,159.9 +1849-01,156.7 +1849-02,131.7 +1849-03,96.5 +1849-04,102.5 +1849-05,80.6 +1849-06,81.2 +1849-07,78.0 +1849-08,61.3 +1849-09,93.7 +1849-10,71.5 +1849-11,99.7 +1849-12,97.0 +1850-01,78.0 +1850-02,89.4 +1850-03,82.6 +1850-04,44.1 +1850-05,61.6 +1850-06,70.0 +1850-07,39.1 +1850-08,61.6 +1850-09,86.2 +1850-10,71.0 +1850-11,54.8 +1850-12,60.0 +1851-01,75.5 +1851-02,105.4 +1851-03,64.6 +1851-04,56.5 +1851-05,62.6 +1851-06,63.2 +1851-07,36.1 +1851-08,57.4 +1851-09,67.9 +1851-10,62.5 +1851-11,50.9 +1851-12,71.4 +1852-01,68.4 +1852-02,67.5 +1852-03,61.2 +1852-04,65.4 +1852-05,54.9 +1852-06,46.9 +1852-07,42.0 +1852-08,39.7 +1852-09,37.5 +1852-10,67.3 +1852-11,54.3 +1852-12,45.4 +1853-01,41.1 +1853-02,42.9 +1853-03,37.7 +1853-04,47.6 +1853-05,34.7 +1853-06,40.0 +1853-07,45.9 +1853-08,50.4 +1853-09,33.5 +1853-10,42.3 +1853-11,28.8 +1853-12,23.4 +1854-01,15.4 +1854-02,20.0 +1854-03,20.7 +1854-04,26.4 +1854-05,24.0 +1854-06,21.1 +1854-07,18.7 +1854-08,15.8 +1854-09,22.4 +1854-10,12.7 +1854-11,28.2 +1854-12,21.4 +1855-01,12.3 +1855-02,11.4 +1855-03,17.4 +1855-04,4.4 +1855-05,9.1 +1855-06,5.3 +1855-07,0.4 +1855-08,3.1 +1855-09,0.0 +1855-10,9.7 +1855-11,4.3 +1855-12,3.1 +1856-01,0.5 +1856-02,4.9 +1856-03,0.4 +1856-04,6.5 +1856-05,0.0 +1856-06,5.0 +1856-07,4.6 +1856-08,5.9 +1856-09,4.4 +1856-10,4.5 +1856-11,7.7 +1856-12,7.2 +1857-01,13.7 +1857-02,7.4 +1857-03,5.2 +1857-04,11.1 +1857-05,29.2 +1857-06,16.0 +1857-07,22.2 +1857-08,16.9 +1857-09,42.4 +1857-10,40.6 +1857-11,31.4 +1857-12,37.2 +1858-01,39.0 +1858-02,34.9 +1858-03,57.5 +1858-04,38.3 +1858-05,41.4 +1858-06,44.5 +1858-07,56.7 +1858-08,55.3 +1858-09,80.1 +1858-10,91.2 +1858-11,51.9 +1858-12,66.9 +1859-01,83.7 +1859-02,87.6 +1859-03,90.3 +1859-04,85.7 +1859-05,91.0 +1859-06,87.1 +1859-07,95.2 +1859-08,106.8 +1859-09,105.8 +1859-10,114.6 +1859-11,97.2 +1859-12,81.0 +1860-01,81.5 +1860-02,88.0 +1860-03,98.9 +1860-04,71.4 +1860-05,107.1 +1860-06,108.6 +1860-07,116.7 +1860-08,100.3 +1860-09,92.2 +1860-10,90.1 +1860-11,97.9 +1860-12,95.6 +1861-01,62.3 +1861-02,77.8 +1861-03,101.0 +1861-04,98.5 +1861-05,56.8 +1861-06,87.8 +1861-07,78.0 +1861-08,82.5 +1861-09,79.9 +1861-10,67.2 +1861-11,53.7 +1861-12,80.5 +1862-01,63.1 +1862-02,64.5 +1862-03,43.6 +1862-04,53.7 +1862-05,64.4 +1862-06,84.0 +1862-07,73.4 +1862-08,62.5 +1862-09,66.6 +1862-10,42.0 +1862-11,50.6 +1862-12,40.9 +1863-01,48.3 +1863-02,56.7 +1863-03,66.4 +1863-04,40.6 +1863-05,53.8 +1863-06,40.8 +1863-07,32.7 +1863-08,48.1 +1863-09,22.0 +1863-10,39.9 +1863-11,37.7 +1863-12,41.2 +1864-01,57.7 +1864-02,47.1 +1864-03,66.3 +1864-04,35.8 +1864-05,40.6 +1864-06,57.8 +1864-07,54.7 +1864-08,54.8 +1864-09,28.5 +1864-10,33.9 +1864-11,57.6 +1864-12,28.6 +1865-01,48.7 +1865-02,39.3 +1865-03,39.5 +1865-04,29.4 +1865-05,34.5 +1865-06,33.6 +1865-07,26.8 +1865-08,37.8 +1865-09,21.6 +1865-10,17.1 +1865-11,24.6 +1865-12,12.8 +1866-01,31.6 +1866-02,38.4 +1866-03,24.6 +1866-04,17.6 +1866-05,12.9 +1866-06,16.5 +1866-07,9.3 +1866-08,12.7 +1866-09,7.3 +1866-10,14.1 +1866-11,9.0 +1866-12,1.5 +1867-01,0.0 +1867-02,0.7 +1867-03,9.2 +1867-04,5.1 +1867-05,2.9 +1867-06,1.5 +1867-07,5.0 +1867-08,4.9 +1867-09,9.8 +1867-10,13.5 +1867-11,9.3 +1867-12,25.2 +1868-01,15.6 +1868-02,15.8 +1868-03,26.5 +1868-04,36.6 +1868-05,26.7 +1868-06,31.1 +1868-07,28.6 +1868-08,34.4 +1868-09,43.8 +1868-10,61.7 +1868-11,59.1 +1868-12,67.6 +1869-01,60.9 +1869-02,59.3 +1869-03,52.7 +1869-04,41.0 +1869-05,104.0 +1869-06,108.4 +1869-07,59.2 +1869-08,79.6 +1869-09,80.6 +1869-10,59.4 +1869-11,77.4 +1869-12,104.3 +1870-01,77.3 +1870-02,114.9 +1870-03,159.4 +1870-04,160.0 +1870-05,176.0 +1870-06,135.6 +1870-07,132.4 +1870-08,153.8 +1870-09,136.0 +1870-10,146.4 +1870-11,147.5 +1870-12,130.0 +1871-01,88.3 +1871-02,125.3 +1871-03,143.2 +1871-04,162.4 +1871-05,145.5 +1871-06,91.7 +1871-07,103.0 +1871-08,110.0 +1871-09,80.3 +1871-10,89.0 +1871-11,105.4 +1871-12,90.3 +1872-01,79.5 +1872-02,120.1 +1872-03,88.4 +1872-04,102.1 +1872-05,107.6 +1872-06,109.9 +1872-07,105.5 +1872-08,92.9 +1872-09,114.6 +1872-10,103.5 +1872-11,112.0 +1872-12,83.9 +1873-01,86.7 +1873-02,107.0 +1873-03,98.3 +1873-04,76.2 +1873-05,47.9 +1873-06,44.8 +1873-07,66.9 +1873-08,68.2 +1873-09,47.5 +1873-10,47.4 +1873-11,55.4 +1873-12,49.2 +1874-01,60.8 +1874-02,64.2 +1874-03,46.4 +1874-04,32.0 +1874-05,44.6 +1874-06,38.2 +1874-07,67.8 +1874-08,61.3 +1874-09,28.0 +1874-10,34.3 +1874-11,28.9 +1874-12,29.3 +1875-01,14.6 +1875-02,22.2 +1875-03,33.8 +1875-04,29.1 +1875-05,11.5 +1875-06,23.9 +1875-07,12.5 +1875-08,14.6 +1875-09,2.4 +1875-10,12.7 +1875-11,17.7 +1875-12,9.9 +1876-01,14.3 +1876-02,15.0 +1876-03,31.2 +1876-04,2.3 +1876-05,5.1 +1876-06,1.6 +1876-07,15.2 +1876-08,8.8 +1876-09,9.9 +1876-10,14.3 +1876-11,9.9 +1876-12,8.2 +1877-01,24.4 +1877-02,8.7 +1877-03,11.7 +1877-04,15.8 +1877-05,21.2 +1877-06,13.4 +1877-07,5.9 +1877-08,6.3 +1877-09,16.4 +1877-10,6.7 +1877-11,14.5 +1877-12,2.3 +1878-01,3.3 +1878-02,6.0 +1878-03,7.8 +1878-04,0.1 +1878-05,5.8 +1878-06,6.4 +1878-07,0.1 +1878-08,0.0 +1878-09,5.3 +1878-10,1.1 +1878-11,4.1 +1878-12,0.5 +1879-01,0.8 +1879-02,0.6 +1879-03,0.0 +1879-04,6.2 +1879-05,2.4 +1879-06,4.8 +1879-07,7.5 +1879-08,10.7 +1879-09,6.1 +1879-10,12.3 +1879-11,12.9 +1879-12,7.2 +1880-01,24.0 +1880-02,27.5 +1880-03,19.5 +1880-04,19.3 +1880-05,23.5 +1880-06,34.1 +1880-07,21.9 +1880-08,48.1 +1880-09,66.0 +1880-10,43.0 +1880-11,30.7 +1880-12,29.6 +1881-01,36.4 +1881-02,53.2 +1881-03,51.5 +1881-04,51.7 +1881-05,43.5 +1881-06,60.5 +1881-07,76.9 +1881-08,58.0 +1881-09,53.2 +1881-10,64.0 +1881-11,54.8 +1881-12,47.3 +1882-01,45.0 +1882-02,69.3 +1882-03,67.5 +1882-04,95.8 +1882-05,64.1 +1882-06,45.2 +1882-07,45.4 +1882-08,40.4 +1882-09,57.7 +1882-10,59.2 +1882-11,84.4 +1882-12,41.8 +1883-01,60.6 +1883-02,46.9 +1883-03,42.8 +1883-04,82.1 +1883-05,32.1 +1883-06,76.5 +1883-07,80.6 +1883-08,46.0 +1883-09,52.6 +1883-10,83.8 +1883-11,84.5 +1883-12,75.9 +1884-01,91.5 +1884-02,86.9 +1884-03,86.8 +1884-04,76.1 +1884-05,66.5 +1884-06,51.2 +1884-07,53.1 +1884-08,55.8 +1884-09,61.9 +1884-10,47.8 +1884-11,36.6 +1884-12,47.2 +1885-01,42.8 +1885-02,71.8 +1885-03,49.8 +1885-04,55.0 +1885-05,73.0 +1885-06,83.7 +1885-07,66.5 +1885-08,50.0 +1885-09,39.6 +1885-10,38.7 +1885-11,33.3 +1885-12,21.7 +1886-01,29.9 +1886-02,25.9 +1886-03,57.3 +1886-04,43.7 +1886-05,30.7 +1886-06,27.1 +1886-07,30.3 +1886-08,16.9 +1886-09,21.4 +1886-10,8.6 +1886-11,0.3 +1886-12,12.4 +1887-01,10.3 +1887-02,13.2 +1887-03,4.2 +1887-04,6.9 +1887-05,20.0 +1887-06,15.7 +1887-07,23.3 +1887-08,21.4 +1887-09,7.4 +1887-10,6.6 +1887-11,6.9 +1887-12,20.7 +1888-01,12.7 +1888-02,7.1 +1888-03,7.8 +1888-04,5.1 +1888-05,7.0 +1888-06,7.1 +1888-07,3.1 +1888-08,2.8 +1888-09,8.8 +1888-10,2.1 +1888-11,10.7 +1888-12,6.7 +1889-01,0.8 +1889-02,8.5 +1889-03,7.0 +1889-04,4.3 +1889-05,2.4 +1889-06,6.4 +1889-07,9.7 +1889-08,20.6 +1889-09,6.5 +1889-10,2.1 +1889-11,0.2 +1889-12,6.7 +1890-01,5.3 +1890-02,0.6 +1890-03,5.1 +1890-04,1.6 +1890-05,4.8 +1890-06,1.3 +1890-07,11.6 +1890-08,8.5 +1890-09,17.2 +1890-10,11.2 +1890-11,9.6 +1890-12,7.8 +1891-01,13.5 +1891-02,22.2 +1891-03,10.4 +1891-04,20.5 +1891-05,41.1 +1891-06,48.3 +1891-07,58.8 +1891-08,33.2 +1891-09,53.8 +1891-10,51.5 +1891-11,41.9 +1891-12,32.3 +1892-01,69.1 +1892-02,75.6 +1892-03,49.9 +1892-04,69.6 +1892-05,79.6 +1892-06,76.3 +1892-07,76.8 +1892-08,101.4 +1892-09,62.8 +1892-10,70.5 +1892-11,65.4 +1892-12,78.6 +1893-01,75.0 +1893-02,73.0 +1893-03,65.7 +1893-04,88.1 +1893-05,84.7 +1893-06,88.2 +1893-07,88.8 +1893-08,129.2 +1893-09,77.9 +1893-10,79.7 +1893-11,75.1 +1893-12,93.8 +1894-01,83.2 +1894-02,84.6 +1894-03,52.3 +1894-04,81.6 +1894-05,101.2 +1894-06,98.9 +1894-07,106.0 +1894-08,70.3 +1894-09,65.9 +1894-10,75.5 +1894-11,56.6 +1894-12,60.0 +1895-01,63.3 +1895-02,67.2 +1895-03,61.0 +1895-04,76.9 +1895-05,67.5 +1895-06,71.5 +1895-07,47.8 +1895-08,68.9 +1895-09,57.7 +1895-10,67.9 +1895-11,47.2 +1895-12,70.7 +1896-01,29.0 +1896-02,57.4 +1896-03,52.0 +1896-04,43.8 +1896-05,27.7 +1896-06,49.0 +1896-07,45.0 +1896-08,27.2 +1896-09,61.3 +1896-10,28.4 +1896-11,38.0 +1896-12,42.6 +1897-01,40.6 +1897-02,29.4 +1897-03,29.1 +1897-04,31.0 +1897-05,20.0 +1897-06,11.3 +1897-07,27.6 +1897-08,21.8 +1897-09,48.1 +1897-10,14.3 +1897-11,8.4 +1897-12,33.3 +1898-01,30.2 +1898-02,36.4 +1898-03,38.3 +1898-04,14.5 +1898-05,25.8 +1898-06,22.3 +1898-07,9.0 +1898-08,31.4 +1898-09,34.8 +1898-10,34.4 +1898-11,30.9 +1898-12,12.6 +1899-01,19.5 +1899-02,9.2 +1899-03,18.1 +1899-04,14.2 +1899-05,7.7 +1899-06,20.5 +1899-07,13.5 +1899-08,2.9 +1899-09,8.4 +1899-10,13.0 +1899-11,7.8 +1899-12,10.5 +1900-01,9.4 +1900-02,13.6 +1900-03,8.6 +1900-04,16.0 +1900-05,15.2 +1900-06,12.1 +1900-07,8.3 +1900-08,4.3 +1900-09,8.3 +1900-10,12.9 +1900-11,4.5 +1900-12,0.3 +1901-01,0.2 +1901-02,2.4 +1901-03,4.5 +1901-04,0.0 +1901-05,10.2 +1901-06,5.8 +1901-07,0.7 +1901-08,1.0 +1901-09,0.6 +1901-10,3.7 +1901-11,3.8 +1901-12,0.0 +1902-01,5.2 +1902-02,0.0 +1902-03,12.4 +1902-04,0.0 +1902-05,2.8 +1902-06,1.4 +1902-07,0.9 +1902-08,2.3 +1902-09,7.6 +1902-10,16.3 +1902-11,10.3 +1902-12,1.1 +1903-01,8.3 +1903-02,17.0 +1903-03,13.5 +1903-04,26.1 +1903-05,14.6 +1903-06,16.3 +1903-07,27.9 +1903-08,28.8 +1903-09,11.1 +1903-10,38.9 +1903-11,44.5 +1903-12,45.6 +1904-01,31.6 +1904-02,24.5 +1904-03,37.2 +1904-04,43.0 +1904-05,39.5 +1904-06,41.9 +1904-07,50.6 +1904-08,58.2 +1904-09,30.1 +1904-10,54.2 +1904-11,38.0 +1904-12,54.6 +1905-01,54.8 +1905-02,85.8 +1905-03,56.5 +1905-04,39.3 +1905-05,48.0 +1905-06,49.0 +1905-07,73.0 +1905-08,58.8 +1905-09,55.0 +1905-10,78.7 +1905-11,107.2 +1905-12,55.5 +1906-01,45.5 +1906-02,31.3 +1906-03,64.5 +1906-04,55.3 +1906-05,57.7 +1906-06,63.2 +1906-07,103.6 +1906-08,47.7 +1906-09,56.1 +1906-10,17.8 +1906-11,38.9 +1906-12,64.7 +1907-01,76.4 +1907-02,108.2 +1907-03,60.7 +1907-04,52.6 +1907-05,42.9 +1907-06,40.4 +1907-07,49.7 +1907-08,54.3 +1907-09,85.0 +1907-10,65.4 +1907-11,61.5 +1907-12,47.3 +1908-01,39.2 +1908-02,33.9 +1908-03,28.7 +1908-04,57.6 +1908-05,40.8 +1908-06,48.1 +1908-07,39.5 +1908-08,90.5 +1908-09,86.9 +1908-10,32.3 +1908-11,45.5 +1908-12,39.5 +1909-01,56.7 +1909-02,46.6 +1909-03,66.3 +1909-04,32.3 +1909-05,36.0 +1909-06,22.6 +1909-07,35.8 +1909-08,23.1 +1909-09,38.8 +1909-10,58.4 +1909-11,55.8 +1909-12,54.2 +1910-01,26.4 +1910-02,31.5 +1910-03,21.4 +1910-04,8.4 +1910-05,22.2 +1910-06,12.3 +1910-07,14.1 +1910-08,11.5 +1910-09,26.2 +1910-10,38.3 +1910-11,4.9 +1910-12,5.8 +1911-01,3.4 +1911-02,9.0 +1911-03,7.8 +1911-04,16.5 +1911-05,9.0 +1911-06,2.2 +1911-07,3.5 +1911-08,4.0 +1911-09,4.0 +1911-10,2.6 +1911-11,4.2 +1911-12,2.2 +1912-01,0.3 +1912-02,0.0 +1912-03,4.9 +1912-04,4.5 +1912-05,4.4 +1912-06,4.1 +1912-07,3.0 +1912-08,0.3 +1912-09,9.5 +1912-10,4.6 +1912-11,1.1 +1912-12,6.4 +1913-01,2.3 +1913-02,2.9 +1913-03,0.5 +1913-04,0.9 +1913-05,0.0 +1913-06,0.0 +1913-07,1.7 +1913-08,0.2 +1913-09,1.2 +1913-10,3.1 +1913-11,0.7 +1913-12,3.8 +1914-01,2.8 +1914-02,2.6 +1914-03,3.1 +1914-04,17.3 +1914-05,5.2 +1914-06,11.4 +1914-07,5.4 +1914-08,7.7 +1914-09,12.7 +1914-10,8.2 +1914-11,16.4 +1914-12,22.3 +1915-01,23.0 +1915-02,42.3 +1915-03,38.8 +1915-04,41.3 +1915-05,33.0 +1915-06,68.8 +1915-07,71.6 +1915-08,69.6 +1915-09,49.5 +1915-10,53.5 +1915-11,42.5 +1915-12,34.5 +1916-01,45.3 +1916-02,55.4 +1916-03,67.0 +1916-04,71.8 +1916-05,74.5 +1916-06,67.7 +1916-07,53.5 +1916-08,35.2 +1916-09,45.1 +1916-10,50.7 +1916-11,65.6 +1916-12,53.0 +1917-01,74.7 +1917-02,71.9 +1917-03,94.8 +1917-04,74.7 +1917-05,114.1 +1917-06,114.9 +1917-07,119.8 +1917-08,154.5 +1917-09,129.4 +1917-10,72.2 +1917-11,96.4 +1917-12,129.3 +1918-01,96.0 +1918-02,65.3 +1918-03,72.2 +1918-04,80.5 +1918-05,76.7 +1918-06,59.4 +1918-07,107.6 +1918-08,101.7 +1918-09,79.9 +1918-10,85.0 +1918-11,83.4 +1918-12,59.2 +1919-01,48.1 +1919-02,79.5 +1919-03,66.5 +1919-04,51.8 +1919-05,88.1 +1919-06,111.2 +1919-07,64.7 +1919-08,69.0 +1919-09,54.7 +1919-10,52.8 +1919-11,42.0 +1919-12,34.9 +1920-01,51.1 +1920-02,53.9 +1920-03,70.2 +1920-04,14.8 +1920-05,33.3 +1920-06,38.7 +1920-07,27.5 +1920-08,19.2 +1920-09,36.3 +1920-10,49.6 +1920-11,27.2 +1920-12,29.9 +1921-01,31.5 +1921-02,28.3 +1921-03,26.7 +1921-04,32.4 +1921-05,22.2 +1921-06,33.7 +1921-07,41.9 +1921-08,22.8 +1921-09,17.8 +1921-10,18.2 +1921-11,17.8 +1921-12,20.3 +1922-01,11.8 +1922-02,26.4 +1922-03,54.7 +1922-04,11.0 +1922-05,8.0 +1922-06,5.8 +1922-07,10.9 +1922-08,6.5 +1922-09,4.7 +1922-10,6.2 +1922-11,7.4 +1922-12,17.5 +1923-01,4.5 +1923-02,1.5 +1923-03,3.3 +1923-04,6.1 +1923-05,3.2 +1923-06,9.1 +1923-07,3.5 +1923-08,0.5 +1923-09,13.2 +1923-10,11.6 +1923-11,10.0 +1923-12,2.8 +1924-01,0.5 +1924-02,5.1 +1924-03,1.8 +1924-04,11.3 +1924-05,20.8 +1924-06,24.0 +1924-07,28.1 +1924-08,19.3 +1924-09,25.1 +1924-10,25.6 +1924-11,22.5 +1924-12,16.5 +1925-01,5.5 +1925-02,23.2 +1925-03,18.0 +1925-04,31.7 +1925-05,42.8 +1925-06,47.5 +1925-07,38.5 +1925-08,37.9 +1925-09,60.2 +1925-10,69.2 +1925-11,58.6 +1925-12,98.6 +1926-01,71.8 +1926-02,70.0 +1926-03,62.5 +1926-04,38.5 +1926-05,64.3 +1926-06,73.5 +1926-07,52.3 +1926-08,61.6 +1926-09,60.8 +1926-10,71.5 +1926-11,60.5 +1926-12,79.4 +1927-01,81.6 +1927-02,93.0 +1927-03,69.6 +1927-04,93.5 +1927-05,79.1 +1927-06,59.1 +1927-07,54.9 +1927-08,53.8 +1927-09,68.4 +1927-10,63.1 +1927-11,67.2 +1927-12,45.2 +1928-01,83.5 +1928-02,73.5 +1928-03,85.4 +1928-04,80.6 +1928-05,76.9 +1928-06,91.4 +1928-07,98.0 +1928-08,83.8 +1928-09,89.7 +1928-10,61.4 +1928-11,50.3 +1928-12,59.0 +1929-01,68.9 +1929-02,64.1 +1929-03,50.2 +1929-04,52.8 +1929-05,58.2 +1929-06,71.9 +1929-07,70.2 +1929-08,65.8 +1929-09,34.4 +1929-10,54.0 +1929-11,81.1 +1929-12,108.0 +1930-01,65.3 +1930-02,49.2 +1930-03,35.0 +1930-04,38.2 +1930-05,36.8 +1930-06,28.8 +1930-07,21.9 +1930-08,24.9 +1930-09,32.1 +1930-10,34.4 +1930-11,35.6 +1930-12,25.8 +1931-01,14.6 +1931-02,43.1 +1931-03,30.0 +1931-04,31.2 +1931-05,24.6 +1931-06,15.3 +1931-07,17.4 +1931-08,13.0 +1931-09,19.0 +1931-10,10.0 +1931-11,18.7 +1931-12,17.8 +1932-01,12.1 +1932-02,10.6 +1932-03,11.2 +1932-04,11.2 +1932-05,17.9 +1932-06,22.2 +1932-07,9.6 +1932-08,6.8 +1932-09,4.0 +1932-10,8.9 +1932-11,8.2 +1932-12,11.0 +1933-01,12.3 +1933-02,22.2 +1933-03,10.1 +1933-04,2.9 +1933-05,3.2 +1933-06,5.2 +1933-07,2.8 +1933-08,0.2 +1933-09,5.1 +1933-10,3.0 +1933-11,0.6 +1933-12,0.3 +1934-01,3.4 +1934-02,7.8 +1934-03,4.3 +1934-04,11.3 +1934-05,19.7 +1934-06,6.7 +1934-07,9.3 +1934-08,8.3 +1934-09,4.0 +1934-10,5.7 +1934-11,8.7 +1934-12,15.4 +1935-01,18.9 +1935-02,20.5 +1935-03,23.1 +1935-04,12.2 +1935-05,27.3 +1935-06,45.7 +1935-07,33.9 +1935-08,30.1 +1935-09,42.1 +1935-10,53.2 +1935-11,64.2 +1935-12,61.5 +1936-01,62.8 +1936-02,74.3 +1936-03,77.1 +1936-04,74.9 +1936-05,54.6 +1936-06,70.0 +1936-07,52.3 +1936-08,87.0 +1936-09,76.0 +1936-10,89.0 +1936-11,115.4 +1936-12,123.4 +1937-01,132.5 +1937-02,128.5 +1937-03,83.9 +1937-04,109.3 +1937-05,116.7 +1937-06,130.3 +1937-07,145.1 +1937-08,137.7 +1937-09,100.7 +1937-10,124.9 +1937-11,74.4 +1937-12,88.8 +1938-01,98.4 +1938-02,119.2 +1938-03,86.5 +1938-04,101.0 +1938-05,127.4 +1938-06,97.5 +1938-07,165.3 +1938-08,115.7 +1938-09,89.6 +1938-10,99.1 +1938-11,122.2 +1938-12,92.7 +1939-01,80.3 +1939-02,77.4 +1939-03,64.6 +1939-04,109.1 +1939-05,118.3 +1939-06,101.0 +1939-07,97.6 +1939-08,105.8 +1939-09,112.6 +1939-10,88.1 +1939-11,68.1 +1939-12,42.1 +1940-01,50.5 +1940-02,59.4 +1940-03,83.3 +1940-04,60.7 +1940-05,54.4 +1940-06,83.9 +1940-07,67.5 +1940-08,105.5 +1940-09,66.5 +1940-10,55.0 +1940-11,58.4 +1940-12,68.3 +1941-01,45.6 +1941-02,44.5 +1941-03,46.4 +1941-04,32.8 +1941-05,29.5 +1941-06,59.8 +1941-07,66.9 +1941-08,60.0 +1941-09,65.9 +1941-10,46.3 +1941-11,38.3 +1941-12,33.7 +1942-01,35.6 +1942-02,52.8 +1942-03,54.2 +1942-04,60.7 +1942-05,25.0 +1942-06,11.4 +1942-07,17.7 +1942-08,20.2 +1942-09,17.2 +1942-10,19.2 +1942-11,30.7 +1942-12,22.5 +1943-01,12.4 +1943-02,28.9 +1943-03,27.4 +1943-04,26.1 +1943-05,14.1 +1943-06,7.6 +1943-07,13.2 +1943-08,19.4 +1943-09,10.0 +1943-10,7.8 +1943-11,10.2 +1943-12,18.8 +1944-01,3.7 +1944-02,0.5 +1944-03,11.0 +1944-04,0.3 +1944-05,2.5 +1944-06,5.0 +1944-07,5.0 +1944-08,16.7 +1944-09,14.3 +1944-10,16.9 +1944-11,10.8 +1944-12,28.4 +1945-01,18.5 +1945-02,12.7 +1945-03,21.5 +1945-04,32.0 +1945-05,30.6 +1945-06,36.2 +1945-07,42.6 +1945-08,25.9 +1945-09,34.9 +1945-10,68.8 +1945-11,46.0 +1945-12,27.4 +1946-01,47.6 +1946-02,86.2 +1946-03,76.6 +1946-04,75.7 +1946-05,84.9 +1946-06,73.5 +1946-07,116.2 +1946-08,107.2 +1946-09,94.4 +1946-10,102.3 +1946-11,123.8 +1946-12,121.7 +1947-01,115.7 +1947-02,113.4 +1947-03,129.8 +1947-04,149.8 +1947-05,201.3 +1947-06,163.9 +1947-07,157.9 +1947-08,188.8 +1947-09,169.4 +1947-10,163.6 +1947-11,128.0 +1947-12,116.5 +1948-01,108.5 +1948-02,86.1 +1948-03,94.8 +1948-04,189.7 +1948-05,174.0 +1948-06,167.8 +1948-07,142.2 +1948-08,157.9 +1948-09,143.3 +1948-10,136.3 +1948-11,95.8 +1948-12,138.0 +1949-01,119.1 +1949-02,182.3 +1949-03,157.5 +1949-04,147.0 +1949-05,106.2 +1949-06,121.7 +1949-07,125.8 +1949-08,123.8 +1949-09,145.3 +1949-10,131.6 +1949-11,143.5 +1949-12,117.6 +1950-01,101.6 +1950-02,94.8 +1950-03,109.7 +1950-04,113.4 +1950-05,106.2 +1950-06,83.6 +1950-07,91.0 +1950-08,85.2 +1950-09,51.3 +1950-10,61.4 +1950-11,54.8 +1950-12,54.1 +1951-01,59.9 +1951-02,59.9 +1951-03,59.9 +1951-04,92.9 +1951-05,108.5 +1951-06,100.6 +1951-07,61.5 +1951-08,61.0 +1951-09,83.1 +1951-10,51.6 +1951-11,52.4 +1951-12,45.8 +1952-01,40.7 +1952-02,22.7 +1952-03,22.0 +1952-04,29.1 +1952-05,23.4 +1952-06,36.4 +1952-07,39.3 +1952-08,54.9 +1952-09,28.2 +1952-10,23.8 +1952-11,22.1 +1952-12,34.3 +1953-01,26.5 +1953-02,3.9 +1953-03,10.0 +1953-04,27.8 +1953-05,12.5 +1953-06,21.8 +1953-07,8.6 +1953-08,23.5 +1953-09,19.3 +1953-10,8.2 +1953-11,1.6 +1953-12,2.5 +1954-01,0.2 +1954-02,0.5 +1954-03,10.9 +1954-04,1.8 +1954-05,0.8 +1954-06,0.2 +1954-07,4.8 +1954-08,8.4 +1954-09,1.5 +1954-10,7.0 +1954-11,9.2 +1954-12,7.6 +1955-01,23.1 +1955-02,20.8 +1955-03,4.9 +1955-04,11.3 +1955-05,28.9 +1955-06,31.7 +1955-07,26.7 +1955-08,40.7 +1955-09,42.7 +1955-10,58.5 +1955-11,89.2 +1955-12,76.9 +1956-01,73.6 +1956-02,124.0 +1956-03,118.4 +1956-04,110.7 +1956-05,136.6 +1956-06,116.6 +1956-07,129.1 +1956-08,169.6 +1956-09,173.2 +1956-10,155.3 +1956-11,201.3 +1956-12,192.1 +1957-01,165.0 +1957-02,130.2 +1957-03,157.4 +1957-04,175.2 +1957-05,164.6 +1957-06,200.7 +1957-07,187.2 +1957-08,158.0 +1957-09,235.8 +1957-10,253.8 +1957-11,210.9 +1957-12,239.4 +1958-01,202.5 +1958-02,164.9 +1958-03,190.7 +1958-04,196.0 +1958-05,175.3 +1958-06,171.5 +1958-07,191.4 +1958-08,200.2 +1958-09,201.2 +1958-10,181.5 +1958-11,152.3 +1958-12,187.6 +1959-01,217.4 +1959-02,143.1 +1959-03,185.7 +1959-04,163.3 +1959-05,172.0 +1959-06,168.7 +1959-07,149.6 +1959-08,199.6 +1959-09,145.2 +1959-10,111.4 +1959-11,124.0 +1959-12,125.0 +1960-01,146.3 +1960-02,106.0 +1960-03,102.2 +1960-04,122.0 +1960-05,119.6 +1960-06,110.2 +1960-07,121.7 +1960-08,134.1 +1960-09,127.2 +1960-10,82.8 +1960-11,89.6 +1960-12,85.6 +1961-01,57.9 +1961-02,46.1 +1961-03,53.0 +1961-04,61.4 +1961-05,51.0 +1961-06,77.4 +1961-07,70.2 +1961-08,55.9 +1961-09,63.6 +1961-10,37.7 +1961-11,32.6 +1961-12,40.0 +1962-01,38.7 +1962-02,50.3 +1962-03,45.6 +1962-04,46.4 +1962-05,43.7 +1962-06,42.0 +1962-07,21.8 +1962-08,21.8 +1962-09,51.3 +1962-10,39.5 +1962-11,26.9 +1962-12,23.2 +1963-01,19.8 +1963-02,24.4 +1963-03,17.1 +1963-04,29.3 +1963-05,43.0 +1963-06,35.9 +1963-07,19.6 +1963-08,33.2 +1963-09,38.8 +1963-10,35.3 +1963-11,23.4 +1963-12,14.9 +1964-01,15.3 +1964-02,17.7 +1964-03,16.5 +1964-04,8.6 +1964-05,9.5 +1964-06,9.1 +1964-07,3.1 +1964-08,9.3 +1964-09,4.7 +1964-10,6.1 +1964-11,7.4 +1964-12,15.1 +1965-01,17.5 +1965-02,14.2 +1965-03,11.7 +1965-04,6.8 +1965-05,24.1 +1965-06,15.9 +1965-07,11.9 +1965-08,8.9 +1965-09,16.8 +1965-10,20.1 +1965-11,15.8 +1965-12,17.0 +1966-01,28.2 +1966-02,24.4 +1966-03,25.3 +1966-04,48.7 +1966-05,45.3 +1966-06,47.7 +1966-07,56.7 +1966-08,51.2 +1966-09,50.2 +1966-10,57.2 +1966-11,57.2 +1966-12,70.4 +1967-01,110.9 +1967-02,93.6 +1967-03,111.8 +1967-04,69.5 +1967-05,86.5 +1967-06,67.3 +1967-07,91.5 +1967-08,107.2 +1967-09,76.8 +1967-10,88.2 +1967-11,94.3 +1967-12,126.4 +1968-01,121.8 +1968-02,111.9 +1968-03,92.2 +1968-04,81.2 +1968-05,127.2 +1968-06,110.3 +1968-07,96.1 +1968-08,109.3 +1968-09,117.2 +1968-10,107.7 +1968-11,86.0 +1968-12,109.8 +1969-01,104.4 +1969-02,120.5 +1969-03,135.8 +1969-04,106.8 +1969-05,120.0 +1969-06,106.0 +1969-07,96.8 +1969-08,98.0 +1969-09,91.3 +1969-10,95.7 +1969-11,93.5 +1969-12,97.9 +1970-01,111.5 +1970-02,127.8 +1970-03,102.9 +1970-04,109.5 +1970-05,127.5 +1970-06,106.8 +1970-07,112.5 +1970-08,93.0 +1970-09,99.5 +1970-10,86.6 +1970-11,95.2 +1970-12,83.5 +1971-01,91.3 +1971-02,79.0 +1971-03,60.7 +1971-04,71.8 +1971-05,57.5 +1971-06,49.8 +1971-07,81.0 +1971-08,61.4 +1971-09,50.2 +1971-10,51.7 +1971-11,63.2 +1971-12,82.2 +1972-01,61.5 +1972-02,88.4 +1972-03,80.1 +1972-04,63.2 +1972-05,80.5 +1972-06,88.0 +1972-07,76.5 +1972-08,76.8 +1972-09,64.0 +1972-10,61.3 +1972-11,41.6 +1972-12,45.3 +1973-01,43.4 +1973-02,42.9 +1973-03,46.0 +1973-04,57.7 +1973-05,42.4 +1973-06,39.5 +1973-07,23.1 +1973-08,25.6 +1973-09,59.3 +1973-10,30.7 +1973-11,23.9 +1973-12,23.3 +1974-01,27.6 +1974-02,26.0 +1974-03,21.3 +1974-04,40.3 +1974-05,39.5 +1974-06,36.0 +1974-07,55.8 +1974-08,33.6 +1974-09,40.2 +1974-10,47.1 +1974-11,25.0 +1974-12,20.5 +1975-01,18.9 +1975-02,11.5 +1975-03,11.5 +1975-04,5.1 +1975-05,9.0 +1975-06,11.4 +1975-07,28.2 +1975-08,39.7 +1975-09,13.9 +1975-10,9.1 +1975-11,19.4 +1975-12,7.8 +1976-01,8.1 +1976-02,4.3 +1976-03,21.9 +1976-04,18.8 +1976-05,12.4 +1976-06,12.2 +1976-07,1.9 +1976-08,16.4 +1976-09,13.5 +1976-10,20.6 +1976-11,5.2 +1976-12,15.3 +1977-01,16.4 +1977-02,23.1 +1977-03,8.7 +1977-04,12.9 +1977-05,18.6 +1977-06,38.5 +1977-07,21.4 +1977-08,30.1 +1977-09,44.0 +1977-10,43.8 +1977-11,29.1 +1977-12,43.2 +1978-01,51.9 +1978-02,93.6 +1978-03,76.5 +1978-04,99.7 +1978-05,82.7 +1978-06,95.1 +1978-07,70.4 +1978-08,58.1 +1978-09,138.2 +1978-10,125.1 +1978-11,97.9 +1978-12,122.7 +1979-01,166.6 +1979-02,137.5 +1979-03,138.0 +1979-04,101.5 +1979-05,134.4 +1979-06,149.5 +1979-07,159.4 +1979-08,142.2 +1979-09,188.4 +1979-10,186.2 +1979-11,183.3 +1979-12,176.3 +1980-01,159.6 +1980-02,155.0 +1980-03,126.2 +1980-04,164.1 +1980-05,179.9 +1980-06,157.3 +1980-07,136.3 +1980-08,135.4 +1980-09,155.0 +1980-10,164.7 +1980-11,147.9 +1980-12,174.4 +1981-01,114.0 +1981-02,141.3 +1981-03,135.5 +1981-04,156.4 +1981-05,127.5 +1981-06,90.0 +1981-07,143.8 +1981-08,158.7 +1981-09,167.3 +1981-10,162.4 +1981-11,137.5 +1981-12,150.1 +1982-01,111.2 +1982-02,163.6 +1982-03,153.8 +1982-04,122.0 +1982-05,82.2 +1982-06,110.4 +1982-07,106.1 +1982-08,107.6 +1982-09,118.8 +1982-10,94.7 +1982-11,98.1 +1982-12,127.0 +1983-01,84.3 +1983-02,51.0 +1983-03,66.5 +1983-04,80.7 +1983-05,99.2 +1983-06,91.1 +1983-07,82.2 +1983-08,71.8 +1983-09,50.3 +1983-10,55.8 +1983-11,33.3 +1983-12,33.4 diff --git a/public/n4l/sunspots.n4l/locales/en.json b/public/n4l/sunspots.n4l/locales/en.json new file mode 100644 index 0000000..c207185 --- /dev/null +++ b/public/n4l/sunspots.n4l/locales/en.json @@ -0,0 +1,42 @@ +{ + "columns": { + "Month": "Month", + "Sunspots": "Sunspots" + }, + "tasks": { + "time-series": { + "name": "Sunspots", + "summary": "The mean number of sunspots each month, from 1749 to 1983: it rises and falls in cycles of about 11 years that do not always last the same.", + "description": { + "text": [ + "The monthly mean relative sunspot number (the Wolf number), from January 1749 to December 1983: 2,820 months. It was measured at the Swiss Federal Observatory in Zurich until 1960 and then at the Tokyo Astronomical Observatory. Sunspots are the series with which Yule proposed autoregressive models in 1927.", + "It rises and falls in cycles of about 11 years (the solar cycle), but this is not a seasonality: each cycle lasts a different time (from 9 to 14 years) and reaches a different height, so it is harder to forecast than a series with a fixed period. The maximum is in October 1957, and between 1790 and 1830 the cycles are much lower (the Dalton minimum).", + "The series is still being measured: the Royal Observatory of Belgium publishes the current version at SILSO. It was revised in 2015, so its numbers are somewhat different." + ], + "sections": [ + { + "title": "Variables", + "items": [ + "Month: the month (year-month).", + "Sunspots: the mean number of sunspots that month. This is what is forecast." + ] + }, + { + "title": "Pre-trained model", + "items": [ + "A network with one Dense layer of 32 neurons that sees the previous 24 months. On the test part (the last 47 years, which it did not see while training) it is off by {{test_mae, number(maximumFractionDigits: 1)}} sunspots on average one step ahead, a little less than repeating the previous month ({{test_naive_mae, number(maximumFractionDigits: 1)}}). Forecasting the whole test part at once it is off by {{test_recursive_mae, number(maximumFractionDigits: 1)}}: two years are not enough to follow an eleven-year cycle." + ] + }, + { + "title": "References", + "items": [ + "sunspots in the R documentation, with its original source.", + "The CSV, from the jbrownlee/Datasets repository.", + "The current SILSO data." + ] + } + ] + } + } + } +} diff --git a/public/n4l/sunspots.n4l/locales/es.json b/public/n4l/sunspots.n4l/locales/es.json new file mode 100644 index 0000000..da29516 --- /dev/null +++ b/public/n4l/sunspots.n4l/locales/es.json @@ -0,0 +1,42 @@ +{ + "columns": { + "Month": "Mes", + "Sunspots": "Manchas solares" + }, + "tasks": { + "time-series": { + "name": "Manchas solares", + "summary": "El número medio de manchas solares de cada mes, de 1749 a 1983: sube y baja en ciclos de unos 11 años que no duran siempre lo mismo.", + "description": { + "text": [ + "El número relativo medio de manchas solares (el número de Wolf) de cada mes, de enero de 1749 a diciembre de 1983: 2.820 meses. Se midió en el Observatorio Federal Suizo de Zúrich hasta 1960 y después, en el Observatorio Astronómico de Tokio. Con las manchas solares propuso Yule en 1927 los modelos autorregresivos.", + "Sube y baja en ciclos de unos 11 años (el ciclo solar), pero no es una estacionalidad: cada ciclo dura algo distinto (de 9 a 14 años) y llega a una altura diferente, así que es más difícil de predecir que una serie con un periodo fijo. El máximo es de octubre de 1957, y entre 1790 y 1830 los ciclos son mucho más bajos (el mínimo de Dalton).", + "La serie se sigue midiendo: el Observatorio Real de Bélgica publica la versión actual en SILSO. Se revisó en 2015, así que sus números son algo distintos." + ], + "sections": [ + { + "title": "Variables", + "items": [ + "Month: el mes (año-mes).", + "Sunspots: el número medio de manchas solares de ese mes. Es lo que se predice." + ] + }, + { + "title": "Modelo ya entrenado", + "items": [ + "Una red con una capa Dense de 32 neuronas que ve los 24 meses anteriores. Con la prueba (los últimos 47 años, que no vio al entrenar) se equivoca {{test_mae, number(maximumFractionDigits: 1)}} manchas de media a un paso, algo menos que repetir el mes anterior ({{test_naive_mae, number(maximumFractionDigits: 1)}}). Prediciendo toda la prueba seguida se equivoca {{test_recursive_mae, number(maximumFractionDigits: 1)}}: dos años no bastan para seguir un ciclo de once." + ] + }, + { + "title": "Referencias", + "items": [ + "sunspots en la documentación de R, con su fuente original.", + "El CSV, del repositorio jbrownlee/Datasets.", + "Los datos actuales de SILSO." + ] + } + ] + } + } + } +} diff --git a/public/n4l/sunspots.n4l/locales/ja.json b/public/n4l/sunspots.n4l/locales/ja.json new file mode 100644 index 0000000..dfed22d --- /dev/null +++ b/public/n4l/sunspots.n4l/locales/ja.json @@ -0,0 +1,42 @@ +{ + "columns": { + "Month": "月", + "Sunspots": "黒点数" + }, + "tasks": { + "time-series": { + "name": "太陽黒点", + "summary": "1749 年から 1983 年までの月ごとの太陽黒点数の平均です。約 11 年の周期で増減しますが、周期の長さは毎回同じではありません。", + "description": { + "text": [ + "1749 年 1 月から 1983 年 12 月までの月ごとの相対黒点数(ウォルフ数)の平均(2,820 か月)です。1960 年まではチューリッヒのスイス連邦天文台で、その後は東京天文台で観測されました。Yule が 1927 年に自己回帰モデルを提案したのも太陽黒点のデータでした。", + "約 11 年の周期(太陽周期)で増減しますが、季節性ではありません。周期ごとに長さ(9〜14 年)も高さも異なるため、周期が一定の系列より予測が難しくなります。最大値は 1957 年 10 月で、1790 年から 1830 年ごろは周期がずっと低くなっています(ダルトン極小期)。", + "この系列は今も観測が続いています。ベルギー王立天文台が最新版を SILSO で公開していますが、2015 年に改訂されたため数値は少し異なります。" + ], + "sections": [ + { + "title": "変数", + "items": [ + "Month:月(年-月)。", + "Sunspots:その月の平均黒点数。予測する値です。" + ] + }, + { + "title": "学習済みモデル", + "items": [ + "32 ニューロンの Dense 層 1 つで、直前の 24 か月を見るネットワークです。学習で見ていないテスト部分(最後の 47 年)での誤差は、1 ステップ先で平均 {{test_mae, number(maximumFractionDigits: 1)}} 個で、前月の値を繰り返す場合({{test_naive_mae, number(maximumFractionDigits: 1)}})より少し小さくなります。テスト部分全体を続けて予測すると {{test_recursive_mae, number(maximumFractionDigits: 1)}} です。11 年の周期を追うには 2 年では足りません。" + ] + }, + { + "title": "参考文献", + "items": [ + "R のドキュメントの sunspots(元の出典つき)。", + "CSV ファイル(jbrownlee/Datasets リポジトリ)。", + "SILSO の最新データ。" + ] + } + ] + } + } + } +} diff --git a/public/n4l/sunspots.n4l/manifest.json b/public/n4l/sunspots.n4l/manifest.json new file mode 100644 index 0000000..20f6ecf --- /dev/null +++ b/public/n4l/sunspots.n4l/manifest.json @@ -0,0 +1,93 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "sunspots", + "version": "1.1.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/sunspots.html", + "links": { + "link2": "https://github.com/jbrownlee/Datasets/blob/master/monthly-sunspots.csv", + "link3": "https://www.sidc.be/SILSO/datafiles" + }, + "citation": "@book{andrews1985data,\n author = {Andrews, David F. and Herzberg, Agnes M.},\n title = {Data: A Collection of Problems from Many Fields for the Student and Research Worker},\n publisher = {Springer},\n address = {New York, NY},\n year = {1985},\n doi = {10.1007/978-1-4612-5098-2}\n}" + }, + "datasets": [ + { + "id": "sunspots", + "file": "data/monthly-sunspots.csv", + "rows": 2820, + "frequency": "month", + "columns": [ + { + "name": "Month", + "role": "ID", + "type": "Date", + "missing": 0, + "description": "month (YYYY-MM)" + }, + { + "name": "Sunspots", + "role": "Target", + "type": "Continuous", + "missing": 0, + "description": "monthly mean relative sunspot number" + } + ] + } + ], + "tasks": [ + { + "task": "time-series", + "key": "SUNSPOTS", + "runtime": "time-series", + "datasets": [ + "sunspots" + ], + "order": 3, + "preprocessing": [], + "models": [ + { + "id": "forecast", + "format": "tfjs-layers", + "path": "models/forecast/model.json", + "dataset": "sunspots", + "input": "scaled", + "metrics": { + "test_mae": 13.2534, + "test_rmse": 18.0343, + "test_recursive_mae": 49.971, + "test_naive_mae": 14.8369 + } + } + ], + "training": { + "layers": [ + { + "class": "dense", + "units": 32, + "activation": "relu" + }, + { + "class": "dense", + "units": 1, + "activation": "linear", + "locked": true + } + ], + "learningRate": 0.001, + "epochs": 30 + }, + "forecast": { + "window": 24, + "difference": false, + "testSize": 20 + } + } + ] +} diff --git a/public/n4l/sunspots.n4l/models/forecast/model.json b/public/n4l/sunspots.n4l/models/forecast/model.json new file mode 100644 index 0000000..095823e --- /dev/null +++ b/public/n4l/sunspots.n4l/models/forecast/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_5","layers":[{"class_name":"Dense","config":{"units":32,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense9","trainable":true,"batch_input_shape":[null,24],"dtype":"float32"}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"normal","seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense10","trainable":true}}]},"keras_version":"tfjs-layers 4.22.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.22.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense9/kernel","shape":[24,32],"dtype":"float32"},{"name":"dense_Dense9/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense10/kernel","shape":[32,1],"dtype":"float32"},{"name":"dense_Dense10/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/n4l/sunspots.n4l/models/forecast/model.weights.bin b/public/n4l/sunspots.n4l/models/forecast/model.weights.bin new file mode 100644 index 0000000..b935d32 Binary files /dev/null and b/public/n4l/sunspots.n4l/models/forecast/model.weights.bin differ diff --git a/public/datasets/01-regression/wine-quality/wine-quality-red.csv b/public/n4l/wine-quality.n4l/data/wine-quality-red.csv similarity index 100% rename from public/datasets/01-regression/wine-quality/wine-quality-red.csv rename to public/n4l/wine-quality.n4l/data/wine-quality-red.csv diff --git a/public/datasets/01-regression/wine-quality/wine-quality-white.csv b/public/n4l/wine-quality.n4l/data/wine-quality-white.csv similarity index 100% rename from public/datasets/01-regression/wine-quality/wine-quality-white.csv rename to public/n4l/wine-quality.n4l/data/wine-quality-white.csv diff --git a/public/datasets/01-regression/wine-quality/wine-quality.names b/public/n4l/wine-quality.n4l/data/wine-quality.names similarity index 100% rename from public/datasets/01-regression/wine-quality/wine-quality.names rename to public/n4l/wine-quality.n4l/data/wine-quality.names diff --git a/public/n4l/wine-quality.n4l/locales/en.json b/public/n4l/wine-quality.n4l/locales/en.json new file mode 100644 index 0000000..c64d182 --- /dev/null +++ b/public/n4l/wine-quality.n4l/locales/en.json @@ -0,0 +1,62 @@ +{ + "columns": { + "fixed_acidity": "fixed_acidity", + "volatile_acidity": "volatile_acidity", + "citric_acid": "citric_acid", + "residual_sugar": "residual_sugar", + "chlorides": "chlorides", + "free_sulfur_dioxide": "free_sulfur_dioxide", + "total_sulfur_dioxide": "total_sulfur_dioxide", + "density": "density", + "pH": "pH", + "sulphates": "sulphates", + "alcohol": "alcohol", + "quality": "quality" + }, + "tasks": { + "regression": { + "title": "Wine Quality", + "name": "Wine", + "summary": "The quality of Portuguese vinho verde, red and white, from its chemical analysis.", + "description": { + "text": [ + "There are two data sets, one of red wine and one of white wine, both Portuguese vinho verde. They only have chemical measurements of the wine (the inputs) and the score some tasters gave it (the output). They do not include the grape type, the brand or the price.", + "The dataset contains multivariate type data, real type attributes, 4898 instances, and 12 distinct attributes.", + "It can be used to classify (which score a wine has) or to predict the score as a number (regression). The scores are in order, but there are not the same number of wines for each one: most have average scores.", + "For more information about this data set visit the repository archive.ics.uci.edu." + ], + "sections": [ + { + "title": "Input", + "items": [ + "Fixed Acidity: Fixed acidity refers to the concentration of non-volatile acids in wine, mainly tartaric acid. It contributes to the freshness and stability of the wine.", + "Volatile Acidity: Volatile acidity refers to the concentration of volatile acids, such as acetic acid, which can give an unpleasant taste if present in excess.", + "Citric Acid: Citric acid is one of the natural organic acids present in wine. It can influence the flavor and freshness of the wine.", + "Residual Sugar: It is the amount of sugar that remains in the wine after fermentation. A wine can be dry (little residual sugar) or sweet (more residual sugar).", + "Chlorides: The concentration of chlorides in wine can affect its flavor and aroma, and high levels can indicate problems in production.", + "Free Sulfur Dioxide: Sulfur dioxide is a common preservative in wine that helps prevent oxidation and the growth of unwanted microorganisms.", + "Total Sulfur Dioxide: Represents the sum of free sulfur dioxide and sulfur dioxide bound to other molecules in the wine. It is also related to the conservation of wine.", + "Density: Density refers to the mass of the wine per unit of volume. It can provide information on alcohol and sugar concentration.", + "pH: The pH measures the acidity or alkalinity of the wine. A low pH indicates acidity, while a high pH indicates alkalinity. It can influence flavor perception.", + "Sulphates: Sulfates are additives that are sometimes used in wine production. They can influence the stability and aroma of the wine.", + "Alcohol: The concentration of alcohol in wine can vary and affects both the flavor and mouthfeel.", + "Quality: This is the overall quality score of the wine, generally on a scale of 0 to 10, with higher values indicating better quality wines as assessed by tasters." + ] + }, + { + "title": "Output", + "items": [ + "Calculated regression" + ] + }, + { + "title": "References", + "items": [ + "Wine quality" + ] + } + ] + } + } + } +} diff --git a/public/n4l/wine-quality.n4l/locales/es.json b/public/n4l/wine-quality.n4l/locales/es.json new file mode 100644 index 0000000..634acab --- /dev/null +++ b/public/n4l/wine-quality.n4l/locales/es.json @@ -0,0 +1,62 @@ +{ + "columns": { + "fixed_acidity": "fixed_acidity", + "volatile_acidity": "volatile_acidity", + "citric_acid": "citric_acid", + "residual_sugar": "residual_sugar", + "chlorides": "chlorides", + "free_sulfur_dioxide": "free_sulfur_dioxide", + "total_sulfur_dioxide": "total_sulfur_dioxide", + "density": "density", + "pH": "pH", + "sulphates": "sulphates", + "alcohol": "alcohol", + "quality": "quality" + }, + "tasks": { + "regression": { + "title": "Calidad del vino", + "name": "Wine", + "summary": "La calidad de vinos verdes portugueses, tintos y blancos, según su análisis químico.", + "description": { + "text": [ + "Son dos conjuntos de datos, uno de vino tinto y otro de vino blanco, los dos de vino verde portugués. Solo tienen medidas químicas del vino (las entradas) y la nota que le dieron unos catadores (la salida). No dicen el tipo de uva, la marca ni el precio.", + "El conjunto de datos contiene datos de tipo multivariado, atributos de tipo reales, 4898 instancias y 12 atributos distintos.", + "Sirve para clasificar (qué nota tiene un vino) o para predecir la nota como un número (regresión). Las notas van en orden, pero no hay el mismo número de vinos de cada una: casi todos tienen notas medias.", + "Para obtener más información acerca de este conjunto de datos visita el repositorio archive.ics.uci.edu." + ], + "sections": [ + { + "title": "Datos de entrada", + "items": [ + "Fixed Acidity (Acidez Fija): La acidez fija se refiere a la concentración de ácidos no volátiles en el vino, principalmente ácido tartárico. Contribuye a la frescura y estabilidad del vino.", + "Volatile Acidity (Acidez Volátil): La acidez volátil se refiere a la concentración de ácidos volátiles, como el ácido acético, que pueden dar un sabor desagradable si están presentes en exceso.", + "Citric Acid (Ácido Cítrico): El ácido cítrico es uno de los ácidos orgánicos naturales presentes en el vino. Puede influir en el sabor y la frescura del vino.", + "Residual Sugar (Azúcar Residual): Es la cantidad de azúcar que queda en el vino después de la fermentación. Un vino puede ser seco (poco azúcar residual) o dulce (más azúcar residual).", + "Chlorides (Cloruros): La concentración de cloruros en el vino puede afectar su sabor y aroma, y niveles altos pueden indicar problemas en la producción.", + "Free Sulfur Dioxide (Dióxido de Azufre Libre): El dióxido de azufre es un conservante común en el vino que ayuda a prevenir la oxidación y el crecimiento de microorganismos no deseados.", + "Total Sulfur Dioxide (Dióxido de Azufre Total): Representa la suma de dióxido de azufre libre y dióxido de azufre unido a otras moléculas en el vino. También se relaciona con la conservación del vino.", + "Density (Densidad): La densidad se refiere a la masa del vino por unidad de volumen. Puede proporcionar información sobre la concentración de alcohol y azúcar.", + "pH: El pH mide la acidez o alcalinidad del vino. Un pH bajo indica acidez, mientras que un pH alto indica alcalinidad. Puede influir en la percepción del sabor.", + "Sulphates (Sulfatos): Los sulfatos son aditivos que se utilizan a veces en la producción de vino. Pueden influir en la estabilidad y el aroma del vino.", + "Alcohol: La concentración de alcohol en el vino puede variar y afecta tanto el sabor como la sensación en boca.", + "Quality (Calidad): Esta es la puntuación general de calidad del vino, generalmente en una escala de 0 a 10, donde valores más altos indican vinos de mejor calidad según la evaluación de los catadores." + ] + }, + { + "title": "Datos de salida", + "items": [ + "Regresión calculada" + ] + }, + { + "title": "Referencias", + "items": [ + "Calidad del vino" + ] + } + ] + } + } + } +} diff --git a/public/n4l/wine-quality.n4l/locales/ja.json b/public/n4l/wine-quality.n4l/locales/ja.json new file mode 100644 index 0000000..80aec63 --- /dev/null +++ b/public/n4l/wine-quality.n4l/locales/ja.json @@ -0,0 +1,62 @@ +{ + "columns": { + "fixed_acidity": "fixed_acidity", + "volatile_acidity": "volatile_acidity", + "citric_acid": "citric_acid", + "residual_sugar": "residual_sugar", + "chlorides": "chlorides", + "free_sulfur_dioxide": "free_sulfur_dioxide", + "total_sulfur_dioxide": "total_sulfur_dioxide", + "density": "density", + "pH": "pH", + "sulphates": "sulphates", + "alcohol": "alcohol", + "quality": "quality" + }, + "tasks": { + "regression": { + "title": "ワインの品質", + "name": "ワイン", + "summary": "ポルトガルのヴィーニョ・ヴェルデ(赤と白)の品質を、化学分析から予測します。", + "description": { + "text": [ + "この2つのデータセットは関連しており、ポルトガルワインの赤ワインと白ワインのバリアントが含まれています。このデータセットには、理化学変数(入力)と感覚変数(出力)のみが含まれており、ブドウの品種、ワインのブランド、または販売価格のデータは含まれていません。", + "データセットには多変量データ、実数型の属性、4898インスタンス、および12個の異なる属性が含まれています。", + "このデータセットは、分類タスクまたは回帰タスクに使用できます。クラスは順序付けされていますが、データセットは不均衡です。", + "このデータセットの詳細については、archive.ics.uci.eduリポジトリをご覧ください。" + ], + "sections": [ + { + "title": "入力データ", + "items": [ + "Fixed Acidity (固定酸度): ワイン中の非揮発性酸の濃度を指します。新鮮さと安定性に貢献します。", + "Volatile Acidity (揮発性酸度): 酢酸などの揮発性酸の濃度を指します。過剰に存在すると不快な味を与える可能性があります。", + "Citric Acid (クエン酸): ワインに存在する天然の有機酸の1つです。風味と新鮮さに影響を与える可能性があります。", + "Residual Sugar (残糖): 発酵後にワインに残る砂糖の量です。", + "Chlorides (塩化物): ワイン中の塩化物濃度は、その風味と香りに影響を与えます。", + "Free Sulfur Dioxide (遊離二酸化硫黄): 酸化や不要な微生物の増殖を防ぐ一般的な防腐剤です。", + "Total Sulfur Dioxide (総二酸化硫黄): 遊離二酸化硫黄と結合した二酸化硫黄の合計を表します。ワインの保存にも関連しています。", + "Density (密度): 単位体積あたりのワインの質量を指します。アルコールと砂糖の濃度に関する情報を提供できます。", + "pH: ワインの酸性度またはアルカリ度を測定します。", + "Sulphates (硫酸塩): ワインの生産で時々使用される添加剤です。安定性と香りに影響を与える可能性があります。", + "Alcohol (アルコール): ワイン中のアルコール濃度。風味と口当たりに影響します。", + "Quality (品質): テイスターの評価に従って、通常0から10のスケールで、ワインの全体的な品質スコア。" + ] + }, + { + "title": "出力データ", + "items": [ + "計算された回帰" + ] + }, + { + "title": "参照元", + "items": [ + "ワインの品質" + ] + } + ] + } + } + } +} diff --git a/public/n4l/wine-quality.n4l/manifest.json b/public/n4l/wine-quality.n4l/manifest.json new file mode 100644 index 0000000..5c1cf52 --- /dev/null +++ b/public/n4l/wine-quality.n4l/manifest.json @@ -0,0 +1,249 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "wine-quality", + "version": "1.2.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://archive.ics.uci.edu/dataset/186/wine+quality", + "citation": "@misc{misc_wine_quality_186,\n author = {Cortez,Paulo, Cerdeira,A., Almeida,F., Matos,T., and Reis,J.},\n title = {{Wine Quality}},\n year = {2009},\n howpublished = {UCI Machine Learning Repository},\n note = {{DOI}: https://doi.org/10.24432/C56S3T}\n}" + }, + "datasets": [ + { + "id": "wine-red", + "file": "data/wine-quality-red.csv", + "info": "data/wine-quality.names", + "rows": 1599, + "columns": [ + { + "name": "fixed_acidity", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "volatile_acidity", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "citric_acid", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "residual_sugar", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "chlorides", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "free_sulfur_dioxide", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "total_sulfur_dioxide", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "density", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "pH", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "sulphates", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "alcohol", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "quality", + "role": "Target", + "type": "Integer", + "missing": 0, + "description": "score between 0 and 10" + } + ] + }, + { + "id": "wine-white", + "file": "data/wine-quality-white.csv", + "info": "data/wine-quality.names", + "rows": 4898, + "columns": [ + { + "name": "fixed_acidity", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "volatile_acidity", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "citric_acid", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "residual_sugar", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "chlorides", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "free_sulfur_dioxide", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "total_sulfur_dioxide", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "density", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "pH", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "sulphates", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "alcohol", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "quality", + "role": "Target", + "type": "Integer", + "missing": 0, + "description": "score between 0 and 10" + } + ] + } + ], + "tasks": [ + { + "task": "regression", + "key": "WINE", + "runtime": "regression", + "datasets": [ + "wine-red", + "wine-white" + ], + "preprocessing": [ + { + "op": "min-max", + "columns": "features" + } + ], + "models": [ + { + "id": "red", + "format": "tfjs-layers", + "path": "models/red/model.json", + "dataset": "wine-red", + "input": "scaled", + "metrics": { + "test_r2": 0.3639, + "test_mae": 0.5121, + "test_baseline_mae": 0.7025 + } + }, + { + "id": "white", + "format": "tfjs-layers", + "path": "models/white/model.json", + "dataset": "wine-white", + "input": "scaled", + "metrics": { + "test_r2": 0.3923, + "test_mae": 0.5461, + "test_baseline_mae": 0.6567 + } + } + ], + "training": { + "layers": [ + { + "class": "dense", + "units": 11, + "activation": "relu", + "locked": true + }, + { + "class": "dense", + "units": 32, + "activation": "relu" + }, + { + "class": "dense", + "units": 16, + "activation": "relu" + }, + { + "class": "dense", + "units": 1, + "activation": "linear", + "locked": true + } + ] + } + } + ] +} diff --git a/public/n4l/wine-quality.n4l/models/red/model.json b/public/n4l/wine-quality.n4l/models/red/model.json new file mode 100644 index 0000000..c6fd15d --- /dev/null +++ b/public/n4l/wine-quality.n4l/models/red/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_3","layers":[{"class_name":"Dense","config":{"units":128,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1020}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense7","trainable":true,"batch_input_shape":[null,11],"dtype":"float32"}},{"class_name":"Dense","config":{"units":64,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1021}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense8","trainable":true}},{"class_name":"Dense","config":{"units":32,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1022}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense9","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1119}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense10","trainable":true}}]},"keras_version":"tfjs-layers 4.22.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.22.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense7/kernel","shape":[11,128],"dtype":"float32"},{"name":"dense_Dense7/bias","shape":[128],"dtype":"float32"},{"name":"dense_Dense8/kernel","shape":[128,64],"dtype":"float32"},{"name":"dense_Dense8/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense9/kernel","shape":[64,32],"dtype":"float32"},{"name":"dense_Dense9/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense10/kernel","shape":[32,1],"dtype":"float32"},{"name":"dense_Dense10/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/n4l/wine-quality.n4l/models/red/model.weights.bin b/public/n4l/wine-quality.n4l/models/red/model.weights.bin new file mode 100644 index 0000000..29b178f Binary files /dev/null and b/public/n4l/wine-quality.n4l/models/red/model.weights.bin differ diff --git a/public/n4l/wine-quality.n4l/models/white/model.json b/public/n4l/wine-quality.n4l/models/white/model.json new file mode 100644 index 0000000..c6fd15d --- /dev/null +++ b/public/n4l/wine-quality.n4l/models/white/model.json @@ -0,0 +1 @@ +{"modelTopology":{"class_name":"Sequential","config":{"name":"sequential_3","layers":[{"class_name":"Dense","config":{"units":128,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1020}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense7","trainable":true,"batch_input_shape":[null,11],"dtype":"float32"}},{"class_name":"Dense","config":{"units":64,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1021}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense8","trainable":true}},{"class_name":"Dense","config":{"units":32,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1022}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense9","trainable":true}},{"class_name":"Dense","config":{"units":1,"activation":"linear","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":"fan_avg","distribution":"uniform","seed":1119}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense10","trainable":true}}]},"keras_version":"tfjs-layers 4.22.0","backend":"tensor_flow.js"},"format":"layers-model","generatedBy":"TensorFlow.js tfjs-layers v4.22.0","convertedBy":null,"weightsManifest":[{"paths":["model.weights.bin"],"weights":[{"name":"dense_Dense7/kernel","shape":[11,128],"dtype":"float32"},{"name":"dense_Dense7/bias","shape":[128],"dtype":"float32"},{"name":"dense_Dense8/kernel","shape":[128,64],"dtype":"float32"},{"name":"dense_Dense8/bias","shape":[64],"dtype":"float32"},{"name":"dense_Dense9/kernel","shape":[64,32],"dtype":"float32"},{"name":"dense_Dense9/bias","shape":[32],"dtype":"float32"},{"name":"dense_Dense10/kernel","shape":[32,1],"dtype":"float32"},{"name":"dense_Dense10/bias","shape":[1],"dtype":"float32"}]}]} \ No newline at end of file diff --git a/public/n4l/wine-quality.n4l/models/white/model.weights.bin b/public/n4l/wine-quality.n4l/models/white/model.weights.bin new file mode 100644 index 0000000..a6b886d Binary files /dev/null and b/public/n4l/wine-quality.n4l/models/white/model.weights.bin differ diff --git a/public/datasets/wine.csv b/public/n4l/wine.n4l/data/wine.csv similarity index 98% rename from public/datasets/wine.csv rename to public/n4l/wine.n4l/data/wine.csv index 87c09b0..11ee6cb 100644 --- a/public/datasets/wine.csv +++ b/public/n4l/wine.n4l/data/wine.csv @@ -1,4 +1,4 @@ -Alcohol,Malic acid,Ash,Alcalinity of ash ,Magnesium,Total phenols,Flavanoids,Nonflavanoid phenols,Proanthocyanins,Color intensity,Hue,OD280/OD315 of diluted wines,Proline,Target +Alcohol,Malic acid,Ash,Alcalinity of ash,Magnesium,Total phenols,Flavanoids,Nonflavanoid phenols,Proanthocyanins,Color intensity,Hue,OD280/OD315 of diluted wines,Proline,Target 14.23,1.71,2.43,15.6,127,2.8,3.06,.28,2.29,5.64,1.04,3.92,1065,1 13.2,1.78,2.14,11.2,100,2.65,2.76,.26,1.28,4.38,1.05,3.4,1050,1 13.16,2.36,2.67,18.6,101,2.8,3.24,.3,2.81,5.68,1.03,3.17,1185,1 diff --git a/public/n4l/wine.n4l/locales/en.json b/public/n4l/wine.n4l/locales/en.json new file mode 100644 index 0000000..5b131ac --- /dev/null +++ b/public/n4l/wine.n4l/locales/en.json @@ -0,0 +1,24 @@ +{ + "columns": { + "Alcohol": "Alcohol", + "Malic acid": "Malic acid", + "Ash": "Ash", + "Alcalinity of ash": "Alcalinity of ash", + "Magnesium": "Magnesium", + "Total phenols": "Total phenols", + "Flavanoids": "Flavanoids", + "Nonflavanoid phenols": "Nonflavanoid phenols", + "Proanthocyanins": "Proanthocyanins", + "Color intensity": "Color intensity", + "Hue": "Hue", + "OD280/OD315 of diluted wines": "OD280/OD315 of diluted wines", + "Proline": "Proline", + "Target": "Target" + }, + "tasks": { + "clustering": { + "name": "Wine cultivars (without the cultivar)", + "summary": "13 chemical components of 178 wines: unscaled, proline rules; scaled, the groups are almost the three cultivars." + } + } +} diff --git a/public/n4l/wine.n4l/locales/es.json b/public/n4l/wine.n4l/locales/es.json new file mode 100644 index 0000000..4696eeb --- /dev/null +++ b/public/n4l/wine.n4l/locales/es.json @@ -0,0 +1,24 @@ +{ + "columns": { + "Alcohol": "Alcohol", + "Malic acid": "Malic acid", + "Ash": "Ash", + "Alcalinity of ash": "Alcalinity of ash", + "Magnesium": "Magnesium", + "Total phenols": "Total phenols", + "Flavanoids": "Flavanoids", + "Nonflavanoid phenols": "Nonflavanoid phenols", + "Proanthocyanins": "Proanthocyanins", + "Color intensity": "Color intensity", + "Hue": "Hue", + "OD280/OD315 of diluted wines": "OD280/OD315 of diluted wines", + "Proline": "Proline", + "Target": "Target" + }, + "tasks": { + "clustering": { + "name": "Variedades de vino (sin la variedad)", + "summary": "13 componentes químicos de 178 vinos: sin escalar manda la prolina; escalados, los grupos son casi las tres variedades." + } + } +} diff --git a/public/n4l/wine.n4l/locales/ja.json b/public/n4l/wine.n4l/locales/ja.json new file mode 100644 index 0000000..f3f1b60 --- /dev/null +++ b/public/n4l/wine.n4l/locales/ja.json @@ -0,0 +1,24 @@ +{ + "columns": { + "Alcohol": "Alcohol", + "Malic acid": "Malic acid", + "Ash": "Ash", + "Alcalinity of ash": "Alcalinity of ash", + "Magnesium": "Magnesium", + "Total phenols": "Total phenols", + "Flavanoids": "Flavanoids", + "Nonflavanoid phenols": "Nonflavanoid phenols", + "Proanthocyanins": "Proanthocyanins", + "Color intensity": "Color intensity", + "Hue": "Hue", + "OD280/OD315 of diluted wines": "OD280/OD315 of diluted wines", + "Proline": "Proline", + "Target": "Target" + }, + "tasks": { + "clustering": { + "name": "ワインの品種(品種なし)", + "summary": "178本のワインの13の化学成分:スケーリングしないとプロリンが支配し、スケーリングするとグループは3品種とほぼ同じになります。" + } + } +} diff --git a/public/n4l/wine.n4l/manifest.json b/public/n4l/wine.n4l/manifest.json new file mode 100644 index 0000000..0249ebf --- /dev/null +++ b/public/n4l/wine.n4l/manifest.json @@ -0,0 +1,126 @@ +{ + "$schema": "../n4l.schema.json", + "format": "n4l", + "formatVersion": 1, + "id": "wine", + "version": "1.0.0", + "locales": [ + "es", + "en", + "ja" + ], + "source": { + "url": "https://archive.ics.uci.edu/dataset/109/wine" + }, + "datasets": [ + { + "id": "wine", + "file": "data/wine.csv", + "rows": 178, + "columns": [ + { + "name": "Alcohol", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "Malic acid", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "Ash", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "Alcalinity of ash", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "Magnesium", + "role": "Feature", + "type": "Integer", + "missing": 0 + }, + { + "name": "Total phenols", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "Flavanoids", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "Nonflavanoid phenols", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "Proanthocyanins", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "Color intensity", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "Hue", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "OD280/OD315 of diluted wines", + "role": "Feature", + "type": "Continuous", + "missing": 0 + }, + { + "name": "Proline", + "role": "Feature", + "type": "Integer", + "missing": 0 + }, + { + "name": "Target", + "role": "Target", + "type": "Categorical", + "missing": 0, + "description": "class identifier (1-3)", + "options": [ + "1", + "2", + "3" + ] + } + ] + } + ], + "tasks": [ + { + "task": "clustering", + "key": "WINE", + "runtime": "clustering", + "datasets": [ + "wine" + ], + "preprocessing": [], + "models": [] + } + ] +} diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 0000000..3dfe1e9 --- /dev/null +++ b/public/sw.js @@ -0,0 +1,117 @@ +/* + * Service worker de Nets4Learning: para seguir usando sin conexión lo que ya se ha abierto (en clase, con mala wifi) y + * para no volver a descargar los modelos preentrenados. No descarga nada por adelantado: guarda lo que se va usando. + * - Páginas: primero la red; sin conexión, la última versión guardada de la aplicación. + * - Código (ficheros con hash en el nombre, no cambian nunca): guardado la primera vez. + * - Traducciones y conjuntos de datos: lo guardado enseguida y, por detrás, se actualiza. + * - Modelos preentrenados, en su propia caché (n4l-models-…): los de otras webs (Google Storage, jsDelivr…: los de + * detección de objetos de MediaPipe, MoveNet, COCO-SSD…), guardados la primera vez y sin volver a descargarlos; los + * de la aplicación (models/: face-api…), lo guardado enseguida y, por detrás, se actualiza. + * - Analíticas: nunca. + * Con `sw.js?models` (en desarrollo) solo guarda los modelos: el código lo sirve Vite y guardarlo serviría código viejo. + * Se borra desde /settings (y con «Restablecer todo»). Al cambiar VERSION se borran las cachés de la aplicación de la + * anterior; los modelos tienen su propia versión, MODELS_VERSION, para no volver a descargarlos con cada versión. + */ +const VERSION = 'v1' +const MODELS_VERSION = 'v1' +const SHELL = `n4l-shell-${VERSION}` +const RUNTIME = `n4l-runtime-${VERSION}` +const MODELS = `n4l-models-${MODELS_VERSION}` +const CDN_HOSTS = ['storage.googleapis.com', 'tfhub.dev', 'www.kaggle.com', 'cdn.jsdelivr.net', 'unpkg.com'] +const SKIP_HOSTS = ['google-analytics.com', 'googletagmanager.com', 'analytics.google.com'] +const MODELS_ONLY = new URL(self.location.href).searchParams.has('models') + +// La raíz de la aplicación (https://…/ o https://…/n4l/): ahí está su index.html +const scope = self.registration.scope + +const isModel = (url) => CDN_HOSTS.includes(url.hostname) || url.href.startsWith(`${scope}models/`) + +// Los modelos que la versión anterior guardaba con todo lo demás pasan a su caché, sin volver a descargarlos +async function moveModels() { + if (!(await caches.has(RUNTIME))) return + const [runtime, models] = await Promise.all([caches.open(RUNTIME), caches.open(MODELS)]) + for (const request of await runtime.keys()) { + if (!isModel(new URL(request.url))) continue + const response = await runtime.match(request) + if (response) await models.put(request, response) + await runtime.delete(request) + } +} + +self.addEventListener('install', (event) => { + if (MODELS_ONLY) { + event.waitUntil(self.skipWaiting()) + return + } + event.waitUntil(caches.open(SHELL) + .then((cache) => cache.add(new Request(scope, { cache: 'reload' }))) + .then(() => self.skipWaiting())) +}) + +self.addEventListener('activate', (event) => { + event.waitUntil((async () => { + await moveModels() + const keep = MODELS_ONLY ? [MODELS] : [SHELL, RUNTIME, MODELS] + const keys = await caches.keys() + await Promise.all(keys.filter((key) => key.startsWith('n4l-') && !keep.includes(key)).map((key) => caches.delete(key))) + await self.clients.claim() + })()) +}) + +const isHashedAsset = (url) => /\/assets\/[^/]+-[A-Za-z0-9_-]{8,}\.\w+$/.test(url.pathname) + +async function networkFirstPage(request) { + try { + const response = await fetch(request) + if (response.ok) await (await caches.open(SHELL)).put(scope, response.clone()) + return response + } catch { + return (await caches.match(scope)) ?? Response.error() + } +} + +async function cacheFirst(request, name) { + const cache = await caches.open(name) + const cached = await cache.match(request) + if (cached) return cached + const response = await fetch(request) + if (response.ok) await cache.put(request, response.clone()) + return response +} + +async function staleWhileRevalidate(event, name) { + const cache = await caches.open(name) + const cached = await cache.match(event.request) + const update = fetch(event.request) + .then(async (response) => { + if (response.ok) await cache.put(event.request, response.clone()) + return response + }) + .catch(() => cached ?? Response.error()) + if (cached) { + event.waitUntil(update) + return cached + } + return update +} + +self.addEventListener('fetch', (event) => { + const { request } = event + if (request.method !== 'GET' || request.headers.has('range')) return + const url = new URL(request.url) + if (SKIP_HOSTS.some((host) => url.hostname.endsWith(host))) return + // Los modelos: los de otras webs no cambian (su dirección lleva la versión); los de la aplicación, quizá sí + if (isModel(url)) { + event.respondWith(url.origin === self.location.origin ? staleWhileRevalidate(event, MODELS) : cacheFirst(request, MODELS)) + return + } + if (MODELS_ONLY) return + if (request.mode === 'navigate') { + event.respondWith(networkFirstPage(request)) + return + } + if (url.origin === self.location.origin) { + if (!url.href.startsWith(scope)) return + event.respondWith(isHashedAsset(url) ? cacheFirst(request, RUNTIME) : staleWhileRevalidate(event, RUNTIME)) + } +}) diff --git a/src/App.tsx b/src/App.tsx index ccb6293..65b340c 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,14 +1,26 @@ -import { lazy, Suspense, useEffect } from 'react' -import { BrowserRouter, Routes, Route, Navigate } from 'react-router' -import ReactGA from 'react-ga4' +import { lazy, Suspense, use, useEffect, type ReactNode } from 'react' +import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router' import Loading from './pages/Loading' import N4LNavbar from './components/header/N4LNavbar' import N4LFooter from './components/footer/N4LFooter' +import N4LCookiesBanner from './components/cookiesBanner/N4LCookiesBanner' +import N4LAnalytics from './components/analytics/N4LAnalytics' +import N4LScrollManager from './components/navigation/N4LScrollManager' +import N4LPageTitle from '@components/navigation/N4LPageTitle' +import N4LSkipLink, { SKIP_LINK_TARGET } from '@components/navigation/N4LSkipLink' +import N4LAnnouncer from '@components/a11y/N4LAnnouncer' +import N4LDialogFocusWrap from '@components/a11y/N4LDialogFocusWrap' +import { readConsent, startAnalytics } from '@core/analytics' +import { startupTFBackend } from '@core/tfBackend' +import { trackLearningPath } from '@core/learning/learningPath' +import N4LLearningToast from './components/learning/N4LLearningToast' +import N4LOfflineBar from './components/offline/N4LOfflineBar' import './ConfigChartJS' const PageHome = lazy(() => import( './pages/_home/Home')) +const PageTask = lazy(() => import( './pages/task/Task')) const PageMenuSelectModel = lazy(() => import( './pages/menu/MenuSelectModel')) const PageMenuSelectDataset = lazy(() => import( './pages/menu/MenuSelectDataset')) const PagePlayground = lazy(() => import( './pages/playground/Playground')) @@ -16,11 +28,17 @@ const PageDescriptionRegression = lazy(() => import( './pages/playground/1_Regre const PageManual = lazy(() => import( './pages/manual/Manual')) const PageGlossary = lazy(() => import( './pages/glossary/Glossary')) const PageDatasets = lazy(() => import( './pages/datasets/Datasets')) +const PagePackages = lazy(() => import( './pages/packages/Packages')) const PageAnalyzeDataFrame = lazy(() => import( './pages/analyze/AnalyzeDataFrame')) const PageContribute = lazy(() => import( './pages/contribute/Contribute')) const PageTermsAndConditions = lazy(() => import( './pages/terms/TermsAndConditions')) const PageNotFoundPage = lazy(() => import( './pages/notFound/NotFoundPage')) const PageVersion = lazy(() => import( './pages/version/Version')) +const PageSettings = lazy(() => import( './pages/settings/Settings')) +const PageLearn = lazy(() => import( './pages/learn/Learn')) +const PageLab = lazy(() => import( './pages/lab/Lab')) +const PageReport = lazy(() => import( './pages/report/TrainingReport')) +const PageAccessibility = lazy(() => import( './pages/accessibility/Accessibility')) // Páginas de pruebas para desarrollo: no se publican en producción. // /*#__PURE__*/ permite a Rollup descartar sus chunks cuando no se usan. const SHOW_DEV_PAGES = import.meta.env.VITE_ENVIRONMENT !== 'production' @@ -29,48 +47,91 @@ const TestPageEasy_lazy = /*#__PURE__*/ lazy(() => import( '@pages/TestPageEasy' const TestPageAdvanced_lazy = /*#__PURE__*/ lazy(() => import( '@pages/TestPageAdvanced')) const VITE_PATH = import.meta.env.VITE_PATH -const VITE_GA_MEASUREMENT_ID = import.meta.env.VITE_GA_MEASUREMENT_ID + +// «Empieza aquí» marca sus pasos con los eventos de la aplicación desde el principio (también la primera página vista) +trackLearningPath() + +// Las páginas usan TF.js en cuanto se montan: esperan a que esté activo el backend elegido en el menú +function TFBackendReady({ children }: { children: ReactNode }) { + const startup = startupTFBackend() + if (startup !== null) use(startup) + return children +} + +// Una ruta que no existe lleva a la 404 diciéndole cuál era (para las analíticas: enlaces rotos) +function NotFoundRedirect() { + const { pathname } = useLocation() + return +} function App() { + // Google Analytics solo se carga si el usuario lo ha aceptado (N4LCookiesBanner) useEffect(() => { - ReactGA.initialize(VITE_GA_MEASUREMENT_ID) + if (readConsent() === 'accepted') startAnalytics() }, []) return (
- + {/* Sin transiciones: con ellas, React deja a la vista la página anterior mientras llega el código de la nueva y no se + ve que está cargando; sin ellas, se ve Loading (el fallback de Suspense) */} + + {/* Primero «Saltar al contenido» y después el aviso de cookies (aunque se vea abajo): con el teclado se llega a + él enseguida, no después de toda la página */} + + + + + + + + + + + {/* El destino de «Saltar al contenido» (N4LSkipLink): las páginas, sin la barra de navegación */} + +
diff --git a/src/CONSTANTS_ACTIONS.ts b/src/CONSTANTS_ACTIONS.ts index b6794d2..f3dca07 100644 --- a/src/CONSTANTS_ACTIONS.ts +++ b/src/CONSTANTS_ACTIONS.ts @@ -7,6 +7,14 @@ export const GLOSSARY_ACTIONS = { STEP_4_HYPERPARAMETERS : 'task-00-editor-hyperparameters-open', STEP_5_TABLE_OF_MODELS : 'task-00-table-of-models-open' }, + REGRESSION: { + STEP_1_UPLOAD_AND_PROCESS: 'task-01-upload-and-process-open', + STEP_2_DATASET : 'task-01-dataset-open', + STEP_3_0_LAYER_DESIGN : 'task-01-layer-design-open', + STEP_3_LAYERS : 'task-01-editor-layers-open', + STEP_4_HYPERPARAMETERS : 'task-01-editor-hyperparameters-open', + STEP_5_TABLE_OF_MODELS : 'task-01-table-of-models-open' + }, IMAGE_CLASSIFICATION: { STEP_1_UPLOAD_AND_PROCESS: 'task-03-upload-and-process-open', STEP_2_DATASET : 'task-03-dataset-open', @@ -14,7 +22,10 @@ export const GLOSSARY_ACTIONS = { STEP_3_LAYERS : 'task-03-editor-layers-open', STEP_4_HYPERPARAMETERS : 'task-03-editor-hyperparameters-open', STEP_5_TABLE_OF_MODELS : 'task-03-table-of-models-open' - } + }, + TIME_SERIES: { + STEP_2_DATASET: 'task-05-dataset-open', + }, } export const MANUAL_ACTIONS = { diff --git a/src/CONSTANTS_DanfoJS.ts b/src/CONSTANTS_DanfoJS.ts deleted file mode 100644 index 7afcad0..0000000 --- a/src/CONSTANTS_DanfoJS.ts +++ /dev/null @@ -1,133 +0,0 @@ -import * as _Types from "@core/types" - -export const TABLE_PLOT_STYLE_HEADER_STYLE = { - align : "center", - fill : { color: ["gray"] }, - font : { family: "Arial", size: 15, color: "white" }, - columnwidth: 200, -} -export const TABLE_PLOT_STYLE_CELL_STYLE = { - align: ["center"], - line : { color: "black", width: 1 }, -} - -export const TABLE_PLOT_STYLE_CONFIG = { - tableHeaderStyle: TABLE_PLOT_STYLE_HEADER_STYLE, - tableCellStyle : TABLE_PLOT_STYLE_CELL_STYLE, -} - -export const TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_1 = { - ...TABLE_PLOT_STYLE_CONFIG, - tableHeaderStyle: { - ...TABLE_PLOT_STYLE_CONFIG.tableHeaderStyle, - fill: { color: ["rgb(48,13,159)"] }, - font: { family: "Arial", size: 15, color: "white" }, - }, -} - -export const TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_2 = { - ...TABLE_PLOT_STYLE_CONFIG, - tableHeaderStyle: { - ...TABLE_PLOT_STYLE_CONFIG.tableHeaderStyle, - fill: { color: ["rgb(72,0,105)"] }, - font: { family: "Arial", size: 15, color: "white" }, - }, -} -/** - * - * @param {string[]} columns - * @param {_Types.DataFrameColumnTransformEnable_t[]} listColumnNameTransformations - * @param {string} columnNameTarget - * @returns - */ -export const F_TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_2 = ( - columns: string[], - listColumnNameTransformations: _Types.DataFrameColumnTransformEnable_t[], - columnNameTarget: string -) => { - const array_color = columns.map((column_name) => { - // Verificar si la columna es el target - if (column_name === columnNameTarget) { - return "rgb(255,0,105)" - } - - // Buscar la transformación correspondiente a la columna - const transformation = listColumnNameTransformations.find((trans) => trans.column_name === column_name) - - // Si no hay transformación o no está habilitada, devolver un color por defecto - if (!transformation || !transformation.column_enable) { - return "rgb(0,0,0)" // Color por defecto, puedes cambiarlo - } - - // Devolver el color basado en column_transform - switch (transformation.column_transform) { - // "string" | "one-hot-encoder" | "label-encoder" | "int32" | "float32" | "replace__NaN" | "replace_?_NaN" | "drop_?" | "drop" | "dropNa" | "ignored" - case "string": { - // naranja - return "rgb(255, 165, 0)" - } - case "one-hot-encoder": { - // verde - return "rgb(0, 128, 0)" - } - case "label-encoder": { - // azul - return "rgb(0, 0, 255)" - } - case "int32": { - // índigo - return "rgb(75, 0, 130)" - } - case "float32": { - // violeta - return "rgb(238, 130, 238)" - } - case "replace__NaN": { - // rosa - return "rgb(255, 192, 203)" - } - case "replace_?_NaN": { - // rosa profundo - return "rgb(255, 20, 147)" - } - case "drop_?": { - // rojo anaranjado - return "rgb(255, 69, 0)" - } - case "drop": { - // rojo - return "rgb(255, 0, 0)" - } - case "dropNa": { - // rojo oscuro - return "rgb(139, 0, 0)" - } - case "ignored": { - // gris - return "rgb(128, 128, 128)" - } - default: { - // Color por defecto para transformaciones desconocidas - return "rgb(0,0,0)" - } - } - }) - - return { - ...TABLE_PLOT_STYLE_CONFIG, - tableHeaderStyle: { - ...TABLE_PLOT_STYLE_CONFIG.tableHeaderStyle, - fill: { color: array_color }, - font: { family: "Arial", size: 15, color: "white" }, - }, - } -} - -export const CONFIG_DANFOJS_FRAME = { - frameConfig: { - config: { - tableMaxColInConsole: 20, - tableMaxRow : 40, - }, - }, -} diff --git a/src/ConfigChartJS.ts b/src/ConfigChartJS.ts index 6977ee4..8848210 100644 --- a/src/ConfigChartJS.ts +++ b/src/ConfigChartJS.ts @@ -9,8 +9,11 @@ import { Tooltip, LineController, BarController, + ScatterController, } from 'chart.js' +import { prefersReducedMotion, subscribeDisplaySettings } from '@core/a11y/displaySettings' + ChartJS.register( LinearScale, CategoryScale, @@ -20,5 +23,15 @@ ChartJS.register( Legend, Tooltip, LineController, - BarController -) \ No newline at end of file + BarController, + ScatterController +) + +// Sin animaciones si se pide menos movimiento (en /settings o en el sistema): las gráficas que se creen desde entonces +const DEFAULT_ANIMATION = ChartJS.defaults.animation +const syncAnimation = () => { + ChartJS.defaults.animation = prefersReducedMotion() ? false : DEFAULT_ANIMATION +} +syncAnimation() +subscribeDisplaySettings(syncAnimation) +window.matchMedia?.('(prefers-reduced-motion: reduce)').addEventListener?.('change', syncAnimation) diff --git a/src/DATA_MODEL.ts b/src/DATA_MODEL.ts index a6e6568..117e883 100644 --- a/src/DATA_MODEL.ts +++ b/src/DATA_MODEL.ts @@ -2,46 +2,18 @@ import { MAP_TC_CLASSES } from '@pages/playground/0_TabularClassification/models import { MAP_LR_CLASSES } from '@pages/playground/1_Regression/models' import { MAP_OD_CLASSES } from '@pages/playground/2_ObjectDetection/models' import { MAP_IC_CLASSES } from '@pages/playground/3_ImageClassification/models' +import { MAP_TS_CLASSES } from '@pages/playground/5_TimeSeries/models' import type { ModelRegistry } from '@core/models/modelRegistry' import { TASKS, UPLOAD, type TASKS_TYPE_K, type TASKS_TYPE_V } from '@/TASKS' -import { IC_MODEL_KEYS, LR_MODEL_KEYS, OD_MODEL_KEYS, TC_MODEL_KEYS } from '@/MODEL_KEYS' +import { TASK_DATASET_OPTIONS, TASK_MODEL_OPTIONS } from '@/TASK_OPTIONS' export type { TASKS_TYPE_K, TASKS_TYPE_V } +export type { TASK_MODEL_OPTIONS_TYPE, MODEL_OPTIONS_TYPE, TASK_DATASET_OPTIONS_TYPE, DATASET_OPTIONS_TYPE } from '@/TASK_OPTIONS' // Este módulo solo contiene claves, etiquetas y registros de carga perezosa: importarlo no // descarga ningún modelo. Las clases se cargan con `loadModelClass(TASK_MODEL_REGISTRY[task], key)`. - -const TASK_MODEL_OPTIONS = { - [TASKS.TABULAR_CLASSIFICATION]: [ - { i18n: 'datasets-models.0-tabular-classification.list-models.0-option-1', value: TC_MODEL_KEYS.CAR }, - { i18n: 'datasets-models.0-tabular-classification.list-models.0-option-2', value: TC_MODEL_KEYS.IRIS }, - { i18n: 'datasets-models.0-tabular-classification.list-models.0-option-3', value: TC_MODEL_KEYS.LYMPHOGRAPHY }, - ], - [TASKS.REGRESSION]: [ - // { i18n: 'datasets-models.1-regression.list-models.salary', value: LR_MODEL_KEYS.SALARY }, - { i18n: 'datasets-models.1-regression.list-models.auto-mpg', value: LR_MODEL_KEYS.AUTO_MPG }, - // { i18n: 'datasets-models.1-regression.list-models.housing-prices', value: LR_MODEL_KEYS.HOUSING_PRICES }, - // { i18n: 'datasets-models.1-regression.list-models.breast-cancer', value: LR_MODEL_KEYS.BREAST_CANCER }, - { i18n: 'datasets-models.1-regression.list-models.student-performance', value: LR_MODEL_KEYS.STUDENT_PERFORMANCE }, - { i18n: 'datasets-models.1-regression.list-models.wine', value: LR_MODEL_KEYS.WINE }, - ], - [TASKS.OBJECT_DETECTION]: [ - { i18n: 'datasets-models.2-object-detection.list-models.2-option-1', value: OD_MODEL_KEYS.FACE_DETECTOR }, - { i18n: 'datasets-models.2-object-detection.list-models.2-option-2', value: OD_MODEL_KEYS.FACE_MESH }, - { i18n: 'datasets-models.2-object-detection.list-models.2-option-3', value: OD_MODEL_KEYS.MOVE_NET_POSE_NET }, - { i18n: 'datasets-models.2-object-detection.list-models.2-option-4', value: OD_MODEL_KEYS.COCO_SSD }, - { i18n: 'datasets-models.2-object-detection.list-models.2-option-5', value: OD_MODEL_KEYS.FACE_API }, - { i18n: 'datasets-models.2-object-detection.list-models.2-option-6', value: OD_MODEL_KEYS.HAND_SIGN }, - ], - [TASKS.IMAGE_CLASSIFICATION]: [ - { i18n: 'datasets-models.3-image-classifier.list-models.3-option-1', value: IC_MODEL_KEYS.MNIST }, - { i18n: 'datasets-models.3-image-classifier.list-models.3-option-4', value: IC_MODEL_KEYS.KMNIST }, - { i18n: 'datasets-models.3-image-classifier.list-models.3-option-2', value: IC_MODEL_KEYS.MOBILENET }, - ], -} -export type TASK_MODEL_OPTIONS_TYPE = typeof TASK_MODEL_OPTIONS -export type MODEL_OPTIONS_TYPE = TASK_MODEL_OPTIONS_TYPE[keyof TASK_MODEL_OPTIONS_TYPE] +// Las listas de opciones viven en TASK_OPTIONS.ts y se reexportan aquí. /** Lo que los menús necesitan de cualquier modelo: su título y su descripción. */ export type MenuModel_t = { i18n_TITLE: string, DESCRIPTION: () => React.ReactNode } @@ -52,34 +24,9 @@ const TASK_MODEL_REGISTRY: Record> = { [TASKS.REGRESSION] : MAP_LR_CLASSES, [TASKS.OBJECT_DETECTION] : MAP_OD_CLASSES, [TASKS.IMAGE_CLASSIFICATION] : MAP_IC_CLASSES, + [TASKS.TIME_SERIES] : MAP_TS_CLASSES, } -const TASK_DATASET_OPTIONS = { - [TASKS.TABULAR_CLASSIFICATION]: [ - { i18n: 'pages.menu-selection-dataset.0-tabular-classification.csv', value: UPLOAD }, - { i18n: 'datasets-models.0-tabular-classification.list-datasets.0-option-1', value: TC_MODEL_KEYS.CAR }, - { i18n: 'datasets-models.0-tabular-classification.list-datasets.0-option-2', value: TC_MODEL_KEYS.IRIS }, - { i18n: 'datasets-models.0-tabular-classification.list-datasets.0-option-3', value: TC_MODEL_KEYS.LYMPHOGRAPHY }, - ], - [TASKS.REGRESSION]: [ - // TODO - { i18n: 'pages.menu-selection-dataset.1-regression.csv', value: UPLOAD }, - { i18n: 'datasets-models.1-regression.list-datasets.salary', value: LR_MODEL_KEYS.SALARY }, - { i18n: 'datasets-models.1-regression.list-datasets.auto-mpg', value: LR_MODEL_KEYS.AUTO_MPG }, - { i18n: 'datasets-models.1-regression.list-datasets.housing-prices', value: LR_MODEL_KEYS.HOUSING_PRICES }, - // { i18n: 'datasets-models.1-regression.list-datasets.breast-cancer', value: LR_MODEL_KEYS.BREAST_CANCER }, - { i18n: 'datasets-models.1-regression.list-datasets.student-performance', value: LR_MODEL_KEYS.STUDENT_PERFORMANCE }, - { i18n: 'datasets-models.1-regression.list-datasets.wine', value: LR_MODEL_KEYS.WINE }, - ], - [TASKS.OBJECT_DETECTION] : [], - [TASKS.IMAGE_CLASSIFICATION]: [ - { i18n: 'datasets-models.3-image-classification.list-datasets.mnist', value: IC_MODEL_KEYS.MNIST }, - { i18n: 'datasets-models.3-image-classification.list-datasets.kmnist', value: IC_MODEL_KEYS.KMNIST }, - ], -} -export type TASK_DATASET_OPTIONS_TYPE = typeof TASK_DATASET_OPTIONS -export type DATASET_OPTIONS_TYPE = TASK_DATASET_OPTIONS_TYPE[keyof TASK_DATASET_OPTIONS_TYPE] - export { TASKS, TASK_MODEL_OPTIONS, diff --git a/src/MODEL_KEYS.ts b/src/MODEL_KEYS.ts index a961eda..01ff964 100644 --- a/src/MODEL_KEYS.ts +++ b/src/MODEL_KEYS.ts @@ -32,5 +32,7 @@ export const IC_MODEL_KEYS = { MNIST : 'IMAGE-MNIST', KMNIST : 'IMAGE-KMNIST', MOBILENET: 'IMAGE-MOBILENET', - RESNET : 'IMAGE-RESNET', + CIFAR10 : 'IMAGE-CIFAR10', } as const + +// Agrupamiento: sus conjuntos (IRIS, WINE, NEW-THYROID) están en paquetes .n4l (public/n4l/) diff --git a/src/TASKS.ts b/src/TASKS.ts index 6841479..98e3ad5 100644 --- a/src/TASKS.ts +++ b/src/TASKS.ts @@ -1,14 +1,18 @@ // Constantes ligeras de las tareas. Están separadas de DATA_MODEL (que importa todas las // clases de modelos) para que páginas como la home o el playground no carguen los modelos // solo por usar estos identificadores. -export type TASKS_TYPE_K = 'TABULAR_CLASSIFICATION' | 'REGRESSION' | 'IMAGE_CLASSIFICATION' | 'OBJECT_DETECTION' -export type TASKS_TYPE_V = 'tabular-classification' | 'regression' | 'image-classification' | 'object-detection' +export type TASKS_TYPE_K = 'TABULAR_CLASSIFICATION' | 'REGRESSION' | 'IMAGE_CLASSIFICATION' | 'OBJECT_DETECTION' | 'CLUSTERING' | 'TIME_SERIES' +export type TASKS_TYPE_V = 'tabular-classification' | 'regression' | 'image-classification' | 'object-detection' | 'clustering' | 'time-series' export const TASKS: Record = { TABULAR_CLASSIFICATION: 'tabular-classification', REGRESSION : 'regression', IMAGE_CLASSIFICATION : 'image-classification', OBJECT_DETECTION : 'object-detection', + // Agrupar sin etiquetas (aprendizaje no supervisado): k-means + CLUSTERING : 'clustering', + // Predecir los siguientes valores de una serie a partir de los anteriores + TIME_SERIES : 'time-series', } export const UPLOAD = 'UPLOAD' diff --git a/src/TASK_OPTIONS.ts b/src/TASK_OPTIONS.ts new file mode 100644 index 0000000..63b3bca --- /dev/null +++ b/src/TASK_OPTIONS.ts @@ -0,0 +1,130 @@ +import { TASKS, UPLOAD, type TASKS_TYPE_V } from '@/TASKS' +import { OD_MODEL_KEYS } from '@/MODEL_KEYS' +import { n4lPackagesOf, n4lPublicFile } from '@core/n4l/catalog' +import { isImageDataset, isTableDataset, n4lNamespace, n4lTaskText, type N4LFrequency_t } from '@core/n4l/format' + +// Modelos preentrenados y datasets de cada tarea (clave y etiqueta). Separado de DATA_MODEL, que importa los +// registros de modelos, para que la home o las migas de pan puedan usar estas listas sin cargarlos. +// Las tareas que ya están en paquetes .n4l (public/n4l/) los toman del catálogo: n4lModelOptions y n4lDatasetOptions. + +/** Los paquetes de una tarea que salen en los menús, en su orden (`order`; sin él, por su carpeta) */ +const listedPackages = (task: TASKS_TYPE_V) => n4lPackagesOf(task) + .filter(({ section }) => section.listed !== false) + .sort((a, b) => (a.section.order ?? Infinity) - (b.section.order ?? Infinity)) + +/** Los modelos ya entrenados de los paquetes de una tarea */ +const n4lModelOptions = (task: TASKS_TYPE_V): TaskOption_t[] => listedPackages(task) + .filter(({ section }) => section.models.length > 0) + .map(({ entry, section }) => ({ i18n: n4lTaskText(n4lNamespace(entry.id), task) + 'name', value: section.key, summary: n4lTaskText(n4lNamespace(entry.id), task) + 'summary' })) + +/** + * Los conjuntos de datos de los paquetes de una tarea, con lo que se cuenta de ellos en su tarjeta. Solo los que traen + * sus datos (con uno externo, como ImageNet, no se entrena) + */ +const n4lDatasetOptions = (task: TASKS_TYPE_V): TaskOption_t[] => listedPackages(task) + .filter(({ datasets }) => datasets.every(({ kind }) => kind !== 'external')) + .map(({ entry, section, datasets, dataset }) => { + const tables = datasets.filter(isTableDataset) + const features = new Set(tables.map(({ columns }) => columns.filter(({ role }) => role === 'Feature').length)) + const target = isTableDataset(dataset) ? dataset.columns.find(({ role }) => role === 'Target') : undefined + // Una serie se predice con sus valores anteriores: no tiene columnas de entrada, y sus filas son meses, días… + const isSeries = task === TASKS.TIME_SERIES + return { + i18n : n4lTaskText(n4lNamespace(entry.id), task) + 'name', + value : section.key, + summary: n4lTaskText(n4lNamespace(entry.id), task) + 'summary', + info : { + source: entry.source?.url, + // Los CSV (se pueden ver y descargar en /datasets); las imágenes, no + ...(tables.length > 0 && { files: tables.map(({ file }) => n4lPublicFile(entry, file)) }), + rows : datasets.map(({ rows }) => rows ?? 0), + ...(isImageDataset(dataset) && { images: dataset.image }), + // Las de entrada, solo si todos sus ficheros tienen las mismas + ...(tables.length > 0 && features.size === 1 && !isSeries && { features: [...features][0] }), + ...(isSeries && isTableDataset(dataset) && { frequency: dataset.frequency }), + // Regresión y series: lo que se predice; si no, las clases (las salidas del modelo o los valores distintos del objetivo) + ...(task === TASKS.REGRESSION || isSeries + ? { target: target?.name } + : { classes: section.classes?.length ?? target?.options?.length }), + }, + } + }) + +const TASK_MODEL_OPTIONS = { + [TASKS.TABULAR_CLASSIFICATION]: n4lModelOptions(TASKS.TABULAR_CLASSIFICATION), + [TASKS.REGRESSION] : n4lModelOptions(TASKS.REGRESSION), + [TASKS.OBJECT_DETECTION] : [ + { i18n: 'datasets-models.2-object-detection.list-models.2-option-1', value: OD_MODEL_KEYS.FACE_DETECTOR }, + { i18n: 'datasets-models.2-object-detection.list-models.2-option-2', value: OD_MODEL_KEYS.FACE_MESH }, + { i18n: 'datasets-models.2-object-detection.list-models.2-option-3', value: OD_MODEL_KEYS.MOVE_NET_POSE_NET }, + { i18n: 'datasets-models.2-object-detection.list-models.2-option-4', value: OD_MODEL_KEYS.COCO_SSD }, + { i18n: 'datasets-models.2-object-detection.list-models.2-option-5', value: OD_MODEL_KEYS.FACE_API }, + { i18n: 'datasets-models.2-object-detection.list-models.2-option-6', value: OD_MODEL_KEYS.HAND_SIGN }, + ], + [TASKS.IMAGE_CLASSIFICATION]: n4lModelOptions(TASKS.IMAGE_CLASSIFICATION), + // Agrupar no necesita un modelo entrenado antes: se hace al momento con los datos + [TASKS.CLUSTERING] : [], + [TASKS.TIME_SERIES] : n4lModelOptions(TASKS.TIME_SERIES), +} +export type TASK_MODEL_OPTIONS_TYPE = typeof TASK_MODEL_OPTIONS +export type MODEL_OPTIONS_TYPE = TASK_MODEL_OPTIONS_TYPE[keyof TASK_MODEL_OPTIONS_TYPE] + +const TASK_DATASET_OPTIONS = { + [TASKS.TABULAR_CLASSIFICATION]: [ + { i18n: 'pages.menu-selection-dataset.0-tabular-classification.csv', value: UPLOAD }, + ...n4lDatasetOptions(TASKS.TABULAR_CLASSIFICATION), + ], + [TASKS.REGRESSION]: [ + { i18n: 'pages.menu-selection-dataset.1-regression.csv', value: UPLOAD }, + ...n4lDatasetOptions(TASKS.REGRESSION), + ], + [TASKS.OBJECT_DETECTION] : [], + [TASKS.IMAGE_CLASSIFICATION]: n4lDatasetOptions(TASKS.IMAGE_CLASSIFICATION), + // Conjuntos con clases conocidas: se agrupan sin verlas y al final se comparan los grupos con ellas + [TASKS.CLUSTERING] : [ + { i18n: 'pages.menu-selection-dataset.clustering.csv', value: UPLOAD }, + ...n4lDatasetOptions(TASKS.CLUSTERING), + ], + // Series temporales: las de ejemplo o una propia (con su columna de fechas y la de sus valores) + [TASKS.TIME_SERIES]: [ + { i18n: 'pages.menu-selection-dataset.time-series.csv', value: UPLOAD }, + ...n4lDatasetOptions(TASKS.TIME_SERIES), + ], +} +export type TASK_DATASET_OPTIONS_TYPE = typeof TASK_DATASET_OPTIONS +export type DATASET_OPTIONS_TYPE = TASK_DATASET_OPTIONS_TYPE[keyof TASK_DATASET_OPTIONS_TYPE] + +/** Lo que se cuenta de un dataset en su tarjeta (los números salen de sus CSV; un test lo comprueba) */ +export type DatasetInfo_t = { + /** CSV del dataset, relativos a public/ (los mismos que carga la clase del modelo) */ + files? : string[] + /** Filas de cada CSV, o imágenes del dataset */ + rows : number[] + /** Columnas de entrada (sin la variable objetivo); solo si todos los CSV tienen las mismas */ + features? : number + /** Clasificación: número de clases */ + classes? : number + /** Regresión y series temporales: variable que se predice */ + target? : string + /** Serie temporal: cada cuánto hay una fila (las filas se cuentan en meses, días…) */ + frequency?: N4LFrequency_t + /** Imágenes en lugar de filas de un CSV: cómo son (tamaño y canales: 1 gris, 3 color) */ + images? : { width: number, height: number, channels: number } + /** Página original del dataset (UCI, Kaggle…) */ + source? : string +} + +/** Un modelo o un conjunto de un menú: su título (i18n), su clave en la dirección y, si la tiene, su frase en /datasets */ +export type TaskOption_t = { i18n: string, value: string, summary?: string, info?: DatasetInfo_t } +export type TaskKind_t = 'model' | 'dataset' + +/** Modelos preentrenados (`model`) o datasets con los que entrenar (`dataset`) de una tarea */ +export function taskOptions(task: string, kind: TaskKind_t): TaskOption_t[] { + const options: Record = kind === 'model' ? TASK_MODEL_OPTIONS : TASK_DATASET_OPTIONS + return options[task] ?? [] +} + +export { + TASK_MODEL_OPTIONS, + TASK_DATASET_OPTIONS, +} diff --git a/src/assets/es.svg b/src/assets/es.svg deleted file mode 100644 index 815e0f8..0000000 --- a/src/assets/es.svg +++ /dev/null @@ -1,544 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/assets/gb.svg b/src/assets/gb.svg deleted file mode 100644 index dbac25e..0000000 --- a/src/assets/gb.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/src/assets/moon.svg b/src/assets/moon.svg deleted file mode 100644 index 4cd8820..0000000 --- a/src/assets/moon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/src/assets/sun.svg b/src/assets/sun.svg deleted file mode 100644 index c311208..0000000 --- a/src/assets/sun.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/src/components/_context/DataFramePlotContext.tsx b/src/components/_context/DataFramePlotContext.tsx index 60f973b..5909709 100644 --- a/src/components/_context/DataFramePlotContext.tsx +++ b/src/components/_context/DataFramePlotContext.tsx @@ -1,8 +1,8 @@ -import { createContext, useState } from "react" -import { DataFrame } from "danfojs" +import { createContext, useState } from 'react' +import { DataFrame } from 'danfojs' -import { DEFAULT_DATAFRAME_PLOT_CONFIG } from "./CONSTANTS" -import type { DataframePlotConfig_t } from "@core/types" +import { DEFAULT_DATAFRAME_PLOT_CONFIG } from './CONSTANTS' +import type { DataframePlotConfig_t } from '@core/types' /** * @typedef DataFramePlotContext_t @@ -27,7 +27,6 @@ type DataFramePlotContext_t = { setShowOptions : React.Dispatch> } -/** @type {import('react').Context} */ // TypeScript change antes {} en vez de null const DataFramePlotContext = createContext(null as unknown as DataFramePlotContext_t) diff --git a/src/components/a11y/N4LAnnouncer.tsx b/src/components/a11y/N4LAnnouncer.tsx new file mode 100644 index 0000000..72e466d --- /dev/null +++ b/src/components/a11y/N4LAnnouncer.tsx @@ -0,0 +1,36 @@ +import { useEffect, useState } from 'react' + +import { subscribeAnnouncements } from '@core/a11y/announce' + +/** Lo que se espera entre vaciar la región y poner el mensaje: así se anuncia también uno igual al anterior */ +const RESET_MS = 100 + +/** + * La región (oculta) en la que el lector de pantalla oye lo que se anuncia con `announce()`. Lo que llega casi a la vez + * (borrar una capa y que se arregle su aviso) se dice junto: si no, el último taparía a los demás + */ +export default function N4LAnnouncer() { + const [message, setMessage] = useState('') + useEffect(() => { + let timer = 0 + let pending: string[] = [] + const unsubscribe = subscribeAnnouncements((next) => { + if (pending.at(-1) !== next) pending.push(next) + setMessage('') + window.clearTimeout(timer) + timer = window.setTimeout(() => { + setMessage(pending.join(' ')) + pending = [] + }, RESET_MS) + }) + return () => { + unsubscribe() + window.clearTimeout(timer) + } + }, []) + return ( +
+ {message} +
+ ) +} diff --git a/src/components/a11y/N4LDialogFocusWrap.tsx b/src/components/a11y/N4LDialogFocusWrap.tsx new file mode 100644 index 0000000..e5001e2 --- /dev/null +++ b/src/components/a11y/N4LDialogFocusWrap.tsx @@ -0,0 +1,39 @@ +import { useEffect } from 'react' + +const TABBABLE = 'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), summary, [tabindex]:not([tabindex="-1"])' + +/** El diálogo modal abierto que está encima de los demás (el último en la página), si hay alguno */ +const topDialog = () => Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"], [role="alertdialog"][aria-modal="true"]')) + .filter((dialog) => dialog.getClientRects().length > 0) + .at(-1) + +/** + * Con un diálogo modal abierto, el tabulador da la vuelta dentro de él (de lo último a lo primero y al revés), como + * pide el patrón de diálogo de ARIA. Los modales de React-Bootstrap devuelven el foco si sale a otra parte de la + * página, pero no si pasa de su último elemento: entonces se iba a la barra del navegador. + */ +export default function N4LDialogFocusWrap() { + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key !== 'Tab' || event.defaultPrevented) return + const dialog = topDialog() + if (dialog === undefined) return + const tabbables = Array.from(dialog.querySelectorAll(TABBABLE)).filter((element) => element.getClientRects().length > 0) + if (tabbables.length === 0) return + const first = tabbables[0] + const last = tabbables[tabbables.length - 1] + const active = document.activeElement + const isOutside = active === null || !dialog.contains(active) + if (event.shiftKey && (active === first || active === dialog || isOutside)) { + event.preventDefault() + last.focus() + } else if (!event.shiftKey && (active === last || isOutside)) { + event.preventDefault() + first.focus() + } + } + document.addEventListener('keydown', handleKeyDown) + return () => document.removeEventListener('keydown', handleKeyDown) + }, []) + return null +} diff --git a/src/components/analytics/N4LAnalytics.tsx b/src/components/analytics/N4LAnalytics.tsx new file mode 100644 index 0000000..1fd8928 --- /dev/null +++ b/src/components/analytics/N4LAnalytics.tsx @@ -0,0 +1,109 @@ +import { useEffect, useLayoutEffect, useState, useSyncExternalStore } from 'react' +import { useLocation } from 'react-router' +import { useTranslation } from 'react-i18next' + +import { setUserProperties, trackEvent, trackPageView } from '@core/analytics' +import { clickTargetName, pageContextFromPath } from '@core/analyticsPage' +import { getActiveTFBackend, subscribeActiveTFBackend } from '@core/tfBackend' +import { useTheme } from '@hooks/useTheme' + +const BASENAME = import.meta.env.VITE_PATH ?? '' +// Errores distintos que se envían como mucho en una visita: un error en bucle no llena las analíticas +const MAX_EXCEPTIONS = 10 + +/** Cuenta el tiempo con la pestaña visible; `send` envía lo contado desde la última vez (si llega a un segundo) */ +function createPageTimer() { + let accumulated = 0 + let visibleSince: number | null = document.visibilityState === 'visible' ? performance.now() : null + return { + pause() { + if (visibleSince !== null) accumulated += performance.now() - visibleSince + visibleSince = null + }, + resume() { + visibleSince ??= performance.now() + }, + send() { + const now = performance.now() + const seconds = Math.round((accumulated + (visibleSince === null ? 0 : now - visibleSince)) / 1000) + accumulated = 0 + if (visibleSince !== null) visibleSince = now + if (seconds >= 1) trackEvent('page_time', { engaged_seconds: seconds }) + }, + } +} + +/** + * Las analíticas que no dependen de cada página (docs/analytics.md): páginas vistas con su contexto, tiempo en cada + * página, clics, idioma, tema y backend del usuario, y errores sin capturar. Sin consentimiento, trackEvent no envía nada. + */ +export default function N4LAnalytics() { + const location = useLocation() + const { i18n } = useTranslation() + const language = i18n.resolvedLanguage ?? i18n.language + const theme = useTheme() + const backend = useSyncExternalStore(subscribeActiveTFBackend, getActiveTFBackend) + const [timer] = useState(createPageTimer) + + // Antes que los efectos de la página nueva: lo que envíe al montarse ya lleva su contexto. El tiempo, de la anterior + useLayoutEffect(() => { + timer.send() + const context = pageContextFromPath(location.pathname, location.search) + // Una ruta que no existe redirige enseguida a la 404, que la registra (not_found): no es una página vista más + if (context.page_type !== 'other') trackPageView(window.location.href, context) + }, [timer, location.pathname, location.search]) + + // Al ocultar la pestaña (cambiar de app, bloquear el móvil, cerrarla) se envía el tiempo: puede no haber otra ocasión + useEffect(() => { + const handleVisibility = () => { + if (document.visibilityState === 'hidden') { + timer.pause() + timer.send() + } else { + timer.resume() + } + } + document.addEventListener('visibilitychange', handleVisibility) + return () => document.removeEventListener('visibilitychange', handleVisibility) + }, [timer]) + + // Los clics, en la fase de captura: los ve aunque un componente pare la propagación + useEffect(() => { + const handleClick = (event: MouseEvent) => { + const element = clickTargetName(event.target, BASENAME) + if (element !== null) trackEvent('ui_click', { element }) + } + document.addEventListener('click', handleClick, { capture: true }) + return () => document.removeEventListener('click', handleClick, { capture: true }) + }, []) + + // Idioma, tema y backend, para segmentar todo lo demás (los cambios del usuario los registran changeUserLanguage, + // changeUserTheme y changeUserTFBackend: aquí también cambian al cargar) + useEffect(() => { + setUserProperties({ app_language: language, app_theme: theme, tf_backend: backend }) + }, [language, theme, backend]) + + // Errores que nadie captura: qué falla y en qué página + useEffect(() => { + const sent = new Set() + const report = (description: string) => { + const text = description.slice(0, 100) + if (sent.has(text) || sent.size >= MAX_EXCEPTIONS) return + sent.add(text) + trackEvent('exception', { description: text, fatal: false }) + } + const handleError = (event: ErrorEvent) => report(event.message || 'error') + const handleRejection = (event: PromiseRejectionEvent) => { + const reason: unknown = event.reason + report(reason instanceof Error ? `${reason.name}: ${reason.message}` : String(reason)) + } + window.addEventListener('error', handleError) + window.addEventListener('unhandledrejection', handleRejection) + return () => { + window.removeEventListener('error', handleError) + window.removeEventListener('unhandledrejection', handleRejection) + } + }, []) + + return null +} diff --git a/src/components/breadcrumb/N4LBreadcrumb.tsx b/src/components/breadcrumb/N4LBreadcrumb.tsx new file mode 100644 index 0000000..9798070 --- /dev/null +++ b/src/components/breadcrumb/N4LBreadcrumb.tsx @@ -0,0 +1,120 @@ +import { Dropdown } from 'react-bootstrap' +import { Link } from 'react-router' +import { Trans, useTranslation } from 'react-i18next' + +import { N4LDropdownLink } from '@components/dropdown/N4LDropdownItems' +import { TASK_INFO } from '@components/task/taskInfo' +import { taskOptions, type TaskKind_t } from '@/TASK_OPTIONS' +import { UPLOAD, type TASKS_TYPE_V } from '@/TASKS' +import { useLocalPackageName } from '@hooks/useLocalPackages' + +const KIND_I18N: Record = { + model : 'breadcrumb.models', + dataset: 'breadcrumb.datasets', +} + +// Desde un modelo preentrenado se puede ir a entrenar con su dataset, y al revés (comparten la clave) +const OTHER_KIND: Record = { + model : { kind: 'dataset', i18n: 'breadcrumb.train-with-dataset' }, + dataset: { kind: 'model', i18n: 'breadcrumb.try-pretrained' }, +} + +type N4LBreadcrumbProps = { + task : TASKS_TYPE_V + /** Sin él, la última miga es la tarea (su página: /task/) */ + kind? : TaskKind_t + /** Modelo o dataset abierto en el playground; sin él, la última miga es la página de selección */ + example?: string +} + +/** + * Inicio › tarea › modelos preentrenados o entrenar › modelo o dataset abierto. La tarea lleva a su página (elegir + * entre los modelos ya entrenados y diseñar una red) y la última miga es un desplegable para cambiar a otro modelo o dataset de la misma lista sin volver a la + * página de selección (y, si existe, al dataset del modelo o al modelo del dataset). Siempre en una línea: si no cabe, + * los nombres se recortan con puntos suspensivos. + */ +export default function N4LBreadcrumb(props: N4LBreadcrumbProps) { + const { t } = useTranslation() + const { i18nTitle } = TASK_INFO[props.task] + if (props.kind === undefined) { + return ( + + ) + } + return +} + +function N4LBreadcrumbKind({ task, kind, example }: N4LBreadcrumbProps & { kind: TaskKind_t }) { + const { t } = useTranslation() + const { i18nTitle } = TASK_INFO[task] + const options = taskOptions(task, kind) + const current = options.find((option) => option.value === example) + const upload = options.find(({ value }) => value === UPLOAD) + const examples = options.filter(({ value }) => value !== UPLOAD) + const other = OTHER_KIND[kind] + const hasOther = example !== undefined && example !== UPLOAD && taskOptions(task, other.kind).some(({ value }) => value === example) + const href = (value: string, itemKind: TaskKind_t = kind) => `/playground/${task}/${itemKind}/${value}` + // Un paquete .n4l abierto por el usuario (local-): su nombre, el guardado con él + const localName = useLocalPackageName(task, example) + const exampleName = (value: string) => localName ?? value + + const item = ({ i18n, value }: { i18n: string, value: string }) => ( + + {t(i18n)} + + ) + + return ( + + ) +} diff --git a/src/components/chart/N4LChartData.tsx b/src/components/chart/N4LChartData.tsx new file mode 100644 index 0000000..18b7e58 --- /dev/null +++ b/src/components/chart/N4LChartData.tsx @@ -0,0 +1,72 @@ +import { useId, useMemo, useState } from 'react' +import { Button, Table } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import N4LPagination from '@components/table/N4LPagination' + +export type ChartDataCell_t = string | number | null | undefined + +type N4LChartDataProps = { + /** Qué tabla es («Pérdida por época»): su título y el nombre de su región */ + caption : string + /** Encabezados; la primera columna es el encabezado de cada fila (la época, la fecha, la clase…) */ + columns : string[] + rows : ChartDataCell_t[][] + /** Filas por página: con más, la tabla se pagina */ + pageSize? : number + /** Decimales como mucho de los números */ + digits? : number + className?: string +} + +/** + * «Ver los datos» de una gráfica (WCAG 1.1.1, 1.3.1): un botón que despliega una tabla con lo que está dibujado, para + * quien no ve la gráfica o prefiere leer los valores. La frase que describe la gráfica (su aria-label) dice lo + * importante; la tabla, todo. + */ +export default function N4LChartData({ caption, columns, rows, pageSize = 25, digits = 4, className = '' }: N4LChartDataProps) { + const { t, i18n } = useTranslation() + const [isOpen, setIsOpen] = useState(false) + const [page, setPage] = useState(0) + const panelId = useId() + const number = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumFractionDigits: digits }), [i18n.language, digits]) + const format = (value: ChartDataCell_t) => (value === null || value === undefined || (typeof value === 'number' && !Number.isFinite(value)) + ? '—' + : typeof value === 'number' ? number.format(value) : value) + + const pageCount = Math.ceil(rows.length / pageSize) + const current = Math.min(page, Math.max(0, pageCount - 1)) + const shown = rows.slice(current * pageSize, (current + 1) * pageSize) + + return ( +
+ + {isOpen &&
+
+ + + + {columns.map((column) => )} + + + {shown.map((row, index) => ( + + {row.map((cell, column) => (column === 0 + ? + : ))} + + ))} + +
+ {caption} + {pageCount > 1 && , {t('chart-data.rows', { from: current * pageSize + 1, to: current * pageSize + shown.length, total: rows.length })}} +
{column}
{format(cell)}{format(cell)}
+
+ +
} +
+ ) +} diff --git a/src/components/chart/plotTables.ts b/src/components/chart/plotTables.ts new file mode 100644 index 0000000..b3557dd --- /dev/null +++ b/src/components/chart/plotTables.ts @@ -0,0 +1,30 @@ +import type { Data } from 'plotly.js' + +import type { ChartDataCell_t } from '@components/chart/N4LChartData' +import type { PlotTable_t } from '@components/dataframe/N4LPlot' + +type BarTrace_t = { type?: string, name?: string, x?: ArrayLike, y?: ArrayLike } +type BoxTrace_t = { type?: string, name?: string, q1?: number[], median?: number[], q3?: number[], mean?: number[], lowerfence?: number[], upperfence?: number[] } + +/** + * La tabla de unas barras de Plotly (un histograma, unas frecuencias): una fila por cada valor del eje X y una + * columna por serie (cada clase, o el total si no hay clases) + */ +export function barTracesTable(traces: Data[], xLabel: string, valueLabel: string): PlotTable_t { + const bars = (traces as BarTrace_t[]).filter(({ type }) => type === undefined || type === 'bar') + const xs = Array.from(bars[0]?.x ?? []) + return { + columns: [xLabel, ...bars.map(({ name }, index) => (bars.length === 1 || name === undefined ? valueLabel : name ?? String(index + 1)))], + rows : xs.map((x, row) => [x, ...bars.map(({ y }) => (y === undefined ? null : y[row]))]), + } +} + +/** La tabla de unos diagramas de caja de Plotly: cada grupo con sus cuartiles, su media y sus límites */ +export function boxTracesTable(traces: Data[], columns: { group: string, lower: string, q1: string, median: string, q3: string, upper: string, mean: string }): PlotTable_t { + const boxes = (traces as BoxTrace_t[]).filter(({ type }) => type === 'box') + return { + columns: [columns.group, columns.lower, columns.q1, columns.median, columns.q3, columns.upper, columns.mean], + rows : boxes.map(({ name, q1, median, q3, mean, lowerfence, upperfence }) => + [name ?? '', lowerfence?.[0], q1?.[0], median?.[0], q3?.[0], upperfence?.[0], mean?.[0]]), + } +} diff --git a/src/components/cookiesBanner/AnalyticsDisclosure.tsx b/src/components/cookiesBanner/AnalyticsDisclosure.tsx new file mode 100644 index 0000000..ccea2b1 --- /dev/null +++ b/src/components/cookiesBanner/AnalyticsDisclosure.tsx @@ -0,0 +1,38 @@ +import { Col, Row } from 'react-bootstrap' +import { CheckCircleFill, XCircleFill } from 'react-bootstrap-icons' +import { useTranslation } from 'react-i18next' + +/** Qué mide Google Analytics y qué no se envía nunca (el aviso de cookies y los términos dicen lo mismo) */ +export default function AnalyticsDisclosure() { + const { t } = useTranslation() + // Sin las traducciones cargadas, t devuelve la clave: entonces no hay lista + const list = (key: string): string[] => { + const value: unknown = t(key, { returnObjects: true }) + return Array.isArray(value) ? value : [] + } + + return ( + + +

{t('cookies-policies.measured-title')}

+
    + {list('cookies-policies.measured').map((item) => ( +
  • + {item} +
  • + ))} +
+ + +

{t('cookies-policies.never-title')}

+
    + {list('cookies-policies.never').map((item) => ( +
  • + {item} +
  • + ))} +
+ +
+ ) +} diff --git a/src/components/cookiesBanner/N4LCookiesBanner.tsx b/src/components/cookiesBanner/N4LCookiesBanner.tsx new file mode 100644 index 0000000..4364ffd --- /dev/null +++ b/src/components/cookiesBanner/N4LCookiesBanner.tsx @@ -0,0 +1,127 @@ +import { useEffect, useLayoutEffect, useRef, useState } from 'react' +import { Button, CloseButton, Container } from 'react-bootstrap' +import { Link } from 'react-router' +import { Trans, useTranslation } from 'react-i18next' + +import { OPEN_CONSENT_EVENT, readConsent, saveConsent, type AnalyticsConsent_t } from '@core/analytics' +import AnalyticsDisclosure from './AnalyticsDisclosure' + +/** + * Aviso de cookies en la parte de abajo. No bloquea la página: se puede seguir usando sin decidir, y mientras tanto no + * se carga Google Analytics. Explica para qué sirven las analíticas y, desplegando, qué se mide y qué no se envía nunca. + * Aceptar y rechazar están al mismo nivel, uno junto al otro y del mismo tamaño (lo exigen el RGPD y la AEPD: si + * rechazar costara más, el consentimiento no valdría). Al abrirlo otra vez desde "Preferencias de cookies" dice qué se + * decidió y se puede cerrar sin cambiar nada. + */ +export default function N4LCookiesBanner() { + const { t } = useTranslation() + const [show, setShow] = useState(() => readConsent() === null) + const [consent, setConsent] = useState(readConsent) + const banner_ref = useRef(null) + // Lo que lo abrió desde el pie («Preferencias de cookies»): al cerrarlo, el foco vuelve ahí + const opener_ref = useRef(null) + const focusOnShow_ref = useRef(false) + + // El pie de página permite cambiar la decisión más adelante; al abrirlo así, el foco va al aviso (si no, quien usa el + // teclado no sabría que ha aparecido: está al principio de la página) + useEffect(() => { + const open = () => { + opener_ref.current = document.activeElement instanceof HTMLElement ? document.activeElement : null + focusOnShow_ref.current = true + setConsent(readConsent()) + setShow(true) + } + window.addEventListener(OPEN_CONSENT_EVENT, open) + return () => window.removeEventListener(OPEN_CONSENT_EVENT, open) + }, []) + useEffect(() => { + if (!show || !focusOnShow_ref.current) return + focusOnShow_ref.current = false + document.getElementById('n4l-cookies-banner-title')?.focus() + }, [show]) + + // Está fijo abajo: la página deja su alto libre al final, para que no tape lo último ni lo que tiene el foco (WCAG + // 2.4.11; --n4l-cookies-height en globals.css) + useLayoutEffect(() => { + const element = banner_ref.current + const root = document.documentElement + if (!show || element === null) return + const update = () => root.style.setProperty('--n4l-cookies-height', `${element.offsetHeight}px`) + update() + const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(update) + observer?.observe(element) + return () => { + observer?.disconnect() + root.style.removeProperty('--n4l-cookies-height') + } + }, [show]) + + // Al cerrarlo, el foco no se pierde: vuelve a lo que lo abrió o, la primera vez, a la página + const hide = () => { + const hadFocus = banner_ref.current?.contains(document.activeElement) ?? false + setShow(false) + if (!hadFocus) return + const opener = opener_ref.current + opener_ref.current = null + window.requestAnimationFrame(() => { + if (opener !== null && opener.isConnected) { + opener.focus() + return + } + const main = Array.from(document.querySelectorAll('main')).find((element) => element.getClientRects().length > 0) + if (main === undefined) return + if (!main.hasAttribute('tabindex')) main.setAttribute('tabindex', '-1') + main.focus({ preventScroll: true }) + }) + } + + const handleClick_Decide = (decision: AnalyticsConsent_t) => { + saveConsent(decision, 'banner') + setConsent(decision) + hide() + } + + if (!show) return null + + return ( +
+ +
+
+

{t('cookies-policies.banner-title')}

+

+ +

+
+ {t('cookies-policies.details')} +
+ +
+
+

+ {consent !== null && {t('pages.settings.privacy.status-' + consent)}} + setShow(false)}> + {/* Un separador que se ve, pero el lector no lee */} + | + setShow(false)}> +

+
+
+ + + {/* Ya hay una decisión: se puede cerrar sin cambiarla */} + {consent !== null && } +
+
+
+
+ ) +} diff --git a/src/components/cookiesModal/CookiesModal.css b/src/components/cookiesModal/CookiesModal.css deleted file mode 100644 index c5efbd4..0000000 --- a/src/components/cookiesModal/CookiesModal.css +++ /dev/null @@ -1,10 +0,0 @@ -.n4l-cookies .modal-dialog { - display: flex; - flex-direction: row; - align-items: center; - justify-content: center; - height: 80vh; -} -.n4l-cookies .modal-content { - width: 100%; -} diff --git a/src/components/cookiesModal/CookiesModal.tsx b/src/components/cookiesModal/CookiesModal.tsx deleted file mode 100644 index 414b5c7..0000000 --- a/src/components/cookiesModal/CookiesModal.tsx +++ /dev/null @@ -1,78 +0,0 @@ -import './CookiesModal.css' -import { useState } from 'react' -import { Button, Modal } from 'react-bootstrap' -import { Trans } from 'react-i18next' - -// Constante para evitar errores de escritura -const COOKIE_NAME = 'n4l-accept-cookies' -const COOKIE_EXPIRATION_DAYS = 120 - -// Utilidad para obtener cookies de forma segura en TS -const getCookie = (name: string): string | null => { - const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)')) - if (match) return match[2] - return null -} - -// Utilidad para establecer cookies -const setCookie = (name: string, value: string, days: number) => { - const d = new Date() - d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000) - const expires = 'expires=' + d.toUTCString() - // SameSite=Lax es recomendable hoy en día para seguridad básica - document.cookie = `${name}=${value};${expires};path=/;SameSite=Lax` -} - -export default function CookiesModal() { - // Inicializamos el estado comprobando la cookie directamente. - // Esto se ejecuta solo una vez al montar el componente. - const [show, setShow] = useState(() => { - const cookieValue = getCookie(COOKIE_NAME) - return cookieValue !== 'true' - }) - - const handleAccept = () => { - setCookie(COOKIE_NAME, 'true', COOKIE_EXPIRATION_DAYS) - setShow(false) - } - - // Si la cookie ya existe y es true, no renderizamos nada (opcional, pero limpio) - if (!show) return null - - return ( - setShow(false)} - size="lg" - centered // Centra el modal verticalmente (buena práctica visual) - > - - - - - - - -

- -

-

- -

-
- - - - -
- ) -} \ No newline at end of file diff --git a/src/components/dataframe/DataFrameCard.tsx b/src/components/dataframe/DataFrameCard.tsx index e5913bf..b802edd 100644 --- a/src/components/dataframe/DataFrameCard.tsx +++ b/src/components/dataframe/DataFrameCard.tsx @@ -24,7 +24,7 @@ export default function DataFrameCard({ title, ready = true, description, childr const [showDescription, setShowDescription] = useState(false) return <> - +

{description && (
diff --git a/src/components/dataframe/DataFrameCorrelationMatrix.tsx b/src/components/dataframe/DataFrameCorrelationMatrix.tsx deleted file mode 100644 index 5bddff3..0000000 --- a/src/components/dataframe/DataFrameCorrelationMatrix.tsx +++ /dev/null @@ -1,117 +0,0 @@ -import { useMemo, useRef } from 'react' -import { useTranslation } from 'react-i18next' -import Plot from './Plot' -import * as dfd from 'danfojs' - -import math from '@utils/math' -import { pearsonCorrelation } from '@utils/statistics' - -type CorrelationMatrix_t = { - xValues : string[], - yValues : string[], - zValues : number[][], - annotations: any[] -} - -const DEFAULT_CORRELATION_MATRIX: CorrelationMatrix_t = { - xValues : [], - yValues : [], - zValues : [], - annotations: [] -} - -export default function DataFrameCorrelationMatrix({ dataframe }: { dataframe: dfd.DataFrame }) { - const { t } = useTranslation() - // Usamos useRef con tipo 'any' o el tipo específico de Plotly si lo tienes - const refPlotly = useRef(null) - - // REFACTORIZACIÓN: Usamos useMemo en lugar de useState + useEffect - const correlationMatrix = useMemo((): CorrelationMatrix_t => { - // 1. Filtrar columnas numéricas - const columns: string[] = dataframe.columns.filter((column_name) => { - // Nota: Asegúrate de que tu versión de danfojs soporte esta comprobación de dtype - return dataframe[column_name].dtype !== 'string' - }) - - if (columns.length === 0) return DEFAULT_CORRELATION_MATRIX - - const columns_X: string[] = Array.from(columns) - const columns_Y: string[] = Array.from(columns).reverse() - - const _matrix: number[][] = [] - const _annotations: any[] = [] - - // 2. Calcular matriz y anotaciones - for (let i = 0; i < columns_X.length; i++) { - const column_name_x = columns_X[i] - _matrix.push([]) - - for (let j = 0; j < columns_Y.length; j++) { - const column_name_y = columns_Y[j] - - const correlation = pearsonCorrelation(dataframe, column_name_x, column_name_y) - _matrix[i][j] = correlation - - // Lógica de anotación (color del texto según valor) - const textColor = (correlation <= 0.0) ? 'white' : 'black' - - _annotations.push({ - xref: 'x1', - yref: 'y1', - x : column_name_x, - y : column_name_y, - text: (correlation.toFixed(4)).toString(), - font: { - family: 'Arial', - size : 12, - color : textColor - }, - showarrow: false, - }) - } - } - - // 3. Transponer si es necesario (según tu lógica original) - const new_matrix: number[][] = math.transpose(_matrix) - - return { - xValues : columns_X, - yValues : columns_Y, - zValues : new_matrix, - annotations: _annotations - } - - }, [dataframe]) // 👈 Solo recalculamos si cambia el dataframe - - return <> - - - -} \ No newline at end of file diff --git a/src/components/dataframe/DataFrameCorrelationMatrixCard.tsx b/src/components/dataframe/DataFrameCorrelationMatrixCard.tsx deleted file mode 100644 index 9a74786..0000000 --- a/src/components/dataframe/DataFrameCorrelationMatrixCard.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import * as dfd from 'danfojs' -import DataFrameCard from '@components/dataframe/DataFrameCard' -import DataFrameCorrelationMatrix from '@components/dataframe/DataFrameCorrelationMatrix' -import DataFrameCorrelationMatrixModalDescription from '@components/dataframe/DataFrameCorrelationMatrixModalDescription' - -type DataFrameCorrelationMatrixCardProps = { - dataframe : dfd.DataFrame - isDataFrameProcessed: boolean -} - -export default function DataFrameCorrelationMatrixCard({ dataframe, isDataFrameProcessed }: DataFrameCorrelationMatrixCardProps) { - return ( - - - - ) -} diff --git a/src/components/dataframe/DataFrameCorrelationMatrixModalDescription.tsx b/src/components/dataframe/DataFrameCorrelationMatrixModalDescription.tsx index f661c5b..318dba6 100644 --- a/src/components/dataframe/DataFrameCorrelationMatrixModalDescription.tsx +++ b/src/components/dataframe/DataFrameCorrelationMatrixModalDescription.tsx @@ -1,5 +1,6 @@ +import { useId } from 'react' import { Modal } from 'react-bootstrap' -import { Trans } from 'react-i18next' +import { Trans, useTranslation } from 'react-i18next' import N4LLatex from '@components/latex/N4LLatex' type DataFrameCorrelationMatrixModalDescriptionProps = { @@ -7,17 +8,20 @@ type DataFrameCorrelationMatrixModalDescriptionProps = { setShowDescription: (show: boolean) => void } export default function DataFrameCorrelationMatrixModalDescription(props: DataFrameCorrelationMatrixModalDescriptionProps) { + const { t } = useTranslation() + // El diálogo se llama como su título (WCAG 4.1.2) y su botón de cerrar, en el idioma de la página + const titleId = useId() const { showDescription, setShowDescription } = props const URL = 'https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.corr.html' return <> - setShowDescription(false)} size={'xl'} fullscreen={'md-down'}> - - + +

@@ -47,7 +51,7 @@ export default function DataFrameCorrelationMatrixModalDescription(props: DataFr

link + link1: link }} />

diff --git a/src/components/dataframe/DataFrameDataset.tsx b/src/components/dataframe/DataFrameDataset.tsx deleted file mode 100644 index e4dfdb2..0000000 --- a/src/components/dataframe/DataFrameDataset.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as dfd from 'danfojs' -import N4LTablePagination from '@components/table/N4LTablePagination' -import { DataFrameIterRows } from '@core/dataframe/DataFrameUtils' - -type DataFrameDatasetProps = { - dataframe: dfd.DataFrame -} - -/** Tabla paginada con las filas de un dataframe. */ -export default function DataFrameDataset({ dataframe }: DataFrameDatasetProps) { - return -} diff --git a/src/components/dataframe/DataFrameDatasetCard.tsx b/src/components/dataframe/DataFrameDatasetCard.tsx deleted file mode 100644 index 5636ff9..0000000 --- a/src/components/dataframe/DataFrameDatasetCard.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import * as dfd from 'danfojs' -import DataFrameCard from '@components/dataframe/DataFrameCard' -import DataFrameDataset from '@components/dataframe/DataFrameDataset' - -type DataFrameDatasetCardProps = { - dataframe: dfd.DataFrame -} - -export default function DataFrameDatasetCard({ dataframe }: DataFrameDatasetCardProps) { - return ( - - - - ) -} diff --git a/src/components/dataframe/DataFrameDescribe.tsx b/src/components/dataframe/DataFrameDescribe.tsx deleted file mode 100644 index 83ba926..0000000 --- a/src/components/dataframe/DataFrameDescribe.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { useEffect, useId } from 'react' -import { useTranslation } from 'react-i18next' -import { TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_2 } from '@/CONSTANTS_DanfoJS' -import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' -import * as dfd from 'danfojs' - -export default function DataFrameDescribe(props: { dataframe: dfd.DataFrame }) { - const { dataframe } = props - const dataframeID = useId() - const { t } = useTranslation() - - useEffect(() => { - if (dataframe.columns.length > 0) { - DataFrameUtils.DataFrameDescribePlot(dataframe, dataframeID, { - config : TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_2, - emptyText: t('dataframe.describe.no-numeric'), - transpose: true, - }) - } - }, [dataframe, dataframeID, t]) - - return <> -
- -} diff --git a/src/components/dataframe/DataFrameDescribeCard.tsx b/src/components/dataframe/DataFrameDescribeCard.tsx deleted file mode 100644 index 66b929c..0000000 --- a/src/components/dataframe/DataFrameDescribeCard.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import * as dfd from 'danfojs' -import DataFrameCard from '@components/dataframe/DataFrameCard' -import DataFrameDescribe from '@components/dataframe/DataFrameDescribe' -import DataFrameDescribeModalDescription from '@components/dataframe/DataFrameDescribeModalDescription' - -type DataFrameDescribeCardProps = { - dataframe : dfd.DataFrame - isDataFrameProcessed: boolean -} - -export default function DataFrameDescribeCard({ dataframe, isDataFrameProcessed }: DataFrameDescribeCardProps) { - return ( - - - - ) -} diff --git a/src/components/dataframe/DataFrameDescribeModalDescription.tsx b/src/components/dataframe/DataFrameDescribeModalDescription.tsx index 698b142..3b67202 100644 --- a/src/components/dataframe/DataFrameDescribeModalDescription.tsx +++ b/src/components/dataframe/DataFrameDescribeModalDescription.tsx @@ -1,4 +1,5 @@ -import { Trans } from 'react-i18next' +import { useId } from 'react' +import { Trans, useTranslation } from 'react-i18next' import { Modal } from 'react-bootstrap' type DataFrameDescribeModalDescriptionProps = { @@ -6,16 +7,19 @@ type DataFrameDescribeModalDescriptionProps = { setShowDescription: (show: boolean) => void } export default function DataFrameDescribeModalDescription (props: DataFrameDescribeModalDescriptionProps) { + const { t } = useTranslation() + // El diálogo se llama como su título (WCAG 4.1.2) y su botón de cerrar, en el idioma de la página + const titleId = useId() const { showDescription, setShowDescription } = props const URL = 'https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.describe.html' return <> - setShowDescription(false)} size={'xl'} fullscreen={'md-down'}> - - + +

@@ -25,7 +29,7 @@ export default function DataFrameDescribeModalDescription (props: DataFrameDescr

link + link1: link }} />

diff --git a/src/components/dataframe/DataFramePlot.tsx b/src/components/dataframe/DataFramePlot.tsx index d60caca..bd84dbb 100644 --- a/src/components/dataframe/DataFramePlot.tsx +++ b/src/components/dataframe/DataFramePlot.tsx @@ -17,6 +17,8 @@ import DataFramePlotModalDescription from './DataFramePlotModalDescription' import DataFramePlotContext from '../_context/DataFramePlotContext' import { E_PLOTS, LIST_PLOTS } from '../_context/CONSTANTS' import { VERBOSE } from '@/CONSTANTS' +import { useTheme } from '@hooks/useTheme' +import { TABLE_PALETTE } from '@core/dataframe/DataFrameTable' /** * @typedef DataFramePlotProps_t @@ -51,6 +53,7 @@ export default function DataFramePlot(props: DataFramePlotProps_t) { const showDataframe = isDataFrameProcessed const dataframe_plot_ID = useId() + const theme = useTheme() const init = useCallback(() => { // Funciones para inicializar TIME_SERIES_PLOTS @@ -129,10 +132,14 @@ export default function DataFramePlot(props: DataFramePlotProps_t) { return { warnings: [] } } + // Fondo transparente y texto del tema: el gráfico se ve igual que la tarjeta en modo claro y oscuro const layout = { - title: dataframePlotConfig.LAYOUT.title, - xaxis: { title: dataframePlotConfig.LAYOUT.x_axis }, - yaxis: { title: dataframePlotConfig.LAYOUT.y_axis }, + title : dataframePlotConfig.LAYOUT.title, + xaxis : { title: dataframePlotConfig.LAYOUT.x_axis, gridcolor: TABLE_PALETTE[theme].line, zerolinecolor: TABLE_PALETTE[theme].line }, + yaxis : { title: dataframePlotConfig.LAYOUT.y_axis, gridcolor: TABLE_PALETTE[theme].line, zerolinecolor: TABLE_PALETTE[theme].line }, + paper_bgcolor: 'rgba(0, 0, 0, 0)', + plot_bgcolor : 'rgba(0, 0, 0, 0)', + font : { family: getComputedStyle(document.body).fontFamily, color: TABLE_PALETTE[theme].text }, } const warnings: string[] = [] @@ -220,7 +227,7 @@ export default function DataFramePlot(props: DataFramePlotProps_t) { } return { warnings, draw } - }, [dataFrameLocal, dataframePlotConfig, dataframe_plot_ID, showDataframe]) + }, [dataFrameLocal, dataframePlotConfig, dataframe_plot_ID, showDataframe, theme]) const listWarning = plot.warnings useEffect(() => { @@ -258,12 +265,12 @@ export default function DataFramePlot(props: DataFramePlotProps_t) { if (VERBOSE) console.debug('render DataFramePlot') return <> - -

-
+ +

+
handleChange_Plot(e)} > @@ -279,16 +286,12 @@ export default function DataFramePlot(props: DataFramePlotProps_t) { -
- - - - -
- -
+ + { setStringToQuery(e.target.value) }} /> + + dataframe: df + + + +
+ +
+ + + + {result !== null && <> +

+ df[{JSON.stringify(columnOf(applied.column))}]{applied.query} +

+ {'error' in result &&

{t('dataframe.query.error', { message: result.error })}

} + {'dataframe' in result && (result.dataframe.shape[0] === 0 + ?

{t('dataframe.query.no-rows')}

+ : )} + } -} \ No newline at end of file +} diff --git a/src/components/dataframe/DataFrameQueryCard.tsx b/src/components/dataframe/DataFrameQueryCard.tsx deleted file mode 100644 index 76fa282..0000000 --- a/src/components/dataframe/DataFrameQueryCard.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import * as dfd from 'danfojs' -import { VERBOSE } from '@/CONSTANTS' -import DataFrameCard from '@components/dataframe/DataFrameCard' -import DataFrameQuery from '@components/dataframe/DataFrameQuery' -import DataFrameQueryModalDescription from '@components/dataframe/DataFrameQueryModalDescription' - -type DataFrameQueryCardProps = { - dataframe : dfd.DataFrame - isDataFrameProcessed: boolean -} - -export default function DataFrameQueryCard({ dataframe, isDataFrameProcessed }: DataFrameQueryCardProps) { - if (VERBOSE) console.debug('render DataFrameQueryCard') - return ( - - - - ) -} diff --git a/src/components/dataframe/DataFrameQueryModalDescription.tsx b/src/components/dataframe/DataFrameQueryModalDescription.tsx index fcefd6c..c24d701 100644 --- a/src/components/dataframe/DataFrameQueryModalDescription.tsx +++ b/src/components/dataframe/DataFrameQueryModalDescription.tsx @@ -1,20 +1,24 @@ +import { useId } from 'react' import { Modal } from 'react-bootstrap' -import { Trans } from 'react-i18next' +import { Trans, useTranslation } from 'react-i18next' type DataFrameQueryModalDescriptionProps = { showDescription : boolean setShowDescription: (show: boolean) => void } export default function DataFrameQueryModalDescription (props: DataFrameQueryModalDescriptionProps) { + const { t } = useTranslation() + // El diálogo se llama como su título (WCAG 4.1.2) y su botón de cerrar, en el idioma de la página + const titleId = useId() const { showDescription, setShowDescription } = props const URL = 'https://danfo.jsdata.org/api-reference/dataframe/danfo.dataframe.query' return <> - setShowDescription(false)} size={'xl'} fullscreen={'md-down'}> - - + +

@@ -46,7 +50,7 @@ export default function DataFrameQueryModalDescription (props: DataFrameQueryMod

link + link1: link }} />

diff --git a/src/components/dataframe/DataFrameScatterPlot.tsx b/src/components/dataframe/DataFrameScatterPlot.tsx deleted file mode 100644 index 82cc2a1..0000000 --- a/src/components/dataframe/DataFrameScatterPlot.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import '@styles/ScrollBar.css' -import { useMemo, useRef } from 'react' -import { useTranslation } from 'react-i18next' -import Plot from './Plot' -import * as dfd from 'danfojs' - -import { VERBOSE } from '@/CONSTANTS' -import { PLOTLY_CONFIG_DEFAULT } from '@/CONSTANTS_ChartsJs' - - -type DataFrameScatterPlotProps = { - dataframe : dfd.DataFrame, - selector_x: string, - selector_y: string, -} - -export default function DataFrameScatterPlot(props: DataFrameScatterPlotProps) { - const { dataframe, selector_x, selector_y } = props - - const { t } = useTranslation() - const refPlot = useRef(null) - const data = useMemo(() => { - if (dataframe.columns.length > 0) - if (dataframe.columns.includes(selector_x) && dataframe.columns.includes(selector_y)) { - const trace: Plotly.Data = { - x : dataframe[selector_x].values.map((v: any) => v), - y : dataframe[selector_y].values.map((v: any) => v), - name : t('{{X_feature}} x {{target}}', { X_feature: selector_x, target: selector_y }), - mode : 'markers', - type : 'scatter', - opacity: 1, - marker : { - color: 'blue' - } - } - return [trace] - } - return [] - }, [dataframe, selector_x, selector_y, t]) - - if (VERBOSE) console.debug('render DataFramePlot') - return <> - - -} \ No newline at end of file diff --git a/src/components/dataframe/DataFrameScatterPlotCard.tsx b/src/components/dataframe/DataFrameScatterPlotCard.tsx deleted file mode 100644 index 2d7310f..0000000 --- a/src/components/dataframe/DataFrameScatterPlotCard.tsx +++ /dev/null @@ -1,78 +0,0 @@ -import '@styles/ScrollBar.css' -import React, { useState } from 'react' -import { Card, Form } from 'react-bootstrap' -import { Trans } from 'react-i18next' -import * as dfd from 'danfojs' - -import { VERBOSE } from '@/CONSTANTS' -import DataFrameScatterPlot from '@components/dataframe/DataFrameScatterPlot' - -type DataFrameScatterPlotCardProps = { - dataframe: dfd.DataFrame, -} -export default function DataFrameScatterPlotCard(props: DataFrameScatterPlotCardProps) { - const { dataframe } = props - const DEFAULT_SELECTOR = 'select-attr' - - const [selector, setSelector] = useState({ - selector_x: DEFAULT_SELECTOR, - selector_y: DEFAULT_SELECTOR - }) - - const handleChange_SelectorX = (event: React.ChangeEvent) => { - setSelector((prevState) => { - return { ...prevState, selector_x: event.target.value } - }) - } - const handleChange_SelectorY = (event: React.ChangeEvent) => { - setSelector((prevState) => { - return { ...prevState, selector_y: event.target.value } - }) - } - - if (VERBOSE) console.debug('render DataFrameScatterPlotCard') - return <> - - -

-
- - - - <> - {dataframe.columns.map((value, index) => { - return - })} - - - - - - <> - - {dataframe.columns.map((value, index) => { - return - })} - - - -
-
- - - -
- -} \ No newline at end of file diff --git a/src/components/dataframe/DataFrameShow.tsx b/src/components/dataframe/DataFrameShow.tsx deleted file mode 100644 index 3cd3500..0000000 --- a/src/components/dataframe/DataFrameShow.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { useEffect, useId } from 'react' -import * as dfd from 'danfojs' - -import { TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_2 } from '@/CONSTANTS_DanfoJS' - -export default function DataFrameShow(props: { dataframe: dfd.DataFrame }) { - const { dataframe } = props - const dataframeID = useId() - - useEffect(() => { - dataframe - .plot(dataframeID) - .table({ config: TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_2 }) - }, [dataframe, dataframeID]) - - return <> -
- -} \ No newline at end of file diff --git a/src/components/dataframe/DataFrameShowCard.tsx b/src/components/dataframe/DataFrameShowCard.tsx deleted file mode 100644 index db2574d..0000000 --- a/src/components/dataframe/DataFrameShowCard.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as dfd from 'danfojs' -import DataFrameCard from '@components/dataframe/DataFrameCard' -import DataFrameShow from './DataFrameShow' - -type DataFrameShowCardProps = { - dataframe : dfd.DataFrame - isDataFrameProcessed: boolean -} - -export default function DataFrameShowCard({ dataframe, isDataFrameProcessed }: DataFrameShowCardProps) { - return ( - - - - ) -} diff --git a/src/components/dataframe/N4LDataFrameDescribe.tsx b/src/components/dataframe/N4LDataFrameDescribe.tsx new file mode 100644 index 0000000..d717c96 --- /dev/null +++ b/src/components/dataframe/N4LDataFrameDescribe.tsx @@ -0,0 +1,29 @@ +import { useMemo } from 'react' +import { useTranslation } from 'react-i18next' +import type * as dfd from 'danfojs' + +import { DataFrameDescribeTable } from '@core/dataframe/DataFrameTable' +import N4LDataFrameTable from '@components/dataframe/N4LDataFrameTable' + +type N4LDataFrameDescribeProps = { + dataframe: dfd.DataFrame + /** Columna objetivo: su fila se resalta. Por defecto la última del dataframe; null para ninguna */ + target? : string | null +} + +/** describe() de danfo con una fila por columna numérica (count, mean, std…) y la del objetivo resaltada */ +export default function N4LDataFrameDescribe({ dataframe, target }: N4LDataFrameDescribeProps) { + const { t } = useTranslation() + const describe = useMemo(() => (dataframe.columns.length > 0 ? DataFrameDescribeTable(dataframe) : null), [dataframe]) + const targetRow = target === undefined ? dataframe.columns[dataframe.columns.length - 1] ?? null : target + + if (describe === null) return

{t('dataframe.describe.no-numeric')}

+ return ( + + ) +} diff --git a/src/components/dataframe/N4LDataFrameTable.tsx b/src/components/dataframe/N4LDataFrameTable.tsx new file mode 100644 index 0000000..acb18ee --- /dev/null +++ b/src/components/dataframe/N4LDataFrameTable.tsx @@ -0,0 +1,88 @@ +import { useEffect, useRef } from 'react' +import { Trans, useTranslation } from 'react-i18next' +import type * as dfd from 'danfojs' + +import { useTheme } from '@hooks/useTheme' +import { scheduleIdle } from '@core/scheduler/idleQueue' +import { + DEFAULT_MAX_ROWS, + DataFrameTablePlot, + DataFrameTablePurge, + DataFrameTableResize, + resolveTableTarget, + type DataFrameTableOptions_t, +} from '@core/dataframe/DataFrameTable' + +type N4LDataFrameTableProps = Omit & { + dataframe : dfd.DataFrame + /** Número de filas y columnas bajo la tabla (por defecto sí) */ + showShape?: boolean + className?: string +} + +/** + * Un dataframe como tabla de Plotly con los colores del tema: la columna objetivo resaltada (por defecto la última) y + * debajo qué significa ese color y el tamaño del dataframe. + */ +export default function N4LDataFrameTable({ + dataframe, + target, + targetAxis = 'column', + index = true, + indexHeader, + subtitles = null, + maxRows = DEFAULT_MAX_ROWS, + title, + showShape = true, + className = '', +}: N4LDataFrameTableProps) { + const { t } = useTranslation() + const theme = useTheme() + const ref = useRef(null) + + // Se dibuja cuando el navegador está libre: con varias tablas y gráficos, cada uno en su propia tarea corta + useEffect(() => { + if (ref.current === null || dataframe.columns.length === 0) return + const element = ref.current + return scheduleIdle(() => DataFrameTablePlot(element, dataframe, { target, targetAxis, index, indexHeader, subtitles, maxRows, title, theme })) + }, [dataframe, target, targetAxis, index, indexHeader, subtitles, maxRows, title, theme]) + + // Plotly solo se ajusta al redimensionar la ventana: si la tabla se dibuja oculta (en un
cerrado, en una + // pestaña) o cambia el ancho de la columna, se ajusta al cambiar el tamaño del contenedor + useEffect(() => { + const element = ref.current + let observer: ResizeObserver | undefined + if (element !== null && typeof ResizeObserver !== 'undefined') { + let width = element.clientWidth + observer = new ResizeObserver(() => { + if (element.clientWidth === width) return + width = element.clientWidth + DataFrameTableResize(element) + }) + observer.observe(element) + } + return () => { + observer?.disconnect() + DataFrameTablePurge(element) + } + }, []) + + const highlighted = resolveTableTarget(dataframe, { target, targetAxis }) + const [rows, columns] = dataframe.columns.length === 0 ? [0, 0] : dataframe.shape + return ( +
+
+ {(highlighted !== null || showShape) && +

+ {highlighted !== null && + + }} /> + } + {showShape && + {t('dataframe.table.shape', { rows, columns })} + {rows > maxRows && <>. {t('dataframe.table.scroll-rows')}} + } +

} +
+ ) +} diff --git a/src/components/dataframe/N4LDatasetProcessForm.tsx b/src/components/dataframe/N4LDatasetProcessForm.tsx new file mode 100644 index 0000000..f0c7642 --- /dev/null +++ b/src/components/dataframe/N4LDatasetProcessForm.tsx @@ -0,0 +1,249 @@ +import { useMemo, useState } from 'react' +import { Alert, Badge, Button, ButtonGroup, Col, Form, Nav, Row, Tab } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' +import type * as dfd from 'danfojs' + +import type * as _Types from '@core/types' +import { DEFAULT_SCALER } from '@/CONSTANTS' +import { profileColumns, type ColumnProfile_t } from '@core/dataframe/columnProfile' +import N4LDataFrameTable from '@components/dataframe/N4LDataFrameTable' + +/** Lo elegido en el formulario, ya como transformación de cada columna (las que no se usan, "drop") */ +export type DatasetProcessPlan_t = { + target : string + scaler : _Types.ScalerKey_t + transforms: _Types.DataFrameColumnTransform_t[] +} + +/** Lo que ya se ha procesado, para la pestaña de los datos procesados */ +export type DatasetProcessed_t = { + /** Codificado: cada categoría ya es un número */ + dataframe : dfd.DataFrame + /** Escalado: lo que recibe la red */ + X : dfd.DataFrame + target : string + transforms: _Types.DataFrameColumnTransform_t[] +} + +type N4LDatasetProcessFormProps = { + kind : 'classification' | 'regression' + /** El conjunto tal como se ha subido */ + dataframe: _Types.DataFrame_t + processed: DatasetProcessed_t | null + onProcess: (plan: DatasetProcessPlan_t) => void | Promise +} + +type ColumnChoice_t = { use: boolean, transform: _Types.ColumnTransform_t } +type Tab_t = 'original' | 'form' | 'processed' + +// Por encima de esto, la columna elegida como clase probablemente no lo es (un número continuo, un identificador…) +const MANY_CLASSES = 20 +const prefix = 'dataset-process.' + +/** Cómo se convierte en números una columna de entrada: las de texto, solo como categoría; las numéricas, también así */ +const transformsFor = (profile: ColumnProfile_t): _Types.ColumnTransform_t[] => + (profile.numeric ? [profile.type as _Types.ColumnTransform_t, 'label-encoder'] : ['label-encoder']) + +const defaultChoice = (profile: ColumnProfile_t): ColumnChoice_t => ({ use: true, transform: transformsFor(profile)[0] }) + +/** + * Preparar un conjunto de datos subido por el usuario, en tres pestañas: los datos tal cual; qué columna se predice, + * cómo se escalan las entradas y qué columnas se usan y cómo se convierten en números (con el resumen de lo que entrará + * en la red); y los datos procesados, codificados y escalados. Lo comparten la clasificación tabular y la regresión: cada + * una procesa a su manera lo elegido (onProcess). + */ +export default function N4LDatasetProcessForm({ kind, dataframe, processed, onProcess }: N4LDatasetProcessFormProps) { + const { t, i18n } = useTranslation() + const number = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 2 }), [i18n.language]) + const profiles = useMemo(() => profileColumns(dataframe), [dataframe]) + + const [tab, setTab] = useState(processed === null ? 'form' : 'processed') + const [target, setTarget] = useState(() => dataframe.columns.at(-1) ?? '') + const [scaler, setScaler] = useState<_Types.ScalerKey_t>(DEFAULT_SCALER) + const [choices, setChoices] = useState>(() => Object.fromEntries(profiles.map((p) => [p.name, defaultChoice(p)]))) + const [isProcessing, setIsProcessing] = useState(false) + // Otro fichero: el formulario empieza de nuevo + const [previous, setPrevious] = useState(dataframe) + if (previous !== dataframe) { + setPrevious(dataframe) + setTarget(dataframe.columns.at(-1) ?? '') + setChoices(Object.fromEntries(profiles.map((p) => [p.name, defaultChoice(p)]))) + setTab('form') + } + + const targetProfile = profiles.find(({ name }) => name === target) + const inputs = profiles.filter(({ name }) => name !== target && (choices[name]?.use ?? true)) + const targetIsText = kind === 'regression' && targetProfile !== undefined && !targetProfile.numeric + const canProcess = inputs.length > 0 && targetProfile !== undefined && !targetIsText + + const handleSubmit = async (event: React.FormEvent) => { + event.preventDefault() + if (!canProcess) return + const transforms = profiles.map((profile): _Types.DataFrameColumnTransform_t => { + const choice = choices[profile.name] ?? defaultChoice(profile) + // La clase se codifica con un número por clase; el número que se predice se queda como está + if (profile.name === target) return { column_name: profile.name, column_transform: kind === 'classification' ? 'label-encoder' : profile.type as _Types.ColumnTransform_t } + return { column_name: profile.name, column_transform: choice.use ? choice.transform : 'drop' } + }) + setIsProcessing(true) + try { + await onProcess({ target, scaler, transforms }) + setTab('processed') + } finally { + setIsProcessing(false) + } + } + + const describe = (profile: ColumnProfile_t) => profile.numeric && profile.min !== undefined + ? t(prefix + 'range', { min: number.format(profile.min), max: number.format(profile.max!), count: profile.distinct }) + : t(prefix + 'distinct', { count: profile.distinct, sample: profile.sample.join(', ') }) + + const targetInfo = () => { + if (targetProfile === undefined) return null + if (kind === 'classification') { + const many = targetProfile.distinct > MANY_CLASSES + return <> +

+ {t(prefix + 'target-classes', { name: target, count: targetProfile.distinct, sample: targetProfile.sample.join(', ') + (targetProfile.distinct > targetProfile.sample.length ? '…' : '') })} +

+ {many && {t(prefix + 'target-too-many', { count: targetProfile.distinct })}} + + } + if (targetIsText) return {t(prefix + 'target-not-numeric', { name: target })} + return

+ {t(prefix + 'target-range', { name: target, min: number.format(targetProfile.min!), max: number.format(targetProfile.max!), mean: number.format(targetProfile.mean!) })} +

+ } + + const scaled = useMemo(() => processed?.X.round(3) ?? null, [processed]) + const [view, setView] = useState<'encoded' | 'scaled'>('scaled') + const subtitles = useMemo(() => Object.fromEntries((processed?.transforms ?? []).map(({ column_name, column_transform }) => [column_name, t(prefix + 'transforms.' + column_transform, { defaultValue: column_transform })])), [processed, t]) + + return ( + setTab((key as Tab_t | null) ?? 'form')}> + + + +

{t(prefix + 'original-help', { rows: dataframe.shape[0], columns: dataframe.shape[1] })}

+ +
+ + +
+ + {/* QUÉ SE PREDICE */} + +
+

{t(prefix + kind + '.target-title')}

+

{t(prefix + kind + '.target-help')}

+ + {t(prefix + kind + '.target-title')} + setTarget(event.target.value)}> + {profiles.map(({ name }) => )} + + + {targetInfo()} +
+ + + {/* ESCALADO */} + +
+ {t(prefix + 'scaler-title')} +

{t(prefix + 'scaler-help')}

+ {(['min-max-scaler', 'standard-scaler'] as const).map((key) => ( + setScaler(key)} + label={<>{t(prefix + 'scalers.' + key + '.name')} + {t(prefix + 'scalers.' + key + '.help')}} /> + ))} +
+ +
+ + {/* COLUMNAS DE ENTRADA */} +
+

{t(prefix + 'columns-title')}

+

{t(prefix + 'columns-help')}

+ + {profiles.map((profile) => { + const isTarget = profile.name === target + const choice = choices[profile.name] ?? defaultChoice(profile) + const options = transformsFor(profile) + const setChoice = (patch: Partial) => setChoices((current) => ({ ...current, [profile.name]: { ...choice, ...patch } })) + return ( + +
+
+ {profile.name} + {isTarget + ? {t(prefix + kind + '.target-badge')} + : setChoice({ use: event.target.checked })} />} +
+
+ {t(prefix + 'types.' + profile.type, { defaultValue: profile.type })} + {describe(profile)} +
+ {isTarget + ?

{t(prefix + kind + '.target-transform')}

+ : options.length === 1 + ?

{t(prefix + 'transforms.' + options[0])}

+ : setChoice({ transform: event.target.value as _Types.ColumnTransform_t })}> + {options.map((option) => )} + } +
+ + ) + })} +
+
+ + {/* RESUMEN Y PROCESAR */} +
+

+ {inputs.length === 0 + ? t(prefix + 'no-inputs') + : t(prefix + kind + '.summary', { + count : inputs.length, + target, + classes: targetProfile?.distinct ?? 0, + scaler : t(prefix + 'scalers.' + scaler + '.name'), + })} +

+
+ +
+
+
+
+ + + {processed !== null && scaled !== null && <> + + {t(prefix + 'done', { rows: processed.X.shape[0], count: processed.X.shape[1], target: processed.target })} + +
+ + + + + {t(prefix + 'views.' + view + '-help')} +
+ {view === 'scaled' + ? + : } + } +
+
+
+ ) +} diff --git a/src/components/dataframe/N4LDatasetViews.tsx b/src/components/dataframe/N4LDatasetViews.tsx new file mode 100644 index 0000000..f9dffc0 --- /dev/null +++ b/src/components/dataframe/N4LDatasetViews.tsx @@ -0,0 +1,74 @@ +import { useMemo, useState } from 'react' +import { Nav } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' +import * as dfd from 'danfojs' + +import type * as _Types from '@core/types' +import N4LTablePagination from '@components/table/N4LTablePagination' + +type View_t = 'original' | 'encoded' | 'scaled' +const VIEWS: View_t[] = ['original', 'encoded', 'scaled'] +const prefix = 'dataset-view.' + +// Los valores escalados, con estos decimales: con todos no se leen +const DECIMALS = 3 + +type N4LDatasetViewsProps = { + dataset: _Types.DatasetProcessed_t +} + +/** + * Un conjunto de datos ya procesado, en las tres formas por las que pasa: tal cual está en el fichero; codificado (cada + * categoría convertida en un número y sin las columnas que no se usan); y escalado, que es exactamente lo que recibe la + * red, junto a lo que tiene que predecir. La columna que se predice va resaltada. + */ +export default function N4LDatasetViews({ dataset }: N4LDatasetViewsProps) { + const { t } = useTranslation() + const [view, setView] = useState('original') + const processed = dataset.data_processed + const target = processed?.column_name_target ?? null + + const table = useMemo(() => { + if (view === 'original' || view === 'encoded' || processed === undefined) { + const dataframe = view === 'encoded' ? dataset.dataframe_processed : dataset.dataframe_original + return { head: dataframe.columns, body: dataframe.values as Array>, rows: dataframe.shape[0], columns: dataframe.shape[1] } + } + // Las entradas escaladas y, al final, lo que se predice (eso no se escala) + const inputs = processed.X.values as number[][] + const targets = (processed.y.values as Array) + const round = (value: number) => Math.round(value * 10 ** DECIMALS) / 10 ** DECIMALS + return { + head : [...processed.X.columns, processed.column_name_target], + body : inputs.map((row, index) => [...row.map(round), Array.isArray(targets[index]) ? (targets[index] as number[]).join(', ') : targets[index] as number]), + rows : processed.X.shape[0], + columns: processed.X.shape[1], + } + }, [view, dataset, processed]) + + const scaler = processed?.scaler instanceof dfd.StandardScaler ? 'standard-scaler' : 'min-max-scaler' + + return ( + <> + +

+ {t(prefix + view + '-help', { + rows : table.rows, + columns: table.columns, + target : target ?? '', + scaler : t('dataset-process.scalers.' + scaler + '.name'), + })} +

+
+ +
+ + ) +} diff --git a/src/components/dataframe/N4LPlot.tsx b/src/components/dataframe/N4LPlot.tsx new file mode 100644 index 0000000..ae3128f --- /dev/null +++ b/src/components/dataframe/N4LPlot.tsx @@ -0,0 +1,39 @@ +import { useMemo } from 'react' +import type { Data, Layout } from 'plotly.js' +import Plot from '@components/dataframe/Plot' +import { useTheme } from '@hooks/useTheme' +import { useIdleValue } from '@hooks/useIdleValue' +import { PLOTLY_CONFIG, plotlyLayout } from '@core/dataframe/plotlyTheme' +import N4LChartData, { type ChartDataCell_t } from '@components/chart/N4LChartData' + +/** Los datos del gráfico en una tabla («Ver los datos»); sin `caption`, la tabla se llama como el gráfico */ +export type PlotTable_t = { caption?: string, columns: string[], rows: ChartDataCell_t[][] } + +type N4LPlotProps = { + data : Data[] + layout?: Partial + height?: number + /** Texto para lectores de pantalla (el gráfico es un SVG sin texto alternativo) */ + label? : string + table? : PlotTable_t +} + +/** + * Gráfico de Plotly con los colores del tema y todo el ancho de su contenedor. Se dibuja (y se redibuja) cuando el + * navegador está libre: con muchos gráficos en la página, cada uno va en su propia tarea corta + */ +export default function N4LPlot({ data, layout = {}, height = 360, label, table }: N4LPlotProps) { + const theme = useTheme() + const figure = useMemo(() => ({ data, layout: plotlyLayout(theme, { height, autosize: true, ...layout }) }), [data, layout, height, theme]) + const shown = useIdleValue(figure) + return <> +
+ {shown && } +
+ {table !== undefined && } + +} diff --git a/src/components/dataframe/PreProcessDataFrame.tsx b/src/components/dataframe/PreProcessDataFrame.tsx deleted file mode 100644 index 5c5e072..0000000 --- a/src/components/dataframe/PreProcessDataFrame.tsx +++ /dev/null @@ -1,375 +0,0 @@ -import React, { useState, useId, useEffect } from 'react' -import { flushSync } from 'react-dom' -import { Button, Form, Row, Col } from 'react-bootstrap' -import { Trans, useTranslation } from 'react-i18next' - -import { TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_1, F_TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_2 } from '@/CONSTANTS_DanfoJS' -import * as _Types from '@core/types' -import { DataFrameTransform, DataFrameDeepCopy } from '@core/dataframe/DataFrameUtils' -import { VERBOSE } from '@/CONSTANTS' -import AlertHelper from '@utils/alertHelper' - -// @formatter:off -const DEFAULT_OPTIONS = [ - { value: 'int32', i18n: 'int32' }, - { value: 'float32', i18n: 'float32' }, - { value: 'string', i18n: 'string' }, - { value: 'label-encoder', i18n: 'label-encoder' }, - { value: 'drop', i18n: 'drop' }, -] -// @formatter:on -/** - * @typedef PreProcessDataFrameProps_t - * @property {DataFrame} dataFrameOriginal - * @property {React.Dispatch>} setDataFrameOriginal - * @property {DataFrame} dataFrameProcessed - * @property {React.Dispatch>} setDataFrameProcessed - * @property {boolean} isDataFrameProcessed - * @property {React.Dispatch>} setIsDataFrameProcessed - */ -export type PreProcessDataFrameProps_t = { - dataFrameOriginal : _Types.DataFrame_t, - setDataFrameOriginal : React.Dispatch>, - dataFrameProcessed : _Types.DataFrame_t, - setDataFrameProcessed : React.Dispatch>, - isDataFrameProcessed : boolean, - setIsDataFrameProcessed: React.Dispatch>, -} -/** Estado inicial del formulario para un dataframe: todas las columnas activas y el objetivo en la última. */ -function getDefaultColumns(dataframe: _Types.DataFrame_t) { - /** - * FIX - * @type {_Types.DataFrameColumnNameAndType_t[]} - */ - const _listColumnNameType: _Types.DataFrameColumnNameTypeEnable_t[] = dataframe.columns.map((_, index) => { - return { - column_name : dataframe.columns[index], - column_type : dataframe.dtypes[index] as _Types.DataFrameColumnType_t, - column_enable : true, - column_transform: dataframe.dtypes[index], - } - }) - const _listTransformations: _Types.DataFrameColumnTransformEnable_t[] = _listColumnNameType.map(({ column_name, column_type }) => { - const _column_transform = (column_type === 'string') ? 'label-encoder' : column_type - return { - column_name : column_name, - column_type : column_type as _Types.DataFrameColumnType_t, - column_enable : true, - column_transform: _column_transform, - } - }) - return { - listColumnNameType : _listColumnNameType, - listColumnNameTransformations: _listTransformations, - columnNameTarget : dataframe.columns[dataframe.columns.length - 1], - } -} - -/** - * - * @param {PreProcessDataFrameProps_t} props - * @returns - */ -export default function PreProcessDataFrame(props: PreProcessDataFrameProps_t) { - - const { - dataFrameOriginal, - dataFrameProcessed, - setDataFrameProcessed, - setIsDataFrameProcessed - } = props - - const prefix = 'form-dataframe.' - const { t } = useTranslation() - - const plotDataFrameOriginalID = useId() - const plotDataFrameProcessedID = useId() - - /** - * @type {ReturnType>>} - */ - const [listColumnNameType, setListColumnNameTypes] = useState<_Types.DataFrameColumnNameTypeEnable_t[]>(() => getDefaultColumns(dataFrameOriginal).listColumnNameType) - /** - * @type {ReturnType>} - */ - const [listColumnNameTransformations, setListColumnNameTransformations] = useState<_Types.DataFrameColumnTransformEnable_t[]>(() => getDefaultColumns(dataFrameOriginal).listColumnNameTransformations) - const [columnNameTarget, setColumnNameTarget] = useState(() => getDefaultColumns(dataFrameOriginal).columnNameTarget) - - // Al cambiar de dataframe se reinicia el formulario. Se ajusta durante el render, no en un efecto: - // https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes - const [prevDataFrameOriginal, setPrevDataFrameOriginal] = useState(dataFrameOriginal) - if (dataFrameOriginal !== prevDataFrameOriginal) { - const defaultColumns = getDefaultColumns(dataFrameOriginal) - setPrevDataFrameOriginal(dataFrameOriginal) - setListColumnNameTypes(defaultColumns.listColumnNameType) - setListColumnNameTransformations(defaultColumns.listColumnNameTransformations) - setColumnNameTarget(defaultColumns.columnNameTarget) - } - - const [isButtonDisabled, setIsButtonDisabled] = useState(false) - - const [typeScaler, setTypeScaler] = useState('min-max-scaler') - - const mapColumnType = (column_type: _Types.DataFrameColumnType_t): _Types.DatasetColumnType_t | undefined => { - switch (column_type) { - case 'int32': - return 'Integer' - case 'float32': - return 'Continuous' - case 'string': - return 'Categorical' - case 'boolean': - return 'Binary' - case 'datetime': - return 'Date' - default: - return undefined - } - } - - - const [showDetails, setShowDetails] = useState({ - show_dataframe_original : false, - show_dataframe_form : true, - show_dataframe_processed: false, - }) - - useEffect(() => { - dataFrameOriginal - .plot(plotDataFrameOriginalID) - .table({ - config: TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_1, - layout: { - title: t('dataframe-original'), - }, - }) - }, [dataFrameOriginal, plotDataFrameOriginalID, t]) - - useEffect(() => { - // TODO - - }, [dataFrameProcessed, plotDataFrameProcessedID, columnNameTarget, t]) - - const handleChange_ColumnTransformEnable = (e: React.ChangeEvent, column_name: string) => { - setListColumnNameTransformations((prevState) => { - return prevState.map((oldColumn) => { - if (oldColumn.column_name === column_name) { - return { ...oldColumn, column_enable: e.target.checked, column_transform: 'drop' } - } - return { ...oldColumn } - }) - }) - } - - const handleChange_ColumnTransform = (e: React.ChangeEvent, column_name: string) => { - setListColumnNameTransformations((prevState) => { - return prevState.map((oldColumn) => { - if (oldColumn.column_name === column_name) { - const newTransform = e.target.value - return { - ...oldColumn, - column_transform: newTransform - } as _Types.DataFrameColumnTransformEnable_t - } else { - return oldColumn - } - }) - }) - - } - - const handleChange_ColumnNameTarget = (e: React.ChangeEvent) => { - setColumnNameTarget(e.target.value) - setListColumnNameTransformations((prevState) => - prevState.map((oldColumn) => - (oldColumn.column_name === e.target.value) ? { - ...oldColumn, column_transform: 'label-encoder' - } : oldColumn, - ) - ) - } - - const exec = async () => { - let dataframe_processed = DataFrameDeepCopy(dataFrameOriginal) - const dataframe_transforms: _Types.DataFrameColumnTransform_t[] = listColumnNameTransformations - .filter(({ column_enable }) => column_enable) - .map(({ column_name, column_transform, column_type, match }) => ({ - column_name, - column_transform: column_transform as _Types.ColumnTransform_t, - column_type : mapColumnType(column_type), - match, - })) - - dataframe_processed = DataFrameTransform(dataframe_processed, dataframe_transforms) - - dataframe_processed - .plot(plotDataFrameProcessedID) - .table({ - config: F_TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_2(dataframe_processed.columns, listColumnNameTransformations, columnNameTarget), - layout: { - title: t('dataframe-processed'), - }, - }) - flushSync(() => { - setDataFrameProcessed(dataframe_processed) - setIsDataFrameProcessed(true) - setShowDetails((prevState) => ({ - ...prevState, - show_dataframe_original : false, - show_dataframe_form : false, - show_dataframe_processed: true, - })) - }) - } - - const handleSubmit_ProcessDataFrame = async (event: React.FormEvent) => { - event.preventDefault() - setIsButtonDisabled(() => { - return true - }) - - // Simula un delay de 2 segundos - await new Promise((resolve) => setTimeout(resolve, 2000)) - await exec() - await AlertHelper.alertSuccess(t('preprocessing.title'), { - text: t('alert.success'), - }) - - setIsButtonDisabled(() => { - return false - }) - } - - if (VERBOSE) console.log('render PreProcessDataFrame') - return <> - - -
- -
- - -
- - -
-
- -
-
- - -
-
- - -
- -

-
- - - - {typeScaler} - setTypeScaler(e.target.value)}> - - - - Scaler - - - - - {columnNameTarget} - - <> - {listColumnNameType.map(({ column_name }, index) => { - return - })} - - - - - - - -
- -

-
- - {listColumnNameTransformations.map(({ column_enable, column_name, column_type, column_transform, }, index) => { - return -
- handleChange_ColumnTransformEnable(e, column_name)} - /> - - {column_name} - handleChange_ColumnTransform(e, column_name)}> - <> - {DEFAULT_OPTIONS.map((optionValue, optionIndex) => { - return - })} - - - Dtype: [{column_type}] -> {column_transform} - -
- - })} -
- -
- - - -
- -
- -
-
-
- -
-
- - -
- -
- - -
- - -
-
- -
- -} \ No newline at end of file diff --git a/src/components/dataframe/PreProcessDataFrameCard.tsx b/src/components/dataframe/PreProcessDataFrameCard.tsx deleted file mode 100644 index 99934b4..0000000 --- a/src/components/dataframe/PreProcessDataFrameCard.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import DataFrameCard from '@components/dataframe/DataFrameCard' -import PreProcessDataFrame from './PreProcessDataFrame' -import type { PreProcessDataFrameProps_t } from './PreProcessDataFrame' - -/** - * @typedef PreProcessDataFrameProps_t - * @type {import('./PreProcessDataFrame').PreProcessDataFrameProps_t} - */ - - -/** - * @typedef PreProcessDataFrameCardProps_t - * @property {boolean} isDataFrameUpload - */ -type PreProcessDataFrameCardProps_t = { - isDataFrameUpload: boolean -} - -/** - * - * @param {PreProcessDataFrameProps_t & PreProcessDataFrameCardProps_t} props - * @returns - */ -type Props = PreProcessDataFrameProps_t & PreProcessDataFrameCardProps_t -export default function PreProcessDataFrameCard(props: Props) { - const { - dataFrameOriginal, - setDataFrameOriginal, - dataFrameProcessed, - setDataFrameProcessed, - isDataFrameProcessed, - setIsDataFrameProcessed, - isDataFrameUpload - } = props - - return ( - - - - ) -} diff --git a/src/components/dataset/N4LDatasetInfo.tsx b/src/components/dataset/N4LDatasetInfo.tsx new file mode 100644 index 0000000..e3151a2 --- /dev/null +++ b/src/components/dataset/N4LDatasetInfo.tsx @@ -0,0 +1,21 @@ +import { useTranslation } from 'react-i18next' + +import type { DatasetInfo_t } from '@/TASK_OPTIONS' + +/** Resumen del dataset: "150 filas, 4 características, 3 clases"; el de una serie, "144 meses, objetivo: Passengers" */ +export default function N4LDatasetInfo({ info, className = 'card-text small text-body-secondary' }: { info: DatasetInfo_t, className?: string }) { + const { t, i18n } = useTranslation() + const format = (value: number) => new Intl.NumberFormat(i18n.language).format(value) + const prefix = 'pages.menu.info.' + const parts: string[] = [] + if (info.images !== undefined) { + const { width, height, channels } = info.images + parts.push(t(prefix + (channels === 1 ? 'images' : 'images-color'), { value: format(info.rows[0]), size: `${width}×${height}` })) + } + else if (info.rows.length === 1) parts.push(t(prefix + (info.frequency !== undefined ? 'series.' + info.frequency : 'rows'), { value: format(info.rows[0]) })) + else parts.push(t(prefix + 'rows-files', { files: info.rows.length, values: info.rows.map(format).join(' / ') })) + if (info.features !== undefined) parts.push(t(prefix + 'features', { value: info.features })) + if (info.classes !== undefined) parts.push(t(prefix + 'classes', { value: info.classes })) + if (info.target !== undefined) parts.push(t(prefix + 'target', { value: info.target })) + return

{parts.join(', ')}

+} diff --git a/src/components/divider/N4LDivider.tsx b/src/components/divider/N4LDivider.tsx index cc4748d..b7e56be 100644 --- a/src/components/divider/N4LDivider.tsx +++ b/src/components/divider/N4LDivider.tsx @@ -1,13 +1,27 @@ import { Trans } from 'react-i18next' import { VERBOSE } from '@/CONSTANTS' +import { sectionId } from './sectionId' -export default function N4LDivider (props = { i18nKey: '' }) { - const { i18nKey } = props +type N4LDividerProps = { + i18nKey: string + /** Secciones de la página en orden (sus i18nKey): si se pasa, el título lleva su número ("3. Modelo") */ + steps? : string[] +} + +export default function N4LDivider({ i18nKey, steps }: N4LDividerProps) { + const step = steps ? steps.indexOf(i18nKey) + 1 : 0 if (VERBOSE) console.debug('render N4LDivider') return <> -
-

+ {/* tabIndex -1: el índice lateral lleva el foco aquí al saltar a la sección. Es el encabezado de la sección (h2): + con él se recorre la página con un lector de pantalla; lo de dentro va de h3 en adelante */} +
+

+ + {step > 0 && `${step}. `} + + +

-} \ No newline at end of file +} diff --git a/src/components/divider/N4LSectionLayout.tsx b/src/components/divider/N4LSectionLayout.tsx new file mode 100644 index 0000000..5fec570 --- /dev/null +++ b/src/components/divider/N4LSectionLayout.tsx @@ -0,0 +1,37 @@ +import type { ReactNode } from 'react' +import { Container } from 'react-bootstrap' +import N4LSectionNav, { N4LSectionBar } from './N4LSectionNav' +import { useActiveSection } from './useActiveSection' + +type N4LSectionLayoutProps = { + /** Secciones de la página en orden (las i18nKey de sus N4LDivider) */ + steps : string[] + /** Contenedor ancho (páginas de trabajo); sin él, el ancho de Bootstrap (páginas de lectura, como el glosario) */ + wide? : boolean + className?: string + children : ReactNode +} + +/** + * Contenedor de los entrenadores: en escritorio (xl) el índice de secciones va fijo en una columna estrecha a la + * izquierda y el contenido se queda con el resto del ancho; en pantallas más estrechas el índice es una barra que + * aparece arriba al bajar de la cabecera de la página y se desliza en horizontal. + */ +export default function N4LSectionLayout({ steps, wide = true, className = '', children }: N4LSectionLayoutProps) { + const { activeId, started } = useActiveSection(steps) + return ( + +
+
+ +
+ +
+ {children} +
+
+
+ ) +} diff --git a/src/components/divider/N4LSectionNav.tsx b/src/components/divider/N4LSectionNav.tsx new file mode 100644 index 0000000..fba095d --- /dev/null +++ b/src/components/divider/N4LSectionNav.tsx @@ -0,0 +1,81 @@ +import { useEffect, useRef } from 'react' +import { useTranslation } from 'react-i18next' +import { sectionId } from './sectionId' +import { goToSection } from './useActiveSection' +import { prefersReducedMotion } from '@core/a11y/displaySettings' + +type N4LSectionNavProps = { + /** Secciones de la página en orden (las i18nKey de sus N4LDivider) */ + steps : string[] + /** id del separador de la sección que se está viendo (useActiveSection) */ + activeId: string | null +} + +/** + * Índice de la página en escritorio: un enlace por sección, con la que se está viendo marcada. Va fijo (sticky) en su + * columna mientras se baja por la página. + */ +export default function N4LSectionNav({ steps, activeId }: N4LSectionNavProps) { + const { t } = useTranslation() + + return ( + + ) +} + +/** + * El mismo índice en pantallas estrechas: una barra fija arriba con una pestaña por sección que se desliza en + * horizontal; la de la sección que se está viendo se queda siempre a la vista. + */ +export function N4LSectionBar({ steps, activeId }: N4LSectionNavProps) { + const { t } = useTranslation() + const listRef = useRef(null) + + useEffect(() => { + const list = listRef.current + const active = list?.querySelector('.active') + if (!list || !active) return + const left = active.offsetLeft - (list.clientWidth - active.offsetWidth) / 2 + const reduceMotion = prefersReducedMotion() + list.scrollTo?.({ left: Math.max(0, left), behavior: reduceMotion ? 'auto' : 'smooth' }) + }, [activeId]) + + return ( + + ) +} diff --git a/src/components/divider/sectionId.ts b/src/components/divider/sectionId.ts new file mode 100644 index 0000000..a8f47ab --- /dev/null +++ b/src/components/divider/sectionId.ts @@ -0,0 +1,2 @@ +/** id del separador de una sección (N4LDivider), al que enlaza el índice lateral (N4LSectionNav) */ +export const sectionId = (i18nKey: string) => 'n4l-section-' + i18nKey.replace(/[^a-z0-9]+/gi, '-') diff --git a/src/components/divider/useActiveSection.ts b/src/components/divider/useActiveSection.ts new file mode 100644 index 0000000..b3d0bed --- /dev/null +++ b/src/components/divider/useActiveSection.ts @@ -0,0 +1,71 @@ +import { useEffect, useState, type MouseEvent } from 'react' +import { sectionId } from './sectionId' +import { prefersReducedMotion } from '@core/a11y/displaySettings' + +// Una sección pasa a ser la actual cuando su título sube por encima de esta parte de la ventana +const ACTIVE_LINE = 0.25 + +/** + * La sección que se está viendo: la última cuyo separador ya ha pasado la línea; al final de la página, la última + * (puede ser corta y no llegar nunca arriba). `started`: el separador de la primera sección ya ha subido por debajo de + * la barra de navegación (el título de la página ya no se ve). + */ +export function useActiveSection(steps: string[]) { + const [activeId, setActiveId] = useState(null) + const [started, setStarted] = useState(false) + // Las páginas crean `steps` en cada render: el efecto depende de su contenido, no del array + const stepsKey = steps.join('|') + + useEffect(() => { + let frame = 0 + const update = () => { + frame = 0 + const elements = stepsKey.split('|').map((step) => document.getElementById(sectionId(step))).filter((element) => element !== null) + if (elements.length === 0) return + let current = elements[0].id + for (const element of elements) { + if (element.getBoundingClientRect().top <= window.innerHeight * ACTIVE_LINE) current = element.id + } + const atBottom = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 4 + setActiveId(atBottom ? elements[elements.length - 1].id : current) + // Por debajo de la barra de navegación, que va fija arriba + const navbarHeight = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--n4l-navbar-height')) || 0 + setStarted(elements[0].getBoundingClientRect().top < navbarHeight) + } + const schedule = () => { + if (frame === 0) frame = requestAnimationFrame(update) + } + schedule() + window.addEventListener('scroll', schedule, { passive: true }) + window.addEventListener('resize', schedule) + // El contenido cambia de alto sin hacer scroll (acordeones, modelos nuevos, gráficas…) + const resizeObserver = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(schedule) + resizeObserver?.observe(document.body) + return () => { + cancelAnimationFrame(frame) + window.removeEventListener('scroll', schedule) + window.removeEventListener('resize', schedule) + resizeObserver?.disconnect() + } + }, [stepsKey]) + + return { activeId, started } +} + +/** + * Baja (o sube) hasta la sección, sin quedar bajo las barras fijas (su scroll-margin), con un desplazamiento suave + * salvo si se pide menos movimiento, y le da el foco, para seguir con el teclado o el lector de pantalla desde ahí. + * Dice si la ha encontrado + */ +export function scrollToSection(id: string) { + const element = document.getElementById(id) + if (element === null) return false + element.scrollIntoView({ behavior: prefersReducedMotion() ? 'auto' : 'smooth', block: 'start' }) + element.focus({ preventScroll: true }) + return true +} + +/** Lleva a la sección (y le da el foco) en vez de saltar al ancla */ +export function goToSection(event: MouseEvent, id: string) { + if (scrollToSection(id)) event.preventDefault() +} diff --git a/src/components/dragAndDrop/DragAndDrop.tsx b/src/components/dragAndDrop/DragAndDrop.tsx index e7c5f04..2e231e9 100644 --- a/src/components/dragAndDrop/DragAndDrop.tsx +++ b/src/components/dragAndDrop/DragAndDrop.tsx @@ -1,37 +1,44 @@ -import { useMemo } from 'react' +import { useId, useMemo } from 'react' import { useDropzone, type DropEvent, type DropzoneRootProps, type FileRejection } from 'react-dropzone' import { useTranslation } from 'react-i18next' +import { trackEvent } from '@core/analytics' + +// Para las analíticas, del fichero solo la extensión: el nombre puede ser personal +const fileFormat = (fileName: string) => fileName.includes('.') ? fileName.split('.').pop()!.toLowerCase() : 'none' + const baseStyle = { flex : 1, display : 'flex', + flexWrap : 'wrap', alignItems : 'center', + gap : '0.75rem', padding : '20px', borderWidth : 2, borderRadius : 3, - borderColor : '#b1b1b1', + // El borde dice dónde está la zona: al menos 3:1 sobre la tarjeta en los dos temas (WCAG 1.4.11; el #b1b1b1 de antes + // se quedaba en 2,1:1 sobre blanco) + borderColor : 'var(--n4l-input-border-color)', borderStyle : 'dashed', backgroundColor: 'var(--bc-drag-and-drop)', - color : '#bdbdbd', - outline : 'none', + // El gris secundario del tema: se lee sobre el fondo de la zona en el tema claro y en el oscuro (el #bdbdbd de antes + // se quedaba en 1,5:1 sobre el gris claro) + color : 'var(--bs-secondary-color)', transition : 'border .24s ease-in-out', -} -// border-color: rgb(177 177 177); -// border-style: dashed; -// background-color: rgb(229 229 229); - -const focusedStyle = { - borderColor: '#2196f3', -} +} as const +// Al arrastrar un fichero encima: verde si se admite y rojo si no (los de Bootstrap, con contraste en los dos temas) const acceptStyle = { - borderColor: '#00e676', + borderColor: 'var(--bs-success)', } const rejectStyle = { - borderColor: '#ff1744', + borderColor: 'var(--bs-danger)', } +/** Los motivos de rechazo de react-dropzone que se traducen (el resto, con su mensaje en inglés) */ +const REJECTION_CODES = ['file-invalid-type', 'file-too-large', 'file-too-small', 'too-many-files'] + /** * Properties for the drop zone component. * @@ -77,28 +84,36 @@ export default function DragAndDrop (props: DragAndDropProps) { const { getRootProps, getInputProps, - isFocused, + open, isDragAccept, isDragReject, acceptedFiles, fileRejections, } = useDropzone({ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types - onDropAccepted: (files, event) => function_DropAccepted(files, event), - onDropRejected: (files, event) => function_DropRejected(files, event) , - accept : accept, - multiple : multiple, + onDropAccepted: (files, event) => { + for (const file of files) trackEvent('file_upload', { zone: name, format: fileFormat(file.name), size_kb: Math.round(file.size / 1024) }) + function_DropAccepted(files, event) + }, + onDropRejected: (files, event) => { + for (const { file } of files) trackEvent('file_rejected', { zone: name, format: fileFormat(file.name) }) + function_DropRejected(files, event) + }, + accept : accept, + multiple : multiple, + // Con el teclado se usa el botón «Elegir fichero» (un botón de verdad, con su nombre): la zona no recibe el foco + noKeyboard: true, + noClick : true, }) const styles = useMemo(() => ({ ...baseStyle, - ...(isFocused ? focusedStyle : {}), ...(isDragAccept ? acceptStyle : {}), ...(isDragReject ? rejectStyle : {}), }), [ - isFocused, isDragAccept, isDragReject, ]) + const helpId = useId() const acceptedFileItems = acceptedFiles.map((file) => (
  • @@ -110,25 +125,35 @@ export default function DragAndDrop (props: DragAndDropProps) {
  • {file.name} - {file.size} bytes
      - {errors.map(e =>
    • {e.message}
    • )} + {errors.map(e =>
    • {REJECTION_CODES.includes(e.code) ? t('drag-and-drop.errors.' + e.code) : e.message}
    • )}
  • ) }) - const dropzone_root_props: DropzoneRootProps = { style: styles, name } + // Con el ratón, un clic en cualquier parte de la zona también abre el selector de ficheros + const dropzone_root_props: DropzoneRootProps = { style: styles, name, onClick: open } return (
    + {/* Se suelta el fichero en la zona o se elige con el botón; el botón dice qué formatos admite (aria-describedby) */}
    - -

    {text}

    + + +

    {text}

    - +
      {rejectionFileItems}
    +
    ) } \ No newline at end of file diff --git a/src/components/dropdown/N4LDropdownItems.tsx b/src/components/dropdown/N4LDropdownItems.tsx new file mode 100644 index 0000000..35b3fbb --- /dev/null +++ b/src/components/dropdown/N4LDropdownItems.tsx @@ -0,0 +1,18 @@ +import { forwardRef, type ButtonHTMLAttributes } from 'react' +import { Link, type LinkProps } from 'react-router' + +// Para el `as` de Dropdown.Item y NavDropdown.Item. React-Bootstrap pone aria-selected en todos sus elementos, y ese +// atributo no vale en un enlace ni en un botón (WCAG 4.1.2; axe: aria-allowed-attr): estos lo quitan. El elegido se +// marca con aria-current (la página actual o la opción activa), que sí vale. + +type WithoutSelected_t = { 'aria-selected'?: boolean | 'true' | 'false' } + +/** Un enlace de un desplegable (react-router) */ +export const N4LDropdownLink = forwardRef( + ({ 'aria-selected': _selected, ...props }, ref) => ) +N4LDropdownLink.displayName = 'N4LDropdownLink' + +/** Una opción de un desplegable que hace algo sin cambiar de página (idioma, tema…) */ +export const N4LDropdownButton = forwardRef & WithoutSelected_t>( + ({ 'aria-selected': _selected, type = 'button', ...props }, ref) => + ) + } + return ( +
    + {question} + + +
    + ) +} diff --git a/src/components/form/N4LNumberField.tsx b/src/components/form/N4LNumberField.tsx new file mode 100644 index 0000000..3d61c17 --- /dev/null +++ b/src/components/form/N4LNumberField.tsx @@ -0,0 +1,68 @@ +import { useId, useState, type ReactNode } from 'react' +import { Form } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +type N4LNumberFieldProps = { + controlId : string + label : ReactNode + help? : ReactNode + /** El valor que se usa (siempre válido) */ + value : number + min : number + max? : number + /** Solo se recibe un valor dentro de [min, max] */ + onChange : (value: number) => void + labelClassName? : string + controlClassName?: string + className? : string + /** Para las guías (data-guide) */ + guide? : string + disabled? : boolean +} + +/** + * Un campo para un número entero entre `min` y `max` (WCAG 3.3.1, 3.3.3). Se puede borrar y escribir otro número + * tranquilamente: lo que no vale no se recorta en silencio, sino que se dice junto al campo qué se puede escribir y qué + * valor se sigue usando mientras tanto (`aria-invalid` y `aria-describedby`; el lector lo oye al cambiar). + */ +export default function N4LNumberField({ controlId, label, help, value, min, max, onChange, labelClassName, controlClassName, className, guide, disabled = false }: N4LNumberFieldProps) { + const { t } = useTranslation() + const prefix = 'form.number.' + const [text, setText] = useState(String(value)) + // Si el valor cambia desde fuera (otra sesión, un botón que lo arregla…), el campo lo enseña + const [shown, setShown] = useState(value) + if (shown !== value) { + setShown(value) + if (Number(text) !== value) setText(String(value)) + } + + const parsed = text.trim() === '' ? Number.NaN : Number(text) + const isValid = Number.isInteger(parsed) && parsed >= min && (max === undefined || parsed <= max) + const error = isValid ? null : `${t(prefix + (max === undefined ? 'at-least' : 'range'), { min, max })} ${t(prefix + 'in-use', { value })}` + + const helpId = useId() + const errorId = useId() + const describedBy = [help !== undefined ? helpId : null, error !== null ? errorId : null].filter((id) => id !== null).join(' ') + + return ( + + {label} + { + setText(event.target.value) + const next = Number(event.target.value) + if (event.target.value.trim() !== '' && Number.isInteger(next) && next >= min && (max === undefined || next <= max)) { + setShown(next) + onChange(next) + } + }} /> + {/* Siempre en la página (vacío si no hay error): una región aria-live que aparece con su texto no siempre se lee */} +
    + {error} +
    + {help !== undefined && {help}} +
    + ) +} diff --git a/src/components/guide/N4LGuide.css b/src/components/guide/N4LGuide.css new file mode 100644 index 0000000..184ea2d --- /dev/null +++ b/src/components/guide/N4LGuide.css @@ -0,0 +1,56 @@ +/* Bocadillo de la guía (N4LGuide): con los colores del tema, también en modo oscuro */ +.n4l-guide-tooltip { + position: relative; + width: min(26rem, calc(100vw - 2rem)); + padding: 1.25rem 1rem 1rem; + overflow: hidden; + border: var(--bs-border-width) solid var(--bs-border-color); + border-radius: var(--bs-border-radius-lg); + background-color: var(--bs-body-bg); + color: var(--bs-body-color); + box-shadow: var(--bs-box-shadow-lg); + text-align: start; +} + +/* El progreso, como una línea en el borde de arriba */ +.n4l-guide-progress { + position: absolute; + top: 0; + right: 0; + left: 0; + height: .25rem; + border-radius: 0; +} + +.n4l-guide-content { + margin-bottom: 1rem; + line-height: 1.55; +} + +/* Ir a un paso y elegir la voz: dos desplegables, uno debajo del otro si no caben */ +.n4l-guide-options { + display: flex; + flex-wrap: wrap; + gap: .5rem .75rem; + margin-top: .75rem; + padding-top: .75rem; + border-top: var(--bs-border-width) solid var(--bs-border-color-translucent); +} + +.n4l-guide-option { + flex: 1 1 10rem; + min-width: 0; +} + +/* Mientras lee en voz alta, el botón de la voz late */ +@media (prefers-reduced-motion: no-preference) { + .n4l-guide-speaking { + animation: n4l-guide-pulse 1.2s ease-in-out infinite; + } +} + +@keyframes n4l-guide-pulse { + 50% { + box-shadow: 0 0 0 .3rem rgba(var(--bs-primary-rgb), .25); + } +} diff --git a/src/components/guide/N4LGuide.tsx b/src/components/guide/N4LGuide.tsx new file mode 100644 index 0000000..1e9c226 --- /dev/null +++ b/src/components/guide/N4LGuide.tsx @@ -0,0 +1,405 @@ +import './N4LGuide.css' +import { createContext, useContext, useEffect, useEffectEvent, useId, useMemo, useRef, useState } from 'react' +import { Button, CloseButton, Form, ProgressBar } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' +import { ArrowRepeat, PauseFill, PlayFill, Signpost2Fill, SkipStartFill, VolumeMuteFill, VolumeUpFill } from 'react-bootstrap-icons' +import Joyride, { ACTIONS, EVENTS, STATUS, type CallBackProps, type Step, type TooltipRenderProps } from 'react-joyride' + +import { trackEvent } from '@core/analytics' +import { announce } from '@core/a11y/announce' + +import { clearGuideProgress, readGuideProgress, saveGuideProgress, shouldRestore } from './guideProgress' +import { setGuideVoice, updateGuideSettings, useGuideSettings } from './guideSettings' +import { readingMs, useSpeech, useVoices, voicesForLanguage } from './speech' + +/** Dónde va el bocadillo respecto al elemento ('auto': donde quepa; 'center': en medio de la pantalla) */ +export type GuidePlacement_t = NonNullable + +export type GuideStep_t = { + /** Selector del elemento que señala; 'body' con placement 'center', en medio de la pantalla */ + target : string + title : string + /** Texto sin marcado: es también lo que se lee en voz alta */ + content : string + placement?: GuidePlacement_t +} + +type N4LGuideProps = { + /** Nombre de la guía: con él se guarda en el navegador por qué paso va */ + id : string + steps : GuideStep_t[] + /** Solo el botón, para ir entre otros (la cabecera de las páginas de entrenamiento): relleno y con icono, para que no + * se confunda con los de al lado. Si no, ocupa todo el ancho */ + compact?: boolean +} + +/** Lo que manejan los botones del bocadillo, que react-joyride pinta por su cuenta */ +type GuideControls_t = { + voice : boolean + voiceSupported: boolean + speaking : boolean + auto : boolean + toggleVoice : () => void + toggleAuto : () => void + repeat : () => void + restart : () => void + /** Títulos de los pasos, para ir directamente a uno */ + titles : string[] + goTo : (index: number) => void + /** Voces del idioma de la aplicación y la elegida ("" si la elige la aplicación) */ + voices : SpeechSynthesisVoice[] + voiceURI : string + setVoice : (voiceURI: string) => void +} + +const GuideControls = createContext(null) + +/** El navegador deja hablar: hasta que se toca la página (también tras recargarla), speechSynthesis no suena */ +const hasUserActivation = () => + (navigator as Navigator & { userActivation?: { hasBeenActive: boolean } }).userActivation?.hasBeenActive !== false + +/** + * Guía paso a paso de una página: el botón "Guía" la empieza y cada paso señala una parte de la página y explica qué + * es, leyéndolo en voz alta. Se puede silenciar la voz, repetir el paso o dejar que avance sola al terminar de leer + * cada uno. Se guarda por qué paso va: al recargar la página (el móvil lo hace al desbloquearlo) se vuelve a abrir en + * ese paso si estaba abierta y, si se cerró, el botón sigue desde ahí. No arranca sola en ningún otro caso. + */ +export default function N4LGuide({ id, steps, compact = false }: N4LGuideProps) { + const { t, i18n } = useTranslation() + // Voz, avanzar solo, velocidad y voz elegida: los mismos que en /settings + const { voice, auto, rate, voices: chosenVoices } = useGuideSettings() + const language = (i18n.language || 'es').slice(0, 2) + const voiceURI = chosenVoices[language] ?? '' + const { supported, speaking, speak, cancel } = useSpeech(i18n.language, { voiceURI, rate }) + const languageVoices = voicesForLanguage(useVoices(), language) + + // Lo guardado antes de recargar o de una visita anterior + const [saved] = useState(() => readGuideProgress(id)) + const [run, setRun] = useState(false) + // El paso que se ve o, con la guía cerrada, desde el que sigue el botón + const [stepIndex, setStepIndex] = useState(() => Math.min(saved?.step ?? 0, Math.max(0, steps.length - 1))) + // Cada "Repetir" vuelve a leer el paso + const [repeats, setRepeats] = useState(0) + // El paso que se ha terminado de leer: con "avanzar solo", entonces se pasa al siguiente + const [spoken, setSpoken] = useState(null) + // Al empezar: el color del bocadillo (para su flecha) y lo que tapa la barra de navegación fija + const [layout, setLayout] = useState({ arrow: '#fff', scrollOffset: 80 }) + + const voiceActive = voice && supported + const step = run ? steps[stepIndex] : undefined + // Lo que se lee: el título y la explicación, con un punto entre los dos si el título no termina ya en uno (o en "?") + const text = step ? `${step.title}${/[.!?:。!?]$/u.test(step.title) ? '' : '.'} ${step.content}` : '' + + // Al cerrar la guía, el foco vuelve a su botón (si estaba en el bocadillo, que desaparece): WCAG 2.4.3 + const button_ref = useRef(null) + const returnFocus = () => { + const active = document.activeElement + if (active !== null && active !== document.body && active.closest('.n4l-guide-tooltip') === null) return + window.requestAnimationFrame(() => button_ref.current?.focus()) + } + + const start = (index: number) => { + const navbar = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--n4l-navbar-height')) || 60 + setLayout({ arrow: getComputedStyle(document.body).backgroundColor, scrollOffset: navbar + 24 }) + setSpoken(null) + setStepIndex(index) + setRun(true) + saveGuideProgress(id, index, true) + trackEvent('guide_start', { guide_id: id, step: index + 1, steps: steps.length }) + } + + // Terminada: la próxima vez, desde el principio + const finish = () => { + setRun(false) + setStepIndex(0) + setSpoken(null) + cancel() + returnFocus() + clearGuideProgress(id) + trackEvent('guide_end', { guide_id: id, step: steps.length, steps: steps.length, outcome: 'completed' }) + } + + // Cerrada a medias: no se vuelve a abrir sola y el botón sigue desde este paso + const close = (index: number) => { + setRun(false) + setSpoken(null) + cancel() + returnFocus() + saveGuideProgress(id, index, false) + trackEvent('guide_end', { guide_id: id, step: index + 1, steps: steps.length, outcome: 'closed' }) + } + + const goTo = (index: number) => { + if (index >= steps.length) { + finish() + return + } + const next = Math.max(0, index) + setSpoken(null) + setStepIndex(next) + saveGuideProgress(id, next, true) + } + + const handleCallback = ({ action, index, status, type }: CallBackProps) => { + if (status === STATUS.FINISHED) { + finish() + return + } + if (status === STATUS.SKIPPED || action === ACTIONS.CLOSE) { + close(index) + return + } + // Siguiente o atrás; un paso cuyo elemento no está en la página se salta. Solo los del paso que se ve: al cambiarlo + // desde fuera (desplegable de pasos, avanzar solo, volver al principio), react-joyride avisa también del anterior, + // y moverse otra vez desde él llevaba a otro paso + if ((type === EVENTS.STEP_AFTER || type === EVENTS.TARGET_NOT_FOUND) && index === stepIndex) { + goTo(index + (action === ACTIONS.PREV ? -1 : 1)) + } + } + + // Abierta hace poco: se ha recargado la página. Se vuelve a abrir en su paso cuando el elemento que señala ya está + // (los datos del modelo tardan un poco); si no aparece en 10 s, se abre igual y ese paso se salta + const restore = useEffectEvent((force: boolean) => { + const target = steps[stepIndex]?.target + if (!force && target !== undefined && target !== 'body' && document.querySelector(target) === null) return false + start(stepIndex) + return true + }) + useEffect(() => { + if (!shouldRestore(saved)) return + let tries = 0 + const timer = window.setInterval(() => { + tries += 1 + if (restore(tries >= 50)) window.clearInterval(timer) + }, 200) + return () => window.clearInterval(timer) + }, [saved]) + + // Cada paso se lee al mostrarse (y otra vez con "Repetir"). Recién recargada la página, el navegador no deja hablar + // hasta que se toca algo: se lee entonces + useEffect(() => { + if (!run || !voiceActive || text === '') return + const index = stepIndex + const read = () => speak(text, () => setSpoken(index)) + if (hasUserActivation()) { + read() + return () => cancel() + } + let done = false + const onInteraction = () => { + if (done) return + done = true + read() + } + window.addEventListener('click', onInteraction, true) + window.addEventListener('keydown', onInteraction, true) + return () => { + window.removeEventListener('click', onInteraction, true) + window.removeEventListener('keydown', onInteraction, true) + cancel() + } + }, [run, voiceActive, text, stepIndex, repeats, speak, cancel]) + + // Cada paso, también para el lector de pantalla (que no lo oye por la voz de la guía si está desactivada): WCAG 4.1.3 + useEffect(() => { + if (run && text !== '') announce(`${t('guide.step', { current: stepIndex + 1, total: steps.length })}. ${text}`) + }, [run, text, stepIndex, steps.length, t]) + + // Avanzar solo: con voz, al terminar de leer el paso (y, por si el navegador no avisa, como mucho el doble de lo que + // se tarda en leerlo); sin voz, lo que se tarda en leerlo. En el último paso se queda, y tras recargar espera a que + // se toque la página (hasta entonces no se ha leído nada) + const advance = useEffectEvent(() => { + if (stepIndex < steps.length - 1) goTo(stepIndex + 1) + }) + useEffect(() => { + if (!run || !auto || text === '') return + if (voiceActive && !hasUserActivation()) return + const delay = !voiceActive ? readingMs(text) : spoken === stepIndex ? 800 : readingMs(text) * 2 + 3000 + const timer = window.setTimeout(advance, delay) + return () => window.clearTimeout(timer) + }, [run, auto, voiceActive, spoken, stepIndex, text]) + + const controls: GuideControls_t = { + voice : voiceActive, + voiceSupported: supported, + speaking, + auto, + toggleVoice : () => updateGuideSettings({ voice: !voice }), + toggleAuto : () => updateGuideSettings({ auto: !auto }), + repeat : () => { + setSpoken(null) + setRepeats((count) => count + 1) + }, + restart : () => goTo(0), + titles : steps.map(({ title }) => title), + goTo, + voices : languageVoices, + voiceURI: languageVoices.some((option) => option.voiceURI === voiceURI) ? voiceURI : '', + // Con otra voz se vuelve a leer el paso (el efecto de la lectura depende de la voz) + setVoice: (uri: string) => { + setSpoken(null) + setGuideVoice(language, uri) + }, + } + + const joyrideSteps = useMemo(() => steps.map(({ target, title, content, placement }) => ({ + target, + title, + content, + placement : placement ?? 'auto', + disableBeacon : true, + spotlightPadding: 6, + })), [steps]) + + const button = ( + + ) + + return <> + {compact ? button :
    {button}
    } + {run && + + + } + +} + +/** El bocadillo de cada paso: progreso, título, explicación, controles de la voz y botones para moverse */ +function GuideTooltip({ index, size, step, backProps, primaryProps, closeProps, tooltipProps }: TooltipRenderProps) { + const controls = useContext(GuideControls) + const { t } = useTranslation() + // El diálogo de la guía se llama como el título del paso (WCAG 4.1.2) + const titleId = useId() + // Al abrirse, el foco entra en el bocadillo, en el título del paso (se sigue leyendo desde ahí). Al cambiar de paso + // el bocadillo es el mismo y el foco se queda donde estaba (en «Siguiente») + // react-joyride lo pinta oculto mientras lo coloca, y lo oculto no recibe el foco: se intenta hasta que se ve (1 s) + useEffect(() => { + let frame = 0 + let tries = 0 + const attempt = () => { + const title = document.getElementById(titleId) + const tooltip = title?.closest('.n4l-guide-tooltip') + if (title === null || tooltip === null || tooltip === undefined || tooltip.contains(document.activeElement)) return + if (getComputedStyle(title).visibility === 'visible') title.focus({ preventScroll: true }) + if (document.activeElement !== title && tries++ < 60) frame = window.requestAnimationFrame(attempt) + } + attempt() + return () => window.cancelAnimationFrame(frame) + }, [titleId]) + // Las flechas también pasan de paso (salvo en el desplegable de los pasos y en el de las voces, que las usan) + const handleKeyDown = useEffectEvent((event: globalThis.KeyboardEvent) => { + if (controls === null || event.target instanceof HTMLSelectElement || event.target instanceof HTMLInputElement) return + if (event.key === 'ArrowRight') { + event.preventDefault() + controls.goTo(index + 1) + } else if (event.key === 'ArrowLeft' && index > 0) { + event.preventDefault() + controls.goTo(index - 1) + } + }) + useEffect(() => { + const tooltip = document.getElementById(titleId)?.closest('.n4l-guide-tooltip') + if (tooltip === null || tooltip === undefined) return + const listener = (event: globalThis.KeyboardEvent) => handleKeyDown(event) + tooltip.addEventListener('keydown', listener) + return () => tooltip.removeEventListener('keydown', listener) + }, [titleId]) + if (controls === null) return null + + const voiceLabel = !controls.voiceSupported ? t('guide.no-voice') : t(controls.voice ? 'guide.voice-off' : 'guide.voice-on') + const autoLabel = t(controls.auto ? 'guide.auto-off' : 'guide.auto-on') + const VoiceIcon = controls.voice ? VolumeUpFill : VolumeMuteFill + const AutoIcon = controls.auto ? PauseFill : PlayFill + + return ( +
    + +
    +
    +
    {t('guide.step', { current: index + 1, total: size })}
    +

    {step.title}

    +
    + {/* Sin el resto de closeProps: react-joyride también le pasa el texto (children) y se veía junto a la X */} + +
    +

    {step.content}

    +
    +
    + + + + {index > 0 && + } +
    +
    + {index > 0 && } + +
    +
    + {/* Ir directamente a un paso y elegir la voz (las del idioma de la aplicación) */} +
    + + {t('guide.go-to')} + controls.goTo(Number(event.target.value))} + data-testid={'Test-GuideStepSelect'}> + {controls.titles.map((title, option) => )} + + + {controls.voiceSupported && controls.voices.length > 0 && + + {t('guide.voice')} + controls.setVoice(event.target.value)} + data-testid={'Test-GuideVoiceSelect'}> + + {controls.voices.map((voice) => ( + + ))} + + } +
    +
    + ) +} diff --git a/src/components/guide/buildGuideSteps.ts b/src/components/guide/buildGuideSteps.ts new file mode 100644 index 0000000..fb3084a --- /dev/null +++ b/src/components/guide/buildGuideSteps.ts @@ -0,0 +1,32 @@ +import type { GuidePlacement_t, GuideStep_t } from './N4LGuide' + +/** Un paso de la guía de una página: su clave de i18n, el elemento que señala y dónde va el bocadillo */ +export type GuideStepSpec_t = { + key : string + target : string + placement?: GuidePlacement_t +} + +/** i18next acepta varias claves: devuelve la primera que existe */ +export type GuideTranslate_t = (keys: string | string[]) => string + +/** + * Los pasos de la guía de un modelo, con sus textos: los de ese modelo (`..`) y, si no los tiene, + * los comunes a todos los de su tarea (`.common.`), para las partes de la página que son iguales. + */ +export function buildGuideSteps(t: GuideTranslate_t, prefix: string, model: string, specs: GuideStepSpec_t[]): GuideStep_t[] { + const text = (key: string, part: 'title' | 'content') => t([`${prefix}.${model}.${key}.${part}`, `${prefix}.common.${key}.${part}`]) + return specs.map(({ key, target, placement = 'auto' }) => ({ + target, + placement, + title : text(key, 'title'), + content: text(key, 'content'), + })) +} + +/** Primer y último paso, en medio de la pantalla */ +export const centerStep = (key: string): GuideStepSpec_t => ({ key, target: 'body', placement: 'center' }) + +/** Un paso que señala el elemento con ese data-guide */ +export const guideStep = (key: string, guide: string, placement?: GuidePlacement_t): GuideStepSpec_t => + ({ key, target: `[data-guide="${guide}"]`, placement }) diff --git a/src/components/guide/guideProgress.ts b/src/components/guide/guideProgress.ts new file mode 100644 index 0000000..0562871 --- /dev/null +++ b/src/components/guide/guideProgress.ts @@ -0,0 +1,56 @@ +// Por qué paso va cada guía (localStorage, en el navegador de quien la usa): al recargar la página, también cuando el +// móvil la recarga al desbloquearlo, se sigue donde se estaba en vez de empezar de cero. + +export type GuideProgress_t = { + /** Paso en el que se estaba (desde 0) */ + step : number + /** La guía estaba abierta: al recargar se vuelve a abrir sola */ + open : boolean + savedAt: number +} + +/** Una guía abierta hace más de esto ya no se abre sola al volver (se sigue con el botón) */ +export const RESTORE_MS = 60 * 60 * 1000 + +const storageKey = (id: string) => `n4l-guide-progress.${id}` + +export function readGuideProgress(id: string): GuideProgress_t | null { + try { + const value: unknown = JSON.parse(localStorage.getItem(storageKey(id)) ?? 'null') + if (value === null || typeof value !== 'object') return null + const { step, open, savedAt } = value as Partial + if (typeof step !== 'number' || !Number.isInteger(step) || step < 0 || typeof savedAt !== 'number') return null + return { step, open: open === true, savedAt } + } catch { + return null + } +} + +export function saveGuideProgress(id: string, step: number, open: boolean) { + try { + localStorage.setItem(storageKey(id), JSON.stringify({ step, open, savedAt: Date.now() })) + } catch { + // Sin almacenamiento, la guía empieza de cero al recargar + } +} + +export function clearGuideProgress(id: string) { + try { + localStorage.removeItem(storageKey(id)) + } catch { + // Nada que borrar + } +} + +/** Olvida por qué paso va cada guía: todas vuelven a empezar desde el principio */ +export function clearAllGuideProgress() { + try { + Object.keys(localStorage).filter((key) => key.startsWith('n4l-guide-progress.')).forEach((key) => localStorage.removeItem(key)) + } catch { + // Sin almacenamiento no había nada guardado + } +} + +/** Si la guía estaba abierta hace poco, se vuelve a abrir sola al cargar la página */ +export const shouldRestore = (progress: GuideProgress_t | null, now = Date.now()) => + progress !== null && progress.open && now - progress.savedAt < RESTORE_MS diff --git a/src/components/guide/guideSettings.ts b/src/components/guide/guideSettings.ts new file mode 100644 index 0000000..9aed3f1 --- /dev/null +++ b/src/components/guide/guideSettings.ts @@ -0,0 +1,89 @@ +import { useSyncExternalStore } from 'react' + +// Ajustes de la voz de las guías: los cambia la propia guía (desde su bocadillo) y /settings, y los dos se enteran al +// momento. Se guardan en el navegador de quien los elige. + +export type GuideSettings_t = { + /** Leer cada paso en voz alta */ + voice : boolean + /** Pasar al siguiente paso al terminar de leer el actual */ + auto : boolean + /** Velocidad de la voz: 1 es la normal */ + rate : number + /** La voz elegida para cada idioma ("es", "en", "ja"…), por su voiceURI; sin ella, la elige la aplicación */ + voices: Record +} + +export const DEFAULT_GUIDE_SETTINGS: GuideSettings_t = { voice: true, auto: false, rate: 1, voices: {} } + +/** Velocidades que se pueden elegir */ +export const MIN_RATE = 0.5 +export const MAX_RATE = 2 + +export const GUIDE_SETTINGS_STORAGE_KEY = 'n4l-guide-settings' + +/** Lo guardado, con lo que no sea válido cambiado por su valor por defecto */ +function readSettings(): GuideSettings_t { + try { + const saved: unknown = JSON.parse(localStorage.getItem(GUIDE_SETTINGS_STORAGE_KEY) ?? 'null') + if (saved === null || typeof saved !== 'object') return DEFAULT_GUIDE_SETTINGS + const { voice, auto, rate, voices } = saved as Partial + return { + voice : typeof voice === 'boolean' ? voice : DEFAULT_GUIDE_SETTINGS.voice, + auto : typeof auto === 'boolean' ? auto : DEFAULT_GUIDE_SETTINGS.auto, + rate : typeof rate === 'number' && rate >= MIN_RATE && rate <= MAX_RATE ? rate : DEFAULT_GUIDE_SETTINGS.rate, + voices: voices !== null && typeof voices === 'object' + ? Object.fromEntries(Object.entries(voices).filter(([, uri]) => typeof uri === 'string')) + : {}, + } + } catch { + return DEFAULT_GUIDE_SETTINGS + } +} + +let current: GuideSettings_t | null = null +const listeners = new Set<() => void>() + +export const getGuideSettings = (): GuideSettings_t => (current ??= readSettings()) + +function notify() { + listeners.forEach((listener) => listener()) +} + +export function updateGuideSettings(patch: Partial) { + current = { ...getGuideSettings(), ...patch } + try { + localStorage.setItem(GUIDE_SETTINGS_STORAGE_KEY, JSON.stringify(current)) + } catch { + // Sin almacenamiento los ajustes valen solo para esta visita + } + notify() +} + +/** Elige la voz de un idioma ("" vuelve a la que elige la aplicación) */ +export function setGuideVoice(language: string, voiceURI: string) { + const voices = { ...getGuideSettings().voices } + if (voiceURI === '') delete voices[language] + else voices[language] = voiceURI + updateGuideSettings({ voices }) +} + +/** Vuelve a los ajustes por defecto (y los olvida) */ +export function resetGuideSettings() { + current = DEFAULT_GUIDE_SETTINGS + try { + localStorage.removeItem(GUIDE_SETTINGS_STORAGE_KEY) + } catch { + // Nada que borrar + } + notify() +} + +function subscribe(listener: () => void) { + listeners.add(listener) + return () => { + listeners.delete(listener) + } +} + +export const useGuideSettings = () => useSyncExternalStore(subscribe, getGuideSettings, () => DEFAULT_GUIDE_SETTINGS) diff --git a/src/components/guide/speech.ts b/src/components/guide/speech.ts new file mode 100644 index 0000000..1db88e6 --- /dev/null +++ b/src/components/guide/speech.ts @@ -0,0 +1,152 @@ +import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react' + +// Lectura en voz alta de la guía con la Web Speech API del navegador (speechSynthesis): sin servidor ni claves. Las +// voces son las del sistema; si no hay ninguna del idioma, el navegador lee con la suya por defecto. + +/** Idioma de la app → etiqueta de idioma de las voces (la preferida; si no la hay, vale cualquiera del idioma) */ +const SPEECH_LANGS: Record = { es: 'es-ES', en: 'en-US', ja: 'ja-JP' } + +/** Hasta dónde se junta texto en un mismo enunciado: Chrome corta los largos (unos 15 s) sin avisar */ +const MAX_CHUNK = 180 + +export const speechLang = (language: string) => SPEECH_LANGS[language.slice(0, 2)] ?? language + +export const isSpeechSupported = () => + typeof window !== 'undefined' && 'speechSynthesis' in window && typeof window.SpeechSynthesisUtterance === 'function' + +/** El texto en trozos cortos: frase a frase y, si una frase es muy larga, por sus comas */ +export function splitSentences(text: string): string[] { + // Tras ".", "!" o "?" con espacio (no parte "1.5"); en japonés, tras "。", "!" o "?", que no llevan espacio + const sentences = text.replace(/\s+/g, ' ').trim().split(/(?<=[.!?])\s+|(?<=[。!?])/u).filter((sentence) => sentence.trim() !== '') + const chunks: string[] = [] + for (const sentence of sentences) { + if (sentence.length <= MAX_CHUNK) { + chunks.push(sentence.trim()) + continue + } + let current = '' + for (const part of sentence.split(/(?<=[,;:、])\s*/u)) { + if (current !== '' && (current + ' ' + part).length > MAX_CHUNK) { + chunks.push(current.trim()) + current = part + } else { + current = current === '' ? part : current + ' ' + part + } + } + if (current.trim() !== '') chunks.push(current.trim()) + } + return chunks +} + +const normalizeLang = (lang: string) => lang.toLowerCase().replace('_', '-') + +/** + * La voz para un idioma: la elegida (`voiceURI`) si es de ese idioma; si no, la de su variante preferida (es-ES…) y, + * si no la hay, otra del idioma. Entre varias, la del sistema primero. + */ +export function pickVoice(voices: SpeechSynthesisVoice[], language: string, voiceURI?: string): SpeechSynthesisVoice | null { + const preferred = speechLang(language).toLowerCase() + const base = preferred.slice(0, 2) + const chosen = voiceURI ? voices.find((voice) => voice.voiceURI === voiceURI) : undefined + if (chosen && normalizeLang(chosen.lang).startsWith(base)) return chosen + const byDefault = (a: SpeechSynthesisVoice, b: SpeechSynthesisVoice) => Number(b.default) - Number(a.default) + const exact = voices.filter(({ lang }) => normalizeLang(lang) === preferred).sort(byDefault) + if (exact.length > 0) return exact[0] + const sameLanguage = voices.filter(({ lang }) => normalizeLang(lang).startsWith(base)).sort(byDefault) + return sameLanguage[0] ?? null +} + +/** Las voces de un idioma, para elegir: primero las de su variante preferida (es-ES…) y después por nombre */ +export function voicesForLanguage(voices: SpeechSynthesisVoice[], language: string): SpeechSynthesisVoice[] { + const preferred = speechLang(language).toLowerCase() + const base = preferred.slice(0, 2) + return voices + .filter(({ lang }) => normalizeLang(lang).startsWith(base)) + .sort((a, b) => Number(normalizeLang(b.lang) === preferred) - Number(normalizeLang(a.lang) === preferred) || a.name.localeCompare(b.name)) +} + +// Las voces del sistema: algunos navegadores (Chrome) las cargan después y avisan con "voiceschanged". La lista se +// guarda para devolver la misma mientras no cambie (useSyncExternalStore lo necesita) +let voicesSnapshot: SpeechSynthesisVoice[] = [] +const NO_VOICES: SpeechSynthesisVoice[] = [] + +function readVoices() { + if (!isSpeechSupported()) return NO_VOICES + const voices = window.speechSynthesis.getVoices() + const changed = voices.length !== voicesSnapshot.length || voices.some((voice, index) => voice.voiceURI !== voicesSnapshot[index]?.voiceURI) + if (changed) voicesSnapshot = voices + return voicesSnapshot +} + +function subscribeVoices(listener: () => void) { + if (!isSpeechSupported()) return () => {} + const synth = window.speechSynthesis + synth.addEventListener?.('voiceschanged', listener) + return () => synth.removeEventListener?.('voiceschanged', listener) +} + +/** Las voces del sistema (se actualiza cuando el navegador termina de cargarlas) */ +export const useVoices = () => useSyncExternalStore(subscribeVoices, readVoices, () => NO_VOICES) + +/** Lo que se tarda en leer un texto en voz alta, más o menos, en ms (para avanzar solo sin voz) */ +export const readingMs = (text: string) => Math.max(3000, text.split(/\s+/).length * 380) + +type SpeechOptions_t = { + /** La voz elegida (si es del idioma); sin ella, pickVoice */ + voiceURI?: string + /** Velocidad: 1 es la normal */ + rate? : number +} + +/** + * Leer textos en voz alta. `speak` corta lo que se estuviera leyendo; `onEnd` solo llega si el texto se ha leído + * entero (no si se ha cortado con otro `speak` o con `cancel`). + */ +export function useSpeech(appLanguage: string | undefined, { voiceURI, rate = 1 }: SpeechOptions_t = {}) { + // Mientras i18next no ha resuelto el idioma, el del navegador + const language = appLanguage || (typeof navigator === 'undefined' ? 'es' : navigator.language) + const supported = isSpeechSupported() + // Cada lectura tiene su número: los avisos de una lectura cortada (Chrome avisa de su fin) no cuentan + const reading = useRef(0) + const [speaking, setSpeaking] = useState(false) + + const cancel = useCallback(() => { + reading.current += 1 + if (isSpeechSupported()) window.speechSynthesis.cancel() + setSpeaking(false) + }, []) + + const speak = useCallback((text: string, onEnd?: () => void) => { + if (!supported) return + const synth = window.speechSynthesis + const id = ++reading.current + synth.cancel() + const chunks = splitSentences(text) + if (chunks.length === 0) return + const voice = pickVoice(synth.getVoices(), language, voiceURI) + chunks.forEach((chunk, index) => { + const utterance = new SpeechSynthesisUtterance(chunk) + utterance.lang = voice?.lang ?? speechLang(language) + utterance.rate = rate + if (voice) utterance.voice = voice + if (index === 0) utterance.onstart = () => { if (id === reading.current) setSpeaking(true) } + utterance.onerror = () => { if (id === reading.current) setSpeaking(false) } + if (index === chunks.length - 1) { + utterance.onend = () => { + if (id !== reading.current) return + setSpeaking(false) + onEnd?.() + } + } + synth.speak(utterance) + }) + }, [supported, language, voiceURI, rate]) + + // Al salir de la página no se sigue leyendo + useEffect(() => () => { + reading.current += 1 + if (isSpeechSupported()) window.speechSynthesis.cancel() + }, []) + + return { supported, speaking, speak, cancel } +} diff --git a/src/components/guide/trainerGuide.ts b/src/components/guide/trainerGuide.ts new file mode 100644 index 0000000..cd37f2a --- /dev/null +++ b/src/components/guide/trainerGuide.ts @@ -0,0 +1,55 @@ +import type { GuideStep_t } from './N4LGuide' +import { buildGuideSteps, centerStep, guideStep, type GuideTranslate_t } from './buildGuideSteps' + +/** Tareas con página de entrenamiento: el prefijo de sus textos (guide.train.) */ +export type TrainerTask_t = '0-tabular-classification' | '1-regression' | '3-image-classification' + +type TrainerGuideOptions_t = { + /** Conjunto de datos propio: primero hay que subirlo y procesarlo */ + upload : boolean + /** La página enseña el conjunto de datos en una tabla (la de imágenes no) */ + datasetTable: boolean + /** data-guide del campo con el porcentaje de datos que se reserva para la prueba */ + testSize : 'hp-train-rate' | 'hp-test-size' + /** La sección Paso a paso (redes densas pequeñas): detrás del botón de entrenar o de la tabla de modelos */ + stepByStep : 'after-train' | 'after-models' | false + /** Un paso por capa (lo que hace cada una), detrás del de las capas */ + layerSteps? : GuideStep_t[] +} + +/** + * La guía de una página de entrenamiento (/playground//dataset/), en el orden de la página: los datos, la + * red y sus capas, cada hiperparámetro, el entrenamiento, los modelos generados, la predicción y la explicabilidad. + * Textos en guide.train.. (la presentación y lo propio de cada conjunto) y, lo demás, en .common. Los + * elementos que señala llevan data-guide; uno que todavía no está (p. ej. sin datos procesados) se salta. Los bloques + * grandes (la red, las capas, las tablas) no fijan dónde va el bocadillo: con 'auto' va donde quepa entero. + */ +export function trainerGuide(t: GuideTranslate_t, task: TrainerTask_t, dataset: string, options: TrainerGuideOptions_t): GuideStep_t[] { + const steps = buildGuideSteps(t, 'guide.train.' + task, dataset, [ + centerStep('intro'), + guideStep('session', 'session', 'bottom'), + guideStep('manual', 'manual', 'bottom'), + guideStep('dataset-info', 'dataset-info', 'bottom'), + ...(options.upload ? [guideStep('process', 'process')] : []), + ...(options.datasetTable ? [guideStep('dataset', 'dataset')] : []), + guideStep('layer-design', 'layer-design'), + guideStep('layers', 'layers'), + guideStep('layers-add', 'layers-add', 'bottom'), + guideStep('learning-rate', 'hp-learning-rate'), + guideStep('epochs', 'hp-number-of-epochs'), + guideStep('test-size', options.testSize), + guideStep('optimizer', 'hp-optimizer'), + guideStep('loss', 'hp-loss'), + guideStep('metrics', 'hp-metrics'), + guideStep('train', 'train'), + ...(options.stepByStep === 'after-train' ? [guideStep('step-by-step', 'step-by-step')] : []), + guideStep('models', 'models'), + ...(options.stepByStep === 'after-models' ? [guideStep('step-by-step', 'step-by-step')] : []), + guideStep('predict', 'predict'), + guideStep('explain', 'explain'), + centerStep('end'), + ]) + if (options.layerSteps === undefined || options.layerSteps.length === 0) return steps + const afterLayers = steps.findIndex(({ target }) => target === '[data-guide="layers"]') + 1 + return [...steps.slice(0, afterLayers), ...options.layerSteps, ...steps.slice(afterLayers)] +} diff --git a/src/components/header/N4LNavbar.css b/src/components/header/N4LNavbar.css index 0eff6be..47028ff 100644 --- a/src/components/header/N4LNavbar.css +++ b/src/components/header/N4LNavbar.css @@ -1,6 +1,251 @@ -.custom-navbar { - box-shadow: 5px 6px 6px 6px rgba(247, 3, 3, 0.2); -} +/* El icono de GitHub, del tamaño del texto como los de Bootstrap Icons (el SVG trae 16 × 16 y no crecía con él) */ .n4l-icon-1rem svg { - width: 1rem; -} \ No newline at end of file + width: 1em; + height: 1em; +} + +/* Icono de un ajuste (idioma, tema, backend) y de sus opciones: a la altura del texto, como en Bootstrap Icons */ +.n4l-navbar-icon { + display: inline-block; + margin-right: .375rem; + vertical-align: -.125em; +} + +.n4l-navbar-icon svg { + display: block; +} + +/* Valor actual de un ajuste (idioma, tema, backend) junto a su nombre */ +.n4l-navbar-value { + margin-left: .375rem; + color: var(--bs-secondary-color); + font-size: .875em; +} + +/* El botón del menú: el anillo de foco solo con teclado (con el dedo se quedaba un borde negro grueso) */ +.n4l-navbar .navbar-toggler:focus:not(:focus-visible) { + box-shadow: none; +} + +/* Con el menú abierto, el botón es una X */ +.n4l-navbar .navbar-toggler[aria-expanded="true"] .navbar-toggler-icon { + background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%2833, 37, 41, 0.75%29' stroke-linecap='round' stroke-width='2' d='M8 8l14 14M22 8L8 22'/%3e%3c/svg%3e"); +} + +[data-bs-theme="dark"] .n4l-navbar .navbar-toggler[aria-expanded="true"] .navbar-toggler-icon { + background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.55%29' stroke-linecap='round' stroke-width='2' d='M8 8l14 14M22 8L8 22'/%3e%3c/svg%3e"); +} + +.n4l-navbar .nav-link.active { + font-weight: 600; +} + +/* Los paquetes .n4l del usuario: con su icono y cuántos hay guardados */ +.n4l-navbar-packages-count { + margin-left: .375rem; + font-size: .7em; + vertical-align: .15em; +} + +/* Escritorio: páginas a la izquierda y ajustes a la derecha; la página actual, subrayada sobre el borde inferior */ +@media (min-width: 992px) { + .n4l-navbar:not(.n4l-navbar-compact) .n4l-navbar-menu { + display: flex; + flex-grow: 1; + align-items: center; + } + + /* Cada enlace en una línea (el japonés se parte entre caracteres) */ + .n4l-navbar:not(.n4l-navbar-compact) .navbar-nav .nav-link { + white-space: nowrap; + } + + .n4l-navbar:not(.n4l-navbar-compact) .n4l-navbar-links .nav-link { + position: relative; + } + + .n4l-navbar:not(.n4l-navbar-compact) .n4l-navbar-links .nav-link.active::after { + content: ""; + position: absolute; + left: var(--bs-navbar-nav-link-padding-x); + right: var(--bs-navbar-nav-link-padding-x); + bottom: calc(-1 * var(--bs-navbar-padding-y)); + height: 3px; + border-radius: 3px 3px 0 0; + background-color: var(--bs-primary); + } +} + +/* Justo por encima de lg cabe todo en una línea con algo menos de aire entre enlaces. En japonés no: "AED + (探索的データ分析)" es mucho más largo y, en una línea, la barra se sale de la pantalla; ahí se deja partir */ +@media (min-width: 992px) and (max-width: 1199.98px) { + .n4l-navbar:not(.n4l-navbar-compact) { + --bs-navbar-nav-link-padding-x: .375rem; + } + + html[lang="ja"] .n4l-navbar:not(.n4l-navbar-compact) .n4l-navbar-links .nav-link { + white-space: normal; + } +} + +/* + * El menú en el botón (.n4l-navbar-collapsed: móvil, tablet y, con el texto agrandado en /settings, cualquier pantalla, + * porque los puntos de corte de Bootstrap van en píxeles y no crecen con el texto). Un panel que se abre sobre la página + * sin empujarla, con la página oscurecida detrás (.n4l-navbar-backdrop): una lista con filas cómodas para el dedo, las + * páginas arriba y los ajustes aparte, con su valor a la derecha + */ +.n4l-navbar-collapsed > .container { + position: relative; +} + +.n4l-navbar-collapsed .navbar-collapse { + position: absolute; + /* Justo debajo de la barra (el contenedor queda dentro de su relleno) */ + top: calc(100% + var(--bs-navbar-padding-y)); + left: 0; + right: 0; + /* El mismo margen que el contenedor: el anillo del foco de las filas cabe sin que lo corte el desplazamiento */ + padding-inline: calc(var(--bs-gutter-x) * .5); + /* Si no cabe en la pantalla (móvil en horizontal, texto grande), se desliza dentro sin mover la página */ + max-height: calc(100dvh - var(--n4l-navbar-height, 56px)); + overflow-y: auto; + overscroll-behavior: contain; + background-color: var(--bs-tertiary-bg); + /* El fondo, de lado a lado de la pantalla aunque el contenedor sea más estrecho (tablet) */ + box-shadow: 0 0 0 100vmax var(--bs-tertiary-bg); + clip-path: inset(0 -100vmax); +} + +.n4l-navbar-backdrop { + position: fixed; + inset: 0; + /* Por encima de la página y del índice de secciones (1015), por debajo de la barra (1020) */ + z-index: 1018; + background-color: rgb(0 0 0 / 40%); + animation: n4l-navbar-backdrop-in .2s ease-out; + /* Deslizar sobre él no mueve la página de detrás */ + touch-action: none; +} + +@keyframes n4l-navbar-backdrop-in { + from { + opacity: 0; + } +} + +.n4l-navbar-collapsed .n4l-navbar-menu { + padding: .5rem 0 .75rem; +} + +.n4l-navbar-collapsed .navbar-nav .nav-link { + display: flex; + align-items: center; + padding: .625rem .75rem; + border-radius: var(--bs-border-radius); +} + +.n4l-navbar-collapsed .n4l-navbar-links .nav-link.active { + background-color: var(--bs-primary-bg-subtle); + color: var(--bs-primary-text-emphasis); +} + +/* El anillo del foco, por dentro: las filas van de lado a lado del panel */ +.n4l-navbar-collapsed .navbar-nav .nav-link:focus-visible { + outline-offset: calc(-1 * var(--n4l-focus-width, 3px)); +} + +.n4l-navbar-collapsed .n4l-navbar-settings { + margin-top: .5rem; + padding-top: .5rem; + border-top: var(--bs-border-width) solid var(--bs-border-color); +} + +/* + * Los desplegables (Tareas, Idioma, Tema, Backend): la flecha a la derecha de la fila, todas en la misma columna, y + * girada hacia arriba con el desplegable abierto. Con bordes, como la de Bootstrap: también se ve en alto contraste + */ +.n4l-navbar-collapsed .navbar-nav .dropdown-toggle::after { + flex-shrink: 0; + width: .5rem; + height: .5rem; + margin: -.25rem .25rem 0 auto; + border: solid currentColor; + border-width: 0 2px 2px 0; + transform: rotate(45deg); + transition: transform .2s ease-in-out, margin .2s ease-in-out; +} + +.n4l-navbar-collapsed .navbar-nav .dropdown-toggle[aria-expanded="true"]::after { + margin-top: .25rem; + transform: rotate(225deg); +} + +/* En los ajustes, el valor elegido va justo antes de la flecha */ +.n4l-navbar-collapsed .n4l-navbar-value { + margin-left: auto; + margin-right: .75rem; +} + +.n4l-navbar-collapsed .n4l-navbar-settings .dropdown-toggle::after { + margin-left: 0; +} + +/* + * Lo de dentro de un desplegable, dentro del menú: sangrado bajo su fila, con una línea a la izquierda y sin la caja + * blanca del escritorio. La opción elegida, como la página actual (fondo suave y negrita) y con una marca a la derecha + */ +.n4l-navbar-collapsed .navbar-nav .dropdown-menu { + --bs-dropdown-link-hover-bg: var(--bs-secondary-bg); + --bs-dropdown-link-active-bg: var(--bs-primary-bg-subtle); + --bs-dropdown-link-active-color: var(--bs-primary-text-emphasis); + margin: 0 0 .25rem 1.25rem; + padding: 0 0 0 .5rem; + border: 0; + border-left: 2px solid var(--bs-border-color); + border-radius: 0; + background-color: transparent; +} + +.n4l-navbar-collapsed .navbar-nav .dropdown-item { + display: flex; + align-items: center; + padding: .625rem .75rem; + border-radius: var(--bs-border-radius); + /* Con el texto grande o en una pantalla de 320 px, una opción larga pasa a otra línea */ + white-space: normal; +} + +.n4l-navbar-collapsed .navbar-nav .dropdown-item.active { + font-weight: 600; +} + +.n4l-navbar-check, +.n4l-navbar-external { + flex-shrink: 0; + margin-left: auto; + padding-left: .5rem; + box-sizing: content-box; +} + +.n4l-navbar-check { + width: 1.125rem; + height: 1.125rem; +} + +/* Tablet (y escritorio con el texto agrandado): dos columnas, páginas y ajustes */ +@media (min-width: 768px) { + .n4l-navbar-collapsed .n4l-navbar-menu { + display: grid; + grid-template-columns: 1fr 1fr; + column-gap: 1.5rem; + align-items: start; + } + + .n4l-navbar-collapsed .n4l-navbar-settings { + margin-top: 0; + padding-top: 0; + padding-left: 1.5rem; + border-top: 0; + border-left: var(--bs-border-width) solid var(--bs-border-color); + } +} diff --git a/src/components/header/N4LNavbar.tsx b/src/components/header/N4LNavbar.tsx index a117e38..df007f6 100644 --- a/src/components/header/N4LNavbar.tsx +++ b/src/components/header/N4LNavbar.tsx @@ -1,98 +1,304 @@ -import "./N4LNavbar.css" -import { useEffect, useState } from 'react' -import { Container, Nav, Navbar, NavDropdown } from 'react-bootstrap' -import { Link } from 'react-router' +import './N4LNavbar.css' +import { useEffect, useRef, useState, useSyncExternalStore, type FocusEvent } from 'react' +import { Badge, Container, Nav, Navbar, NavDropdown } from 'react-bootstrap' +import { Link, useLocation } from 'react-router' import { Trans, useTranslation } from 'react-i18next' -import IconLangES from '@assets/es.svg' -import IconLangGB from '@assets/gb.svg' -import IconThemeLight from '@assets/sun.svg' -import IconThemeDark from '@assets/moon.svg' +import { BoxArrowUpRight, BoxSeam, Check2, Cpu, GpuCard, MoonStarsFill, SunFill, Translate } from 'react-bootstrap-icons' import IconGithub from '@assets/github.svg' -import { changeUserLanguage, type Language_t } from '@core/i18n/language' +import { changeUserLanguage, LANGUAGE_OPTIONS } from '@core/i18n/language' +import { changeUserTheme, type Theme_t } from '@core/theme' +import { useTheme } from '@hooks/useTheme' +import { useMediaQuery } from '@hooks/useMediaQuery' +import { useDisplaySettings } from '@core/a11y/displaySettings' +import { useLocalPackages } from '@hooks/useLocalPackages' +import { N4LDropdownButton, N4LDropdownLink } from '@components/dropdown/N4LDropdownItems' +import { isTask, TASK_INFO } from '@components/task/taskInfo' +import { + changeUserTFBackend, + DEFAULT_TF_BACKEND, + getActiveTFBackend, + detectWebGPUAdapter, + isTFBackendAvailable, + subscribeActiveTFBackend, + TF_BACKEND_LABELS, + TF_BACKENDS, + type TFBackend_t, + type WebGPUAdapter_t, +} from '@core/tfBackend' -// Cada idioma con su nombre en ese idioma -const LANGUAGE_OPTIONS: Array<{ language: Language_t, label: string, icon: React.ReactNode }> = [ - { language: 'en', label: 'English', icon: }, - { language: 'es', label: 'Español', icon: }, - { language: 'ja', label: '日本語', icon: '🇯🇵' }, +// En una constante: jsx-a11y no sabe leer import.meta dentro de las props +const VITE_PATH = import.meta.env.VITE_PATH + +// Páginas del menú; Inicio solo está activa en la home. Detrás de Inicio va el desplegable de las tareas +const [HOME_LINK, ...NAV_LINKS]: Array<{ to: string, i18n: string }> = [ + { to: '/', i18n: 'header.home' }, + { to: '/manual', i18n: 'header.manual' }, + { to: '/glossary', i18n: 'header.glossary' }, + { to: '/datasets', i18n: 'header.datasets' }, + { to: '/analyze', i18n: 'header.analyze' }, ] +// Los paquetes .n4l del usuario, aparte: al final de las páginas, con su icono y cuántos tiene guardados +const PACKAGES_LINK = '/packages' +/** El laboratorio 2D, en el desplegable de las tareas */ +const LAB_LINK = '/lab' + +const isActivePath = (pathname: string, to: string) => (to === '/' ? pathname === '/' : pathname === to || pathname.startsWith(to + '/')) + +// La tarea en la que se está: su página, sus menús de modelos y conjuntos o su playground +const TASK_PAGES = ['task', 'select-model', 'select-dataset', 'playground'] +const taskOfPath = (pathname: string) => { + const [page, task] = pathname.split('/').filter((part) => part !== '') + return TASK_PAGES.includes(page) && isTask(task) ? task : undefined +} + export default function N4LNavbar() { const { t, i18n } = useTranslation() - const [dataTheme, setDataTheme] = useState('light') + const { pathname } = useLocation() + // main.tsx ya ha aplicado el tema inicial (el guardado o el del sistema) + // También cambia si se elige desde /settings + const theme = useTheme() + // Con el texto agrandado en /settings, la barra del escritorio no cabe: la del móvil (con el menú desplegable) también + // en pantallas anchas. Al 125 % cabe desde 1400 px; al 150 % o más, nunca + const { textSize } = useDisplaySettings() + const isVeryWide = useMediaQuery('(min-width: 1400px)') + const isCompact = textSize >= 150 || (textSize === 125 && !isVeryWide) + // El menú va en el botón: en el móvil y la tablet (por debajo de lg) y, con el texto agrandado, en cualquier pantalla + const isDesktop = useMediaQuery('(min-width: 992px)') + const isCollapsed = isCompact || !isDesktop + // Menú desplegado en móvil y tablet. Al cambiar de página se cierra: si no, tapa la página nueva + const [expanded, setExpanded] = useState(false) + const [menuPathname, setMenuPathname] = useState(pathname) + if (menuPathname !== pathname) { + setMenuPathname(pathname) + setExpanded(false) + } + + // La barra va fija arriba (sticky): su alto, sin el menú desplegado, queda en --n4l-navbar-height para lo que tiene + // que ir debajo (la barra del índice del móvil, el índice lateral, las tarjetas fijas y los saltos a una sección) + const navbar_ref = useRef(null) + useEffect(() => { + const navbar = navbar_ref.current + if (navbar === null || typeof ResizeObserver === 'undefined') return + const update = () => { + if (navbar.querySelector('.navbar-collapse.show, .navbar-collapse.collapsing') !== null) return + document.documentElement.style.setProperty('--n4l-navbar-height', `${navbar.offsetHeight}px`) + } + const observer = new ResizeObserver(update) + observer.observe(navbar) + update() + return () => observer.disconnect() + }, []) + + // Con el menú del móvil abierto, Escape lo cierra y deja el foco en su botón (si no hay un desplegable abierto dentro: + // entonces Escape es para él). El botón dice si está abierto o cerrado (aria-expanded), y lo de dentro va justo + // después de él con el tabulador useEffect(() => { - const htmlElement = document.querySelector('html')! - htmlElement.setAttribute('data-bs-theme', dataTheme) - htmlElement.setAttribute('data-theme', dataTheme) - }, [dataTheme]) + if (!expanded) return + const handleKeyDown = (event: KeyboardEvent) => { + const navbar = navbar_ref.current + if (event.key !== 'Escape' || navbar === null || navbar.querySelector('.dropdown-menu.show') !== null) return + setExpanded(false) + navbar.querySelector('.navbar-toggler')?.focus() + } + // En la captura: antes de que el desplegable se cierre con el mismo Escape (después ya no se vería abierto) + document.addEventListener('keydown', handleKeyDown, true) + return () => document.removeEventListener('keydown', handleKeyDown, true) + }, [expanded]) + + // Y si el foco sale de la barra (con el tabulador, después del último enlace), también se cierra: lo de detrás está + // oscurecido. Salvo si va a un aviso (un error al cambiar el backend), que al cerrarse lo devuelve al menú + const handleBlur = (event: FocusEvent) => { + const next = event.relatedTarget + if (!expanded || next === null || event.currentTarget.contains(next) || next.closest('[role="dialog"]') !== null) return + setExpanded(false) + } + + const handleClick_ChangeTheme = (newTheme: Theme_t) => { + changeUserTheme(newTheme) + } + + const tfBackend = useSyncExternalStore(subscribeActiveTFBackend, getActiveTFBackend) + // WebGPU y WebAssembly se descargan al elegirlos: mientras tanto no se puede elegir otro + const [isChangingTFBackend, setIsChangingTFBackend] = useState(false) + // Que exista navigator.gpu no basta para WebGPU: al abrir el menú se pregunta qué adaptador hay + // (undefined mientras no se sabe) + const [webgpuAdapter, setWebgpuAdapter] = useState(undefined) + + const handleToggle_TFBackend = (isOpen: boolean) => { + if (isOpen && isTFBackendAvailable('webgpu')) detectWebGPUAdapter().then(setWebgpuAdapter) + } + + const handleClick_ChangeTFBackend = async (newBackend: TFBackend_t) => { + if (newBackend === tfBackend) return + setIsChangingTFBackend(true) + const changed = await changeUserTFBackend(newBackend) + setIsChangingTFBackend(false) + if (!changed) { + // sweetalert2 solo se descarga si hace falta: el menú va en la carga inicial + const { default: alertHelper } = await import('@utils/alertHelper') + await alertHelper.alertError(t('header.backend-error', { backend: TF_BACKEND_LABELS[newBackend] }), { + text : '', + footer: '', + html : <>{t('header.backend-error-fallback', { backend: TF_BACKEND_LABELS[tfBackend] })}, + }) + } + } + + const activeTask = taskOfPath(pathname) + const savedPackages = useLocalPackages().length + const isPackagesPage = isActivePath(pathname, PACKAGES_LINK) + const isLabPage = isActivePath(pathname, LAB_LINK) + const navLink = ({ to, i18n: i18nKey }: { to: string, i18n: string }) => { + const isActive = isActivePath(pathname, to) + return ( + + setExpanded(false)}> + + + + ) + } + + const currentLanguage = LANGUAGE_OPTIONS.find(({ language }) => i18n.resolvedLanguage === language)?.label ?? i18n.language + // Título de los desplegables de ajustes: su icono (Bootstrap Icons, decorativo), su nombre y, solo en el menú del + // botón, su valor actual (en la barra del escritorio no cabe: ahí, solo el nombre) + const settingTitle = (icon: React.ReactNode, label: string, value: string) => <> + {icon} + {label} + {isCollapsed && {value}} + + // En el menú del botón, la opción elegida de un ajuste lleva una marca (además del color y la negrita) + const checked = (isActive: boolean) => isCollapsed && isActive && + // El backend calcula en la tarjeta gráfica (WebGL, WebGPU) o en el procesador (WASM, CPU) + const backendIcon = (backend: TFBackend_t) => (backend === 'webgl' || backend === 'webgpu' ? : ) return ( <> - - + + N4L + className="d-inline-block align-top me-1" + alt="" /> Nets4Learning - - - - +
    + {/* Con el menú del botón abierto, la página se oscurece detrás y tocarla lo cierra. Solo para el dedo o el ratón: + con el teclado, Escape o salir del menú con el tabulador */} + {isCollapsed && expanded && +
    setExpanded(false)} data-testid={'Test-Navbar-Backdrop'} />} ) } diff --git a/src/components/helpLink/N4LHelpLink.tsx b/src/components/helpLink/N4LHelpLink.tsx new file mode 100644 index 0000000..9aac29a --- /dev/null +++ b/src/components/helpLink/N4LHelpLink.tsx @@ -0,0 +1,24 @@ +import React from 'react' +import { Link } from 'react-router' + +type N4LHelpLinkProps = { + page : 'glossary' | 'manual' + action : string + children?: React.ReactNode +} + +/** + * Enlace a una sección del glosario o del manual. Se abre en otra pestaña para no perder lo que hay en el + * playground (dataset procesado, modelos entrenados…). La sección va en la URL (?action=…) porque el `state` + * del router no llega a una pestaña nueva. + */ +export default function N4LHelpLink({ page, action, children }: N4LHelpLinkProps) { + return ( + + {children} + + ) +} diff --git a/src/components/helpLink/N4LHelpTerm.tsx b/src/components/helpLink/N4LHelpTerm.tsx new file mode 100644 index 0000000..a9069d9 --- /dev/null +++ b/src/components/helpLink/N4LHelpTerm.tsx @@ -0,0 +1,56 @@ +import { useEffect, useId, useRef, useState, type ReactNode } from 'react' +import { Overlay, Popover } from 'react-bootstrap' + +import { prefersReducedMotion } from '@core/a11y/displaySettings' + +/** Lo que se espera antes de cerrar la ayuda al quitar el ratón: da tiempo a llevarlo hasta ella */ +const HIDE_DELAY_MS = 250 + +/** + * Término con su definición, que aparece al pasar el ratón, al llegar con el teclado o al pulsarlo (WCAG 1.4.13): se + * puede llevar el ratón hasta la definición sin que se cierre, se queda mientras se mira y se cierra con Escape. Es un + * botón (sin otra acción) para que se llegue a él con el tabulador; la definición se le asocia (aria-describedby) + * mientras se ve + */ +export default function N4LHelpTerm({ label, help }: { label: ReactNode, help: string }) { + const [show, setShow] = useState(false) + const target = useRef(null) + const hideTimer = useRef(0) + const popoverId = useId() + + const open = () => { + window.clearTimeout(hideTimer.current) + setShow(true) + } + const closeSoon = () => { + window.clearTimeout(hideTimer.current) + hideTimer.current = window.setTimeout(() => setShow(false), HIDE_DELAY_MS) + } + useEffect(() => () => window.clearTimeout(hideTimer.current), []) + + // Escape la cierra sin cerrar también lo que haya debajo (un modal, la guía) + useEffect(() => { + if (!show) return + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key !== 'Escape') return + event.stopPropagation() + setShow(false) + } + window.addEventListener('keydown', handleKeyDown, true) + return () => window.removeEventListener('keydown', handleKeyDown, true) + }, [show]) + + return <> + + + + {help} + + + +} diff --git a/src/components/joyride/N4LJoyride.tsx b/src/components/joyride/N4LJoyride.tsx deleted file mode 100644 index 493403f..0000000 --- a/src/components/joyride/N4LJoyride.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import React, { useCallback, useEffect, useImperativeHandle, useRef } from 'react' -import { useTranslation } from 'react-i18next' -import Joyride, { type StoreHelpers } from 'react-joyride' - -import { VERBOSE } from '@/CONSTANTS' -import type * as _Types from '@core/types' - -type N4LJoyrideProps = { - joyrideButton_ref: React.Ref<_Types.JoyrideHandle_t> - JOYRIDE_state? : _Types.Joyride_t | void - TASK? : string - KEY? : string -} - -export default function N4LJoyride ({ joyrideButton_ref, JOYRIDE_state, TASK = 'DEFAULT', KEY = 'DEFAULT' }: N4LJoyrideProps) { - - const { t } = useTranslation() - - const helpers_ref = useRef(null) - - const joyride_locale = { - back : t('joyride.back'), - close: t('joyride.close'), - last : t('joyride.last'), - next : t('joyride.next'), - open : t('joyride.open'), - skip : t('joyride.skip') - } - - const updateScreenJoyride = useCallback(() => { - window.dispatchEvent(new Event('resize')) - }, []) - - useEffect(() => { - const eventListener_scroll = () => { - updateScreenJoyride() - } - window.addEventListener('scroll', eventListener_scroll, { passive: true }) - - return () => window.removeEventListener('scroll', eventListener_scroll, {}) - }, [updateScreenJoyride]) - - useEffect(() => { - if (localStorage.getItem(`${TASK}.joyride-` + KEY) !== null) { - localStorage.setItem(`${TASK}.joyride-` + KEY, JSON.stringify({ run: true })) - } - }, [TASK, KEY]) - - useImperativeHandle(joyrideButton_ref, () => ({ - // Reinicia el tour desde el primer paso - handleClick_StartJoyride: () => helpers_ref.current?.reset(true) - }), []) - - if(VERBOSE) console.debug('render N4LJoyride') - return <> - { helpers_ref.current = helpers }} - locale={joyride_locale} - callback={JOYRIDE_state?.handleJoyrideCallback} - continuous={JOYRIDE_state?.continuous} - run={JOYRIDE_state?.run} - steps={JOYRIDE_state?.steps ?? []} - showProgress={true} - spotlightClicks={true} /> - -} diff --git a/src/components/joyride/buildJoyride.ts b/src/components/joyride/buildJoyride.ts deleted file mode 100644 index 48b078f..0000000 --- a/src/components/joyride/buildJoyride.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type { TFunction } from 'i18next' -import { ACTIONS, LIFECYCLE, type CallBackProps, type Placement } from 'react-joyride' - -import type * as _Types from '@core/types' -import { delay } from '@utils/utils' -import Errors from '@shared/Errors' - -export type JoyrideStepSpec_t = { - /** Clave de i18n del paso: se usan `.title` y `.content` */ - key : string - /** Selector del elemento que señala el paso */ - target : string - placement: Extract - /** Se ejecuta al mostrarse el paso (p. ej. abrir el acordeón donde está el elemento) */ - onShow? : () => void -} - -/** - * Configuración del tour guiado de una página. Cada paso lleva junto a su selector lo que hay que hacer - * al mostrarlo, así no se pueden desincronizar. - */ -export function buildJoyride(t: TFunction<'translation', undefined>, prefix: string, steps: JoyrideStepSpec_t[]): _Types.Joyride_t { - const handleJoyrideCallback = async (data: CallBackProps) => { - const { action, lifecycle, step } = data - if (action !== ACTIONS.UPDATE || lifecycle !== LIFECYCLE.TOOLTIP) return - steps.find(({ target }) => target === step.target)?.onShow?.() - // Da tiempo a que se abra lo necesario y recoloca el tooltip - await delay(500) - if (!window.dispatchEvent(new Event('resize'))) { - Errors.notDispatchedEvent() - } - } - - return { - run : false, - continuous : true, - handleJoyrideCallback: handleJoyrideCallback, - steps : steps.map(({ key, target, placement }) => ({ - title : t(prefix + key + '.title'), - content: t(prefix + key + '.content'), - target, - placement, - })), - } -} diff --git a/src/components/latex/N4LLatex.tsx b/src/components/latex/N4LLatex.tsx index def63c1..5727089 100644 --- a/src/components/latex/N4LLatex.tsx +++ b/src/components/latex/N4LLatex.tsx @@ -1,5 +1,5 @@ -import "katex/dist/katex.min.css" -import Latex from "react-latex-next" +import 'katex/dist/katex.min.css' +import Latex from 'react-latex-next' const LatexJSX = Latex as unknown as React.FC<{ children : React.ReactNode diff --git a/src/components/learning/N4LLearningToast.tsx b/src/components/learning/N4LLearningToast.tsx new file mode 100644 index 0000000..dce8e80 --- /dev/null +++ b/src/components/learning/N4LLearningToast.tsx @@ -0,0 +1,45 @@ +import { Toast, ToastContainer } from 'react-bootstrap' +import { Link, useLocation } from 'react-router' +import { useTranslation } from 'react-i18next' + +import { dismissJustCompleted, LEARNING_STEPS, nextStep, useJustCompleted, useLearningPath } from '@core/learning/learningPath' + +/** Cuánto se ve el aviso */ +const DELAY_MS = 9000 + +/** + * El aviso al completar un paso de «Empieza aquí» o superar un reto en cualquier página (si ya se ha entrado en + * /learn): qué se ha hecho y qué viene después. En /learn no hace falta: ya se ve allí. + */ +export default function N4LLearningToast() { + const { t } = useTranslation() + const { pathname } = useLocation() + const completed = useJustCompleted() + const { done } = useLearningPath() + if (completed === null || pathname === '/learn') return null + + const prefix = 'pages.learn.' + const isChallenge = completed.type === 'challenge' + const next = nextStep(done) + const title = isChallenge + ? t(prefix + 'toast.challenge') + : t(prefix + 'toast.title', { number: LEARNING_STEPS.findIndex(({ id }) => id === completed.id) + 1, total: LEARNING_STEPS.length }) + const link = isChallenge + ? t(prefix + 'toast.challenges') + : next === undefined ? t(prefix + 'toast.finished') : t(prefix + 'toast.next', { title: t(prefix + 'steps.' + next.id + '.title') }) + + return ( + + + + {title} + + +

    {t(prefix + (isChallenge ? 'challenges.' : 'steps.') + completed.id + '.title')}

    + {link} +
    +
    +
    + ) +} diff --git a/src/components/loading/FakeProgressBar.tsx b/src/components/loading/FakeProgressBar.tsx deleted file mode 100644 index b706316..0000000 --- a/src/components/loading/FakeProgressBar.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import 'bootstrap/dist/css/bootstrap.min.css' -import { useEffect, useState } from 'react' -import { useTranslation } from 'react-i18next' -import { ProgressBar } from 'react-bootstrap' -import { VERBOSE } from '@/CONSTANTS' - -type FakeProgressBarProps = { - isLoading: boolean -} -export default function FakeProgressBar(props: FakeProgressBarProps) { - const { isLoading } = props - - const { t } = useTranslation() - const [progress, setProgress] = useState(0) - - useEffect(() => { - if (VERBOSE) console.debug('useEffect[isLoading]', isLoading); - - // 1. Completion State: If loading is done, snap to 100% immediately - if (!isLoading) { - return // Exit the effect, no interval needed - } - - // 2. Loading State: Initialize variables - let currentInput = 0 // The 'x' in atan(x) - let step = 0.05 // Smaller steps because we update more often - - // 3. Start Animation Loop (50ms = 20fps) - const intervalId = setInterval(() => { - currentInput += step; - - // Calculate percentage based on atan curve - // Result is 0.0 to 1.0, multiplied by 100 - const _progress = (Math.atan(currentInput) / (Math.PI / 2)) * 100; - - // Round to 1 decimal place for cleanliness - setProgress(Math.round(_progress * 10) / 10); - - // Dynamic friction: Slow down the 'step' as we get higher - if (_progress >= 70) { - step = 0.01 // Crawl very slowly past 70% - } else if (_progress >= 50) { - step = 0.025; - } - - }, 50) // Updates every 50ms instead of 1000ms - - // 4. Cleanup - return () => clearInterval(intervalId); - }, [isLoading]); - - const shownProgress = isLoading ? progress : 100 - - return <> -
    - -
    - -} \ No newline at end of file diff --git a/src/components/loading/N4LDeferredMount.tsx b/src/components/loading/N4LDeferredMount.tsx new file mode 100644 index 0000000..a5953b5 --- /dev/null +++ b/src/components/loading/N4LDeferredMount.tsx @@ -0,0 +1,36 @@ +import { useEffect, useRef, useState, type ReactNode } from 'react' +import { scheduleIdle } from '@core/scheduler/idleQueue' + +type N4LDeferredMountProps = { + children : ReactNode + /** Alto mientras espera, para que la página no salte al montarse */ + minHeight?: number +} + +/** + * Monta su contenido cuando le toca en la cola de tiempo libre o, antes, si se acerca a la vista. Así una página larga + * no pinta de golpe todo lo que aún no se ve (TODO-worker.md, fase 6) + */ +export default function N4LDeferredMount({ children, minHeight = 240 }: N4LDeferredMountProps) { + const ref = useRef(null) + const [mounted, setMounted] = useState(false) + + useEffect(() => { + if (mounted) return + const cancel = scheduleIdle(() => setMounted(true)) + let observer: IntersectionObserver | undefined + if (ref.current !== null && typeof IntersectionObserver !== 'undefined') { + observer = new IntersectionObserver((entries) => { + if (entries.some((entry) => entry.isIntersecting)) setMounted(true) + }, { rootMargin: '400px 0px' }) + observer.observe(ref.current) + } + return () => { + cancel() + observer?.disconnect() + } + }, [mounted]) + + if (mounted) return <>{children} + return
    +} diff --git a/src/components/loading/N4LDownloadConsent.tsx b/src/components/loading/N4LDownloadConsent.tsx new file mode 100644 index 0000000..8d2f060 --- /dev/null +++ b/src/components/loading/N4LDownloadConsent.tsx @@ -0,0 +1,31 @@ +import { useMemo } from 'react' +import { Alert, Button } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' +import { Link } from 'react-router' + +import type { PendingDownload_t } from '@core/models/downloadConsent' + +/** + * La pregunta antes de descargar un modelo grande: cuánto pesa, por qué se pregunta (ahorro de datos, conexión lenta o + * porque se pidió en /settings) y el botón para descargarlo. + */ +export default function N4LDownloadConsent({ download }: { download: PendingDownload_t }) { + const { t, i18n } = useTranslation() + const prefix = 'download-consent.' + const mb = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 1 }).format(download.mb), [i18n.language, download.mb]) + + return ( + +

    {t(prefix + 'title', { mb })}

    +

    {t(prefix + 'reason.' + download.reason)}

    +
    + + + }} /> + +
    +
    + ) +} diff --git a/src/components/loading/N4LDownloadProgress.tsx b/src/components/loading/N4LDownloadProgress.tsx new file mode 100644 index 0000000..cb5fe30 --- /dev/null +++ b/src/components/loading/N4LDownloadProgress.tsx @@ -0,0 +1,70 @@ +import { useEffect, useMemo, useState } from 'react' +import { useTranslation } from 'react-i18next' + +import { useDownloadProgress } from '@core/downloadProgress' +import { cancelPendingDownload, usePendingDownload } from '@core/models/downloadConsent' +import N4LDownloadConsent from '@components/loading/N4LDownloadConsent' +import N4LProgressBar from '@components/loading/N4LProgressBar' + +type N4LDownloadProgressProps = { + isLoading: boolean +} + +/** Lo que se ve "Descargado" antes de quitar la barra */ +const DONE_MS = 2000 + +/** Por debajo de esto (las primeras peticiones, como model.json) no se dan MB ni porcentaje: saldría "0,0 de 0,0 MB" */ +const MIN_BYTES = 256 * 1024 + +/** + * La carga de un modelo (lo que esté dentro de trackDownloads): cuántos MB han llegado de cuántos, o una barra animada + * mientras no se sabe el tamaño. Al terminar dice "Descargado" un momento, se desvanece y deja de ocupar sitio. + */ +export default function N4LDownloadProgress({ isLoading }: N4LDownloadProgressProps) { + const { t, i18n } = useTranslation() + const progress = useDownloadProgress() + const format = useMemo(() => new Intl.NumberFormat(i18n.language, { minimumFractionDigits: 1, maximumFractionDigits: 1 }), [i18n.language]) + const mb = (bytes: number) => format.format(bytes / 1024 / 1024) + + // Recién terminada: "Descargado" durante DONE_MS. Sin haber cargado nada (ya estaba), no se enseña + const [wasLoading, setWasLoading] = useState(isLoading) + const [done, setDone] = useState(false) + if (wasLoading !== isLoading) { + setWasLoading(isLoading) + setDone(!isLoading) + } + useEffect(() => { + if (!done) return + const timer = window.setTimeout(() => setDone(false), DONE_MS) + return () => window.clearTimeout(timer) + }, [done]) + + const known = isLoading && progress !== null && progress.total !== null && progress.total >= MIN_BYTES + const percent = known ? Math.min(100, (progress.loaded / progress.total!) * 100) : 100 + const label = !isLoading + ? t('downloaded') + : known + ? t('loading-status.model-progress', { loaded: mb(progress.loaded), total: mb(progress.total!) }) + : progress !== null && progress.loaded >= MIN_BYTES + ? t('loading-status.model-loaded', { loaded: mb(progress.loaded) }) + : t('loading-status.model') + + // Un modelo grande con ahorro de datos o conexión lenta: antes de descargarlo se pregunta (askBeforeDownload) + const pendingDownload = usePendingDownload() + useEffect(() => cancelPendingDownload, []) + + if (isLoading && pendingDownload !== null) return + if (!isLoading && !done) return null + + return ( +
    + {/* La etiqueta va fuera de la barra: dentro no cabe en el móvil cuando la barra va por el principio */} +
    + {label} + {known && {Math.round(percent)} %} +
    + + {isLoading &&

    {t('loading-status.model-help')}

    } +
    + ) +} diff --git a/src/components/loading/N4LEmptyState.tsx b/src/components/loading/N4LEmptyState.tsx new file mode 100644 index 0000000..24e9201 --- /dev/null +++ b/src/components/loading/N4LEmptyState.tsx @@ -0,0 +1,13 @@ +import { Trans } from 'react-i18next' + +/** + * Aviso de que falta un paso del usuario (subir un fichero, procesar los datos, entrenar un modelo…) para ver el + * contenido de la tarjeta. Para una carga en curso se usa WaitingPlaceholder. + */ +export default function N4LEmptyState({ i18nKey }: { i18nKey: string }) { + return ( +

    + +

    + ) +} diff --git a/src/components/loading/N4LProgressBar.tsx b/src/components/loading/N4LProgressBar.tsx new file mode 100644 index 0000000..55a3596 --- /dev/null +++ b/src/components/loading/N4LProgressBar.tsx @@ -0,0 +1,18 @@ +import { ProgressBar, type ProgressBarProps } from 'react-bootstrap' + +type N4LProgressBarProps = Omit & { + /** Lo que dice el lector de pantalla de la barra (no se ve) */ + label: string +} + +/** + * Barra de progreso con nombre para los lectores de pantalla. ProgressBar pone aria-label en su envoltorio, donde no + * vale (no tiene rol), y deja sin nombre la barra (role="progressbar"); como barra hija, la etiqueta llega a la barra. + */ +export default function N4LProgressBar({ label, className, ...props }: N4LProgressBarProps) { + return ( + + + + ) +} diff --git a/src/components/markdown/N4LMarkdown.tsx b/src/components/markdown/N4LMarkdown.tsx index 33b72bb..3932103 100644 --- a/src/components/markdown/N4LMarkdown.tsx +++ b/src/components/markdown/N4LMarkdown.tsx @@ -1,58 +1,57 @@ -import "katex/dist/katex.min.css"; // `rehype-katex` does not import the CSS for you -import Markdown from "react-markdown"; -import rehypeFormat from "rehype-format"; -import rehypeKatex from "rehype-katex"; -import rehypeRaw from "rehype-raw"; +import 'katex/dist/katex.min.css'; // `rehype-katex` does not import the CSS for you +import Markdown from 'react-markdown'; +import rehypeFormat from 'rehype-format'; +import rehypeKatex from 'rehype-katex'; +import rehypeRaw from 'rehype-raw'; -import remarkGfm from "remark-gfm"; -import remarkMath from "remark-math"; -import remarkRehype from "remark-rehype"; +import remarkGfm from 'remark-gfm'; +import remarkMath from 'remark-math'; +import remarkRehype from 'remark-rehype'; -import { Table, Image } from "react-bootstrap"; +import { Table, Image } from 'react-bootstrap'; -import { PrismLight as SyntaxHighlighter } from "react-syntax-highlighter"; +import { PrismLight as SyntaxHighlighter } from 'react-syntax-highlighter'; import { darcula } from 'react-syntax-highlighter/dist/esm/styles/prism'; -import markdown from "react-syntax-highlighter/dist/esm/languages/prism/markdown"; -import typescript from "react-syntax-highlighter/dist/esm/languages/prism/typescript"; -import js from "react-syntax-highlighter/dist/esm/languages/prism/javascript"; -import jsx from "react-syntax-highlighter/dist/esm/languages/prism/jsx"; +import markdown from 'react-syntax-highlighter/dist/esm/languages/prism/markdown'; +import typescript from 'react-syntax-highlighter/dist/esm/languages/prism/typescript'; +import js from 'react-syntax-highlighter/dist/esm/languages/prism/javascript'; +import jsx from 'react-syntax-highlighter/dist/esm/languages/prism/jsx'; -import { Link } from "react-router"; +import { Link } from 'react-router'; -SyntaxHighlighter.registerLanguage("markdown", markdown); -SyntaxHighlighter.registerLanguage("typescript", typescript); -SyntaxHighlighter.registerLanguage("javascript", js); -SyntaxHighlighter.registerLanguage("jsx", jsx); -// SyntaxHighlighter.registerLanguage("jsdoc", jsdoc); +SyntaxHighlighter.registerLanguage('markdown', markdown); +SyntaxHighlighter.registerLanguage('typescript', typescript); +SyntaxHighlighter.registerLanguage('javascript', js); +SyntaxHighlighter.registerLanguage('jsx', jsx); export default function N4LMarkdown(props: { children: string }) { const { children } = props; return ( -
    +
    - {children.toString().replace("{server}", "")} + + {children.toString().replace('{server}', '')} ); } return ( - + {children} ); @@ -71,7 +70,7 @@ export default function N4LMarkdown(props: { children: string }) { }, code(props) { const { children, className, node: _, ...rest } = props; - const match = /language-(\w+)/.exec(className || ""); + const match = /language-(\w+)/.exec(className || ''); if (match) { // TODO FIX const { ref, style, ...safeRest } = rest; @@ -83,12 +82,12 @@ export default function N4LMarkdown(props: { children: string }) { language={match[1]} {...safeRest} > - {String(children).replace(/\n$/, "")} + {String(children).replace(/\n$/, '')} ); } else { return ( - + {children} ); @@ -96,11 +95,11 @@ export default function N4LMarkdown(props: { children: string }) { }, input(props) { const { node: _, ...rest } = props; - if (props.type === "checkbox") + if (props.type === 'checkbox') return ( ); @@ -109,20 +108,21 @@ export default function N4LMarkdown(props: { children: string }) { img(props) { // https://amirardalan.com/blog/use-next-image-with-react-markdown const { node: _, ...rest } = props; - const isServer = !!rest.alt?.toLowerCase().match("{server}"); + const isServer = !!rest.alt?.toLowerCase().match('{server}'); if (isServer && rest.src) { const newSrc = rest.src.replace( - "../", - import.meta.env.VITE_PATH + "/docs/" + '../', + import.meta.env.VITE_PATH + '/docs/' ); return ( {rest.alt} ); } else { @@ -139,22 +139,19 @@ export default function N4LMarkdown(props: { children: string }) { }, blockquote(props) { const { node: _, ...rest } = props; - return
    ; + return
    ; }, p(props) { const { children } = props; - return

    {children}

    ; + return

    {children}

    ; }, ul(props) { - // return
      {props.children}
    return
      {props.children}
    ; }, ol(props) { - // return
      {props.children}
    return
      {props.children}
    ; }, li(props) { - // return
  • {props.children}
  • return
  • {props.children}
  • ; }, table(props) { @@ -165,7 +162,7 @@ export default function N4LMarkdown(props: { children: string }) { bordered={true} borderless={true} hover={true} - size={"sm"} + size={'sm'} responsive={true} {...rest} /> diff --git a/src/components/maximize/N4LMaximize.css b/src/components/maximize/N4LMaximize.css new file mode 100644 index 0000000..b55bb74 --- /dev/null +++ b/src/components/maximize/N4LMaximize.css @@ -0,0 +1,52 @@ +/* Tarjeta maximizada (useMaximize): toda la pantalla, por encima de la barra de navegación (1030) y del visor del + entrenamiento (1035) y por debajo de los modales (1055) */ +.card.n4l-maximized { + position: fixed; + inset: 0; + z-index: 1040; + height: 100vh; + height: 100dvh; + margin: 0 !important; + border-radius: 0; +} + +.card.n4l-maximized > .card-header, +.card.n4l-maximized > .card-footer { + border-radius: 0; +} + +/* El cuerpo ocupa el alto que dejan la cabecera y el pie; lo que lleve n4l-maximized-fill, lo que queda en él */ +.card.n4l-maximized > .card-body { + display: flex; + flex: 1 1 auto; + flex-direction: column; + min-height: 0; + overflow: auto; +} + +.card.n4l-maximized .n4l-maximized-fill { + flex: 1 1 auto; + min-height: 0; +} + +/* Un contenedor .ratio (la cámara) deja de tener el alto de su proporción: el vídeo y el lienzo se ajustan dentro */ +.card.n4l-maximized .ratio.n4l-maximized-fill::before { + padding-top: 0; +} + +/* El botón (N4LMaximizeButton): cuadrado, con el alto de los controles pequeños de al lado (form-select-sm) y el icono + en el centro. Sin flex, el SVG va sobre la línea base del texto y queda 2 px por debajo del centro */ +.n4l-maximize-button { + display: inline-flex; + flex-shrink: 0; + align-items: center; + justify-content: center; + width: calc(1.5em + .5rem + var(--bs-border-width) * 2); + height: calc(1.5em + .5rem + var(--bs-border-width) * 2); + padding: 0; +} + +/* !important: react-joyride (el tutorial) deja en el body un overflow en línea */ +body.n4l-maximized-open { + overflow: hidden !important; +} diff --git a/src/components/maximize/N4LMaximizeButton.tsx b/src/components/maximize/N4LMaximizeButton.tsx new file mode 100644 index 0000000..147f8af --- /dev/null +++ b/src/components/maximize/N4LMaximizeButton.tsx @@ -0,0 +1,30 @@ +import './N4LMaximize.css' +import { Button } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' +import { Fullscreen, FullscreenExit } from 'react-bootstrap-icons' + +type N4LMaximizeButtonProps = { + /** De useMaximize */ + maximized: boolean + onToggle : () => void + disabled?: boolean +} + +/** Botón de la cabecera de una tarjeta que la maximiza (toda la pantalla) y la devuelve a su sitio */ +export default function N4LMaximizeButton({ maximized, onToggle, disabled = false }: N4LMaximizeButtonProps) { + const { t } = useTranslation() + const label = t(maximized ? 'ui.minimize' : 'ui.maximize') + const Icon = maximized ? FullscreenExit : Fullscreen + return ( + + ) +} diff --git a/src/components/maximize/useMaximize.ts b/src/components/maximize/useMaximize.ts new file mode 100644 index 0000000..56ece6c --- /dev/null +++ b/src/components/maximize/useMaximize.ts @@ -0,0 +1,30 @@ +import { useEffect, useState } from 'react' + +/** + * Una tarjeta que se puede maximizar: con `className` en la tarjeta, ocupa toda la pantalla (100dvh) por encima de la + * barra de navegación (N4LMaximize.css). Escape la devuelve a su sitio y, mientras está maximizada, la página de + * detrás no se desplaza. El botón es N4LMaximizeButton. + */ +export function useMaximize() { + const [maximized, setMaximized] = useState(false) + + useEffect(() => { + if (!maximized) return + const onKeyDown = (event: KeyboardEvent) => { + // Con un modal abierto encima, Escape es para cerrarlo + if (event.key === 'Escape' && !document.body.classList.contains('modal-open')) setMaximized(false) + } + document.addEventListener('keydown', onKeyDown) + document.body.classList.add('n4l-maximized-open') + return () => { + document.removeEventListener('keydown', onKeyDown) + document.body.classList.remove('n4l-maximized-open') + } + }, [maximized]) + + return { + maximized, + toggle : () => setMaximized((value) => !value), + className: maximized ? 'n4l-maximized' : '', + } +} diff --git a/src/components/modal/N4LModal.tsx b/src/components/modal/N4LModal.tsx index 3b4ecf0..e087182 100644 --- a/src/components/modal/N4LModal.tsx +++ b/src/components/modal/N4LModal.tsx @@ -1,5 +1,7 @@ import type React from 'react' +import { useId } from 'react' import { Modal } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' type N4LModalProps_t = { showModal : boolean, @@ -22,6 +24,9 @@ const DEFAULT_MODAL_PROPS: N4LModalProps_t = { ComponentFooter: <> } export default function N4LModal(props: N4LModalProps_t = DEFAULT_MODAL_PROPS) { + const { t } = useTranslation() + // El diálogo se llama como su título (WCAG 4.1.2) y su botón de cerrar, en el idioma de la página + const titleId = useId() const { showModal, @@ -35,7 +40,7 @@ export default function N4LModal(props: N4LModalProps_t = DEFAULT_MODAL_PROPS) { } = props return <> - { setShowModal(false) }}> {/**/} - - + + {title} diff --git a/src/components/n4l/N4LDownloadPackage.tsx b/src/components/n4l/N4LDownloadPackage.tsx new file mode 100644 index 0000000..737cafd --- /dev/null +++ b/src/components/n4l/N4LDownloadPackage.tsx @@ -0,0 +1,33 @@ +import { useState } from 'react' +import { Button, Spinner } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import { trackEvent } from '@core/analytics' +import { downloadN4LPackage } from '@core/n4l/export' +import type { N4LPackage_t } from '@core/n4l/source' + +/** Descargar el paquete del modelo en un fichero .n4l (su modelo, sus datos y sus textos) para compartirlo o abrirlo después */ +export default function N4LDownloadPackage({ pkg }: { pkg: N4LPackage_t | null }) { + const { t } = useTranslation() + const [isPacking, setIsPacking] = useState(false) + if (pkg === null) return null + + const handleClick = async () => { + setIsPacking(true) + try { + await downloadN4LPackage(pkg) + trackEvent('n4l_download', { item: pkg.manifest.id }) + } finally { + setIsPacking(false) + } + } + + return ( +
    + +
    + ) +} diff --git a/src/components/n4l/N4LDownloadTrained.tsx b/src/components/n4l/N4LDownloadTrained.tsx new file mode 100644 index 0000000..4d17b67 --- /dev/null +++ b/src/components/n4l/N4LDownloadTrained.tsx @@ -0,0 +1,68 @@ +import { useState } from 'react' +import { Button, Spinner } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' +import type * as tfjs from '@tensorflow/tfjs' + +import { trackEvent } from '@core/analytics' +import { n4lFileName } from '@core/n4l/export' +import { packTrainedModel } from '@core/n4l/exportTrained' +import type { N4LLayer_t, N4LModelInput_t } from '@core/n4l/format' +import type { N4LPackage_t } from '@core/n4l/source' + +type N4LDownloadTrainedProps = { + /** El paquete del conjunto con el que se entrenó; sin él (un CSV subido) no hay botón */ + pkg : N4LPackage_t | null + task : string + model : tfjs.LayersModel + /** Sus capas, como en el manifiesto (serán la red por defecto al entrenar con el paquete) */ + layers : N4LLayer_t[] + /** Lo que recibe, si es una tabla */ + input? : N4LModelInput_t + /** Las clases en el orden de las salidas del modelo */ + classes: string[] + history: Record + /** Su número en la tabla */ + number : number +} + +/** Descargar un modelo entrenado en un .n4l (con el conjunto, su preprocesado y sus textos), para abrirlo después */ +export default function N4LDownloadTrained({ pkg, task, model, layers, input, classes, history, number }: N4LDownloadTrainedProps) { + const { t } = useTranslation() + const [isPacking, setIsPacking] = useState(false) + if (pkg === null) return null + + const handleClick = async () => { + setIsPacking(true) + try { + // Las métricas de la última época + const metrics = Object.fromEntries(Object.entries(history) + .map(([name, values]) => [name, values.at(-1)] as const) + .filter((entry): entry is [string, number] => typeof entry[1] === 'number' && Number.isFinite(entry[1]))) + const { manifest, blob } = await packTrainedModel(pkg, task, { + model, + layers, + classes, + number, + metrics, + input, + }, (_language, name) => `${name} (#${number})`) + const url = URL.createObjectURL(blob) + const link = document.createElement('a') + link.href = url + link.download = n4lFileName(manifest) + link.click() + URL.revokeObjectURL(url) + trackEvent('n4l_download', { item: manifest.id }) + } finally { + setIsPacking(false) + } + } + + return ( + + ) +} diff --git a/src/components/n4l/N4LLocalPackages.tsx b/src/components/n4l/N4LLocalPackages.tsx new file mode 100644 index 0000000..96d71c6 --- /dev/null +++ b/src/components/n4l/N4LLocalPackages.tsx @@ -0,0 +1,108 @@ +import { useState } from 'react' +import { Alert, Badge, Card, Col, Row } from 'react-bootstrap' +import { Link } from 'react-router' +import { useTranslation } from 'react-i18next' + +import { trackEvent } from '@core/analytics' +import { importN4LPackage, localKey, localPackageName, removeLocalPackage, type LocalPackage_t } from '@core/n4l/localPackages' +import { N4LError } from '@core/n4l/validate' +import { useLocalPackages } from '@hooks/useLocalPackages' +import DragAndDrop from '@components/dragAndDrop/DragAndDrop' +import N4LEmptyState from '@components/loading/N4LEmptyState' +import N4LConfirmButton from '@components/form/N4LConfirmButton' +import { isTask, TASK_INFO } from '@components/task/taskInfo' + +const prefix = 'n4l.local.' + +// Un .n4l es un ZIP: según el sistema llega con un tipo u otro (o ninguno) +const N4L_ACCEPT = { 'application/zip': ['.n4l'], 'application/x-zip-compressed': ['.n4l'], 'application/octet-stream': ['.n4l'], 'application/vnd.nets4learning.n4l+zip': ['.n4l'] } + +/** El nombre de un paquete: el de su primera tarea */ +const packageName = (info: LocalPackage_t, language: string) => localPackageName(info, info.tasks[0]?.task ?? '', language) + +/** Un paquete guardado: en cada una de sus tareas, probar su modelo (si trae alguno) o entrenar con su conjunto */ +function LocalPackageCard({ info }: { info: LocalPackage_t }) { + const { t, i18n } = useTranslation() + const size = new Intl.NumberFormat(i18n.language, { style: 'unit', unit: 'kilobyte', maximumFractionDigits: 0 }) + const name = packageName(info, i18n.language) + return ( + + + {name} +

    + {t(prefix + 'version', { version: info.version, size: size.format(Math.max(1, Math.round(info.bytes / 1024))) })} +

    +
      + {info.tasks.map(({ task, models }) => ( +
    • +
      {isTask(task) ? t(TASK_INFO[task].i18nTitle) : task}
      +
      + {models > 0 && + {t('datasets.try-model')}} + {t('datasets.train')} +
      +
    • + ))} +
    +
    + + removeLocalPackage(info.id)} /> + +
    + ) +} + +/** + * Los paquetes .n4l del usuario: abrir uno (se valida y se guarda en el navegador) y los ya guardados, cada uno con sus + * tareas (probar su modelo o entrenar con su conjunto) y para quitarlo + */ +export default function N4LLocalPackages() { + const { t, i18n } = useTranslation() + const packages = useLocalPackages() + const [problems, setProblems] = useState(null) + const [imported, setImported] = useState(null) + + const handleDrop = async (files: File[]) => { + if (files.length !== 1) return + setProblems(null) + setImported(null) + try { + const info = await importN4LPackage(await files[0].arrayBuffer()) + setImported(packageName(info, i18n.language)) + trackEvent('n4l_import', { outcome: 'ok', item: info.id }) + } catch (error) { + setProblems(error instanceof N4LError ? error.problems : [error instanceof Error ? error.message : String(error)]) + trackEvent('n4l_import', { outcome: 'error' }) + } + } + + return ( +
    + +

    {t(prefix + 'open-title')}

    + +

    {t(prefix + 'how')}

    + + {imported !== null && {t(prefix + 'imported', { name: imported })}} + {problems !== null && + +

    {t(prefix + 'error')}

    +
      {problems.map((problem) =>
    • {problem}
    • )}
    +
    } +
    +
    + +
    +

    {t(prefix + 'saved')} {packages.length}

    + {packages.length === 0 && } + {packages.length > 0 && + + {packages.map((info) => )} + } +
    +
    + ) +} diff --git a/src/components/n4l/N4LPackageDescription.tsx b/src/components/n4l/N4LPackageDescription.tsx new file mode 100644 index 0000000..dcc0c5c --- /dev/null +++ b/src/components/n4l/N4LPackageDescription.tsx @@ -0,0 +1,60 @@ +import type { ReactNode } from 'react' +import { Trans, useTranslation } from 'react-i18next' + +import type { N4LManifest_t } from '@core/n4l/format' + +/** La descripción en los textos del paquete: párrafos y apartados desplegables (con su texto y su lista) */ +type Description_t = { + text? : string[] + sections?: Array<{ title: string, text?: string[], items?: string[] }> +} + +type N4LPackageDescriptionProps = { + manifest : N4LManifest_t + namespace: string + task : string + /** Lo propio de la tarea, después de los párrafos (la tabla de caracteres de KMNIST…) */ + children?: ReactNode +} + +/** + * La descripción de un paquete .n4l en una tarea, de sus textos (locales/.json, tasks..description): + * admite , … y , que enlaza a la fuente del conjunto de datos, y las métricas de su primer modelo + * ({{test_accuracy}}…). Al final, la cita en BibTeX del manifiesto + */ +export default function N4LPackageDescription({ manifest, namespace: ns, task, children }: N4LPackageDescriptionProps) { + const { t } = useTranslation(ns) + const prefix = `tasks.${task}.description` + const description = t(prefix, { ns, returnObjects: true }) as Description_t | string + // : la fuente; …, las otras direcciones del paquete + // El texto del enlace lo pone (el de la traducción entre y ) + // eslint-disable-next-line jsx-a11y/anchor-has-content + const link = (href: string | undefined) => (href === undefined ? : ) + const components = { + link1: link(manifest.source?.url), + ...Object.fromEntries(Object.entries(manifest.source?.links ?? {}).map(([name, href]) => [name, link(href)])), + } + const values = manifest.tasks.find((section) => section.task === task)?.models[0]?.metrics ?? {} + const text = (key: string) => + const content = typeof description === 'object' && description !== null ? description : {} + + return ( +
    + {content.text?.map((_, i) =>

    {text(`${prefix}.text.${i}`)}

    )} + {children} + {content.sections?.map((section, i) => ( +
    + {text(`${prefix}.sections.${i}.title`)} + {section.text?.map((_, j) =>

    {text(`${prefix}.sections.${i}.text.${j}`)}

    )} + {section.items !== undefined && +
      {section.items.map((_, j) =>
    1. {text(`${prefix}.sections.${i}.items.${j}`)}
    2. )}
    } +
    + ))} + {manifest.source?.citation !== undefined && +
    + BibTeX +
    {manifest.source.citation}
    +
    } +
    + ) +} diff --git a/src/components/n4l/N4LTestMetrics.tsx b/src/components/n4l/N4LTestMetrics.tsx new file mode 100644 index 0000000..3aeb911 --- /dev/null +++ b/src/components/n4l/N4LTestMetrics.tsx @@ -0,0 +1,24 @@ +import { Alert } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +type N4LTestMetricsProps = { + metrics: { test_r2: number, test_mae: number, test_baseline_mae: number } | null +} + +/** + * Cómo predice un modelo de regresión con datos que no vio al entrenarlo: su error medio frente al de predecir siempre + * la media, y su R². Si no lo mejora, se dice: con esos datos no se puede predecir mucho más + */ +export default function N4LTestMetrics({ metrics }: N4LTestMetricsProps) { + const { t, i18n } = useTranslation() + if (metrics === null) return null + const number = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 2 }) + const isBetter = metrics.test_mae < metrics.test_baseline_mae + return ( + +

    {t('n4l.metrics.title')}

    +

    {t('n4l.metrics.text', { mae: number.format(metrics.test_mae), baseline: number.format(metrics.test_baseline_mae), r2: number.format(metrics.test_r2) })}

    + {!isBetter &&

    {t('n4l.metrics.no-better')}

    } +
    + ) +} diff --git a/src/components/navigation/N4LPageTitle.tsx b/src/components/navigation/N4LPageTitle.tsx new file mode 100644 index 0000000..41a3408 --- /dev/null +++ b/src/components/navigation/N4LPageTitle.tsx @@ -0,0 +1,20 @@ +import { useEffect } from 'react' +import { useLocation } from 'react-router' +import { useTranslation } from 'react-i18next' + +import { pageTitle, pageTitleParts } from '@core/pageTitle' + +/** + * El título de la pestaña según la página y lo que hay abierto en ella (WCAG 2.4.2), en el idioma elegido: es lo + * primero que anuncia el lector de pantalla al cambiar de página + */ +export default function N4LPageTitle() { + const { pathname, search } = useLocation() + const { t, i18n } = useTranslation() + + useEffect(() => { + document.title = pageTitle(pageTitleParts(pathname, search, t)) + }, [pathname, search, t, i18n.language]) + + return null +} diff --git a/src/components/navigation/N4LScrollManager.tsx b/src/components/navigation/N4LScrollManager.tsx new file mode 100644 index 0000000..0bb3b00 --- /dev/null +++ b/src/components/navigation/N4LScrollManager.tsx @@ -0,0 +1,116 @@ +import { useEffect, useLayoutEffect, useRef } from 'react' +import { useLocation, useNavigationType } from 'react-router' + +import { scrollAction, type Place_t, type ScrollAction_t } from '@components/navigation/scrollAction' + +// El scroll al cambiar de página. BrowserRouter no lo toca: sin esto, la página nueva se ve a la altura a la que estaba +// la anterior y parece que no se ha cambiado. Las navegaciones dentro de la misma página (secciones, ?task=…) no son +// cosa de este componente: las lleva cada página. + +/** + * Lo que se espera a que la página (que se carga aparte) tenga el alto o la sección a la que se va. La primera vez su + * código y sus librerías pueden tardar: si quien usa la página se mueve antes, se deja de esperar + */ +const WAIT_MS = 15_000 + +const scrollToY = (top: number) => window.scrollTo({ top, left: 0, behavior: 'instant' }) + +/** + * El
    de la página que se ve. Mientras llega el código de la nueva, React deja la anterior oculta (display: none) + * y enseña el aviso de carga: esa no cuenta + */ +const visibleMain = () => Array.from(document.querySelectorAll('main')).find((main) => main.getClientRects().length > 0) ?? null + +/** La página nueva ya está: se ve su
    y tiene su título */ +const isPageReady = () => visibleMain()?.querySelector('h1') != null + +/** El foco, al título de la página nueva (los lectores de pantalla la anuncian), si la página no lo ha puesto en otro sitio */ +function focusPage(target: HTMLElement | null) { + const main = visibleMain() + if (main === null || main.contains(document.activeElement)) return + const element = target ?? main.querySelector('h1') ?? main + if (!element.hasAttribute('tabindex')) element.setAttribute('tabindex', '-1') + element.focus({ preventScroll: true }) +} + +/** Hace scroll según la navegación y recuerda dónde se estaba en cada página para volver con atrás y adelante */ +export default function N4LScrollManager() { + const location = useLocation() + const navigationType = useNavigationType() + const previous = useRef(null) + const positions = useRef(new Map()) + const currentKey = useRef(location.key) + // Lo decidido para la navegación actual: si el efecto se repite (modo estricto de React), se repite lo mismo + const handled = useRef<{ key: string, action: ScrollAction_t, isPageChange: boolean } | null>(null) + + // Dónde se está en la página actual (para volver a ella con atrás) + useEffect(() => { + let frame = 0 + const save = () => { + cancelAnimationFrame(frame) + frame = requestAnimationFrame(() => positions.current.set(currentKey.current, window.scrollY)) + } + window.addEventListener('scroll', save, { passive: true }) + return () => { + cancelAnimationFrame(frame) + window.removeEventListener('scroll', save) + } + }, []) + + // Antes de pintar la página nueva, para que no se vea un momento a la altura de la anterior + useLayoutEffect(() => { + if (handled.current?.key !== location.key) { + const action = scrollAction(previous.current, location, navigationType, positions.current.get(location.key)) + handled.current = { key: location.key, action, isPageChange: previous.current !== null && previous.current.pathname !== location.pathname } + previous.current = { pathname: location.pathname, hash: location.hash } + currentKey.current = location.key + if (action.type === 'top') scrollToY(0) + } + const { action, isPageChange } = handled.current + if (action.type === 'none') return + + // La sección o el alto al que se vuelve pueden no estar todavía (la página se carga aparte): se espera un poco, y si + // quien usa la página se mueve mientras tanto, se deja de esperar + let frame = 0 + let isCancelled = false + const cancel = () => { isCancelled = true } + const userEvents = ['wheel', 'touchstart', 'keydown', 'mousedown'] as const + userEvents.forEach((name) => window.addEventListener(name, cancel, { passive: true, once: true })) + const startedAt = performance.now() + const attempt = () => { + if (isCancelled) return + const isLate = performance.now() - startedAt > WAIT_MS + if (action.type === 'hash') { + // Una sección (su id) o algo marcado con data-hash-target: las pestañas de /settings, que ya se ven al cargar la + // página. Con ellas la página se queda arriba, con su título, y el foco va a la pestaña. No llevan el id del + // ancla para que el navegador no baje solo hasta ellas al cargar + const element = document.getElementById(action.id) ?? document.querySelector(`[data-hash-target="${CSS.escape(action.id)}"]`) + if (element !== null) { + if (element.dataset.hashTarget !== undefined) scrollToY(0) + else element.scrollIntoView({ block: 'start', behavior: 'instant' }) + if (isPageChange) focusPage(element) + return + } + } else if (action.type === 'restore') { + const maxY = document.documentElement.scrollHeight - window.innerHeight + if ((maxY >= action.y && isPageReady()) || isLate) { + scrollToY(Math.min(action.y, Math.max(0, maxY))) + focusPage(null) + return + } + } else if (isPageReady() || isLate) { + focusPage(null) + return + } + if (!isLate) frame = requestAnimationFrame(attempt) + } + attempt() + return () => { + cancelAnimationFrame(frame) + cancel() + userEvents.forEach((name) => window.removeEventListener(name, cancel)) + } + }, [location, navigationType]) + + return null +} diff --git a/src/components/navigation/N4LSkipLink.tsx b/src/components/navigation/N4LSkipLink.tsx new file mode 100644 index 0000000..57a7a76 --- /dev/null +++ b/src/components/navigation/N4LSkipLink.tsx @@ -0,0 +1,29 @@ +import { useTranslation } from 'react-i18next' + +/** El id de lo que rodea a las páginas (App.tsx): el destino del enlace, aunque lo que recibe el foco es su
    */ +export const SKIP_LINK_TARGET = 'n4l-content' + +/** + * «Saltar al contenido» (WCAG 2.4.1): el primer elemento al que se llega con el tabulador, solo visible entonces. Lleva + * el foco al
    que se ve, sin pasar por los enlaces y menús de la barra de navegación. No cambia la dirección + * (seguir el enlace la cambiaría y el router lo trataría como otra navegación) + */ +export default function N4LSkipLink() { + const { t } = useTranslation() + + const handleClick = (event: React.MouseEvent) => { + event.preventDefault() + // Mientras carga una página, React deja la anterior oculta: la que cuenta es la que se ve + const main = Array.from(document.querySelectorAll('main')).find((element) => element.getClientRects().length > 0) + if (main === undefined) return + if (!main.hasAttribute('tabindex')) main.setAttribute('tabindex', '-1') + main.focus({ preventScroll: true }) + main.scrollIntoView({ block: 'start' }) + } + + return ( + + {t('skip-to-content')} + + ) +} diff --git a/src/components/navigation/scrollAction.ts b/src/components/navigation/scrollAction.ts new file mode 100644 index 0000000..293c107 --- /dev/null +++ b/src/components/navigation/scrollAction.ts @@ -0,0 +1,28 @@ +import { NavigationType, type Location } from 'react-router' + +// Qué hace el scroll al cambiar de página (N4LScrollManager) + +export type ScrollAction_t = + | { type: 'none' } + | { type: 'top' } + | { type: 'hash', id: string } + | { type: 'restore', y: number } + +export type Place_t = Pick + +const SECTION_ID = /^[A-Za-z][\w:.-]*$/ + +/** + * Qué hacer al llegar a `next` desde `previous` (null: la primera página de la visita). Atrás y adelante vuelven a donde + * se estaba; un enlace con #sección, a la sección; cualquier otra página nueva, arriba del todo. + */ +export function scrollAction(previous: Place_t | null, next: Place_t, navigationType: NavigationType, saved: number | undefined): ScrollAction_t { + // Solo si es el id de una sección (no, p. ej., la configuración de un enlace compartido: #n4z=…) + const id = decodeURIComponent(next.hash.slice(1)) + const hash = SECTION_ID.test(id) ? { type: 'hash' as const, id } : null + // Al entrar (o recargar) el navegador ya pone el scroll; solo falta la sección, que aún no existía + if (previous === null) return hash ?? { type: 'none' } + if (previous.pathname === next.pathname) return { type: 'none' } + if (navigationType === NavigationType.Pop && saved !== undefined) return { type: 'restore', y: saved } + return hash ?? { type: 'top' } +} diff --git a/src/components/neural-network/N4LClassificationChart.tsx b/src/components/neural-network/N4LClassificationChart.tsx new file mode 100644 index 0000000..5e19e13 --- /dev/null +++ b/src/components/neural-network/N4LClassificationChart.tsx @@ -0,0 +1,109 @@ +import { useEffect } from 'react' +import { Bar } from 'react-chartjs-2' +import { useTranslation } from 'react-i18next' +import { Badge } from 'react-bootstrap' +import type { ChartData, ChartOptions } from 'chart.js' +import { argMax, isProbabilityDistribution } from '@core/nn-utils/classificationOutput' +import { chartColor, withAlpha } from '@core/chartColors' +import { announce } from '@core/a11y/announce' +import N4LChartData from '@components/chart/N4LChartData' +import { useTheme } from '@hooks/useTheme' +import { prefersReducedMotion } from '@core/a11y/displaySettings' + +type N4LClassificationChartProps = { + /** Salida del modelo para cada clase (probabilidades si la última capa es softmax) */ + values : number[] + classLabels : string[] + /** Clase elegida; por defecto la de mayor valor */ + index? : number + /** Clase real, si se conoce (un ejemplo del conjunto de datos): se indica si el modelo acierta */ + actualIndex?: number | null + /** + * Solo las clases más probables de muchas (p. ej. MobileNet, con 1000): son probabilidades aunque no sumen 1 y el + * título lo dice + */ + topK? : boolean +} + +/** Clase predicha y, en un gráfico de barras, la probabilidad (o la salida) de cada clase, con la elegida resaltada */ +export default function N4LClassificationChart({ values, classLabels, index = argMax(values), actualIndex = null, topK = false }: N4LClassificationChartProps) { + const { t, i18n } = useTranslation() + const prefix = 'pages.playground.generator.classify.' + // Azul y gris: la clase elegida resalta sobre el resto. El relleno es translúcido; el borde, del color entero, se + // distingue del fondo (3:1) también en las barras grises + const theme = useTheme() + const highlight = chartColor('blue', theme) + const muted = chartColor('gray', theme) + const isProbability = topK || isProbabilityDistribution(values) + const title = topK ? t(prefix + 'chart-title-top', { count: values.length }) : t(prefix + (isProbability ? 'chart-title' : 'chart-title-output')) + const help = t(prefix + (topK ? 'chart-help-top' : isProbability ? 'chart-help' : 'chart-help-output')) + const percentFormat = new Intl.NumberFormat(i18n.language, { style: 'percent', maximumFractionDigits: 1 }) + const numberFormat = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 3 }) + const format = (value: number) => (isProbability ? percentFormat.format(value) : numberFormat.format(value)) + const labels = values.map((_, i) => classLabels[i] ?? String(i)) + // Las clases de una o dos letras (dígitos, hiragana) se leen mejor más grandes; los nombres largos, no + const tickFont = labels.every((label) => label.length <= 2) ? { size: 16 } : undefined + const axisValue = t(prefix + (isProbability ? 'axis-probability' : 'axis-output')) + const isHit = actualIndex !== null && actualIndex === index + const actualText = actualIndex === null ? null + : `${t(prefix + 'actual-class', { label: classLabels[actualIndex] ?? String(actualIndex) })} (${t(prefix + (isHit ? 'hit' : 'miss'))})` + + // El resultado, también para el lector de pantalla, sin mover el foco del botón que lo ha pedido (WCAG 4.1.3) + const predicted = `${t(prefix + 'predicted-class')}: ${labels[index]}` + + (isProbability ? `, ${t(prefix + 'confidence', { value: percentFormat.format(values[index]) })}` : '') + const result = actualText === null ? predicted : `${predicted}. ${actualText}` + useEffect(() => announce(result), [result]) + + const data: ChartData<'bar'> = { + labels, + datasets: [{ + label : axisValue, + data : isProbability ? values.map((value) => value * 100) : values, + backgroundColor: values.map((_, i) => (i === index ? withAlpha(highlight, 0.75) : withAlpha(muted, 0.35))), + borderColor : values.map((_, i) => (i === index ? highlight : muted)), + borderWidth : 1, + // Con pocas clases y todo el ancho, las barras no se ensanchan sin límite + maxBarThickness: 96, + }], + } + const options: ChartOptions<'bar'> = { + responsive : true, + maintainAspectRatio: false, + animation : prefersReducedMotion() ? false : { duration: 300 }, + plugins : { + legend : { display: false }, + tooltip: { callbacks: { label: (context) => format(values[context.dataIndex]) } }, + }, + scales: { + x: { title: { display: true, text: t(prefix + 'axis-class') }, ticks: { font: tickFont } }, + y: isProbability + ? { min: 0, max: 100, title: { display: true, text: axisValue }, ticks: { callback: (value) => `${value} %` } } + : { title: { display: true, text: axisValue } }, + }, + } + + return ( +
    +
    + {t(prefix + 'predicted-class')} + {labels[index]} + {isProbability && {t(prefix + 'confidence', { value: percentFormat.format(values[index]) })}} + {actualIndex !== null && + + {t(prefix + 'actual-class', { label: classLabels[actualIndex] ?? String(actualIndex) })} + {/* Si acierta o no, también sin el color (WCAG 1.4.1): con una marca y, para el lector, con palabras */} + {isHit ? '✓' : '✗'} + ({t(prefix + (isHit ? 'hit' : 'miss'))}) + } +
    +

    {title}

    +
    + `${label}: ${format(values[i])}`).join(', ')} /> +
    +

    {help}

    + [label, isProbability ? percentFormat.format(values[i]) : values[i]])} /> +
    + ) +} diff --git a/src/components/neural-network/N4LConfusionMatrix.tsx b/src/components/neural-network/N4LConfusionMatrix.tsx new file mode 100644 index 0000000..0aa60c7 --- /dev/null +++ b/src/components/neural-network/N4LConfusionMatrix.tsx @@ -0,0 +1,89 @@ +import { Table } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import { confusionMatrix, confusionStats } from '@core/history/trainingSummary' +import HelpTerm from '@components/helpLink/N4LHelpTerm' + +type N4LConfusionMatrixProps = { + classes : string[] + /** Clase real y predicha (índices) de cada ejemplo de validación */ + labels : number[] + predictions: number[] +} + +/** Fondo de una celda: verde en los aciertos y rojo en los errores, más intenso cuanto mayor es la parte de su fila */ +const cellBackground = (count: number, rowTotal: number, isHit: boolean) => { + if (count === 0 || rowTotal === 0) return undefined + const alpha = 0.12 + 0.6 * (count / rowTotal) + return `rgba(var(--bs-${isHit ? 'success' : 'danger'}-rgb), ${alpha.toFixed(2)})` +} + +/** Matriz de confusión del conjunto de validación, con la sensibilidad de cada clase real y la precisión de cada predicha */ +export default function N4LConfusionMatrix({ classes, labels, predictions }: N4LConfusionMatrixProps) { + const { t, i18n } = useTranslation() + const prefix = 'pages.playground.generator.training.' + const help = 'pages.playground.generator.help.' + const matrix = confusionMatrix(labels, predictions, classes.length) + const { support, recall, precision, correct, total, accuracy } = confusionStats(matrix) + const percentFormat = new Intl.NumberFormat(i18n.language, { style: 'percent', maximumFractionDigits: 1 }) + const percent = (value: number | null) => (value === null ? '—' : percentFormat.format(value)) + + return ( +
    +

    {t(prefix + 'confusion-title')}

    +

    + {t(prefix + 'confusion-accuracy', { accuracy: percent(accuracy), correct, total })} +

    + + + + {/* La esquina no es el encabezado de nada: una celda vacía */} + + + + + + {classes.map((name) => )} + + + + {matrix.map((row, real) => ( + + {real === 0 && + + } + + {row.map((count, predicted) => ( + + ))} + + + + ))} + + + + + {precision.map((value, predicted) => )} + + + + +
    + {t(prefix + 'confusion-predicted')}{t(prefix + 'confusion-total')} + +
    {t(name)}
    + {t(prefix + 'confusion-real')} + {t(classes[real])} + {count} + {support[real] > 0 ? percent(count / support[real]) : '—'} + {support[real]}{percent(recall[real])}
    + + {percent(value)}{total} + +
    +

    {t(prefix + 'confusion-legend')}

    +
    + ) +} diff --git a/src/components/neural-network/N4LDenseLayerFields.tsx b/src/components/neural-network/N4LDenseLayerFields.tsx new file mode 100644 index 0000000..63e8711 --- /dev/null +++ b/src/components/neural-network/N4LDenseLayerFields.tsx @@ -0,0 +1,49 @@ +import { Form } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' + +import { TYPE_ACTIVATION } from '@core/nn-utils/ArchitectureTypesHelper' +import N4LNumberField from '@components/form/N4LNumberField' +import N4LHelpTerm from '@components/helpLink/N4LHelpTerm' + +export type EditableLayer_t = { + units : number + activation : string | null + /** Capa que el usuario no puede cambiar ni borrar (p. ej. la salida de regresión) */ + is_disabled?: boolean +} + +const prefix = 'pages.playground.generator.editor-layers.' + +type N4LDenseLayerFieldsProps = { + index : number + layer : EditableLayer_t + onChange: (index: number, layer: { units: number, activation: string | null }) => void +} + +/** + * Lo que se edita de una capa dense (clasificación tabular, regresión, las densas de la red de imágenes): sus neuronas + * y su activación, cada una con su definición (N4LHelpTerm). Las neuronas, entre 1 y 200: lo que no vale se dice junto + * al campo y se sigue usando el último valor bueno + */ +export default function N4LDenseLayerFields({ index, layer, onChange }: N4LDenseLayerFieldsProps) { + const { t } = useTranslation() + const help = 'pages.playground.generator.help.' + return <> + } help={t(help + 'units')} />} + value={layer.units} min={1} max={200} disabled={layer.is_disabled} + onChange={(units) => onChange(index, { units, activation: layer.activation })} /> + + } help={t(help + 'activation')} /> + onChange(index, { units: layer.units, activation: e.target.value })}> + {TYPE_ACTIVATION.map(({ key, label }) => )} + + + + + + +} diff --git a/src/components/neural-network/N4LEditorLayers.tsx b/src/components/neural-network/N4LEditorLayers.tsx index 51baa3d..bf5f327 100644 --- a/src/components/neural-network/N4LEditorLayers.tsx +++ b/src/components/neural-network/N4LEditorLayers.tsx @@ -1,93 +1,241 @@ -import React from 'react' -import { Accordion, Button, Card, Form } from 'react-bootstrap' +import React, { useEffect, useRef, useState } from 'react' +import { Accordion, Alert, Button, Card } from 'react-bootstrap' +import { ArrowDown, ArrowUp, GripVertical } from 'react-bootstrap-icons' import { Trans, useTranslation } from 'react-i18next' -import { TYPE_ACTIVATION } from '@core/nn-utils/ArchitectureTypesHelper' -import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +import { announce } from '@core/a11y/announce' -export type EditableLayer_t = { - units : number - activation : string | null - /** Capa que el usuario no puede cambiar ni borrar (p. ej. la salida de regresión) */ - is_disabled?: boolean -} +import N4LEmptyState from '@components/loading/N4LEmptyState' +import { N4LLayerFlag } from '@components/neural-network/N4LLayerCheck' -type N4LEditorLayersProps = { - layers : EditableLayer_t[] - onAddStart: () => void - onAddEnd : () => void - onRemove : (index: number) => void - onChange : (index: number, layer: { units: number, activation: string | null }) => void +type N4LEditorLayersProps = { + layers : L[] + /** Resumen de una capa en su cabecera, para no tener que abrirla («10 neuronas, ReLU», «Conv 2D, …») */ + summary : (layer: L, index: number) => string + /** Lo que se edita de una capa (N4LDenseLayerFields en las dense; tipo y parámetros en las de imágenes) */ + renderFields: (layer: L, index: number) => React.ReactNode + /** Capa que no se puede borrar (la salida de regresión, la primera convolución) */ + isLocked? : (layer: L, index: number) => boolean + /** Sin él, solo se añaden capas al final */ + onAddStart? : () => void + onAddEnd : () => void + onRemove : (index: number) => void + /** + * Con él, las capas se ordenan: arrastrándolas por su asa (ratón, dedo o lápiz) o, abiertas, con «Subir» y «Bajar» + * (también con el teclado y el lector de pantalla). Las capas fijas (isLocked) no se mueven y las demás no pasan por + * encima de ellas + */ + onMove? : (from: number, to: number) => void + /** Con él, al borrar una capa se puede deshacer: recibe las capas de antes (las mismas que se dan a N4LLayerCheck) */ + onRestore? : (layers: L[]) => void /** Sin dataset procesado todavía: se muestra la espera y no se pueden añadir capas */ - waiting? : boolean - titleAs? : 'h2' | 'h3' - footer? : React.ReactNode + waiting? : boolean + titleAs? : 'h2' | 'h3' + footer? : React.ReactNode + /** Lo que está mal en las capas (N4LLayerCheck), encima de ellas */ + check? : React.ReactNode + /** Capas con un error o un aviso, marcadas en su cabecera */ + flagged? : Partial> } const prefix = 'pages.playground.generator.editor-layers.' /** - * Editor de capas dense: añadir al principio o al final, borrar y cambiar unidades y activación. - * Las reglas de cada tarea (capa de salida, número máximo de capas…) las pone quien lo usa. + * El editor de capas de los entrenadores: añadir capas, desplegar cada una para cambiarla, moverla o borrarla, con su + * resumen y la marca de lo que está mal en su cabecera. Lo que tiene cada capa (y sus reglas: la salida, el número + * máximo de capas…) lo pone quien lo usa. */ -export default function N4LEditorLayers(props: N4LEditorLayersProps) { - const { layers, onAddStart, onAddEnd, onRemove, onChange, waiting = false, titleAs: Title = 'h3', footer } = props +export default function N4LEditorLayers(props: N4LEditorLayersProps) { + const { layers, summary, renderFields, isLocked = () => false, onAddStart, onAddEnd, onRemove, onMove, onRestore, waiting = false, titleAs: Title = 'h3', footer, check, flagged = {} } = props const { t } = useTranslation() + // Al borrar una capa, su botón desaparece con ella: el foco pasa a la cabecera de la capa que queda en su sitio (o a + // la anterior, si era la última), o a «Añadir capa» si no queda ninguna, y no al principio de la página (WCAG 2.4.3) + const card_ref = useRef(null) + const focusAfterRemove = useRef(null) + const layerCount = layers.length + useEffect(() => { + const index = focusAfterRemove.current + if (index === null || card_ref.current === null) return + focusAfterRemove.current = null + const headers = card_ref.current.querySelectorAll('.accordion-button') + const target = headers[Math.min(index, headers.length - 1)] ?? card_ref.current.querySelector('[data-guide="layers-add"] button') + target?.focus() + }, [layerCount]) + // Borrar una capa se puede deshacer (WCAG 3.3.4): se guardan las de antes hasta que las capas cambien otra vez. `after` + // son las capas justo después de borrar: si el editor no la ha borrado (p. ej., era la última que quedaba), no hay + // nada que deshacer + const [removed, setRemoved] = useState<{ before: L[], index: number, after?: L[] } | null>(null) + if (removed !== null && removed.after === undefined && layers !== removed.before) { + setRemoved(layers.length === removed.before.length - 1 ? { ...removed, after: layers } : null) + } + if (removed?.after !== undefined && layers !== removed.after) setRemoved(null) + const canUndo = onRestore !== undefined && removed?.after !== undefined + + // La capa abierta: al moverla sigue abierta en su nuevo puesto (cada panel es el de un puesto, no el de una capa) + const [activeKey, setActiveKey] = useState(null) + // Tras moverla, el foco sigue en el mismo botón de la capa movida (o en el otro, si ya no se puede mover hacia ahí) + const focusAfterMove = useRef<{ index: number, direction: 'up' | 'down' } | null>(null) + // El panel de la capa movida se despliega con una animación: mientras está oculto no se le puede dar el foco, así que + // se vuelve a intentar hasta que se vea (como mucho, lo que dura la animación) + useEffect(() => { + const target = focusAfterMove.current + if (target === null || card_ref.current === null) return + focusAfterMove.current = null + const button = (direction: string) => card_ref.current?.querySelector(`[data-move="${direction}-${target.index}"]:not(:disabled)`) + const focus = () => { + const element = button(target.direction) ?? button(target.direction === 'up' ? 'down' : 'up') + element?.focus() + return element !== null && element !== undefined && document.activeElement === element + } + if (focus()) return + let attempts = 0 + const timer = window.setInterval(() => { + if (focus() || ++attempts >= 12) window.clearInterval(timer) + }, 50) + return () => window.clearInterval(timer) + }, [layers]) + const isFree = (index: number) => !isLocked(layers[index], index) + /** Si la capa `from` puede ir al puesto `to`: ni ella ni las que hay por el camino son fijas */ + const canMove = (from: number, to: number) => { + if (from === to || to < 0 || to >= layers.length) return false + for (let index = Math.min(from, to); index <= Math.max(from, to); index++) if (!isFree(index)) return false + return true + } + /** Mueve la capa; el panel abierto sigue con su capa. `withFocus`: con los botones, el foco sigue en la capa movida */ + const handleMove = (from: number, to: number, withFocus = true) => { + if (onMove === undefined || !canMove(from, to)) return + if (withFocus) focusAfterMove.current = { index: to, direction: to < from ? 'up' : 'down' } + const open = activeKey === null ? null : Number(activeKey) + if (open !== null) { + const shift = open === from ? to : from < open && open <= to ? open - 1 : to <= open && open < from ? open + 1 : open + setActiveKey(String(shift)) + } + onMove(from, to) + announce(t(prefix + 'moved', { index: from + 1, position: to + 1 })) + } + + // Arrastrar por el asa: con eventos de puntero (ratón, dedo y lápiz; el arrastre del navegador no va en los móviles). + // Mientras se arrastra, una raya marca dónde caerá; al soltar, se mueve + const [drag, setDrag] = useState<{ from: number, over: number, pointer: number } | null>(null) + /** El puesto en el que caería la capa `from` con el puntero a la altura `y`, sin pasar por encima de una fija */ + const dropIndex = (from: number, y: number) => { + const middles = [...(card_ref.current?.querySelectorAll('[data-layer-item]') ?? [])] + .map((element) => element.getBoundingClientRect()) + .map(({ top, height }) => top + height / 2) + let target = middles.filter((middle, index) => index !== from && middle < y).length + while (target !== from && !canMove(from, target)) target += target > from ? -1 : 1 + return target + } + const handlePointerDown = (event: React.PointerEvent, index: number) => { + if (onMove === undefined || !isFree(index) || event.button !== 0) return + event.preventDefault() + event.currentTarget.setPointerCapture?.(event.pointerId) + setDrag({ from: index, over: index, pointer: event.pointerId }) + } + const handlePointerMove = (event: React.PointerEvent) => { + if (drag === null || event.pointerId !== drag.pointer) return + // Cerca del borde de la ventana, la página se desplaza para llegar a las capas que no se ven + if (event.clientY < 60) window.scrollBy(0, -12) + else if (event.clientY > window.innerHeight - 60) window.scrollBy(0, 12) + const over = dropIndex(drag.from, event.clientY) + if (over !== drag.over) setDrag({ ...drag, over }) + } + const handlePointerUp = (event: React.PointerEvent) => { + if (drag === null || event.pointerId !== drag.pointer) return + setDrag(null) + if (drag.over !== drag.from) handleMove(drag.from, drag.over, false) + } + + const handleRemove = (index: number) => { + focusAfterRemove.current = index + if (onRestore !== undefined) { + setRemoved({ before: layers, index }) + announce(t(prefix + 'removed', { index: index + 1 })) + } + onRemove(index) + } + const handleUndo = () => { + if (removed === null || onRestore === undefined) return + focusAfterRemove.current = removed.index + onRestore(removed.before) + setRemoved(null) + announce(t(prefix + 'restored', { index: removed.index + 1 })) + } + return <> - - + + <Trans i18nKey={prefix + 'title'} /> -
    - - } +
    - {waiting && } + {waiting && } + {!waiting && canUndo && removed !== null && + + + + } + {!waiting && check} {!waiting && ( - - {layers.map((item, index) => ( - - - - + <> + {onMove !== undefined && layers.length > 1 && +

    } + setActiveKey(typeof key === 'string' ? key : null)}> + {layers.map((layer, index) => ( + drag.from ? 'n4l-layer-drop-after' : 'n4l-layer-drop-before') : undefined}> +
    + {/* El asa: solo para arrastrar con el puntero; con el teclado, «Subir» y «Bajar» dentro de la capa */} + {onMove !== undefined && + handlePointerDown(event, index)} onPointerMove={handlePointerMove} + onPointerUp={handlePointerUp} onPointerCancel={() => setDrag(null)}> + + } + + + ({summary(layer, index)}) + + +
    -
    - + +
    } +
    +
    - - - onChange(index, { units: parseInt(e.target.value), activation: item.activation })} /> - - - - onChange(index, { units: item.units, activation: e.target.value })}> - {TYPE_ACTIVATION.map(({ key, label }) => )} - - - - - + {renderFields(layer, index)}
    ))}
    + )}
    {footer && {footer}} diff --git a/src/components/neural-network/N4LFinalMetrics.tsx b/src/components/neural-network/N4LFinalMetrics.tsx new file mode 100644 index 0000000..a9d0704 --- /dev/null +++ b/src/components/neural-network/N4LFinalMetrics.tsx @@ -0,0 +1,38 @@ +import { Badge } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' + +import { historyCurves, type TrainingLogs_t } from '@core/history/trainingSummary' + +/** + * Celda de la tabla de modelos: valor final de cada métrica con los datos de entrenamiento y, si los hay, con los de + * validación, dicho con palabras (antes iba entre paréntesis sin decir qué era) + */ +export default function N4LFinalMetrics({ logs }: { logs: TrainingLogs_t }) { + const { t, i18n } = useTranslation() + const number = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 3 }) + const format = (values: number[]) => { + const last = values[values.length - 1] + return Number.isFinite(last) ? number.format(last) : '-' + } + const prefix = 'pages.playground.generator.training.' + return <> + {historyCurves(logs).map(({ name, train, validation }) => ( + + + {name}: {format(train)} + {validation !== null && <>, {t(prefix + 'validation').toLowerCase()} {format(validation)}} + + + ))} + +} + +/** Marca del modelo con menor pérdida de validación final */ +export function N4LBestBadge() { + const { t } = useTranslation() + return ( + + + + ) +} diff --git a/src/components/neural-network/N4LHyperparameterFields.tsx b/src/components/neural-network/N4LHyperparameterFields.tsx index 2738a21..fa6f0a6 100644 --- a/src/components/neural-network/N4LHyperparameterFields.tsx +++ b/src/components/neural-network/N4LHyperparameterFields.tsx @@ -1,12 +1,41 @@ -import React from 'react' +import React, { useState } from 'react' import { Accordion, Button, Form } from 'react-bootstrap' import { Trans, useTranslation } from 'react-i18next' -import { TYPE_LOSSES, TYPE_METRICS, TYPE_OPTIMIZER } from '@core/nn-utils/ArchitectureTypesHelper' +import N4LNumberField from '@components/form/N4LNumberField' +import N4LHelpTerm from '@components/helpLink/N4LHelpTerm' + +import { TYPE_LOSSES_CLASSIFICATION, TYPE_LOSSES_REGRESSION, TYPE_METRICS, TYPE_OPTIMIZER } from '@core/nn-utils/ArchitectureTypesHelper' // Campos comunes de los editores de hiperparámetros de las tareas que entrenan modelos const prefix = 'pages.playground.generator.general-parameters.' +// Definición breve de cada campo (pages.playground.generator.help.*), según la clave de su etiqueta +const HELP_KEYS: Record = { + 'learning-rate' : 'learning-rate', + 'number-of-epochs': 'epochs', + 'batch-size' : 'batch-size', + 'train-rate' : 'test-size', + 'test-size' : 'test-size', + 'optimizer-id' : 'optimizer', + 'loss-id' : 'loss', + 'metrics-id' : 'metric', + 'metric-id-select': 'metric', +} + +/** Lo que dice la etiqueta de un campo; si el término tiene definición, se ve al pasar el ratón o al llegar con el teclado */ +function FieldLabelContent({ name }: { name: string }) { + const { t } = useTranslation() + const help = HELP_KEYS[name] + if (help === undefined) return + return } help={t('pages.playground.generator.help.' + help)} /> +} + +/** Etiqueta de un campo */ +function FieldLabel({ name }: { name: string }) { + return +} + type HyperparameterNumberProps = { controlId : string /** Clave de i18n del campo: se usan ``, `-placeholder` y `-info` */ @@ -17,26 +46,43 @@ type HyperparameterNumberProps = { onChange : (value: number) => void } -/** Campo numérico de un hiperparámetro. El valor se ajusta a [min, max] (vacío → min). */ +/** + * Campo numérico de un hiperparámetro, entre min y max. Lo que no vale se dice junto al campo (y se sigue usando el + * último valor bueno) en vez de recortarlo en silencio + */ export function HyperparameterNumber({ controlId, name, min, max, defaultValue, onChange }: HyperparameterNumberProps) { - const { t } = useTranslation() + const [value, setValue] = useState(defaultValue) return ( - - - } + help={} value={value} min={min} max={max} + onChange={(next) => { + setValue(next) + onChange(next) + }} /> + ) +} + +// Valores habituales de la tasa de aprendizaje, en escala logarítmica +const LEARNING_RATES = [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1] + +type HyperparameterLearningRateProps = { + controlId : string + defaultValue: number + onChange : (value: number) => void +} + +/** Selector de la tasa de aprendizaje con su valor real (0.01, no "1 %"). */ +export function HyperparameterLearningRate({ controlId, defaultValue, onChange }: HyperparameterLearningRateProps) { + return ( + + + { - const value = parseInt(e.target.value) - onChange(Number.isNaN(value) ? min : Math.min(max, Math.max(min, value))) - }} /> - + onChange={(e) => onChange(parseFloat(e.target.value))}> + {LEARNING_RATES.map((value) => )} + + ) } @@ -54,19 +100,19 @@ type HyperparameterSelectProps = { } export function HyperparameterSelect({ controlId, label, info, value, defaultValue, disabled, onChange, children }: HyperparameterSelectProps) { - const { t } = useTranslation() + // El nombre es la etiqueta que se ve (WCAG 2.5.3); la ayuda, su descripción return ( - - + + onChange(e.target.value)}> {children} - + ) } @@ -76,15 +122,20 @@ export function OptimizerOptions({ valuePrefix = '' }: { valuePrefix?: string }) return <>{TYPE_OPTIMIZER.map(({ key, label }) => )} } -/** Opciones de función de pérdida; con `withMetrics` también se pueden usar las métricas como pérdida. */ -export function LossOptions({ withMetrics = false }: { withMetrics?: boolean }) { - const losses = TYPE_LOSSES.map(({ key, label }) => ) - if (!withMetrics) return <>{losses} +/** Opciones de función de pérdida, agrupadas por tipo de tarea; primero va el grupo de `task`. */ +export function LossOptions({ task }: { task: 'classification' | 'regression' }) { + const { t } = useTranslation() + const groups = [ + { name: 'classification', losses: TYPE_LOSSES_CLASSIFICATION }, + { name: 'regression', losses: TYPE_LOSSES_REGRESSION }, + ] + if (task === 'regression') groups.reverse() return <> - {losses} - - {TYPE_METRICS.map(({ key, label }) => )} - + {groups.map(({ name, losses }) => ( + + {losses.map(({ key, label }) => )} + + ))} } @@ -102,10 +153,10 @@ type MetricsListProps = { /** Lista editable de métricas de entrenamiento: una por pestaña, cada una con su botón de borrar. */ export function MetricsList({ metrics, onChange, onRemove, valuePrefix = '' }: MetricsListProps) { return ( - + {metrics.map((metric, index) => ( - + diff --git a/src/components/neural-network/N4LLayerCheck.tsx b/src/components/neural-network/N4LLayerCheck.tsx new file mode 100644 index 0000000..04a36af --- /dev/null +++ b/src/components/neural-network/N4LLayerCheck.tsx @@ -0,0 +1,82 @@ +import { useEffect, useEffectEvent, useRef } from 'react' +import { Alert, Button } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import type { LayerIssue_t } from '@core/nn-utils/checkLayers' +import { trackEvent } from '@core/analytics' +import { announce } from '@core/a11y/announce' +import { issueValues, LAYER_CHECK_PREFIX as prefix } from '@components/neural-network/layerCheckText' + +/** La marca de una capa con algo que revisar, en la cabecera de su acordeón */ +export function N4LLayerFlag({ severity }: { severity?: 'error' | 'warning' }) { + const { t } = useTranslation() + if (severity === undefined) return null + return ( + + {t(prefix + severity)} + + ) +} + +type N4LLayerCheckProps = { + issues: LayerIssue_t[] + /** Aplicar el arreglo de un problema: las capas ya corregidas */ + onFix : (layers: L[]) => void +} + +/** + * Lo que está mal en las capas antes de entrenar, cada cosa con un botón para arreglarla: los errores (impiden + * entrenar) y los avisos (se puede, pero aprenderá peor). + */ +export default function N4LLayerCheck({ issues, onFix }: N4LLayerCheckProps) { + const { t } = useTranslation() + + // Al cambiar una capa, el lector de pantalla oye lo que acaba de aparecer y cuándo ya no queda nada (WCAG 4.1.3). El + // aviso aparece a la vez que su texto: como región aria-live no siempre se anunciaría + const texts = issues.map((issue) => ({ key: issue.kind + issue.layer, text: `${t(prefix + issue.severity)}: ${t(prefix + issue.kind + '.text', issueValues(t, issue))}` })) + const announcedKeys = useRef([]) + const announceChanges = useEffectEvent(() => { + const previous = announcedKeys.current + announcedKeys.current = texts.map(({ key }) => key) + const added = texts.filter(({ key }) => !previous.includes(key)) + if (added.length > 0) announce(added.map(({ text }) => text).join('. ')) + else if (texts.length === 0 && previous.length > 0) announce(t(prefix + 'all-fixed')) + }) + // Solo cuando cambian los problemas (no, p. ej., al cambiar de idioma) + const textsKey = texts.map(({ key }) => key).join('|') + useEffect(() => announceChanges(), [textsKey]) + + if (issues.length === 0) return null + const hasErrors = issues.some(({ severity }) => severity === 'error') + + return ( + +

    {t(prefix + (hasErrors ? 'title-error' : 'title-warning'))}

    +
      + {issues.map((issue) => { + const values = issueValues(t, issue) + return ( +
    • + + {t(prefix + issue.severity)}: + {t(prefix + issue.kind + '.text', values)} + + +
    • + ) + })} +
    +
    + ) +} diff --git a/src/components/neural-network/N4LLayerDesign.tsx b/src/components/neural-network/N4LLayerDesign.tsx index e235816..f5adfb6 100644 --- a/src/components/neural-network/N4LLayerDesign.tsx +++ b/src/components/neural-network/N4LLayerDesign.tsx @@ -1,15 +1,17 @@ import React, { useRef, useState } from 'react' -import { Link } from 'react-router' import { Trans, useTranslation } from 'react-i18next' import { Card, Form } from 'react-bootstrap' import * as _Types from '@core/types' -import type { Layer_t as ImageLayer_t } from '@/types/types' +import type { ImageLayer_t as ImageLayer_t } from '@/types/types' import { VERBOSE } from '@/CONSTANTS' import NeuralNetwork from './NeuralNetwork' import type { Network } from 'react-vis-graph-wrapper' -import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +import N4LEmptyState from '@components/loading/N4LEmptyState' import { NEURAL_NETWORK_MODES } from './neural_network' +import N4LHelpLink from '@components/helpLink/N4LHelpLink' +import N4LMaximizeButton from '@components/maximize/N4LMaximizeButton' +import { useMaximize } from '@components/maximize/useMaximize' /** * @typedef N4LLayerDesignProps_t @@ -43,20 +45,22 @@ export default function N4LLayerDesign(props: N4LLayerDesignProps_t) { const prefix = 'pages.playground.generator.' const { t } = useTranslation() - const [mode, setMode] = useState<"EXTEND" | "COMPACT">(NEURAL_NETWORK_MODES.COMPACT) + const [mode, setMode] = useState<'EXTEND' | 'COMPACT'>(NEURAL_NETWORK_MODES.COMPACT) const networkRef = useRef(undefined) + // A pantalla completa se ve mejor una red con muchas capas o en modo extendido + const maximize = useMaximize() const handleChange_mode = async (e: React.ChangeEvent) => { - const selectedMode = e.target.value as "EXTEND" | "COMPACT" + const selectedMode = e.target.value as 'EXTEND' | 'COMPACT' setMode(selectedMode) } if (VERBOSE) console.debug('render N4LLayerDesign') return <> - +

    -
    +
    {t(prefix + 'neural_network_modes.extend')} +
    @@ -77,10 +82,11 @@ export default function N4LLayerDesign(props: N4LLayerDesignProps_t) { layers={layers} mode={mode} networkRef={networkRef} + fill={maximize.maximized} /> } {!show && <> - + } {(actions.length > 0 || glossary_action !== '' || manual_action !== '') && <> @@ -99,14 +105,7 @@ export default function N4LLayerDesign(props: N4LLayerDesignProps_t) { , + link1: , }} />

    } @@ -115,14 +114,7 @@ export default function N4LLayerDesign(props: N4LLayerDesignProps_t) { , + link1: , }} />

    diff --git a/src/components/neural-network/N4LModelAside.tsx b/src/components/neural-network/N4LModelAside.tsx new file mode 100644 index 0000000..dc48f0c --- /dev/null +++ b/src/components/neural-network/N4LModelAside.tsx @@ -0,0 +1,8 @@ +/** + * La columna con la tarjeta del modelo (y la de la explicabilidad, si la hay): en pantallas grandes se queda fija al + * bajar, pero con su propio desplazamiento si no cabe (las descripciones largas no se quedan cortadas por abajo); en las + * pequeñas va en su sitio, encima del resto. + */ +export default function N4LModelAside({ children }: { children: React.ReactNode }) { + return
    {children}
    +} diff --git a/src/components/neural-network/N4LModelCard.tsx b/src/components/neural-network/N4LModelCard.tsx new file mode 100644 index 0000000..41c31f4 --- /dev/null +++ b/src/components/neural-network/N4LModelCard.tsx @@ -0,0 +1,25 @@ +import { Card } from 'react-bootstrap' + +type N4LModelCardProps = { + /** El nombre del modelo */ + title : React.ReactNode + /** Botones (p. ej. el resumen de la red), encima de la descripción */ + actions? : React.ReactNode + children?: React.ReactNode +} + +/** + * La tarjeta del modelo de las páginas para probar modelos ya entrenados: su nombre, sus botones y su descripción. Va + * dentro de N4LModelAside, que la deja fija al bajar en pantallas grandes. + */ +export default function N4LModelCard({ title, actions, children }: N4LModelCardProps) { + return ( + +

    {title}

    + + {actions &&
    {actions}
    } + {children} +
    +
    + ) +} diff --git a/src/components/neural-network/N4LModelCode.tsx b/src/components/neural-network/N4LModelCode.tsx new file mode 100644 index 0000000..33706fd --- /dev/null +++ b/src/components/neural-network/N4LModelCode.tsx @@ -0,0 +1,71 @@ +import { useMemo, useState } from 'react' +import { Button, ButtonGroup, Card } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import { trackEvent } from '@core/analytics' +import { kerasCode, tfjsCode, type ModelCode_t } from '@core/nn-utils/modelCode' + +type Language_t = 'tfjs' | 'keras' + +const LANGUAGES: Array<{ id: Language_t, label: string }> = [ + { id: 'tfjs', label: 'TensorFlow.js (JavaScript)' }, + { id: 'keras', label: 'Keras (Python)' }, +] + +/** + * «Ver el código»: la red que se ha diseñado en el editor, escrita en TensorFlow.js o en Keras (Python), igual que la + * entrena la aplicación. Plegada al principio; se actualiza al cambiar las capas o los hiperparámetros. `spec`: null + * mientras no hay datos (no se sabe cuántas entradas tiene la red) + */ +export default function N4LModelCode({ spec, task }: { spec: ModelCode_t | null, task: string }) { + const { t } = useTranslation() + const prefix = 'model-code.' + const [language, setLanguage] = useState('tfjs') + const [copied, setCopied] = useState(false) + const code = useMemo(() => (spec === null ? '' : language === 'tfjs' ? tfjsCode(spec) : kerasCode(spec)), [spec, language]) + if (spec === null) return null + + const handleClick_Copy = async () => { + try { + await navigator.clipboard.writeText(code) + setCopied(true) + trackEvent('model_code', { action: 'copy', language, task }) + } catch { + setCopied(false) + } + } + + return ( + +
    { if ((event.target as HTMLDetailsElement).open) trackEvent('model_code', { action: 'open', language, task }) }}> + + {t(prefix + 'title')} + {t(prefix + 'summary')} + + +
    + + {LANGUAGES.map(({ id, label }) => ( + + ))} + + +
    + {copied ? t(prefix + 'copied') : ''} +
     id === language)!.label })}
    +            data-testid={'Test-ModelCode-Code'}>{code}
    +

    {t(prefix + 'help-' + language)}

    +
    +
    +
    + ) +} diff --git a/src/components/neural-network/N4LModelComparison.tsx b/src/components/neural-network/N4LModelComparison.tsx new file mode 100644 index 0000000..9f19a6f --- /dev/null +++ b/src/components/neural-network/N4LModelComparison.tsx @@ -0,0 +1,184 @@ +import { useMemo } from 'react' +import { Col, Form, Row, Table } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' +import { Line } from 'react-chartjs-2' + +import { bestModelIndex, changedParameters, historyCurves, type ModelParameters_t, type TrainingLogs_t } from '@core/history/trainingSummary' +import { N4LBestBadge } from '@components/neural-network/N4LFinalMetrics' +import { categoryColor, type ChartColor_t } from '@core/chartColors' +import { useTheme } from '@hooks/useTheme' +import N4LChartData from '@components/chart/N4LChartData' + +/** Como mucho se comparan tantos modelos a la vez (con más, las gráficas no se leen) */ +const MAX_COMPARED = 4 +// Un color por modelo: entrenamiento con línea continua y validación discontinua, como en las curvas de uno +const COLORS: readonly ChartColor_t[] = ['blue', 'orange', 'green', 'pink'] +// Y una forma de punto por modelo: no solo el color los distingue (WCAG 1.4.1) +const POINT_STYLES = ['circle', 'triangle', 'rect', 'rectRot'] as const + +type N4LModelComparisonProps = { + histories : TrainingLogs_t[] + /** Hiperparámetros de cada modelo (mismo orden que `histories`), con las claves de generator.table-models.* */ + parameters: ModelParameters_t[] + /** Los modelos elegidos (índices) */ + compared : number[] + onChange : (compared: number[]) => void +} + +/** + * Varios modelos a la vez: sus curvas superpuestas (un color cada uno) y una tabla con sus hiperparámetros, marcando + * los que cambian, y cómo terminó cada uno. Dice también qué se puede concluir: si solo cambia una cosa, la diferencia + * se debe a eso; si cambian varias, no se sabe cuál ha influido. + */ +export default function N4LModelComparison({ histories, parameters, compared, onChange }: N4LModelComparisonProps) { + const { t, i18n } = useTranslation() + const prefix = 'pages.playground.generator.training.' + const theme = useTheme() + const number = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumSignificantDigits: 3 }), [i18n.language]) + + const models = compared.filter((index) => index < histories.length).sort((a, b) => a - b) + const curves = models.map((index) => historyCurves(histories[index])) + const best = models.length > 1 ? models[bestModelIndex(models.map((index) => histories[index]))] : -1 + const names = Object.keys(parameters[models[0]] ?? {}) + const changed = changedParameters(models.map((index) => parameters[index])) + const label = (name: string) => t('generator.table-models.' + name) + const quoted = (name: string) => t(prefix + 'compare-quote', { name: label(name) }) + const list = new Intl.ListFormat(i18n.language, { type: 'conjunction' }) + + const toggle = (index: number) => { + onChange(compared.includes(index) ? compared.filter((i) => i !== index) : [...compared, index]) + } + const finalValue = (values: number[] | null) => { + const last = values?.at(-1) + return last === undefined ? '' : Number.isFinite(last) ? number.format(last) : '-' + } + + return ( +
    +
    + {t(prefix + 'compare-pick', { max: MAX_COMPARED })} + {histories.map((_logs, index) => ( + = MAX_COMPARED} + onChange={() => toggle(index)} /> + ))} +
    + + {models.length < 2 &&

    {t(prefix + 'compare-pick-more')}

    } + {models.length >= 2 && <> +

    + {changed.length === 0 && t(prefix + 'compare-same')} + {changed.length === 1 && t(prefix + 'compare-one', { name: quoted(changed[0]) })} + {changed.length > 1 && t(prefix + 'compare-some', { names: list.format(changed.map(quoted)) })} +

    + + {curves[0].map(({ name }) => { + const epochs = Math.max(...curves.map((model) => model.find((curve) => curve.name === name)?.train.length ?? 0)) + return ( + +
    +

    {name}

    + { + // Para quien no ve la gráfica: cómo empieza y acaba la curva de cada modelo + const curve = curves[position].find((item) => item.name === name) + if (curve === undefined || curve.train.length === 0) return '' + const range = (values: number[]) => ({ first: number.format(values[0]), last: number.format(values[values.length - 1]) }) + return [ + t('model.__index__', { index: index + 1 }) + ':', + t(prefix + 'curve-description', { name, epochs: curve.train.length, ...range(curve.train) }), + ...(curve.validation === null || curve.validation.length === 0 ? [] : [t(prefix + 'curve-description-validation', range(curve.validation))]), + ].join(' ') + }).join(' ')} + options={{ + responsive : true, + animation : false, + interaction: { mode: 'index', intersect: false }, + scales : { x: { title: { display: true, text: t(prefix + 'epoch-axis') } } }, + }} + data={{ + labels : Array.from({ length: epochs }, (_value, epoch) => epoch + 1), + datasets: models.flatMap((index, position) => { + const curve = curves[position].find((item) => item.name === name) + if (curve === undefined) return [] + const color = categoryColor(COLORS, position, theme) + const model = t('model.__index__', { index: index + 1 }) + return [ + { label: model + ', ' + t(prefix + 'train'), data: curve.train, borderColor: color, backgroundColor: color, pointRadius: 3, pointStyle: POINT_STYLES[position % POINT_STYLES.length] }, + ...(curve.validation === null ? [] : [{ + label : model + ', ' + t(prefix + 'validation'), + data : curve.validation, + borderColor : color, + backgroundColor: color, + borderDash : [6, 4], + pointRadius : 3, + pointStyle : POINT_STYLES[position % POINT_STYLES.length], + }]), + ] + }), + }} + /> + { + const model = t('model.__index__', { index: index + 1 }) + return [model + ', ' + t(prefix + 'train'), ...(curves[position].find((item) => item.name === name)?.validation ? [model + ', ' + t(prefix + 'validation')] : [])] + })]} + rows={Array.from({ length: epochs }, (_value, epoch) => [epoch + 1, ...models.flatMap((_index, position) => { + const curve = curves[position].find((item) => item.name === name) + return [curve?.train[epoch], ...(curve?.validation ? [curve.validation[epoch]] : [])] + })])} /> +
    + + ) + })} +
    + + + + + + + {models.map((index, position) => ( + + ))} + + + + {names.map((name) => { + const isChanged = changed.includes(name) + return ( + + + {models.map((index) => )} + + ) + })} + {curves[0].map(({ name }) => ( + + + {models.map((index, position) => { + const curve = curves[position].find((item) => item.name === name) + return ( + + ) + })} + + ))} + +
    {t(prefix + 'compare-caption')}
    {t(prefix + 'compare-parameter')} + + {t('model.__index__', { index: index + 1 })} + {index === best && } +
    + {label(name)} + {isChanged && {t(prefix + 'compare-changed')}} + {parameters[index][name]}
    {t(prefix + 'compare-final', { name })} + {finalValue(curve?.train ?? null)}{curve?.validation && ` (${finalValue(curve.validation)})`} +
    + } +
    + ) +} diff --git a/src/components/neural-network/N4LModelSummaryButton.tsx b/src/components/neural-network/N4LModelSummaryButton.tsx new file mode 100644 index 0000000..c3177c3 --- /dev/null +++ b/src/components/neural-network/N4LModelSummaryButton.tsx @@ -0,0 +1,86 @@ +import { useId, useState } from 'react' +import { Button, Table } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' +import * as tfjs from '@tensorflow/tfjs' + +type N4LModelSummaryButtonProps = { + model: unknown + /** Nombre del modelo: va en el título del resumen */ + title: string +} + +/** Una forma de TF.js, como en Keras: «(—, 10)»; la primera dimensión, sin número, es el lote */ +const formatShape = (shape: tfjs.Shape | tfjs.Shape[]) => { + const shapes = Array.isArray(shape[0]) || shape.length === 0 ? (shape as tfjs.Shape[]) : [shape as tfjs.Shape] + return shapes.map((item) => `(${item.map((dim) => dim ?? '—').join(', ')})`).join(' ') +} + +const countWeights = (weights: tfjs.LayerVariable[]) => + weights.reduce((sum, weight) => sum + (weight.shape ?? []).reduce((size, dim) => size * (dim ?? 1), 1), 0) + +/** + * Botón que despliega el resumen de las capas de un modelo preentrenado: una tabla con cada capa, su forma de salida y + * sus parámetros, y el total. Es una tabla de la página (se lee con el lector de pantalla y se recorre con el teclado), + * no el visor de tfjs-vis. Solo aparece con un LayersModel: el GraphModel de MobileNet y los detectores de + * @tensorflow-models, MediaPipe o face-api no dicen sus capas. + */ +export default function N4LModelSummaryButton({ model, title }: N4LModelSummaryButtonProps) { + const { t, i18n } = useTranslation() + const prefix = 'model-summary-table.' + const [isOpen, setIsOpen] = useState(false) + const panelId = useId() + if (!(model instanceof tfjs.LayersModel)) return null + + const number = new Intl.NumberFormat(i18n.language) + const caption = `${t('model-summary')}: ${title}` + const total = model.countParams() + const trainable = countWeights(model.trainableWeights) + + return ( +
    +
    + +
    + {isOpen && +
    + + + + + + + + + + + {model.layers.map((layer) => ( + + + + + + ))} + + + + + + + {trainable !== total && + + + + } + +
    {caption}
    {t(prefix + 'layer')}{t(prefix + 'output-shape')}{t(prefix + 'params')}
    + {layer.name} + ({layer.getClassName()}) + {formatShape(layer.outputShape)}{number.format(layer.countParams())}
    {t(prefix + 'total')}{number.format(total)}
    {t(prefix + 'trainable')}{number.format(trainable)}
    +

    {t(prefix + 'batch-note')}

    +
    } +
    + ) +} diff --git a/src/components/neural-network/N4LPageHeader.tsx b/src/components/neural-network/N4LPageHeader.tsx new file mode 100644 index 0000000..f0e9a84 --- /dev/null +++ b/src/components/neural-network/N4LPageHeader.tsx @@ -0,0 +1,49 @@ +import { Col, Row } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import N4LGuide, { type GuideStep_t } from '@components/guide/N4LGuide' +import N4LSessionButtons from '@components/session/N4LSessionButtons' +import type { TrainingSession_t } from '@core/session/trainingSession' + +type N4LPageHeaderProps = { + title : React.ReactNode + /** Nombre con el que la guía guarda por qué paso va */ + guideId : string + /** Sin pasos todavía (el modelo se está cargando), no hay botón de guía */ + guideSteps : GuideStep_t[] | null + /** Entrenadores: exportar, importar y compartir la configuración */ + getSession?: () => TrainingSession_t + onImport? : (text: string) => void + /** Qué se hace en la página, en una frase y sus pasos: entrenar una red, probar un modelo ya entrenado o detectar */ + intro? : 'train' | 'review' | 'detect' + className? : string +} + +/** La cabecera de las páginas del playground (entrenar y probar modelos): el título, la guía y, al entrenar, la configuración */ +export default function N4LPageHeader({ title, guideId, guideSteps, getSession, onImport, intro, className = 'mt-3 mb-3' }: N4LPageHeaderProps) { + const { t } = useTranslation() + // Varios pasos por clave; sin traducciones (cargando, en las pruebas) i18next devuelve la clave: nada que listar + const steps: unknown = intro === undefined ? [] : t('page-intro.' + intro + '.steps', { returnObjects: true }) + return ( + + +
    +

    {title}

    +
    + {guideSteps !== null && } + {getSession !== undefined && onImport !== undefined && +
    + +
    } +
    +
    + {/* Lo primero que se lee: qué se hace aquí y en qué orden (sin tener que abrir la guía) */} + {intro !== undefined &&
    +

    {t('page-intro.' + intro + '.text')}

    + {Array.isArray(steps) && steps.length > 0 && +
      {steps.map((step) =>
    1. {String(step)}
    2. )}
    } +
    } + +
    + ) +} diff --git a/src/components/neural-network/N4LStoredModelsNotice.tsx b/src/components/neural-network/N4LStoredModelsNotice.tsx new file mode 100644 index 0000000..0ee4dc8 --- /dev/null +++ b/src/components/neural-network/N4LStoredModelsNotice.tsx @@ -0,0 +1,42 @@ +import { useState } from 'react' +import { Alert, Button } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +type N4LStoredModelsNoticeProps = { + /** Cuántos modelos se han recuperado al entrar (0: no se enseña nada) */ + count : number + /** Borra los modelos guardados de este conjunto y los quita de la tabla */ + onClear: () => void | Promise +} + +/** + * Aviso de que los modelos de la tabla vienen de antes (guardados en el navegador para no perderlos al recargar), con + * la opción de borrarlos. Borrar pide confirmación: también se quitan de la tabla. + */ +export default function N4LStoredModelsNotice({ count, onClear }: N4LStoredModelsNoticeProps) { + const { t } = useTranslation() + const prefix = 'stored-models.' + const [confirming, setConfirming] = useState(false) + const [dismissed, setDismissed] = useState(false) + if (count === 0 || dismissed) return null + + return ( + setDismissed(true)} data-testid={'Test-StoredModels'}> + {t(prefix + (confirming ? 'confirm' : 'restored'), { count })} + {confirming + ? <> + + + + : } + + ) +} diff --git a/src/components/neural-network/N4LTrainButton.tsx b/src/components/neural-network/N4LTrainButton.tsx new file mode 100644 index 0000000..ffe11f0 --- /dev/null +++ b/src/components/neural-network/N4LTrainButton.tsx @@ -0,0 +1,104 @@ +import React, { useCallback, useRef, useState } from 'react' +import { Button } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' + +import type { LastTraining_t, TrainingProgress_t } from '@hooks/useTrainingProgress' +import { formatDuration } from '@core/format/duration' +import N4LProgressBar from '@components/loading/N4LProgressBar' +import { goToSection } from '@components/divider/useActiveSection' +import { sectionId } from '@components/divider/sectionId' + +type N4LTrainButtonProps = { + isTraining : boolean + progress : TrainingProgress_t | null + isStopping : boolean + onStop : () => void + disabled? : boolean + /** + * La sección con el resultado (su i18nKey), si queda lejos del botón: al terminar de entrenar, un enlace lleva a ella + * (WCAG 2.4.3), sin recorrer con el tabulador lo que hay en medio + */ + resultSection?: string + /** Lo que tardó el último entrenamiento (useTrainingProgress): se dice para saber qué esperar del siguiente */ + lastRun? : LastTraining_t | null + children : React.ReactNode +} + +/** + * Botón de entrenar del formulario (type="submit"). Mientras se entrena, en su lugar se ve el progreso por épocas + * y un botón para detener el entrenamiento (el modelo se guarda con las épocas que haya completado). + * + * El foco no se pierde al cambiar uno por otro (WCAG 2.4.3): si estaba en «Entrenar», pasa a «Detener», y al terminar + * vuelve a «Entrenar». Por eso «Deteniendo…» no se desactiva con disabled (que quita el foco), sino con aria-disabled. + */ +export default function N4LTrainButton({ isTraining, progress, isStopping, onStop, disabled = false, resultSection, lastRun = null, children }: N4LTrainButtonProps) { + const { t, i18n } = useTranslation() + const prefix = 'pages.playground.generator.training.' + + // Al quitarse un botón (antes de salir de la página) se apunta si tenía el foco; el que lo sustituye lo recoge + const keepFocus = useRef(false) + const passFocus = useCallback((element: HTMLButtonElement | null) => { + if (element === null) return + if (keepFocus.current) element.focus({ preventScroll: true }) + keepFocus.current = false + return () => { + keepFocus.current = document.activeElement === element + } + }, []) + + // Se ha entrenado al menos una vez en esta visita: ya hay un resultado al que ir + const [wasTraining, setWasTraining] = useState(isTraining) + const [hasTrained, setHasTrained] = useState(false) + if (wasTraining !== isTraining) { + setWasTraining(isTraining) + if (!isTraining) setHasTrained(true) + } + + if (!isTraining) { + const resultId = resultSection === undefined ? null : sectionId(resultSection) + return ( +
    + + {/* Cuánto tardó el anterior: con más épocas, el siguiente tardará más (y se puede parar cuando se quiera) */} + {lastRun !== null && +

    + {t(prefix + 'last-run', { + time : formatDuration(lastRun.ms, i18n.language), + perEpoch: formatDuration(lastRun.ms / lastRun.epochs, i18n.language), + count : lastRun.epochs, + })} +

    } + {hasTrained && resultId !== null && + goToSection(event, resultId)} data-testid={'Test-GoToResult'}> + + } +
    + ) + } + + // Antes de la primera época se preparan los datos y se compila el modelo + const percent = progress ? Math.round((progress.epoch / progress.totalEpochs) * 100) : 0 + // Desde la primera época, también lo que queda (a la velocidad de las épocas hechas) + const remaining = progress?.remainingMs !== undefined && progress.epoch < progress.totalEpochs + ? ', ' + t(prefix + 'remaining', { time: formatDuration(progress.remainingMs, i18n.language) }) + : '' + const label = progress + ? t(prefix + 'epoch', { epoch: progress.epoch, total: progress.totalEpochs }) + remaining + : t(prefix + 'preparing') + + return ( + // Sin aria-live: cambia en cada época; el lector oye cómo va cada pocos segundos (useTrainingProgress) +
    +
    +
    {label}
    + +
    + +
    + ) +} diff --git a/src/components/neural-network/N4LTrainingCurves.tsx b/src/components/neural-network/N4LTrainingCurves.tsx new file mode 100644 index 0000000..63c82c8 --- /dev/null +++ b/src/components/neural-network/N4LTrainingCurves.tsx @@ -0,0 +1,120 @@ +import React, { useState } from 'react' +import { Col, Form, Row } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' +import { Line } from 'react-chartjs-2' + +import { historyCurves, type ModelParameters_t, type TrainingLogs_t } from '@core/history/trainingSummary' +import N4LModelComparison from '@components/neural-network/N4LModelComparison' +import N4LChartData from '@components/chart/N4LChartData' +import { trackEvent } from '@core/analytics' +import { chartColor } from '@core/chartColors' +import { useTheme } from '@hooks/useTheme' + +type N4LTrainingCurvesProps = { + /** Historial de cada modelo generado, en el orden de la tabla (el modelo 1 es el primero) */ + histories : TrainingLogs_t[] + /** Más información del modelo elegido debajo de las curvas (p. ej. su matriz de confusión) */ + renderDetails?: (index: number) => React.ReactNode + /** Hiperparámetros de cada modelo (mismo orden): con ellos y dos modelos o más, se pueden comparar */ + parameters? : ModelParameters_t[] +} + +/** Curvas de pérdida y métricas por época del modelo elegido (por defecto, el último entrenado) */ +export default function N4LTrainingCurves({ histories, renderDetails, parameters }: N4LTrainingCurvesProps) { + const { t, i18n } = useTranslation() + const prefix = 'pages.playground.generator.training.' + // Mismos colores en todas las curvas: entrenamiento (línea continua) y validación (discontinua) + const theme = useTheme() + const trainColor = chartColor('blue', theme) + const validationColor = chartColor('orange', theme) + // null: seguir siempre al último modelo entrenado + const [selected, setSelected] = useState(null) + // Los modelos que se comparan; null, uno solo + const [compared, setCompared] = useState(null) + + if (histories.length === 0) return null + const number = new Intl.NumberFormat(i18n.language, { maximumSignificantDigits: 3 }) + const curveDescription = (name: string, train: number[], validation: number[] | null) => { + const range = (values: number[]) => ({ first: number.format(values[0]), last: number.format(values[values.length - 1]) }) + return [ + t(prefix + 'curve-description', { name, epochs: train.length, ...range(train) }), + ...(validation === null || validation.length === 0 ? [] : [t(prefix + 'curve-description-validation', range(validation))]), + ].join(' ') + } + const index = selected !== null && selected < histories.length ? selected : histories.length - 1 + const curves = historyCurves(histories[index]) + const canCompare = parameters !== undefined && parameters.length === histories.length && histories.length > 1 + const isComparing = canCompare && compared !== null + + return ( +
    +
    +

    +
    + {canCompare && ( + { + if (!isComparing) trackEvent('models_compare', { models: histories.length }) + setCompared(isComparing ? null : [histories.length - 2, histories.length - 1]) + }} /> + )} + {/* Con un solo modelo (el informe) no hay nada que elegir */} + {!isComparing && histories.length > 1 && ( + setSelected(Number(e.target.value))}> + {histories.map((_logs, i) => )} + + )} +
    +
    + {isComparing && parameters !== undefined && compared !== null && ( + + )} + {!isComparing && <> + + {curves.map(({ name, train, validation }) => ( + +
    +

    {name}

    + {/* Lo que enseña la gráfica está en el texto de debajo (la tendencia) y en «Ver los datos» (todo) */} + epoch + 1), + datasets: [ + { label: t(prefix + 'train'), data: train, borderColor: trainColor, backgroundColor: trainColor, pointRadius: 2 }, + ...(validation === null ? [] : [{ + label : t(prefix + 'validation'), + data : validation, + borderColor : validationColor, + backgroundColor: validationColor, + borderDash : [6, 4], + pointRadius : 2, + }]), + ], + }} + /> +

    {curveDescription(name, train, validation)}

    + [epoch + 1, value, ...(validation === null ? [] : [validation[epoch]])])} /> +
    + + ))} +
    + {renderDetails?.(index)} + } +
    + ) +} diff --git a/src/components/neural-network/N4LTrainingDiagnosis.tsx b/src/components/neural-network/N4LTrainingDiagnosis.tsx new file mode 100644 index 0000000..9418edf --- /dev/null +++ b/src/components/neural-network/N4LTrainingDiagnosis.tsx @@ -0,0 +1,63 @@ +import { useEffect, useMemo } from 'react' +import { Alert } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' +import { useLocation } from 'react-router' + +import { trackEvent } from '@core/analytics' +import { diagnoseTraining } from '@core/training/diagnoseTraining' +import { firstComparison, isRightPrediction, usePrediction } from '@core/training/trainingPrediction' + +type N4LTrainingDiagnosisProps = { + /** + * El historial del modelo (pérdida de cada época y, si la hay, la de prueba); sin él no se enseña nada. El de TF.js + * tipa sus valores como número o tensor: tras entrenar son números + */ + history?: Record> + /** Su número en la tabla de modelos (desde 1) */ + model : number +} + +/** + * Cómo ha ido el último entrenamiento, en palabras: si la pérdida se disparó, si apenas aprendió, si se aprendió los + * datos de memoria (sobreajuste), si seguía mejorando o si aprendió bien, con qué probar a continuación. Si antes de + * entrenar se predijo qué pasaría (N4LTrainingPrediction), primero si se acertó. + */ +export default function N4LTrainingDiagnosis({ history, model }: N4LTrainingDiagnosisProps) { + const { t, i18n } = useTranslation() + const prefix = 'training-diagnosis.' + const findings = useMemo(() => (history === undefined + ? [] + : diagnoseTraining(Object.fromEntries(Object.entries(history).map(([name, values]) => [name, values.map(Number)])))), [history]) + const number = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumSignificantDigits: 3 }), [i18n.language]) + const { pathname } = useLocation() + const prediction = usePrediction(pathname, model) + const isRight = prediction !== null && isRightPrediction(prediction, findings.map(({ kind }) => kind)) + useEffect(() => { + if (prediction !== null && findings.length > 0 && firstComparison(pathname, model)) { + trackEvent('training_prediction', { prediction, outcome: isRight ? 'right' : 'wrong' }) + } + }, [prediction, findings, pathname, model, isRight]) + if (findings.length === 0) return null + + return ( +
    +

    {t(prefix + 'title', { model })}

    + {prediction !== null && + +

    + {t('training-prediction.' + (isRight ? 'right' : 'wrong'), { prediction: t('training-prediction.options.' + prediction) })} +

    +
    } + {findings.map(({ kind, severity, values }) => { + const formatted = Object.fromEntries(Object.entries(values).map(([key, value]) => [key, key === 'epoch' || key === 'epochs' ? value : number.format(value)])) + return ( + +

    {t(prefix + kind + '.title')}

    +

    {t(prefix + kind + '.text', formatted)}

    +

    {t(prefix + kind + '.tip', formatted)}

    +
    + ) + })} +
    + ) +} diff --git a/src/components/neural-network/N4LTrainingPrediction.tsx b/src/components/neural-network/N4LTrainingPrediction.tsx new file mode 100644 index 0000000..31481b8 --- /dev/null +++ b/src/components/neural-network/N4LTrainingPrediction.tsx @@ -0,0 +1,42 @@ +import { Form } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' +import { useLocation } from 'react-router' + +import { PREDICTIONS, setPrediction, usePrediction, type Prediction_t } from '@core/training/trainingPrediction' + +/** + * «Antes de entrenar, ¿qué crees que pasará?»: opcional y plegado, junto al botón Entrenar. Lo elegido se compara al + * terminar con el diagnóstico del entrenamiento (N4LTrainingDiagnosis). `nextModel`: el número que tendrá en la tabla + * de modelos el que se va a entrenar; `disabled`: mientras se entrena no se cambia + */ +export default function N4LTrainingPrediction({ nextModel, disabled = false }: { nextModel: number, disabled?: boolean }) { + const { t } = useTranslation() + const { pathname } = useLocation() + const prefix = 'training-prediction.' + const prediction = usePrediction(pathname, nextModel) + const name = `training-prediction-${nextModel}` + + return ( +
    + + {t(prefix + 'title')}{' '} + + {prediction === null ? t(prefix + 'optional') : t(prefix + 'chosen', { prediction: t(prefix + 'options.' + prediction) })} + + +
    + {t(prefix + 'help')} + {PREDICTIONS.map((option) => ( + setPrediction(pathname, nextModel, option as Prediction_t)} /> + ))} + setPrediction(pathname, nextModel, null)} /> +
    +
    + ) +} diff --git a/src/components/neural-network/NeuralNetwork.css b/src/components/neural-network/NeuralNetwork.css new file mode 100644 index 0000000..050f271 --- /dev/null +++ b/src/components/neural-network/NeuralNetwork.css @@ -0,0 +1,35 @@ +/* Columnas de "Entrada" y "Salida" a los lados del diagrama */ +.n4l-nn-side { + display: flex; + align-items: center; + justify-content: center; + gap: 0.25rem; + margin-bottom: 2rem; + padding: 0; +} + +.n4l-nn-side-label { + writing-mode: vertical-rl; +} + +.n4l-nn-side-label-output { + writing-mode: vertical-lr; +} + +.n4l-nn-arrow { + flex-shrink: 0; + font-size: 3rem; +} + +/* El grafo en la tarjeta maximizada: todo el hueco de la columna, menos su margen interior */ +.n4l-nn-fill { + position: absolute; + inset: 0 calc(var(--bs-gutter-x) * .5); +} + +/* En móvil la columna lateral es estrecha: flecha más pequeña para que quepa el texto */ +@media (max-width: 575.98px) { + .n4l-nn-arrow { + font-size: 1.5rem; + } +} diff --git a/src/components/neural-network/NeuralNetwork.tsx b/src/components/neural-network/NeuralNetwork.tsx index 527fa86..74e6183 100644 --- a/src/components/neural-network/NeuralNetwork.tsx +++ b/src/components/neural-network/NeuralNetwork.tsx @@ -1,36 +1,37 @@ -import { useCallback, useEffect, useMemo, useState } from 'react' +import './NeuralNetwork.css' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { Col, Row } from 'react-bootstrap' -import { Trans } from 'react-i18next' +import { Trans, useTranslation } from 'react-i18next' import { ArrowRight } from 'react-bootstrap-icons' import VisGraph, { type GraphData, type Network } from 'react-vis-graph-wrapper' import { VERBOSE } from '@/CONSTANTS' import { NEURAL_NETWORK_MODES, type NEURAL_NETWORK_MODES_t } from './neural_network' +import { layerSummaryParts, type DrawableLayer_t } from './layerSummary' +import { useTheme } from '@hooks/useTheme' -/** Lo que se dibuja de una capa; vale para las dense (tabular, regresión) y las de imágenes */ -type DrawableLayer_t = { - _class? : string - units? : number - activation?: string | null - kernelSize?: number - filters? : number - poolSize? : number - strides? : number -} - type NeuralNetworkProps = { layers : DrawableLayer_t[] /** Id del contenedor cuyo tamaño ocupa el grafo */ id_parent : string networkRef?: React.Ref mode? : NEURAL_NETWORK_MODES_t + /** Ocupa todo el alto que le dé su contenedor (la tarjeta maximizada), no los 250 px de siempre */ + fill? : boolean } +const HEIGHT = 250 + export default function NeuralNetwork(props: NeuralNetworkProps) { - const { layers, id_parent, networkRef, mode = NEURAL_NETWORK_MODES.COMPACT } = props + const { layers, id_parent, networkRef, mode = NEURAL_NETWORK_MODES.COMPACT, fill = false } = props + const { t } = useTranslation() + // vis-network pinta en un canvas: el color de las aristas no sale del CSS + const theme = useTheme() - const [options, setOptions] = useState({ height: 250, width: 300 }) + const [fillHeight, setFillHeight] = useState(HEIGHT) + const height = fill ? fillHeight : HEIGHT + const network = useRef(null) const events = { afterDrawing: (_e: unknown) => { @@ -46,67 +47,40 @@ export default function NeuralNetwork(props: NeuralNetworkProps) { if (VERBOSE) console.debug('resize', { _e }) }, zoom: (_e: unknown) => { - // e.preventDefault() - // e.stopPropagation() - // e.stopImmediatePropagation() } } - const getElementText = (index: number, element: DrawableLayer_t) => { - let label = '' - let title = '' - if (element?._class && element?._class === 'flatten') { - label = `Layer: ${index}\n\nFlatten` - title = `Layer: ${index} {flatten}` - } else if (element?._class && element?._class === 'dense') { - label = `Layer: ${index}\n\nDense\nU: ${element.units} F.A: ${element.activation}` - title = `Layer: ${index} {dense}\nUnits: ${element.units} F.Activation: ${element.activation}` - } else if (element?._class && element?._class === 'conv2d') { - label = `Layer: ${index}\n\nConv 2D\nK: ${element.kernelSize}\nF: ${element.filters}\nF.A: ${element.activation}` - title = `Layer: ${index} {conv2d}\nKernelSize: ${element.kernelSize}\nFilters: ${element.filters}\nF. Activation: ${element.activation}` - } else if (element?._class && element?._class === 'maxPooling2d') { - label = `Layer: ${index}\n\nMax Pooling 2D\nP.S: ${element.poolSize}\nS: ${element.strides}` - title = `Layer: ${index} {maxPooling2d}\nPool Size: ${element.poolSize}\nStrides: ${element.strides}` - } else { - label = `Layer: ${index}\nU: ${element.units}\nF.A: ${element.activation}` - title = `Layer: ${index} {dense}\nUnits: ${element.units}\nF.Activation: ${element.activation}` - } - return { label, title } - } + // Texto de cada nodo (y de su tooltip). Las capas se numeran desde 1, como en los editores de capas + const getElementText = useCallback((index: number, element: DrawableLayer_t) => { + const layer = t('neural-network.layer', { index: index + 1 }) + const parts = layerSummaryParts(t, element) + const lines = element?._class ? [layer, '', ...parts] : [layer, ...parts] + return { label: lines.join('\n'), title: [layer, ...parts].join('\n') } + }, [t]) - // Ajusta el grafo al tamaño del contenedor, también cuando este cambia (p. ej. al redimensionar la ventana) + // Con fill, el alto del contenedor, también cuando cambia (p. ej. al girar el móvil). El grafo va encima (absolute): + // así el contenedor no crece con él y el alto que se mide es el que le da la tarjeta useEffect(() => { + if (!fill) return const element = document.getElementById(id_parent) if (element === null) return const observer = new ResizeObserver(() => { const cs = getComputedStyle(element) - const paddingX = parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight) const paddingY = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom) - const borderX = parseFloat(cs.borderLeftWidth) + parseFloat(cs.borderRightWidth) const borderY = parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth) - const height = Math.max(250, element.offsetHeight - paddingY - borderY) - const width = Math.max(350, element.offsetWidth - paddingX - borderX) - // Mismo tamaño → mismo objeto, para no volver a renderizar - setOptions((prevState) => (prevState.height === height && prevState.width === width ? prevState : { height, width })) + setFillHeight(Math.max(HEIGHT, element.offsetHeight - paddingY - borderY)) }) observer.observe(element) - - - // Quita el evento de zoom para que no moleste al usar el scroll - // Deprecated by zoomView - // const dom = document.querySelectorAll('#vis-network canvas')[0] - // if (dom) { - // const wheel = dom.getEventListeners('wheel') - // if (wheel) { - // const listener = wheel[0].listener - // dom.removeEventListener('wheel', listener) - // } - // } - return () => { observer.disconnect() } - }, [id_parent]) + }, [fill, id_parent]) + + // Con otro alto, el grafo se vuelve a encuadrar (vis-network solo cambia el tamaño del canvas). El efecto de VisGraph, + // que le pasa el alto nuevo, ya ha corrido: los de los hijos van antes + useEffect(() => { + network.current?.fit() + }, [height]) const modeCompact = useCallback(() => { const nodes = [], edges = [] @@ -123,13 +97,16 @@ export default function NeuralNetwork(props: NeuralNetworkProps) { edges.push({ from: index - 1, to: index }) } return { edges, nodes } - }, [layers]) + }, [layers, getElementText]) const modeExtend = useCallback(() => { const nodes = [], edges = [] for (let index = 0; index < layers.length; index++) { const element = layers[index] - const { label, title } = getElementText(index, element) + // Cada neurona es un nodo: solo lleva el nombre de su capa (con todo el texto los nodos se pisan); el + // detalle de la capa sale al pasar el ratón + const { title } = getElementText(index, element) + const label = t('neural-network.layer', { index: index + 1 }) for (let unit = 0; unit < (layers[index].units ?? 0); unit++) { const key_id = index + ' - ' + unit nodes.push({ @@ -146,7 +123,7 @@ export default function NeuralNetwork(props: NeuralNetworkProps) { } } return { nodes, edges } - }, [layers]) + }, [layers, getElementText, t]) const graphState = useMemo(() => { switch (mode) { @@ -161,24 +138,17 @@ export default function NeuralNetwork(props: NeuralNetworkProps) { }, [mode, modeCompact, modeExtend]) return <> - - -
    - -
    -
    - -
    + {/* El grafo es un canvas sin texto: para el lector de pantalla, las capas en una lista, de la entrada a la salida */} +
      + {layers.map((layer, index) =>
    1. {[t('neural-network.layer', { index: index + 1 }), ...layerSummaryParts(t, layer)].join(', ')}
    2. )} +
    + + + + - -
    + +
    { + network.current = instance + // vis-network hace enfocable su lienzo (para sus atajos de teclado, que no se usan): fuera del orden del + // tabulador, porque al lector se le dan las capas en la lista de arriba + document.getElementById(id_parent)?.querySelectorAll('.vis-network').forEach((frame) => { frame.tabIndex = -1 }) + }} ref={networkRef} />
    - -
    - -
    -
    - -
    + + + diff --git a/src/components/neural-network/alertLayerError.tsx b/src/components/neural-network/alertLayerError.tsx new file mode 100644 index 0000000..0172373 --- /dev/null +++ b/src/components/neural-network/alertLayerError.tsx @@ -0,0 +1,16 @@ +import type { TFunction } from 'i18next' + +import alertHelper from '@utils/alertHelper' +import type { LayerIssue_t } from '@core/nn-utils/checkLayers' +import { layerIssueText } from '@components/neural-network/layerCheckText' + +/** + * Antes de entrenar: si las capas tienen algún error (checkDenseLayers, checkImageLayers), lo dice y devuelve false; + * si no, true. Los avisos no impiden entrenar. + */ +export async function layersAreValid(t: TFunction, issues: LayerIssue_t[]): Promise { + const error = issues.find(({ severity }) => severity === 'error') + if (error === undefined) return true + await alertHelper.alertWarning(t('layer-check.title-error'), { footer: '', text: '', html: <>{layerIssueText(t, error)} }) + return false +} diff --git a/src/components/neural-network/layerCheckText.ts b/src/components/neural-network/layerCheckText.ts new file mode 100644 index 0000000..045bd1d --- /dev/null +++ b/src/components/neural-network/layerCheckText.ts @@ -0,0 +1,33 @@ +import type { TFunction } from 'i18next' + +import type { LayerIssue_t } from '@core/nn-utils/checkLayers' +import { TYPE_ACTIVATION } from '@core/nn-utils/ArchitectureTypesHelper' + +// Los textos de lo que está mal en las capas (N4LLayerCheck y la alerta que impide entrenar) + +export const LAYER_CHECK_PREFIX = 'layer-check.' +const prefix = LAYER_CHECK_PREFIX + +/** Los números del texto: la capa desde 1, el nombre del parámetro y el de las activaciones como en el selector */ +export function issueValues(t: TFunction, { layer, values }: Pick, 'layer' | 'values'>) { + const activation = (key: unknown) => TYPE_ACTIVATION.find((option) => option.key === key)?.label ?? String(key) + return { + ...values, + layer: layer + 1, + ...(values.param !== undefined) && { param: t(prefix + 'params.' + values.param) }, + ...(values.activation !== undefined) && { activation: activation(values.activation) }, + ...(values.expected !== undefined) && { expected: activation(values.expected) }, + } +} + +/** Lo que dice el aviso de un problema (también en la alerta que impide entrenar) */ +export function layerIssueText(t: TFunction, issue: Pick, 'kind' | 'layer' | 'values'>) { + return t(prefix + issue.kind + '.text', issueValues(t, issue)) +} + +/** Qué capas tienen algo, para marcarlas en el editor (si una tiene un error y un aviso, el error) */ +export function flaggedLayers(issues: LayerIssue_t[]): Partial> { + const flagged: Partial> = {} + for (const { layer, severity } of issues) if (flagged[layer] !== 'error') flagged[layer] = severity + return flagged +} diff --git a/src/components/neural-network/layerSummary.ts b/src/components/neural-network/layerSummary.ts new file mode 100644 index 0000000..4b2f6cb --- /dev/null +++ b/src/components/neural-network/layerSummary.ts @@ -0,0 +1,53 @@ +import type { TFunction } from 'i18next' + +import { TYPE_ACTIVATION } from '@core/nn-utils/ArchitectureTypesHelper' +import { SERIES_LAYER_LABELS } from '@core/timeSeries/seriesLayers' + +/** Lo que se describe de una capa; vale para las dense (tabular, regresión) y las de imágenes */ +export type DrawableLayer_t = { + _class? : string + units? : number + activation?: string | null + kernelSize?: number + filters? : number + poolSize? : number + strides? : number +} + +/** + * Tipo de la capa y sus parámetros, con el mismo vocabulario en el diagrama y en los editores de capas. Los tipos + * de capa y las activaciones se dejan con su nombre técnico. Sin `_class`, la capa es dense (tabular, regresión). + */ +export function layerSummaryParts(t: TFunction, layer: DrawableLayer_t): string[] { + const units = t('neural-network.units', { units: layer.units }) + switch (layer._class) { + case 'flatten': + return ['Flatten'] + case 'dense': + return ['Dense', units, String(layer.activation)] + // Las recurrentes de las series temporales + case 'simpleRNN': + case 'lstm': + case 'gru': + return [SERIES_LAYER_LABELS[layer._class], units, String(layer.activation)] + case 'conv2d': + return ['Conv 2D', t('neural-network.kernel-size', { value: layer.kernelSize }), + t('neural-network.filters', { value: layer.filters }), String(layer.activation)] + case 'maxPooling2d': + return ['Max Pooling 2D', t('neural-network.pool-size', { value: layer.poolSize }), + t('neural-network.strides', { value: layer.strides })] + default: + return [units, String(layer.activation)] + } +} + +/** Todas las capas en una línea (para comparar modelos): «Dense, 10 neuronas, relu → Dense, 3 neuronas, softmax» */ +export function layersSummary(t: TFunction, layers: DrawableLayer_t[]): string { + return layers.map((layer) => layerSummaryParts(t, layer).join(', ')).join(' → ') +} + +/** Una capa dense en la cabecera de su editor: «10 neuronas, ReLU» (sin activación, ReLU, como el selector) */ +export function denseLayerSummary(t: TFunction, { units, activation }: { units: number, activation: string | null }): string { + const key = activation || 'relu' + return `${t('neural-network.units', { units })}, ${TYPE_ACTIVATION.find((option) => option.key === key)?.label ?? key}` +} diff --git a/src/components/neural-network/moveLayer.ts b/src/components/neural-network/moveLayer.ts new file mode 100644 index 0000000..41228ea --- /dev/null +++ b/src/components/neural-network/moveLayer.ts @@ -0,0 +1,8 @@ +/** Las capas con la de `from` en el puesto `to`, las demás en su orden (para el editor de capas: subir y bajar) */ +export function moveLayer(layers: L[], from: number, to: number): L[] { + if (from === to || from < 0 || to < 0 || from >= layers.length || to >= layers.length) return layers + const next = [...layers] + const [moved] = next.splice(from, 1) + next.splice(to, 0, moved) + return next +} diff --git a/src/components/neural-network/stepByStep/N4LStepByStep.css b/src/components/neural-network/stepByStep/N4LStepByStep.css new file mode 100644 index 0000000..56f9a7a --- /dev/null +++ b/src/components/neural-network/stepByStep/N4LStepByStep.css @@ -0,0 +1,119 @@ +/* Paso a paso: la red a la izquierda y la explicación a la derecha (debajo, en pantallas estrechas) */ +.n4l-sbs { + /* El color de los gradientes y los deltas (lo que va hacia atrás) */ + --n4l-sbs-gradient: #fd7e14; +} + +.n4l-sbs-body { + display: grid; + grid-template-columns: minmax(0, 3fr) minmax(16rem, 1fr); + gap: 1rem; + align-items: start; +} + +@media (max-width: 991.98px) { + .n4l-sbs-body { + grid-template-columns: minmax(0, 1fr); + } +} + +.n4l-sbs-diagram { + display: block; + width: 100%; + height: auto; +} + +/* A pantalla completa, la red cabe entera a lo alto */ +.n4l-maximized .n4l-sbs-diagram { + max-height: calc(100dvh - 14rem); +} + +.n4l-sbs-column { + font-size: 12px; + fill: var(--bs-secondary-color); +} + +.n4l-sbs-label { + font-size: 11px; + fill: var(--bs-body-color); +} + +.n4l-sbs-target { + font-weight: 600; + fill: var(--bs-success-text-emphasis); +} + +.n4l-sbs-value { + font-size: 8px; + fill: var(--bs-body-color); + pointer-events: none; +} + +.n4l-sbs-node { + cursor: pointer; + outline: none; +} + +.n4l-sbs-node:focus-visible circle { + stroke: var(--bs-primary); + stroke-width: 3; +} + +.n4l-sbs-selected { + fill: none; + stroke: var(--bs-emphasis-color); + stroke-width: 1.5; + stroke-dasharray: 3 2; +} + +/* Las conexiones de la capa que se calcula: el trazo avanza hacia la derecha (hacia delante) o hacia la izquierda + (hacia atrás) */ +.n4l-sbs-flow-forward, +.n4l-sbs-flow-backward { + stroke-dasharray: 6 4; + animation: n4l-sbs-flow 0.9s linear infinite; +} + +.n4l-sbs-flow-backward { + animation-direction: reverse; +} + +@keyframes n4l-sbs-flow { + from { + stroke-dashoffset: 10; + } + + to { + stroke-dashoffset: 0; + } +} + +@media (prefers-reduced-motion: reduce) { + .n4l-sbs-flow-forward, + .n4l-sbs-flow-backward { + animation: none; + } +} + +.n4l-sbs-formula { + margin-bottom: 0.75rem; + padding: 0.5rem 0.625rem; + border-radius: var(--bs-border-radius); + background-color: var(--bs-tertiary-bg); + color: var(--bs-body-color); + font-size: 0.8rem; + white-space: pre-wrap; + word-break: break-word; +} + +.n4l-sbs-history { + display: block; + width: 100%; + height: 3rem; +} + +.n4l-sbs-history polyline { + stroke: var(--n4l-sbs-gradient); + stroke-width: 1.5; + vector-effect: non-scaling-stroke; +} diff --git a/src/components/neural-network/stepByStep/N4LStepByStep.tsx b/src/components/neural-network/stepByStep/N4LStepByStep.tsx new file mode 100644 index 0000000..1e31250 --- /dev/null +++ b/src/components/neural-network/stepByStep/N4LStepByStep.tsx @@ -0,0 +1,422 @@ +import './N4LStepByStep.css' +import { useEffect, useMemo, useRef, useState } from 'react' +import { Button, ButtonGroup, Card, Form } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' +import { ArrowCounterclockwise, ChevronLeft, ChevronRight, FastForwardFill, PauseFill, PlayFill } from 'react-bootstrap-icons' + +import { + activationBackward, backward, countNodes, forward, initNetwork, lossOf, MAX_STEP_NODES, stepPhases, update, + type StepLayer_t, type StepLoss_t, type StepNetwork_t, +} from '@core/nn-utils/stepByStep' +import N4LEmptyState from '@components/loading/N4LEmptyState' +import N4LMaximizeButton from '@components/maximize/N4LMaximizeButton' +import { useMaximize } from '@components/maximize/useMaximize' +import N4LVirtualSelect from '@components/select/N4LVirtualSelect' +import StepByStepDiagram, { type StepNode_t } from './StepByStepDiagram' +import { trackEvent } from '@core/analytics' + +type N4LStepByStepProps = { + /** Clasificación (softmax y entropía cruzada) o regresión (un número y error cuadrático) */ + kind : 'classification' | 'regression' + /** Las capas del editor, la de salida incluida (con initialNetwork, las de ese modelo) */ + layers? : StepLayer_t[] + /** + * Los pesos de un modelo ya entrenado (páginas de los modelos): se empieza con ellos y Reiniciar vuelve a ellos; null + * si el modelo no es una red densa. Sin él (páginas de entrenamiento), los pesos empiezan al azar. + */ + initialNetwork?: StepNetwork_t | null + /** Las filas del conjunto de datos tal como las recibe la red */ + X : number[][] + /** El número de cada fila en el conjunto de datos, si no son todas (como en los selectores de fila: desde 0) */ + rowNumbers? : number[] + /** Clasificación: cada fila en one-hot; regresión: el valor real de cada fila */ + y : number[][] + featureNames : string[] + /** Clasificación: las clases; regresión: el nombre de lo que se predice */ + outputNames : string[] + learningRate : number +} + +const SPEEDS = { slow: 1800, normal: 900, fast: 300 } as const +type Speed_t = keyof typeof SPEEDS +// Cuántas actualizaciones se ven en la gráfica de la pérdida +const HISTORY = 60 +// La pérdida media se mide con estas filas como mucho (siempre las mismas): con todas, un conjunto grande tardaría +const LOSS_SAMPLE = 200 +// Cuántos términos de la suma se escriben antes de "…" +const TERMS = 4 + +type Run_t = { + /** La red para la que son estos pesos: si cambian las capas o las entradas, se empieza de nuevo */ + signature : string + /** El modelo ya entrenado del que salen (null: pesos al azar); si cambia de modelo, también */ + source : StepNetwork_t | null + seed : number + network : StepNetwork_t + phase : number + example : number + iterations: number + /** La pérdida media de la muestra antes de empezar y después de cada actualización */ + losses : number[] +} + +const signatureOf = (inputs: number, layers: StepLayer_t[]) => inputs + '|' + layers.map(({ units, activation }) => units + ':' + activation).join(',') +const newRun = (inputs: number, layers: StepLayer_t[], seed: number, example: number, source: StepNetwork_t | null): Run_t => ({ + signature : signatureOf(inputs, layers), + source, + seed, + network : source ?? initNetwork(inputs, layers, seed), + phase : 0, + example, + iterations: 0, + losses : [], +}) + +/** Las filas barajadas, siempre igual: como al entrenar, los ejemplos no van en el orden del fichero (que puede estar + * ordenado por clase y llevaría la red hacia una sola) */ +function shuffledRows(count: number) { + const order = Array.from({ length: count }, (_, index) => index) + let state = 7 + for (let i = count - 1; i > 0; i--) { + state = (state * 1103515245 + 12345) % 2147483648 + const j = state % (i + 1); + [order[i], order[j]] = [order[j], order[i]] + } + return order +} + +/** El objetivo de una fila; en regresión, escalado entre 0 y 1 (ver range) */ +const targetOf = (y: number[][], range: { min: number, span: number } | null, row: number) => + (range === null ? y[row] : [(y[row][0] - range.min) / range.span]) + +const argMax = (values: number[]) => values.reduce((best, value, index) => (value > values[best] ? index : best), 0) + +/** + * El entrenamiento de la red diseñada, paso a paso y con un ejemplo cada vez: el ejemplo entra, recorre la red hacia + * delante capa a capa, se mide el error y el error vuelve hacia atrás hasta cambiar cada peso. Se puede avanzar fase a + * fase, dejar que avance solo o pasar 10 ejemplos de golpe para ver bajar la pérdida. Solo con redes de menos de + * MAX_STEP_NODES neuronas (contando las de entrada): más no se pueden seguir. En el entrenamiento, los pesos empiezan al + * azar; en un modelo ya entrenado (initialNetwork), son los suyos y se ve cómo calcula su respuesta y qué haría un paso + * más de entrenamiento (el modelo de la página no cambia). La actualización es descenso del gradiente simple. + */ +export default function N4LStepByStep({ kind, layers: editorLayers, initialNetwork, X, rowNumbers, y, featureNames, outputNames, learningRate }: N4LStepByStepProps) { + const pretrained = initialNetwork !== undefined + const source = initialNetwork ?? null + const layers = useMemo(() => initialNetwork?.layers ?? editorLayers ?? [], [initialNetwork, editorLayers]) + const prefix = 'pages.playground.step-by-step.' + const { t, i18n } = useTranslation() + const maximize = useMaximize() + const formatter = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 2, minimumFractionDigits: 2 }), [i18n.language]) + const precise = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 4, minimumFractionDigits: 4 }), [i18n.language]) + // Con el signo menos de verdad (−) en vez del guion + const format = (value: number) => formatter.format(Math.abs(value) < 0.005 ? 0 : value).replace('-', '−') + const formatPrecise = (value: number) => precise.format(value).replace('-', '−') + // En una suma, los negativos entre paréntesis: 0,13 × 0,22 + (−0,07) × 0,63 + const term = (value: number) => (value < -0.005 ? `(${format(value)})` : format(value)) + const formatRate = (value: number) => value.toLocaleString(i18n.language, { maximumSignificantDigits: 3 }) + + const inputs = initialNetwork?.inputs ?? X[0]?.length ?? featureNames.length + const lossKind: StepLoss_t = kind === 'classification' ? 'cross-entropy' : 'mse' + const nodes = countNodes(inputs, layers) + const outputUnits = layers.at(-1)?.units ?? 0 + const expectedOutputs = kind === 'classification' ? outputNames.length : 1 + const ready = initialNetwork !== null && X.length > 0 && layers.length > 0 && nodes < MAX_STEP_NODES && outputUnits === expectedOutputs + + // Al entrenar en regresión, el objetivo se escala entre 0 y 1: con los valores reales (salarios, precios) un paso de + // descenso del gradiente simple saltaría lejísimos. Se enseña también en sus unidades. Un modelo ya entrenado predice + // en las unidades reales: con él no se escala + const range = useMemo(() => { + if (kind !== 'regression' || pretrained || y.length === 0) return null + const values = y.map(([value]) => value) + const min = Math.min(...values) + const max = Math.max(...values) + return { min, span: max - min || 1 } + }, [kind, pretrained, y]) + const realValue = (scaled: number) => (range === null ? scaled : scaled * range.span + range.min) + + // Empieza por el primer ejemplo del orden barajado + const [run, setRun] = useState(() => newRun(inputs, layers, 42, shuffledRows(X.length)[0] ?? 0, source)) + const [selected, setSelected] = useState(null) + const [playing, setPlaying] = useState(false) + const [speed, setSpeed] = useState('normal') + const [sameExample, setSameExample] = useState(false) + // Otra red (otras capas o entradas, u otro modelo): pesos nuevos y desde el principio + const current = run.signature === signatureOf(inputs, layers) && run.source === source + if (!current) { + setRun(newRun(inputs, layers, run.seed, shuffledRows(X.length)[0] ?? 0, source)) + setSelected(null) + } + if (playing && !ready) setPlaying(false) + + const phases = useMemo(() => stepPhases(layers.length), [layers.length]) + const order = useMemo(() => shuffledRows(X.length), [X.length]) + const position = useMemo(() => { + const positions = new Array(order.length) + order.forEach((row, index) => { positions[row] = index }) + return positions + }, [order]) + /** La pérdida media de una muestra fija de filas: baja si la red aprende (la de un solo ejemplo da saltos) */ + const meanLoss = (network: StepNetwork_t) => { + const rows = order.slice(0, LOSS_SAMPLE) + return rows.reduce((sum, row) => sum + lossOf(lossKind, forward(network, X[row]).a.at(-1)!, targetOf(y, range, row)), 0) / Math.max(1, rows.length) + } + const phase = phases[Math.min(run.phase, phases.length - 1)] + const example = Math.min(run.example, Math.max(0, X.length - 1)) + + const step = useMemo(() => { + if (!ready || !current) return null + const target = targetOf(y, range, example) + const trace = forward(run.network, X[example]) + const gradients = backward(run.network, trace, target, lossKind) + const loss = lossOf(lossKind, trace.a.at(-1)!, target) + const next = update(run.network, gradients, learningRate) + const lossAfter = lossOf(lossKind, forward(next, X[example]).a.at(-1)!, target) + return { target, trace, gradients, loss, next, lossAfter } + }, [ready, current, run, X, y, range, example, lossKind, learningRate]) + + /** Termina el ejemplo: los pesos nuevos se quedan y se pasa al siguiente (o se repite el mismo) */ + const finishExample = (current: Run_t, network: StepNetwork_t): Run_t => ({ + ...current, + network, + phase : 0, + iterations: current.iterations + 1, + losses : [...(current.losses.length === 0 ? [meanLoss(current.network)] : current.losses), meanLoss(network)].slice(-HISTORY - 1), + example : sameExample ? current.example : order[(position[current.example] + 1) % order.length], + }) + + // Se avisa la primera vez que se avanza (completa el paso del recorrido «Empieza aquí») + const used = useRef(false) + const markUsed = () => { + if (used.current) return + used.current = true + trackEvent('step_by_step', { action: 'step' }) + } + + const next = () => { + if (step === null) return + markUsed() + if (run.phase < phases.length - 1) setRun({ ...run, phase: run.phase + 1 }) + else setRun(finishExample(run, step.next)) + } + + /** 10 ejemplos de golpe, sin enseñar cada fase: para ver cómo baja la pérdida */ + const nextTen = () => { + if (step === null) return + markUsed() + let current = run + for (let i = 0; i < 10; i++) { + const target = targetOf(y, range, current.example) + const trace = forward(current.network, X[current.example]) + const gradients = backward(current.network, trace, target, lossKind) + current = finishExample(current, update(current.network, gradients, learningRate)) + } + setRun(current) + } + + const rowOptions = useMemo(() => y.map((row, index) => ({ + value: index, + label: `#${rowNumbers?.[index] ?? index}: ${kind === 'classification' ? outputNames[argMax(row)] : `${outputNames[0]}: ${formatter.format(row[0])}`}`, + })), [kind, y, rowNumbers, outputNames, formatter]) + + // Avanza solo, fase a fase, a la velocidad elegida + useEffect(() => { + if (!playing) return + const timer = window.setTimeout(next, SPEEDS[speed]) + return () => window.clearTimeout(timer) + }) + + // La neurona que se explica: la elegida o, si no está en la capa de la fase, la primera de esa capa + const activeLayer = phase.kind === 'forward' || phase.kind === 'backward' ? phase.layer : phase.kind === 'input' ? -1 : layers.length - 1 + const focus: StepNode_t = selected ?? { layer: activeLayer, index: 0 } + + const header = ( + +

    + +
    + ) + + if (step === null) { + const detail = [inputs, ...layers.map(({ units }) => units)].join(' + ') + return ( + + {header} + +

    {t(prefix + (pretrained ? 'intro-pretrained' : 'intro'))}

    + {initialNetwork === null &&

    {t(prefix + 'not-dense')}

    } + {initialNetwork !== null && X.length === 0 && } + {initialNetwork !== null && X.length > 0 && nodes >= MAX_STEP_NODES && +

    + {t(prefix + (pretrained ? 'too-big-pretrained' : 'too-big'), { nodes, detail, max: MAX_STEP_NODES })} +

    } + {initialNetwork !== null && X.length > 0 && nodes < MAX_STEP_NODES && outputUnits !== expectedOutputs && +

    {t(prefix + 'mismatch', { units: outputUnits, classes: expectedOutputs })}

    } +
    +
    + ) + } + + const { trace, gradients, loss, lossAfter, target } = step + const L = layers.length + const output = trace.a[L - 1] + const targetIndex = kind === 'classification' ? argMax(target) : null + const activation = (layer: number) => layers[layer]?.activation ?? 'linear' + + const phaseText = (() => { + switch (phase.kind) { + case 'input': + return t(prefix + (pretrained ? 'phase.input-pretrained' : 'phase.input'), { row: rowNumbers?.[example] ?? example, count: inputs }) + case 'forward': + return t(prefix + (activation(phase.layer) === 'softmax' ? 'phase.forward-softmax' : 'phase.forward'), + { layer: phase.layer + 1, activation: activation(phase.layer) }) + case 'loss': + return kind === 'classification' + ? t(prefix + 'phase.loss-classification', { + probability: format(output[targetIndex!]), target: outputNames[targetIndex!], loss: format(loss), predicted: outputNames[argMax(output)], + }) + : t(prefix + (range === null ? 'phase.loss-regression-raw' : 'phase.loss-regression'), { + prediction: format(realValue(output[0])), actual: format(realValue(target[0])), output: format(output[0]), target: format(target[0]), loss: format(loss), + }) + case 'backward': + return t(prefix + (phase.layer === L - 1 ? 'phase.backward-output' : 'phase.backward'), + { layer: phase.layer + 1, activation: activation(phase.layer) }) + case 'update': + return t(prefix + 'phase.update', { rate: formatRate(learningRate), before: format(loss), after: format(lossAfter) }) + } + })() + + // Las cuentas de la neurona que se explica, con sus números + const formula = (() => { + const { layer, index } = focus + if (layer === -1) return t(prefix + 'formula-input', { name: featureNames[index] ?? index + 1, value: format(trace.input[index]) }) + const previous = layer === 0 ? trace.input : trace.a[layer - 1] + const weights = run.network.weights[layer][index] + const terms = weights.slice(0, TERMS).map((w, i) => `${term(w)} × ${term(previous[i])}`).join(' + ') + const sum = `z = ${terms}${weights.length > TERMS ? ' + …' : ''} + ${term(run.network.biases[layer][index])} = ${format(trace.z[layer][index])}` + const computed = phase.kind !== 'input' && !(phase.kind === 'forward' && layer > phase.layer) + if (!computed) return t(prefix + 'formula-pending', { index: index + 1, layer: layer + 1 }) + const act = activation(layer) + const forwardPart = `${sum} → ${act}(z) = ${format(trace.a[layer][index])}` + const showDelta = (phase.kind === 'backward' && layer >= phase.layer) || phase.kind === 'update' + if (!showDelta) return forwardPart + const delta = gradients.deltas[layer][index] + let deltaPart: string + if (layer === L - 1) { + deltaPart = kind === 'classification' && act === 'softmax' + ? `δ = a − y = ${format(output[index])} − ${format(target[index])} = ${format(delta)}` + : `δ = ${format(delta)}` + } else { + const back = run.network.weights[layer + 1].reduce((total, row, j) => total + row[index] * gradients.deltas[layer + 1][j], 0) + const derivative = act === 'softmax' ? null : activationBackward(act, [trace.z[layer][index]], [trace.a[layer][index]], [1])[0] + deltaPart = derivative === null + ? `δ = ${format(delta)}` + : `δ = (Σ w × δ) × ${act}′(z) = ${term(back)} × ${term(derivative)} = ${format(delta)}` + } + if (phase.kind !== 'update') return `${forwardPart}\n${deltaPart}` + const bias = run.network.biases[layer][index] + // El peso de esta neurona que más cambia: el de la entrada con mayor gradiente + const gradientsIn = gradients.gradWeights[layer][index] + const biggest = gradientsIn.reduce((best, g, i) => (Math.abs(g) > Math.abs(gradientsIn[best]) ? i : best), 0) + const updated = { + before : formatPrecise(bias), + after : formatPrecise(step.next.biases[layer][index]), + from : layer === 0 ? featureNames[biggest] ?? String(biggest + 1) : t(prefix + 'from-neuron', { index: biggest + 1, layer }), + weight : formatPrecise(weights[biggest]), + weightAfter: formatPrecise(step.next.weights[layer][index][biggest]), + } + return `${deltaPart}\n${t(prefix + 'formula-update', updated)}` + })() + + return ( + + {header} + +

    {t(prefix + (pretrained ? 'intro-pretrained' : 'intro'))}

    + +
    +
    + { + setRun({ ...run, example: row, phase: 0 }) + setPlaying(false) + }} + label={t(prefix + 'example')} placeholder={t(prefix + 'example')} searchPlaceholder={t(prefix + 'search')} noResultsText={t(prefix + 'no-results')} /> +
    + + + + + + + setSpeed(event.target.value as Speed_t)}> + {(Object.keys(SPEEDS) as Speed_t[]).map((key) => )} + + setSameExample(event.target.checked)} /> + +
    + +
    +
    + +

    {t(prefix + 'legend')}

    +
    +
    +

    + {t(prefix + 'phase-count', { current: run.phase + 1, total: phases.length })} +

    +

    {t(prefix + 'phase-title.' + phase.kind, { layer: 'layer' in phase ? phase.layer + 1 : '' })}

    +

    {phaseText}

    +

    + {focus.layer === -1 + ? t(prefix + 'focus-input', { index: focus.index + 1 }) + : t(prefix + 'focus', { index: focus.index + 1, layer: focus.layer + 1 })} +

    +
    {formula}
    + +
    +
    +
    +
    + ) +} + +type LossHistoryProps = { losses: number[], iterations: number, sample: number, format: (value: number) => string } + +/** La pérdida media de la muestra antes de empezar y tras cada actualización: si la red aprende, la línea baja */ +function LossHistory({ losses, iterations, sample, format }: LossHistoryProps) { + const { t } = useTranslation() + const prefix = 'pages.playground.step-by-step.' + if (losses.length === 0) return

    {t(prefix + 'history-empty')}

    + // Entre la menor y la mayor: los cambios pequeños también se ven + const min = Math.min(...losses) + const span = Math.max(...losses) - min || 1 + const points = losses.map((loss, index) => `${(index / Math.max(1, losses.length - 1)) * 200},${46 - ((loss - min) / span) * 42}`).join(' ') + const caption = t(prefix + 'history', { count: iterations, sample, first: format(losses[0]), last: format(losses.at(-1)!) }) + return ( +
    + + + +
    {caption}
    +
    + ) +} diff --git a/src/components/neural-network/stepByStep/StepByStepDiagram.tsx b/src/components/neural-network/stepByStep/StepByStepDiagram.tsx new file mode 100644 index 0000000..96836c4 --- /dev/null +++ b/src/components/neural-network/stepByStep/StepByStepDiagram.tsx @@ -0,0 +1,157 @@ +import { useTranslation } from 'react-i18next' + +import type { BackwardTrace_t, ForwardTrace_t, StepNetwork_t, StepPhase_t } from '@core/nn-utils/stepByStep' + +/** Una neurona: layer -1 son las de entrada */ +export type StepNode_t = { layer: number, index: number } + +type StepByStepDiagramProps = { + network : StepNetwork_t + trace : ForwardTrace_t + gradients : BackwardTrace_t + phase : StepPhase_t + /** La tasa de aprendizaje ya escrita (0,0005 no se puede redondear a dos decimales) */ + learningRate: string + featureNames: string[] + outputNames : string[] + /** Clasificación: la clase correcta del ejemplo, para marcarla en la salida */ + targetIndex : number | null + selected : StepNode_t | null + onSelect : (node: StepNode_t) => void + format : (value: number) => string +} + +const WIDTH = 760 +const LABEL_LEFT = 118 +const LABEL_RIGHT = 120 + +/** Hasta qué capa se ha calculado la activación (-1: solo la entrada), y desde cuál se conocen los deltas */ +function progress(phase: StepPhase_t, layers: number) { + switch (phase.kind) { + case 'input': return { forwardUntil: -1, backwardFrom: layers } + case 'forward': return { forwardUntil: phase.layer, backwardFrom: layers } + case 'loss': return { forwardUntil: layers - 1, backwardFrom: layers } + case 'backward': return { forwardUntil: layers - 1, backwardFrom: phase.layer } + case 'update': return { forwardUntil: layers - 1, backwardFrom: 0 } + } +} + +const maxAbs = (values: number[]) => values.reduce((max, value) => Math.max(max, Math.abs(value)), 0) || 1 +const truncate = (text: string, length: number) => (text.length > length ? text.slice(0, length - 1) + '…' : text) + +/** Un color del tema mezclado con el fondo: más intenso cuanto mayor es el valor */ +const tint = (color: string, amount: number) => `color-mix(in srgb, ${color} ${Math.round(Math.min(1, amount) * 100)}%, var(--bs-body-bg))` +const signColor = (value: number) => (value >= 0 ? 'var(--bs-primary)' : 'var(--bs-danger)') + +/** + * La red en columnas: la entrada a la izquierda, cada capa y la salida a la derecha. El color de una neurona es su + * activación (azul, positiva; rojo, negativa) y el de una conexión, el signo de su peso, más gruesa cuanto mayor. Al ir + * hacia delante se resaltan las conexiones que llegan a la capa que se calcula; al ir hacia atrás, en naranja, sus + * gradientes, y el borde de cada neurona es su delta. + */ +export default function StepByStepDiagram(props: StepByStepDiagramProps) { + const { network, trace, gradients, phase, learningRate, featureNames, outputNames, targetIndex, selected, onSelect, format } = props + const { t } = useTranslation() + const prefix = 'pages.playground.step-by-step.' + + const columns = [network.inputs, ...network.layers.map(({ units }) => units)] + const tallest = Math.max(...columns) + const spacing = Math.max(22, Math.min(46, 420 / tallest)) + const height = Math.max(220, tallest * spacing + 70) + const radius = Math.min(15, spacing * 0.38) + const showValues = radius >= 10 + const x = (column: number) => LABEL_LEFT + (column * (WIDTH - LABEL_LEFT - LABEL_RIGHT)) / (columns.length - 1) + const y = (column: number, index: number) => 46 + (height - 70) / 2 + (index - (columns[column] - 1) / 2) * spacing + + const L = network.layers.length + const { forwardUntil, backwardFrom } = progress(phase, L) + const activeForward = phase.kind === 'forward' ? phase.layer : null + const activeBackward = phase.kind === 'backward' ? phase.layer : null + + const edges = network.weights.flatMap((layer, l) => { + const maxWeight = maxAbs(layer.flat()) + const maxGradient = maxAbs(gradients.gradWeights[l].flat()) + const showGradient = activeBackward === l || phase.kind === 'update' + const dim = (activeForward !== null && activeForward !== l) || (activeBackward !== null && activeBackward !== l) + return layer.flatMap((row, j) => row.map((w, i) => { + const relative = showGradient ? Math.abs(gradients.gradWeights[l][j][i]) / maxGradient : Math.abs(w) / maxWeight + const opacity = (showGradient ? 0.25 + 0.7 * relative : 0.12 + 0.55 * relative) * (dim ? 0.35 : 1) * (activeForward === l ? 1.4 : 1) + const flow = activeForward === l ? 'n4l-sbs-flow-forward' : activeBackward === l ? 'n4l-sbs-flow-backward' : undefined + return ( + + ) + })) + }) + + const node = (column: number, index: number) => { + const layer = column - 1 + const isInput = layer === -1 + const value = isInput ? trace.input[index] : trace.a[layer][index] + const computed = isInput || layer <= forwardUntil + const columnValues = isInput ? trace.input : trace.a[layer] + const delta = !isInput && layer >= backwardFrom ? gradients.deltas[layer][index] : null + const maxDelta = isInput ? 1 : maxAbs(gradients.deltas[layer]) + const isSelected = selected?.layer === layer && selected.index === index + const label = isInput + ? t(prefix + 'node-input', { name: featureNames[index] ?? index + 1, value: format(value) }) + : t(prefix + 'node', { index: index + 1, layer: layer + 1, value: computed ? format(value) : '?' }) + return ( + onSelect({ layer, index })} + onKeyDown={(event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + onSelect({ layer, index }) + } + }}> + {label} + {isSelected && } + + {showValues && computed && + {format(value)}} + + ) + } + + const outputLabel = (index: number) => { + const name = truncate(outputNames[index] ?? String(index + 1), 14) + const probability = forwardUntil === L - 1 ? ': ' + format(trace.a[L - 1][index]) : '' + return (index === targetIndex ? '✓ ' : '') + name + probability + } + + return ( + + {columns.map((_, column) => ( + + {column === 0 + ? t(prefix + 'column-input') + : t(prefix + (column === columns.length - 1 ? 'column-output' : 'column-layer'), { layer: column, activation: network.layers[column - 1].activation })} + + ))} + {edges} + {featureNames.slice(0, network.inputs).map((name, index) => ( + + {name}{truncate(name, 16)} + + ))} + {Array.from({ length: columns.at(-1)! }, (_, index) => ( + + {outputNames[index]}{outputLabel(index)} + + ))} + {columns.map((count, column) => Array.from({ length: count }, (_, index) => node(column, index)))} + {phase.kind === 'update' && + + {t(prefix + 'update-rule', { rate: learningRate })} + } + + ) +} diff --git a/src/components/neural-network/stepByStep/stepByStepSetting.ts b/src/components/neural-network/stepByStep/stepByStepSetting.ts new file mode 100644 index 0000000..198dcf1 --- /dev/null +++ b/src/components/neural-network/stepByStep/stepByStepSetting.ts @@ -0,0 +1,54 @@ +import { useSyncExternalStore } from 'react' + +import { trackEvent } from '@core/analytics' + +// Si se enseña la sección Paso a paso (N4LStepByStep) en las páginas de entrenamiento y en las de los modelos. Está +// oculta por defecto y se activa en /settings; se guarda en el navegador de quien la elige. + +export const STEP_BY_STEP_STORAGE_KEY = 'n4l-step-by-step' + +function readSaved(): boolean { + try { + return localStorage.getItem(STEP_BY_STEP_STORAGE_KEY) === 'true' + } catch { + return false + } +} + +let current: boolean | null = null +const listeners = new Set<() => void>() + +export const isStepByStepEnabled = (): boolean => (current ??= readSaved()) + +function subscribe(listener: () => void) { + listeners.add(listener) + return () => { listeners.delete(listener) } +} + +export function setStepByStepEnabled(enabled: boolean) { + current = enabled + try { + if (enabled) localStorage.setItem(STEP_BY_STEP_STORAGE_KEY, 'true') + else localStorage.removeItem(STEP_BY_STEP_STORAGE_KEY) + } catch { + // Sin almacenamiento vale solo para esta visita + } + trackEvent('settings_change', { setting: 'step_by_step', value: String(enabled) }) + listeners.forEach((listener) => listener()) +} + +/** Vuelve a ocultarla (y lo olvida): para "Restablecer todo" en /settings */ +export function resetStepByStep() { + current = false + try { + localStorage.removeItem(STEP_BY_STEP_STORAGE_KEY) + } catch { + // Nada que borrar + } + listeners.forEach((listener) => listener()) +} + +/** Si la sección Paso a paso está activada; cambia en cuanto se activa o desactiva en /settings */ +export function useStepByStepEnabled(): boolean { + return useSyncExternalStore(subscribe, isStepByStepEnabled, () => false) +} diff --git a/src/components/neural-network/stepByStep/usePretrainedNetwork.ts b/src/components/neural-network/stepByStep/usePretrainedNetwork.ts new file mode 100644 index 0000000..a0c3ef4 --- /dev/null +++ b/src/components/neural-network/stepByStep/usePretrainedNetwork.ts @@ -0,0 +1,29 @@ +import { useEffect, useState } from 'react' +import type * as tfjs from '@tensorflow/tfjs' + +import { networkFromModel } from '@core/nn-utils/stepByStepModel' +import type { StepNetwork_t } from '@core/nn-utils/stepByStep' + +/** + * Los pesos de un modelo ya entrenado para N4LStepByStep: undefined mientras se leen (o si está desactivado), null si + * no es una red de capas densas. Solo se leen con la sección activada; al cambiar de modelo, otra vez. + */ +export function usePretrainedNetwork(model: tfjs.LayersModel | null, enabled: boolean): StepNetwork_t | null | undefined { + const [read, setRead] = useState<{ model: tfjs.LayersModel, network: StepNetwork_t | null } | null>(null) + + useEffect(() => { + if (!enabled || model === null) return + let isCancelled = false + networkFromModel(model) + .then((network) => { + if (!isCancelled) setRead({ model, network }) + }) + .catch((error: unknown) => { + console.error('usePretrainedNetwork', error) + if (!isCancelled) setRead({ model, network: null }) + }) + return () => { isCancelled = true } + }, [model, enabled]) + + return enabled && model !== null && read?.model === model ? read.network : undefined +} diff --git a/src/components/offline/N4LOfflineBar.tsx b/src/components/offline/N4LOfflineBar.tsx new file mode 100644 index 0000000..c44b337 --- /dev/null +++ b/src/components/offline/N4LOfflineBar.tsx @@ -0,0 +1,15 @@ +import { useTranslation } from 'react-i18next' + +import { useIsOnline } from '@core/offline/offline' + +/** Sin conexión: una franja bajo la barra de navegación que dice qué se puede seguir usando */ +export default function N4LOfflineBar() { + const { t } = useTranslation() + const isOnline = useIsOnline() + if (isOnline) return null + return ( +
    + {t('offline.bar')} +
    + ) +} diff --git a/src/components/report/N4LReportButton.tsx b/src/components/report/N4LReportButton.tsx new file mode 100644 index 0000000..ff421dd --- /dev/null +++ b/src/components/report/N4LReportButton.tsx @@ -0,0 +1,24 @@ +import { Button } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import alertHelper from '@utils/alertHelper' +import { trackEvent } from '@core/analytics' +import { saveReport, type TrainingReport_t } from '@core/report/trainingReport' + +/** Abre en otra pestaña el informe del modelo (para imprimirlo o guardarlo en PDF y entregarlo) */ +export default function N4LReportButton({ getReport }: { getReport: () => TrainingReport_t }) { + const { t } = useTranslation() + const handleClick = async () => { + if (!saveReport(getReport())) { + await alertHelper.alertError(t('report.error-storage')) + return + } + trackEvent('report_open') + window.open(import.meta.env.VITE_PATH + '/report', '_blank') + } + return ( + + ) +} diff --git a/src/components/select/N4LVirtualSelect.tsx b/src/components/select/N4LVirtualSelect.tsx new file mode 100644 index 0000000..19b100e --- /dev/null +++ b/src/components/select/N4LVirtualSelect.tsx @@ -0,0 +1,242 @@ +import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent } from 'react' +import { filterVirtualSelectOptions, type VirtualSelectOption_t } from './filterVirtualSelectOptions' + +export type { VirtualSelectOption_t } + +type N4LVirtualSelectProps = { + options : VirtualSelectOption_t[] + /** Valor elegido (null si todavía no se ha elegido nada) */ + value : number | null + onChange : (value: number) => void + /** Texto del botón mientras no hay nada elegido */ + placeholder : string + /** + * Qué se elige («Ejemplo del conjunto de datos»): el lector de pantalla lo dice antes de la opción elegida (el botón + * solo enseña la opción) y es el nombre de la lista. Sin él, el de la lista es `placeholder` + */ + label? : string + searchPlaceholder: string + noResultsText : string + /** Texto con cuántas opciones coinciden con la búsqueda ("12 de 1728") */ + countText? : (shown: number, total: number) => string + /** Filas visibles a la vez: solo se pintan esas (y unas pocas más), aunque haya miles */ + visibleRows? : number + rowHeight? : number + size? : 'sm' + disabled? : boolean + id? : string + className? : string +} + +// Filas que se pintan de más por encima y por debajo de las visibles, para que no se vea el hueco al hacer scroll +const OVERSCAN = 6 + +/** + * Desplegable para elegir entre miles de opciones: con buscador y "scroll virtual" (solo existen en la página las + * filas que se ven). Se maneja con el teclado como un combobox: flechas, AvPág/RePág, Ctrl+Inicio/Fin, Intro y Esc. + */ +export default function N4LVirtualSelect(props: N4LVirtualSelectProps) { + const { + options, + value, + onChange, + placeholder, + label, + searchPlaceholder, + noResultsText, + countText, + visibleRows = 8, + rowHeight = 32, + size, + disabled = false, + id, + className = '', + } = props + const baseId = useId() + const listId = `${baseId}-list` + const optionId = (index: number) => `${baseId}-option-${index}` + + const root_ref = useRef(null) + const trigger_ref = useRef(null) + const search_ref = useRef(null) + const list_ref = useRef(null) + // Posición a la que se lleva la lista al abrirla (la opción elegida, centrada) + const pendingScroll_ref = useRef(null) + + const [isOpen, setIsOpen] = useState(false) + const [query, setQuery] = useState('') + const [activeIndex, setActiveIndex] = useState(0) + const [scrollTop, setScrollTop] = useState(0) + + const filtered = useMemo(() => filterVirtualSelectOptions(options, query), [options, query]) + const selected = useMemo(() => options.find((option) => option.value === value), [options, value]) + + const listHeight = Math.max(1, Math.min(filtered.length, visibleRows)) * rowHeight + const first = Math.max(0, Math.floor(scrollTop / rowHeight) - OVERSCAN) + const last = Math.min(filtered.length, Math.ceil((scrollTop + listHeight) / rowHeight) + OVERSCAN) + + const scrollListTo = (top: number) => { + if (list_ref.current) list_ref.current.scrollTop = top + setScrollTop(top) + } + + /** Mueve la lista lo justo para que se vea la opción */ + const scrollIntoView = (index: number) => { + const top = index * rowHeight + if (top < scrollTop) scrollListTo(top) + else if (top + rowHeight > scrollTop + listHeight) scrollListTo(top + rowHeight - listHeight) + } + + const open = () => { + const index = Math.max(0, options.findIndex((option) => option.value === value)) + const height = Math.max(1, Math.min(options.length, visibleRows)) * rowHeight + const top = Math.max(0, index * rowHeight - (height - rowHeight) / 2) + setQuery('') + setActiveIndex(index) + setScrollTop(top) + pendingScroll_ref.current = top + setIsOpen(true) + } + + const close = (focusTrigger: boolean) => { + setIsOpen(false) + if (focusTrigger) trigger_ref.current?.focus() + } + + const select = (option: VirtualSelectOption_t) => { + onChange(option.value) + close(true) + } + + // Al abrir: el foco al buscador y la lista en la opción elegida + useEffect(() => { + if (!isOpen) return + search_ref.current?.focus() + if (list_ref.current !== null && pendingScroll_ref.current !== null) { + list_ref.current.scrollTop = pendingScroll_ref.current + pendingScroll_ref.current = null + } + }, [isOpen]) + + // Un clic fuera lo cierra + useEffect(() => { + if (!isOpen) return + const handleMouseDown = (event: MouseEvent) => { + if (!root_ref.current?.contains(event.target as Node)) setIsOpen(false) + } + document.addEventListener('mousedown', handleMouseDown) + return () => document.removeEventListener('mousedown', handleMouseDown) + }, [isOpen]) + + const handleKeyDown_Trigger = (event: KeyboardEvent) => { + if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { + event.preventDefault() + open() + } + } + + const handleKeyDown_Search = (event: KeyboardEvent) => { + const moveTo = (index: number) => { + event.preventDefault() + if (filtered.length === 0) return + const next = Math.min(filtered.length - 1, Math.max(0, index)) + setActiveIndex(next) + scrollIntoView(next) + } + switch (event.key) { + case 'ArrowDown': return moveTo(activeIndex + 1) + case 'ArrowUp': return moveTo(activeIndex - 1) + case 'PageDown': return moveTo(activeIndex + visibleRows) + case 'PageUp': return moveTo(activeIndex - visibleRows) + case 'Home': if (event.ctrlKey) moveTo(0); return + case 'End': if (event.ctrlKey) moveTo(filtered.length - 1); return + case 'Enter': + event.preventDefault() + if (filtered[activeIndex] !== undefined) select(filtered[activeIndex]) + return + case 'Escape': + event.preventDefault() + close(true) + return + case 'Tab': + close(false) + return + } + } + + const handleChange_Search = (text: string) => { + setQuery(text) + setActiveIndex(0) + scrollListTo(0) + } + + return ( +
    + + + {isOpen && +
    + 0 ? optionId(activeIndex) : undefined} + value={query} + onChange={(event) => handleChange_Search(event.target.value)} + onKeyDown={handleKeyDown_Search} /> + {countText && +
    {countText(filtered.length, options.length)}
    } +
    setScrollTop(event.currentTarget.scrollTop)}> + {filtered.length === 0 &&
    {noResultsText}
    } + {filtered.length > 0 && +
    + {filtered.slice(first, last).map((option, offset) => { + const index = first + offset + // Las opciones no reciben el foco: se queda en el buscador, que las recorre con las flechas y elige con + // Enter (aria-activedescendant); el clic es para el ratón + return ( + // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/interactive-supports-focus +
    event.preventDefault()} + onMouseEnter={() => setActiveIndex(index)} + onClick={() => select(option)}> + {option.label} +
    + ) + })} +
    } +
    +
    } +
    + ) +} diff --git a/src/components/select/filterVirtualSelectOptions.ts b/src/components/select/filterVirtualSelectOptions.ts new file mode 100644 index 0000000..3e23bdb --- /dev/null +++ b/src/components/select/filterVirtualSelectOptions.ts @@ -0,0 +1,18 @@ +export type VirtualSelectOption_t = { value: number, label: string } + +// Para ordenar las coincidencias: "12" encuentra antes "#12: …" que "#112: …" +const withoutLeadingSymbols = (text: string) => text.replace(/^[^\p{L}\p{N}]+/u, '') + +/** Opciones que contienen la búsqueda: primero las que empiezan por ella (sin contar símbolos iniciales como "#") */ +export function filterVirtualSelectOptions(options: VirtualSelectOption_t[], query: string): VirtualSelectOption_t[] { + const search = query.trim().toLowerCase() + if (search === '') return options + const starts: VirtualSelectOption_t[] = [] + const contains: VirtualSelectOption_t[] = [] + for (const option of options) { + const label = option.label.toLowerCase() + if (withoutLeadingSymbols(label).startsWith(withoutLeadingSymbols(search)) || label.startsWith(search)) starts.push(option) + else if (label.includes(search)) contains.push(option) + } + return [...starts, ...contains] +} diff --git a/src/components/session/N4LSessionButtons.tsx b/src/components/session/N4LSessionButtons.tsx new file mode 100644 index 0000000..194d740 --- /dev/null +++ b/src/components/session/N4LSessionButtons.tsx @@ -0,0 +1,39 @@ +import { useRef } from 'react' +import { Button } from 'react-bootstrap' +import { Trans } from 'react-i18next' + +import { downloadSession, type TrainingSession_t } from '@core/session/trainingSession' +import N4LShareSession from '@components/session/N4LShareSession' + +type N4LSessionButtonsProps = { + /** La configuración actual de la página: se exporta como fichero o se comparte con un enlace */ + getSession: () => TrainingSession_t + /** Recibe el texto del fichero elegido */ + onImport : (text: string) => void +} + +/** Exportar, importar y compartir la configuración (capas e hiperparámetros) de una página de entrenamiento */ +export default function N4LSessionButtons({ getSession, onImport }: N4LSessionButtonsProps) { + const input_ref = useRef(null) + + const handleChange_File = async (event: React.ChangeEvent) => { + const file = event.target.files?.[0] + // Se vacía para poder volver a elegir el mismo fichero + event.target.value = '' + if (file !== undefined) onImport(await file.text()) + } + + return ( + <> + + + + + + ) +} diff --git a/src/components/session/N4LShareSession.tsx b/src/components/session/N4LShareSession.tsx new file mode 100644 index 0000000..26d9148 --- /dev/null +++ b/src/components/session/N4LShareSession.tsx @@ -0,0 +1,121 @@ +import { useEffect, useId, useState } from 'react' +import { Button, Form, InputGroup, Modal } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import { sessionHash, type TrainingSession_t } from '@core/session/trainingSession' +import { trackEvent } from '@core/analytics' + +/** El código QR como un trazado SVG (un cuadrado por módulo oscuro), con el margen de 4 módulos que pide el estándar */ +type QR_t = { size: number, path: string } +const QUIET_ZONE = 4 + +async function makeQR(text: string): Promise { + const { default: qrcode } = await import('qrcode-generator') + try { + const qr = qrcode(0, 'L') + qr.addData(text) + qr.make() + const count = qr.getModuleCount() + let path = '' + for (let row = 0; row < count; row++) { + for (let col = 0; col < count; col++) { + if (qr.isDark(row, col)) path += `M${col + QUIET_ZONE},${row + QUIET_ZONE}h1v1h-1z` + } + } + return { size: count + QUIET_ZONE * 2, path } + } catch { + // Demasiado largo para un QR: queda el enlace + return null + } +} + +type N4LShareSessionProps = { + /** La configuración actual de la página (se lee al abrir) */ + getSession: () => TrainingSession_t +} + +/** + * Compartir el ejercicio: un enlace (y su QR, para abrirlo con el móvil) con la red y los hiperparámetros de la página. + * Quien lo abre los tiene listos para entrenar con el mismo conjunto de datos (useSharedSession). + */ +export default function N4LShareSession({ getSession }: N4LShareSessionProps) { + // El diálogo se llama como su título (WCAG 4.1.2) y su botón de cerrar, en el idioma de la página + const titleId = useId() + const { t } = useTranslation() + const prefix = 'session.share.' + const [link, setLink] = useState(null) + const [qr, setQR] = useState(undefined) + const [copied, setCopied] = useState(false) + + useEffect(() => { + if (link === null) return + let isCancelled = false + makeQR(link).then((value) => { if (!isCancelled) setQR(value) }) + return () => { isCancelled = true } + }, [link]) + + const handleClick_Open = async () => { + const url = new URL(window.location.href) + url.hash = await sessionHash(getSession()) + setLink(url.toString()) + setQR(undefined) + setCopied(false) + trackEvent('session_share', { action: 'open' }) + } + const handleClick_Copy = async () => { + if (link === null) return + try { + await navigator.clipboard.writeText(link) + setCopied(true) + trackEvent('session_share', { action: 'copy' }) + } catch { + // Sin permiso para el portapapeles: el enlace está seleccionable en el campo + } + } + const handleClick_Share = async () => { + if (link === null) return + try { + await navigator.share({ title: t(prefix + 'title'), url: link }) + trackEvent('session_share', { action: 'native' }) + } catch { + // Cancelado por el usuario + } + } + + return ( + <> + + setLink(null)} centered={true} data-testid={'Test-SessionShare-Modal'}> + + {t(prefix + 'title')} + + +

    {t(prefix + 'text')}

    + + event.target.select()} + data-testid={'Test-SessionShare-Link'} /> + + + {typeof navigator.share === 'function' && ( + + )} + {qr && ( +
    + + {/* Siempre oscuro sobre claro (también en el tema oscuro): así lo leen las cámaras */} + + + +
    {t(prefix + 'qr')}
    +
    + )} +
    +
    + + ) +} diff --git a/src/components/summary/N4LSummary.tsx b/src/components/summary/N4LSummary.tsx index ed58213..cad751f 100644 --- a/src/components/summary/N4LSummary.tsx +++ b/src/components/summary/N4LSummary.tsx @@ -1,25 +1,22 @@ +import { Suspense, useState } from 'react' +import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' -/** - * @typedef {Object} N4LSummaryProps - * @property {React.JSX.Element|string} title - * @property {React.JSX.Element|string} [info=<>] - * @property {React.ReactNode} [children=<>] - */ type N4LSummaryProps = { title : React.JSX.Element | string; info? : React.JSX.Element | string; children?: React.ReactNode; } -/** - * - * @param {N4LSummaryProps} N4LSummaryProps - * @returns + +/** + * Un apartado plegable (`
    `). Su contenido se monta la primera vez que se abre: cerrado no se ve, y así no se + * pinta (ni se descarga, si es perezoso) lo que quizá nunca se abra, como las tablas de Plotly de las descripciones. */ -export default function N4LSummary ({ title, info=<>, children=<> }: N4LSummaryProps) { - return <> -
    +export default function N4LSummary({ title, info = <>, children = <> }: N4LSummaryProps) { + const [opened, setOpened] = useState(false) + return ( +
    event.currentTarget.open && setOpened(true)}> {title} -
    {info} {children}
    +
    {opened && }>{info} {children}}
    - + ) } diff --git a/src/components/table/N4LPagination.tsx b/src/components/table/N4LPagination.tsx index e442877..80cfc08 100644 --- a/src/components/table/N4LPagination.tsx +++ b/src/components/table/N4LPagination.tsx @@ -1,35 +1,56 @@ +import type { ReactNode } from 'react' import { Pagination } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' type N4LPaginationProps = { activePage: number pageCount : number onChange : (page: number) => void className?: string + /** Nombre de la navegación; con varias tablas en la página, distinto en cada una (por defecto, «Páginas de la tabla») */ + label? : string } // Páginas que se muestran a cada lado de la actual const OFFSETS = [-3, -2, -1, 0, 1, 2, 3] -/** Paginación de las tablas: primera/anterior, tres páginas a cada lado de la actual y siguiente/última. */ -export default function N4LPagination({ activePage, pageCount, onChange, className = '' }: N4LPaginationProps) { +/** + * Paginación de las tablas: primera/anterior, hasta tres páginas a cada lado de la actual y siguiente/última. + * Las páginas se cuentan desde 0 por dentro y se enseñan desde 1. Con una sola página no se muestra. + * + * Las flechas son elementos normales y no Pagination.Next & cía.: estas traen su nombre para el lector de pantalla en + * inglés («Next») y no se puede cambiar. Va en un
    diff --git a/src/pages/playground/0_TabularClassification/TabularClassificationEditorHyperparameters.tsx b/src/pages/playground/0_TabularClassification/TabularClassificationEditorHyperparameters.tsx index 5754447..73e3938 100644 --- a/src/pages/playground/0_TabularClassification/TabularClassificationEditorHyperparameters.tsx +++ b/src/pages/playground/0_TabularClassification/TabularClassificationEditorHyperparameters.tsx @@ -1,25 +1,23 @@ -import { Link } from 'react-router' import { Trans } from 'react-i18next' import { Card } from 'react-bootstrap' -import { - DEFAULT_ID_LOSS, - DEFAULT_ID_METRICS, - DEFAULT_ID_OPTIMIZATION, - DEFAULT_LEARNING_RATE, - DEFAULT_NUMBER_EPOCHS, - DEFAULT_TEST_SIZE, -} from './CONSTANTS' import { VERBOSE } from '@/CONSTANTS' -import { HyperparameterNumber, HyperparameterSelect, LossOptions, MetricOptions, OptimizerOptions } from '@components/neural-network/N4LHyperparameterFields' +import { HyperparameterLearningRate, HyperparameterNumber, HyperparameterSelect, LossOptions, MetricOptions, OptimizerOptions } from '@components/neural-network/N4LHyperparameterFields' import { GLOSSARY_ACTIONS, MANUAL_ACTIONS } from '@/CONSTANTS_ACTIONS' import type { IdLoss_t, IdMetric_t, IdOptimizer_t } from '@/types/nn-types' import { useTabularClassificationContext } from '@context/useTabularClassificationContext' +import N4LHelpLink from '@components/helpLink/N4LHelpLink' export default function TabularClassificationEditorHyperparameters() { const { + learningRate, + numberEpochs, + testSize, + idOptimizer, + idLoss, + idMetrics, setLearningRate, setNumberEpochs, setTestSize, @@ -36,22 +34,22 @@ export default function TabularClassificationEditorHyperparameters() {

    - + + defaultValue={numberEpochs} onChange={setNumberEpochs} /> + defaultValue={testSize} onChange={setTestSize} /> setIdOptimizer(value as IdOptimizer_t)}> + defaultValue={idOptimizer} onChange={(value) => setIdOptimizer(value as IdOptimizer_t)}> setIdLoss(value as IdLoss_t)}> - + defaultValue={idLoss} onChange={(value) => setIdLoss(value as IdLoss_t)}> + setIdMetrics(value as IdMetric_t)}> + defaultValue={idMetrics} onChange={(value) => setIdMetrics(value as IdMetric_t)}> @@ -60,27 +58,14 @@ export default function TabularClassificationEditorHyperparameters() { , + link1: , }} />

    , + link1: , }} />

    diff --git a/src/pages/playground/0_TabularClassification/TabularClassificationEditorLayers.tsx b/src/pages/playground/0_TabularClassification/TabularClassificationEditorLayers.tsx index d2d7072..426b9ac 100644 --- a/src/pages/playground/0_TabularClassification/TabularClassificationEditorLayers.tsx +++ b/src/pages/playground/0_TabularClassification/TabularClassificationEditorLayers.tsx @@ -1,12 +1,18 @@ -import { useEffect } from 'react' -import { Link } from 'react-router' +import { useEffect, useMemo } from 'react' import { Trans, useTranslation } from 'react-i18next' import N4LEditorLayers from '@components/neural-network/N4LEditorLayers' +import { moveLayer } from '@components/neural-network/moveLayer' +import N4LDenseLayerFields from '@components/neural-network/N4LDenseLayerFields' +import { denseLayerSummary } from '@components/neural-network/layerSummary' import alertHelper from '@utils/alertHelper' import { VERBOSE } from '@/CONSTANTS' import { GLOSSARY_ACTIONS, MANUAL_ACTIONS } from '@/CONSTANTS_ACTIONS' import * as _Types from '@core/types' import { useTabularClassificationContext } from '@context/useTabularClassificationContext' +import N4LHelpLink from '@components/helpLink/N4LHelpLink' +import N4LLayerCheck from '@components/neural-network/N4LLayerCheck' +import { flaggedLayers } from '@components/neural-network/layerCheckText' +import { checkDenseLayers } from '@core/nn-utils/checkLayers' @@ -20,6 +26,9 @@ export default function TabularClassificationEditorLayers() { const { datasets, index: datasetIndex } = datasetsState const { t } = useTranslation() + const classes = datasets[datasetIndex]?.data_processed?.classes?.length ?? 0 + // La salida, una neurona por clase con softmax (sin datos procesados todavía no se sabe cuántas) + const issues = useMemo(() => checkDenseLayers(layers, classes > 0 ? { units: classes, activation: 'softmax' } : undefined), [layers, classes]) useEffect(() => { // La capa de salida tiene tantas unidades como clases (nuevo array: el estado no se modifica en el sitio) @@ -105,28 +114,27 @@ export default function TabularClassificationEditorLayers() { return ( denseLayerSummary(t, layer)} + renderFields={(layer, index) => ( + handleChange_Layer(changed, { + _class : layers[changed]._class, + units, + activation: activation || 'relu', + })} /> + )} + check={} + flagged={flaggedLayers(issues)} onAddStart={handlerClick_AddLayer_Start} onAddEnd={handlerClick_AddLayer_End} onRemove={handlerClick_RemoveLayer} - onChange={(index, layer) => handleChange_Layer(index, { - _class : layers[index]._class, - units : layer.units, - activation: layer.activation || 'relu', - })} + onMove={(from, to) => setLayers((current) => moveLayer(current, from, to))} + onRestore={setLayers} footer={<>

    , + link1: , }} />

    @@ -134,14 +142,7 @@ export default function TabularClassificationEditorLayers() { , + link1: , }} />

    } diff --git a/src/pages/playground/0_TabularClassification/TabularClassificationPage.tsx b/src/pages/playground/0_TabularClassification/TabularClassificationPage.tsx new file mode 100644 index 0000000..68b2496 --- /dev/null +++ b/src/pages/playground/0_TabularClassification/TabularClassificationPage.tsx @@ -0,0 +1,14 @@ +import { TabularClassificationProvider } from '@context/TabularClassificationContext' +import TabularClassification from './TabularClassification' + +/** + * La página de entrenamiento con su contexto. Va aparte para que el contexto (que importa danfo.js) se descargue con + * ella y no con el playground: las demás tareas no lo necesitan + */ +export default function TabularClassificationPage({ dataset }: { dataset: string }) { + return ( + + + + ) +} diff --git a/src/pages/playground/0_TabularClassification/TabularClassificationPrediction.tsx b/src/pages/playground/0_TabularClassification/TabularClassificationPrediction.tsx index 0bccb30..0f8aa93 100644 --- a/src/pages/playground/0_TabularClassification/TabularClassificationPrediction.tsx +++ b/src/pages/playground/0_TabularClassification/TabularClassificationPrediction.tsx @@ -1,17 +1,16 @@ +import { useMemo, useState } from 'react' import { Button, Card, Form } from 'react-bootstrap' import { Trans, useTranslation } from 'react-i18next' -import { Bar } from 'react-chartjs-2' import * as _tfjs from '@tensorflow/tfjs' import * as _Types from '@core/types' import { UPLOAD } from '@/TASKS' import { VERBOSE } from '@/CONSTANTS' -import { CHARTJS_CONFIG_DEFAULT } from '@/CONSTANTS_ChartsJs' import TabularClassificationPredictionForm from '@pages/playground/0_TabularClassification/TabularClassificationPredictionForm' import TabularClassificationDatasetShowInfo from '@pages/playground/0_TabularClassification/TabularClassificationDatasetShowInfo' -import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' -import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' -import type { BarOptions_t } from '@/types/types' +import N4LEmptyState from '@components/loading/N4LEmptyState' +import N4LClassificationChart from '@components/neural-network/N4LClassificationChart' +import N4LVirtualSelect, { type VirtualSelectOption_t } from '@components/select/N4LVirtualSelect' import { useTabularClassificationContext } from '@context/useTabularClassificationContext' type TabularClassificationPredictionProps_t = { @@ -35,50 +34,52 @@ export default function TabularClassificationPrediction(props: TabularClassifica setModel, setInputDataToPredict, predictionBar, + setPredictionBar, } = useTabularClassificationContext() const prefix = 'pages.playground.generator.dynamic-form-dataset.' const { t } = useTranslation() - const bar_options: BarOptions_t = { - responsive: true, - plugins : { - legend: { - position: 'top', - display : false, - }, - title: { - display: true, - text : t('prediction'), - }, - }, + // Fila del conjunto de datos cuyos valores se han copiado al formulario (null hasta elegir una) + const [selectedRow, setSelectedRow] = useState(null) + const [selectedRowDataset, setSelectedRowDataset] = useState(datasets.index) + // Otro conjunto de datos (al subir uno nuevo): la fila elegida era del anterior + if (selectedRowDataset !== datasets.index) { + setSelectedRowDataset(datasets.index) + setSelectedRow(null) } - const handleChange_ROW = (e: React.ChangeEvent) => { + const dataset_selected = datasets.datasets[datasets.index] + + // Una opción por fila: su número y su clase. Puede haber miles: el desplegable solo pinta las que se ven + const rowOptions = useMemo(() => { + const data_processed = dataset_selected?.data_processed + if (data_processed === undefined) return [] + const targets = dataset_selected.dataframe_original[data_processed.column_name_target].$data as Array + return targets.map((target, index) => ({ value: index, label: `#${index}: ${String(target)}` })) + }, [dataset_selected]) + + const handleChange_Row = (row_index: number) => { + setSelectedRow(row_index) const dataset_processed = datasets.datasets[datasets.index] const { data_processed, dataframe_original, dataset_transforms } = dataset_processed if (data_processed === undefined) { console.error('Error, data_processed is undefined') return } - const { column_name_target } = data_processed - const dataframe = DataFrameUtils.DataFrameDeepCopy(dataframe_original) - dataframe.drop({ columns: [column_name_target], inplace: true }) - for (const { column_name, column_transform } of dataset_transforms) { - if (column_transform === 'drop') { - dataframe.drop({ columns: [column_name], inplace: true }) - } - } - const row_index = parseInt(e.target.value) - - const df = dataframe.iloc({ rows: [row_index] }) - const dataframe_row_default_data = df.values[0] as _Types.N4LDataFrameType[] - setInputDataToPredict(dataframe_row_default_data) + // Solo esa fila y las columnas de entrada (sin la clase ni las descartadas): copiar el conjunto entero para leer una + // fila era lento con miles de ejemplos + const dropped = [data_processed.column_name_target, ...dataset_transforms.filter(({ column_transform }) => column_transform === 'drop').map(({ column_name }) => column_name)] + const row = dataframe_original.iloc({ rows: [row_index] }) + const columns = row.columns.filter((column) => !dropped.includes(column)) + setInputDataToPredict(row.loc({ columns }).values[0] as _Types.N4LDataFrameType[]) } const handleChange_Model = (e: React.ChangeEvent) => { const index: number = parseInt(e.target.value) setModel(generatedModels[index].model) setGeneratedModelsIndex(index) + // El resultado anterior era de otro modelo + setPredictionBar({ classes: [], labels: [], data: [] }) } const canRender_PredictDynamicForm = () => { @@ -94,9 +95,6 @@ export default function TabularClassificationPrediction(props: TabularClassifica } } - const dataset_selected = datasets.datasets[datasets.index] - - if (VERBOSE) console.debug('render TabularClassificationPrediction') return <> @@ -104,41 +102,32 @@ export default function TabularClassificationPrediction(props: TabularClassifica

    {generatedModelsIndex !== -1 && - <>| } + <>{' '}| }

    -
    +
    {(generatedModels.length !== 0 && dataset_selected && dataset_selected.is_dataset_processed) && <> - - + handleChange_ROW(e)}> - {((() => { - const { dataframe_original, data_processed } = dataset_selected - if (data_processed === undefined) { - console.error('Error, data_processed is undefined') - return [] - } - const { column_name_target } = data_processed - return dataframe_original[column_name_target].$data as Array - })()) - .map((target, index) => { - return - })} - - + label={t('pages.playground.generator.example-from-dataset')} + placeholder={t(prefix + 'selector-entity')} + searchPlaceholder={t(prefix + 'search-entity')} + noResultsText={t(prefix + 'no-entity')} + countText={(shown, total) => t(prefix + 'entity-count', { shown, total })} /> +
    } {generatedModels.length !== 0 && <> - + handleChange_Model(e)}> {generatedModels.map((_row, index) => { return })} @@ -149,7 +138,7 @@ export default function TabularClassificationPrediction(props: TabularClassifica {generatedModels.length === 0 && <> - + } @@ -170,7 +159,7 @@ export default function TabularClassificationPrediction(props: TabularClassifica variant={'primary'} size={'lg'} type={'submit'}> - +

    @@ -179,20 +168,8 @@ export default function TabularClassificationPrediction(props: TabularClassifica datasets={datasets} />
    - + {predictionBar.data.length === 0 && } + {predictionBar.data.length > 0 && } } diff --git a/src/pages/playground/0_TabularClassification/TabularClassificationPredictionForm.tsx b/src/pages/playground/0_TabularClassification/TabularClassificationPredictionForm.tsx index 7a0e9b5..331392f 100644 --- a/src/pages/playground/0_TabularClassification/TabularClassificationPredictionForm.tsx +++ b/src/pages/playground/0_TabularClassification/TabularClassificationPredictionForm.tsx @@ -147,7 +147,6 @@ export default function TabularClassificationPredictionForm() { {column_name} handleChange_Select(e, column_name, index)}> @@ -174,7 +173,6 @@ export default function TabularClassificationPredictionForm() { } default: - // console.warn('Error, option not valid', { attribute }) return

    {column_name}

    {column_type}

    diff --git a/src/pages/playground/0_TabularClassification/TabularClassificationTableModels.tsx b/src/pages/playground/0_TabularClassification/TabularClassificationTableModels.tsx index e696eff..ecea941 100644 --- a/src/pages/playground/0_TabularClassification/TabularClassificationTableModels.tsx +++ b/src/pages/playground/0_TabularClassification/TabularClassificationTableModels.tsx @@ -1,39 +1,58 @@ import { useMemo, useState } from 'react' import { Table, Card, Button, Container, Row, Col } from 'react-bootstrap' -import { Trans } from 'react-i18next' +import { Trans, useTranslation } from 'react-i18next' import * as tfvis from '@tensorflow/tfjs-vis' import { VERBOSE } from '@/CONSTANTS' import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' -import { parseLogs } from '@core/history/utils' +import N4LEmptyState from '@components/loading/N4LEmptyState' +import { bestModelIndex, formatEpochs } from '@core/history/trainingSummary' +import N4LFinalMetrics, { N4LBestBadge } from '@components/neural-network/N4LFinalMetrics' +import N4LTrainingCurves from '@components/neural-network/N4LTrainingCurves' +import N4LConfusionMatrix from '@components/neural-network/N4LConfusionMatrix' import { nnLabel } from '@core/nn-utils/ArchitectureTypesHelper' +import { layersSummary } from '@components/neural-network/layerSummary' import type { TabularClassificationGeneratedModel_t } from '@core/types' import N4LPagination from '@components/table/N4LPagination' import { useTabularClassificationContext } from '@context/useTabularClassificationContext' +import { useParams } from 'react-router' +import { TASKS } from '@/TASKS' +import N4LReportButton from '@components/report/N4LReportButton' +import N4LDownloadTrained from '@components/n4l/N4LDownloadTrained' +import { historyNumbers } from '@core/report/trainingReport' +import { denseLayerSummary } from '@components/neural-network/layerSummary' type TabularClassificationTableModelsProps_t = { rowsPerPage?: number, } export default function TabularClassificationTableModels(props: TabularClassificationTableModelsProps_t) { - const { rowsPerPage = 5 } = props - const { generatedModels: listModels, isTraining } = useTabularClassificationContext() + const { rowsPerPage = 5 } = props + const { generatedModels: listModels, isTraining, iModelInstance, datasets } = useTabularClassificationContext() + // Las clases en el orden de las salidas de los modelos (las del conjunto preparado), para descargarlos como .n4l + const classes = datasets.datasets[datasets.index]?.data_processed?.classes ?? [] const prefix = 'generator.table-models.' const [activePage, setActivePage] = useState(0) - // const [pageCount, setPageCount] = useState(0) - - // useEffect(() => { - // if (VERBOSE) console.debug('useEffect[listModels.length, rowsPerPage]') - // const rowsCount = listModels.length - // const pageCount = Math.ceil(rowsCount / rowsPerPage) - - // setPageCount(pageCount) - // }, [listModels.length, rowsPerPage]) const pageCount = useMemo( () => Math.ceil(listModels.length / rowsPerPage), [listModels.length, rowsPerPage] ); + // Historial de cada modelo (mismo orden que la tabla) y el de menor pérdida final, si hay con quién comparar + const histories = listModels.map((generated) => generated.history.history) + const bestIndex = histories.length > 1 ? bestModelIndex(histories) : -1 + // Para compararlos: lo que cambia de un entrenamiento a otro (las métricas solo se miden, no cambian cómo aprende) + const { t } = useTranslation() + const { example } = useParams() + const parameters = listModels.map((generated) => ({ + 'learning-rate': String(generated.learningRate), + 'n-of-epochs' : String(generated.numberOfEpoch), + 'test-size' : Math.round(generated.testSize * 100) + '%', + 'layers' : layersSummary(t, generated.layerList), + 'id-optimizer' : nnLabel(generated.idOptimizer), + 'id-loss' : nnLabel(generated.idLoss), + })) + const handleClick_ChangePage = (pageNumber: number) => { setActivePage(pageNumber) } @@ -53,18 +72,18 @@ export default function TabularClassificationTableModels(props: TabularClassific if (VERBOSE) console.debug('render TabularClassificationTableModels') return <> - +

    | {listModels.length}

    -
    +
    @@ -72,8 +91,7 @@ export default function TabularClassificationTableModels(props: TabularClassific {listModels.length === 0 && <> - - + } {listModels.length > 0 && <> @@ -101,10 +119,10 @@ export default function TabularClassificationTableModels(props: TabularClassific .slice(activePage * rowsPerPage, (activePage * rowsPerPage) + rowsPerPage) .map((value, index) => { return - {(activePage * rowsPerPage) + index + 1} - {value.learningRate * 100}% - {value.numberOfEpoch} - {value.testSize * 100}% + {(activePage * rowsPerPage) + index + 1}{(activePage * rowsPerPage) + index === bestIndex && } + {value.learningRate} + {formatEpochs(value.history.epoch.length, value.numberOfEpoch)} + {Math.round(value.testSize * 100)}% {value.layerList .map((value, index2) => { @@ -119,21 +137,30 @@ export default function TabularClassificationTableModels(props: TabularClassific {nnLabel(value.idLoss)} {nnLabel(value.idMetrics)} - {Object.entries(value.history.history) - .map(([key, logs], index2) => { - const logsArray = logs as Array - return - {key} {parseLogs(logsArray)}
    -
    - })} + + } + layers={value.layerList.map(({ units, activation }) => ({ class: 'dense', units, activation: activation ?? 'linear' }))} + number={(activePage * rowsPerPage) + index + 1} /> + ({ + version : 1, + task : TASKS.TABULAR_CLASSIFICATION, + dataset : example ?? '', + model : (activePage * rowsPerPage) + index + 1, + createdAt : new Date().toISOString(), + layers : value.layerList.map((layer) => denseLayerSummary(t, layer)), + parameters: parameters[(activePage * rowsPerPage) + index], + history : historyNumbers(value.history.history), + ...(value.evaluation !== undefined) && { evaluation: value.evaluation }, + })} /> })} @@ -149,6 +176,12 @@ export default function TabularClassificationTableModels(props: TabularClassific + + + listModels[index].evaluation !== undefined && } /> + +
    }
    diff --git a/src/pages/playground/0_TabularClassification/modelReviewGuide.ts b/src/pages/playground/0_TabularClassification/modelReviewGuide.ts new file mode 100644 index 0000000..0d67535 --- /dev/null +++ b/src/pages/playground/0_TabularClassification/modelReviewGuide.ts @@ -0,0 +1,45 @@ +import { TC_MODEL_KEYS } from '@/MODEL_KEYS' +import type { GuideStep_t } from '@components/guide/N4LGuide' +import { buildGuideSteps, centerStep, guideStep, type GuideTranslate_t } from '@components/guide/buildGuideSteps' + +/** + * Modelos con guía en su página de prueba (/playground/tabular-classification/model/). Sus textos van en + * guide.0-tabular-classification. y, lo que es igual en todos, en guide.0-tabular-classification.common. + * `fieldSteps`: un paso por atributo del formulario (fields.); si son muchos, uno para todo el formulario (form). + */ +const GUIDES: Record = { + [TC_MODEL_KEYS.CAR] : { fieldSteps: true }, + [TC_MODEL_KEYS.IRIS] : { fieldSteps: true }, + [TC_MODEL_KEYS.LYMPHOGRAPHY]: { fieldSteps: false }, +} + +export const TABULAR_REVIEW_GUIDES = Object.keys(GUIDES) + +/** + * Los pasos de la guía de la página de un modelo de clasificación tabular (null si no tiene): qué hace la página, el + * modelo, sus datos, el formulario, cómo se convierte en números, la clasificación y su explicación. Los elementos que + * señala llevan data-guide. + */ +export function tabularReviewGuide(t: GuideTranslate_t, modelKey: string, fields: string[], stepByStep = false): GuideStep_t[] | null { + const guide = GUIDES[modelKey] + if (guide === undefined) return null + return buildGuideSteps(t, 'guide.0-tabular-classification', modelKey, [ + centerStep('intro'), + guideStep('model', 'model'), + guideStep('model-summary', 'model-summary'), + guideStep('dataset', 'dataset'), + guideStep('dataset-processed', 'dataset-processed', 'bottom'), + guideStep('dataset-analysis', 'dataset-analysis', 'bottom'), + guideStep('instances', 'instances', 'bottom'), + ...(guide.fieldSteps + ? fields.map((field) => guideStep('fields.' + field, 'field-' + field, 'bottom')) + : [guideStep('form', 'form')]), + guideStep('vector', 'vector'), + guideStep('classify', 'classify'), + guideStep('result', 'result'), + guideStep('explain', 'explain'), + // Paso a paso, solo si se ha activado en /settings + ...(stepByStep ? [guideStep('step-by-step', 'step-by-step')] : []), + centerStep('end'), + ]) +} diff --git a/src/pages/playground/0_TabularClassification/models/MODEL_CAR.tsx b/src/pages/playground/0_TabularClassification/models/MODEL_CAR.tsx deleted file mode 100644 index 3e7c5cb..0000000 --- a/src/pages/playground/0_TabularClassification/models/MODEL_CAR.tsx +++ /dev/null @@ -1,243 +0,0 @@ -import * as tfjs from '@tensorflow/tfjs' -import { Trans } from 'react-i18next' -import * as dfd from 'danfojs' - -import * as _Types from '@core/types' -import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' -import I_MODEL_TABULAR_CLASSIFICATION, { type LoadModelCallbacks_t, type TabularFormField_t } from './_model' -import { F_FILTER_Categorical, F_MAP_LabelEncoder } from '@core/nn-utils/utils' -import { TC_MODEL_KEYS } from '@/MODEL_KEYS' - -export default class MODEL_CAR extends I_MODEL_TABULAR_CLASSIFICATION { - static KEY = TC_MODEL_KEYS.CAR - static URL = 'https://archive.ics.uci.edu/ml/datasets/Car+Evaluation' - TITLE = 'datasets-models.0-tabular-classification.car.title' - i18n_TITLE = 'datasets-models.0-tabular-classification.car.title' - CLASSES: string[] = [ - '00-tc.car.unacc', - '00-tc.car.acc', - '00-tc.car.good', - '00-tc.car.vgood' - ] - TABLE_HEADER: string[] = [ - '00-tc.car.buying', - '00-tc.car.maint', - '00-tc.car.doors', - '00-tc.car.persons', - '00-tc.car.lug_boot', - '00-tc.car.safety', - '00-tc.car.result' - ] - // @formatter:off - DATA_DEFAULT_KEYS = ['Buying', 'Maint', 'Doors', 'Persons', 'Lug_boot', 'Safety'] - DATA_DEFAULT = { - Buying : 'vhigh', - Maint : 'vhigh', - Doors : '2', - Persons : '2', - Lug_boot: 'small', - Safety : 'low' - } - LIST_EXAMPLES_RESULTS = [ - 'unacc', - 'acc', - 'good', - ] - LIST_EXAMPLES = [ - { Buying: 'low', Maint: 'vhigh', Doors: '4', Persons: '2', Lug_boot: 'small', Safety: 'low' }, - { Buying: 'med', Maint: 'low', Doors: '5more', Persons: 'more', Lug_boot: 'med', Safety: 'med' }, - { Buying: 'low', Maint: 'low', Doors: '5more', Persons: 'more', Lug_boot: 'big', Safety: 'high' } - ] - FORM: TabularFormField_t[] = [ - { - type : 'label-encoder', name : 'Buying', options: [ - { value: 'vhigh', text: 'vhigh' }, - { value: 'high', text: 'high' }, - { value: 'med', text: 'med' }, - { value: 'low', text: 'low' }, - ] - }, - { type: 'label-encoder', name: 'Maint', options: [{ value: 'vhigh', text: 'vhigh' }, { value: 'high', text: 'high' }, { value: 'med', text: 'med' }, { value: 'low', text: 'low' },] }, - { type: 'label-encoder', name: 'Doors', options: [{ value: '2', text: '2' }, { value: '3', text: '3' }, { value: '4', text: '4' }, { value: '5more', text: '5more' },] }, - { type: 'label-encoder', name: 'Persons', options: [{ value: '2', text: '2' }, { value: '4', text: '4' }, { value: 'more', text: 'more' },] }, - { type: 'label-encoder', name: 'Lug_boot', options: [{ value: 'small', text: 'small' }, { value: 'med', text: 'med' }, { value: 'big', text: 'big' },] }, - { type: 'label-encoder', name: 'Safety', options: [{ value: 'low', text: 'low' }, { value: 'med', text: 'med' }, { value: 'high', text: 'high' },] }, - ] - // @formatter:on - - DESCRIPTION() { - const prefix = 'datasets-models.0-tabular-classification.car.description.' - return <> -

    -

    - link, - }} - /> -

    -
    - -
      -
    1. -
    2. -
    3. -
    4. -
    5. -
    -
    -
    - -

    -
      -
    1. -
    2. -
    3. -
    4. -
    5. -
    -
    -
    - -

    -
      -
    1. -
    2. -
    3. -
    4. -
    -
    -
    - -
      -
    1. - - - -
    2. -
    -
    -
    - BibTeX -
    -          {`
    -@misc{misc_car_evaluation_19,
    -  author       = {Bohanec,Marko},
    -  title        = {{Car Evaluation}},
    -  year         = {1997},
    -  howpublished = {UCI Machine Learning Repository},
    -  note         = {{DOI}: https://doi.org/10.24432/C5JP48}
    -}
    -`}
    -        
    -
    - - } - - async DATASETS(): Promise<_Types.DatasetProcessed_t[]> { - const path_dataset = import.meta.env.VITE_PATH + '/models/00-tabular-classification/car/' - const car_info = 'car.names' - const car_csv = 'car.csv' - - const dataset_promise_info = await fetch(path_dataset + car_info) - const car_container_info = await dataset_promise_info.text() - - const dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_dataset + car_csv) - let dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_dataset + car_csv) - /** @type {_Types.Dataset_t} */ - const dataset: _Types.Dataset_t = [ - { column_name: 'Buying', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'Maint', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'Doors', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'Persons', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'Lug_boot', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'Safety', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'Result', column_role: 'Target', column_type: 'Categorical', column_missing_values: false }, - ] - /** @type {Array<_Types.DataFrameColumnTransform_t>} */ - const dataset_transforms = [ - ...dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder) - ] - const car_target = 'Result' - const car_encoders_map = DataFrameUtils.DataFrameEncoder(dataframe_original, dataset_transforms) - dataframe_processed = DataFrameUtils.DataFrameTransform(dataframe_processed, dataset_transforms) - - const car_dataframe_X = dataframe_processed.drop({ columns: [car_target] }) - const car_dataframe_y = dataframe_original[car_target] - const minMaxScaler = new dfd.MinMaxScaler() - const car_minMaxScaler = minMaxScaler.fit(car_dataframe_X) - const car_X = car_minMaxScaler.transform(car_dataframe_X) - const oneHotEncoder = new dfd.OneHotEncoder() - const car_oneHotEncoder = oneHotEncoder.fit(car_dataframe_y) - const car_y = car_oneHotEncoder.transform(car_dataframe_y) - const labelEncoder = new dfd.LabelEncoder() - const car_labelEncoder = labelEncoder.fit(car_dataframe_y.values) - const car_classes = Object.keys(car_labelEncoder.classes) - - const item: _Types.DatasetProcessed_t = { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_dataset, - info : car_info, - container_info : car_container_info, - csv : car_csv, - dataset : dataset, - dataset_transforms : dataset_transforms, - dataframe_original : dataframe_original, - dataframe_processed : dataframe_processed, - data_processed : { - dataframe_X : car_dataframe_X, - dataframe_y : car_dataframe_y, - X : car_X, - y : car_y, - scaler : car_minMaxScaler, - encoders : car_encoders_map, - column_name_target: car_target, - classes : car_classes, - // @formatter:off - attributes : [ - { type: 'label-encoder', name: 'Buying', options: [{ value: 'vhigh', text: 'vhigh' }, { value: 'high', text: 'high' }, { value: 'med', text: 'med' }, { value: 'low', text: 'low' }] }, - { type: 'label-encoder', name: 'Maint', options: [{ value: 'vhigh', text: 'vhigh' }, { value: 'high', text: 'high' }, { value: 'med', text: 'med' }, { value: 'low', text: 'low' }] }, - { type: 'label-encoder', name: 'Doors', options: [{ value: '2', text: '2' }, { value: '3', text: '3' }, { value: '4', text: '4' }, { value: '5more', text: '5more' }] }, - { type: 'label-encoder', name: 'Persons', options: [{ value: '2', text: '2' }, { value: '4', text: '4' }, { value: 'more', text: 'more' }] }, - { type: 'label-encoder', name: 'Lug_boot', options: [{ value: 'small', text: 'small' }, { value: 'med', text: 'med' }, { value: 'big', text: 'big' }] }, - { type: 'label-encoder', name: 'Safety', options: [{ value: 'low', text: 'low' }, { value: 'med', text: 'med' }, { value: 'high', text: 'high' }] } - ], - // @formatter:on - - } - } - return [ - item - ] - } - - - async LOAD_LAYERS_MODEL(callbacks: LoadModelCallbacks_t) { - return await tfjs.loadLayersModel(import.meta.env.VITE_PATH + '/models/00-tabular-classification/car/my-model-car.json', { - onProgress: callbacks.onProgress, - }) - } - - DEFAULT_LAYERS(): _Types.Layer_t[] { - return [ - // { units: 10, activation: 'sigmoid' }, - { _class: 'dense', units: 128, activation: 'relu' }, - { _class: 'dense', units: 64, activation: 'relu' }, - { _class: 'dense', units: 32, activation: 'relu' }, - { _class: 'dense', units: 4, activation: 'softmax' }, - ] - } - - HTML_EXAMPLE() { - const prefix = 'datasets-models.0-tabular-classification.car.html-example.' - return (<> -

    -
    - -

    - ) - } -} diff --git a/src/pages/playground/0_TabularClassification/models/MODEL_IRIS.tsx b/src/pages/playground/0_TabularClassification/models/MODEL_IRIS.tsx deleted file mode 100644 index 1092651..0000000 --- a/src/pages/playground/0_TabularClassification/models/MODEL_IRIS.tsx +++ /dev/null @@ -1,201 +0,0 @@ -import { Trans } from 'react-i18next' -import * as tfjs from '@tensorflow/tfjs' -import * as dfd from 'danfojs' - -import * as _Types from '@core/types' -import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' -import { F_FILTER_Categorical, F_MAP_LabelEncoder } from '@core/nn-utils/utils' -import I_MODEL_TABULAR_CLASSIFICATION, { type LoadModelCallbacks_t, type TabularFormField_t } from './_model' -import { TC_MODEL_KEYS } from '@/MODEL_KEYS' - -export default class MODEL_IRIS extends I_MODEL_TABULAR_CLASSIFICATION { - - static KEY = TC_MODEL_KEYS.IRIS - static URL = 'https://archive.ics.uci.edu/ml/datasets/iris' - static URL_MODEL = '/public/models/classification/iris/my-model-iris.json' - TITLE = 'datasets-models.0-tabular-classification.iris.title' - i18n_TITLE = 'datasets-models.0-tabular-classification.iris.title' - - // region ATTR - DATA_DEFAULT_KEYS = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'] - DATA_DEFAULT = { - sepal_length: 5.1, - sepal_width : 3.5, - petal_length: 1.4, - petal_width : 0.2 - } - FORM: TabularFormField_t[] = [ - { type: 'float32', name: 'sepal_length' }, - { type: 'float32', name: 'sepal_width' }, - { type: 'float32', name: 'petal_length' }, - { type: 'float32', name: 'petal_width' }, - ] - LIST_EXAMPLES = [ - { sepal_length: 5.1, sepal_width: 3.5, petal_length: 1.4, petal_width: 0.2 }, - { sepal_length: 6.1, sepal_width: 3.0, petal_length: 4.6, petal_width: 1.4 }, - { sepal_length: 5.8, sepal_width: 2.7, petal_length: 5.1, petal_width: 1.9 }, - ] - LIST_EXAMPLES_RESULTS: string[] = [ - '0 Iris-setosa', - '1 Iris-versicolor', - '2 Iris-virginica', - ] - - CLASSES: string[] = [ - '00-tc.iris.Iris-setosa', - '00-tc.iris.Iris-versicolor', - '00-tc.iris.Iris-virginica', - ] - TABLE_HEADER: string[] = [ - '00-tc.iris.sepal_length', - '00-tc.iris.sepal_width', - '00-tc.iris.petal_length', - '00-tc.iris.petal_width', - '00-tc.iris.class' - ] - - // endregion - - DESCRIPTION() { - const prefix = 'datasets-models.0-tabular-classification.iris.description.' - return <> -

    -
    - -
      -
    1. -
    2. -
    3. -
    4. -
    -
    -
    - -
      -
    1. -
    2. -
    3. -
    -
    -
    - -
      -
    1. - - - -
    2. -
    -
    -
    - BibTeX -
    -          {`
    -@misc{misc_iris_53,
    -  author       = {Fisher,R. A.},
    -  title        = {{Iris}},
    -  year         = {1988},
    -  howpublished = {UCI Machine Learning Repository},
    -  note         = {{DOI}: https://doi.org/10.24432/C56C76}
    -}
    -`}
    -        
    -
    - - } - - async DATASETS(): Promise<_Types.DatasetProcessed_t[]> { - const path_dataset = import.meta.env.VITE_PATH + '/models/00-tabular-classification/iris/' - const iris_info = 'iris.names' - const iris_csv = 'iris.csv' - const dataset_promise_info = await fetch(path_dataset + iris_info) - const iris_container_info = await dataset_promise_info.text() - const dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_dataset + iris_csv) - let dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_dataset + iris_csv) - /** @type {_Types.Dataset_t} */ - const dataset: _Types.Dataset_t = [ - { column_name: 'sepal length', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'sepal width', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'petal length', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'petal width', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'class', column_role: 'Target', column_type: 'Categorical', column_missing_values: false }, - ] - /** @type {_Types.DataFrameColumnTransform_t[]} */ - const dataset_transforms = [ - ...dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder) - // { column_transform: 'label-encoder', column_name: 'class' }, - ] - const iris_encoders_map = DataFrameUtils.DataFrameEncoder(dataframe_original, dataset_transforms) - dataframe_processed = DataFrameUtils.DataFrameTransform(dataframe_processed, dataset_transforms) - const iris_target = 'class' - const iris_dataframe_X = dataframe_processed.drop({ columns: [iris_target] }) - const iris_dataframe_y = dataframe_original[iris_target] - const minMaxScaler = new dfd.MinMaxScaler() - const iris_minMaxScaler = minMaxScaler.fit(iris_dataframe_X) - const iris_X = iris_minMaxScaler.transform(iris_dataframe_X) - const oneHotEncoder = new dfd.OneHotEncoder() - const iris_oneHotEncoder = oneHotEncoder.fit(iris_dataframe_y) - const iris_y = iris_oneHotEncoder.transform(iris_dataframe_y) - const labelEncoder = new dfd.LabelEncoder() - const iris_labelEncoder = labelEncoder.fit(iris_dataframe_y.values) - const iris_classes = Object.keys(iris_labelEncoder.classes) - const item: _Types.DatasetProcessed_t = { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_dataset, - info : iris_info, - container_info : iris_container_info, - csv : iris_csv, - dataset : dataset, - dataframe_original : dataframe_original, - dataframe_processed : dataframe_processed, - dataset_transforms : dataset_transforms, - data_processed : { - dataframe_X : iris_dataframe_X, - dataframe_y : iris_dataframe_y, - X : iris_X, - y : iris_y, - encoders : iris_encoders_map, - scaler : iris_minMaxScaler, - column_name_target: iris_target, - classes : iris_classes, - attributes : [ - // @formatter:off - { type: 'float32', name: 'sepal_length', options: [] }, - { type: 'float32', name: 'sepal_width', options: [] }, - { type: 'float32', name: 'petal_length', options: [] }, - { type: 'float32', name: 'petal_width', options: [] }, - // @formatter:on - ], - }, - } - return [ - item - ] - } - - - async LOAD_LAYERS_MODEL(callbacks: LoadModelCallbacks_t) { - return await tfjs.loadLayersModel(import.meta.env.VITE_PATH + '/models/00-tabular-classification/iris/my-model-iris.json', { - onProgress: callbacks.onProgress - }) - } - - DEFAULT_LAYERS(): _Types.Layer_t[] { - return [ - { _class: 'dense', units: 10, activation: 'relu' }, - { _class: 'dense', units: 10, activation: 'relu' }, - { _class: 'dense', units: 3, activation: 'softmax' }, - ] - } - - HTML_EXAMPLE() { - const prefix = 'datasets-models.0-tabular-classification.iris.html-example.' - return <> -

    -
    - -

    - - } -} diff --git a/src/pages/playground/0_TabularClassification/models/MODEL_LYMPHOGRAPHY.tsx b/src/pages/playground/0_TabularClassification/models/MODEL_LYMPHOGRAPHY.tsx deleted file mode 100644 index 999e5a9..0000000 --- a/src/pages/playground/0_TabularClassification/models/MODEL_LYMPHOGRAPHY.tsx +++ /dev/null @@ -1,364 +0,0 @@ -import * as tfjs from '@tensorflow/tfjs' -import { Trans } from 'react-i18next' -import * as dfd from 'danfojs' - -import * as _Types from '@core/types' -import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' -import { F_FILTER_Categorical, F_MAP_LabelEncoder } from '@core/nn-utils/utils' -import I_MODEL_TABULAR_CLASSIFICATION, { type LoadModelCallbacks_t, type TabularFormField_t } from './_model' -import { TC_MODEL_KEYS } from '@/MODEL_KEYS' - -export default class MODEL_LYMPHOGRAPHY extends I_MODEL_TABULAR_CLASSIFICATION { - static KEY = TC_MODEL_KEYS.LYMPHOGRAPHY - static URL = 'https://archive.ics.uci.edu/ml/datasets/Lymphography' - TITLE = 'datasets-models.0-tabular-classification.lymphography.title' - i18n_TITLE = 'datasets-models.0-tabular-classification.lymphography.title' - URL_DATASET = 'https://archive.ics.uci.edu/dataset/63/lymphography' - - // region ATTR - // En el orden de las salidas del modelo: el OneHotEncoder de danfo numera las clases por orden de - // aparición en lymphography.csv (3, 2, 4, 1), no de 1 a 4. - CLASSES: string[] = [ - '00-tc.lymphography.malign lymph', - '00-tc.lymphography.metastases', - '00-tc.lymphography.fibrosis', - '00-tc.lymphography.normal find', - ] - TABLE_HEADER: string[] = [ - '00-tc.lymphography.lymphatics', - '00-tc.lymphography.block of affere', - '00-tc.lymphography.bl. of lymph. c', - '00-tc.lymphography.bl. of lymph. s', - '00-tc.lymphography.by pass', - '00-tc.lymphography.extravasates', - '00-tc.lymphography.regeneration', - '00-tc.lymphography.early uptake in', - '00-tc.lymphography.lym.nodes dimin', - '00-tc.lymphography.lym.nodes enlar', - '00-tc.lymphography.changes in lym', - '00-tc.lymphography.defect in node', - '00-tc.lymphography.changes in node', - '00-tc.lymphography.changes in stru', - '00-tc.lymphography.special forms', - '00-tc.lymphography.dislocation of', - '00-tc.lymphography.exclusion of', - '00-tc.lymphography.no. of nodes in', - '00-tc.lymphography.Category', - ] - - DATA_DEFAULT = { - // 4 -> fibrosis - 'lymphatics' : '3', - 'block of affere': '1', - 'bl. of lymph. c': '1', - 'bl. of lymph. s': '1', - 'by pass' : '1', - 'extravasates' : '2', - 'regeneration of': '2', - 'early uptake in': '1', - 'lym.nodes dimin': '3', - 'lym.nodes enlar': '1', - 'changes in lym.': '1', - 'defect in node' : '2', - 'changes in node': '1', - 'changes in stru': '4', - 'special forms' : '2', - 'dislocation of' : '1', - 'exclusion of no': '1', - 'no. of nodes in': '7', - } - DATA_DEFAULT_KEYS = [ - 'lymphatics', - 'block of affere', - 'bl. of lymph. c', - 'bl. of lymph. s', - 'by pass', - 'extravasates', - 'regeneration of', - 'early uptake in', - 'lym.nodes dimin', - 'lym.nodes enlar', - 'changes in lym.', - 'defect in node', - 'changes in node', - 'changes in stru', - 'special forms', - 'dislocation of', - 'exclusion of no', - 'no. of nodes in', - ] - LIST_EXAMPLES_RESULTS = [ - 'normal', - 'metastasis', - 'malign lymph', - 'fibrosis', - ] - LIST_EXAMPLES = [ - // Normal - { - 'lymphatics' : '1', - 'block of affere': '1', - 'bl. of lymph. c': '1', - 'bl. of lymph. s': '1', - 'by pass' : '1', - 'extravasates' : '2', - 'regeneration of': '1', - 'early uptake in': '2', - 'lym.nodes dimin': '1', - 'lym.nodes enlar': '2', - 'changes in lym.': '2', - 'defect in node' : '1', - 'changes in node': '1', - 'changes in stru': '1', - 'special forms' : '1', - 'dislocation of' : '1', - 'exclusion of no': '1', - 'no. of nodes in': '2' - }, - // metastasis (fila 54 de lymphography.csv) - { - 'lymphatics' : '2', - 'block of affere': '2', - 'bl. of lymph. c': '2', - 'bl. of lymph. s': '1', - 'by pass' : '2', - 'extravasates' : '2', - 'regeneration of': '1', - 'early uptake in': '1', - 'lym.nodes dimin': '1', - 'lym.nodes enlar': '2', - 'changes in lym.': '2', - 'defect in node' : '3', - 'changes in node': '3', - 'changes in stru': '4', - 'special forms' : '2', - 'dislocation of' : '1', - 'exclusion of no': '2', - 'no. of nodes in': '1' - }, - // malign lymph - { - 'lymphatics' : '2', - 'block of affere': '1', - 'bl. of lymph. c': '1', - 'bl. of lymph. s': '1', - 'by pass' : '1', - 'extravasates' : '2', - 'regeneration of': '1', - 'early uptake in': '2', - 'lym.nodes dimin': '1', - 'lym.nodes enlar': '3', - 'changes in lym.': '3', - 'defect in node' : '4', - 'changes in node': '2', - 'changes in stru': '7', - 'special forms' : '3', - 'dislocation of' : '2', - 'exclusion of no': '2', - 'no. of nodes in': '3' - }, - // fibrosis - { - 'lymphatics' : '3', - 'block of affere': '1', - 'bl. of lymph. c': '1', - 'bl. of lymph. s': '1', - 'by pass' : '1', - 'extravasates' : '2', - 'regeneration of': '2', - 'early uptake in': '1', - 'lym.nodes dimin': '3', - 'lym.nodes enlar': '1', - 'changes in lym.': '1', - 'defect in node' : '2', - 'changes in node': '1', - 'changes in stru': '4', - 'special forms' : '2', - 'dislocation of' : '1', - 'exclusion of no': '1', - 'no. of nodes in': '7' - }, - ] - // @formatter:off - FORM: TabularFormField_t[] = [ - { type: 'label-encoder', name: 'lymphatics', options: [{ value: '1', text: 'normal' }, { value: '2', text: 'arched' }, { value: '3', text: 'deformed' }, { value: '4', text: 'displaced' }]}, - { type: 'label-encoder', name: 'block of affere', options: [{ value: '1', text: 'No' }, { value: '2', text: '2' }]}, - { type: 'label-encoder', name: 'bl. of lymph. c', options: [{ value: '1', text: 'No' }, { value: '2', text: 'Yes' }]}, - { type: 'label-encoder', name: 'bl. of lymph. s', options: [{ value: '1', text: 'No' }, { value: '2', text: 'Yes' }]}, - { type: 'label-encoder', name: 'by pass', options: [{ value: '1', text: 'No' }, { value: '2', text: 'Yes' }]}, - { type: 'label-encoder', name: 'extravasates', options: [{ value: '1', text: 'No' }, { value: '2', text: 'Yes' }]}, - { type: 'label-encoder', name: 'regeneration of', options: [{ value: '1', text: 'No' }, { value: '2', text: 'Yes' }]}, - { type: 'label-encoder', name: 'early uptake in', options: [{ value: '1', text: 'No' }, { value: '2', text: 'Yes' }]}, - { type: 'label-encoder', name: 'lym.nodes dimin', options: [{ value: '1', text: '1' }, { value: '2', text: '2' }, { value: '3', text: '3' }]}, - { type: 'label-encoder', name: 'lym.nodes enlar', options: [{ value: '1', text: '1' }, { value: '2', text: '2' }, { value: '3', text: '3' }, { value: '4', text: '4' }]}, - { type: 'label-encoder', name: 'changes in lym.', options: [{ value: '1', text: 'bean' }, { value: '2', text: 'oval' }, { value: '3', text: 'round' }]}, - { type: 'label-encoder', name: 'defect in node', options: [{ value: '1', text: 'No' }, { value: '2', text: 'lacunar' }, { value: '3', text: 'lac. marginal' }, { value: '4', text: 'lac. central' }]}, - { type: 'label-encoder', name: 'changes in node', options: [{ value: '1', text: 'No' }, { value: '2', text: 'lacunar' }, { value: '3', text: 'lac. marginal' }, { value: '4', text: 'lac. central' }]}, - { type: 'label-encoder', name: 'changes in stru', options: [{ value: '1', text: 'No' }, { value: '2', text: 'grainy' }, { value: '3', text: 'drop-like' }, { value: '4', text: 'coarse' }, { value: '5', text: 'diluted' }, { value: '6', text: 'reticular' }, { value: '7', text: 'stripped' }, { value: '8', text: 'faint' }]}, - { type: 'label-encoder', name: 'special forms', options: [{ value: '1', text: 'No' }, { value: '2', text: 'chalices' }, { value: '3', text: 'vesicles' }]}, - { type: 'label-encoder', name: 'dislocation of', options: [{ value: '1', text: 'No' }, { value: '2', text: 'Yes' }]}, - { type: 'label-encoder', name: 'exclusion of no', options: [{ value: '1', text: 'No' }, { value: '2', text: 'Yes' }]}, - { type: 'label-encoder', name: 'no. of nodes in', options: [{ value: '1', text: '0-9' }, { value: '2', text: '10-19' }, { value: '3', text: '20-29' }, { value: '4', text: '30-39' }, { value: '5', text: '40-49' }, { value: '6', text: '50-59' }, { value: '7', text: '60-69' }, { value: '8', text: '=>70' }]} - ] - // @formatter:on - // endregion - - DESCRIPTION () { - const prefix = 'datasets-models.0-tabular-classification.lymphography.description.' - return <> -

    -
    - -
      - {Array - .from({ length: 17 }) - .map((_, i) =>
    1. )} -
    -
    -
    - -
      - {Array - .from({ length: 4 }) - .map((_, i) =>
    1. )} -
    -
    -
    - - - -
      -
    1. - - - -
    2. -
    -
    -
    - BibTeX -
    -{`
    -@misc{misc_lymphography_63,
    -  author       = {Zwitter,M. and Soklic,M.},
    -  title        = {{Lymphography}},
    -  year         = {1988},
    -  howpublished = {UCI Machine Learning Repository},
    -  note         = {{DOI}: https://doi.org/10.24432/C54598}
    -}
    -`}
    -        
    -
    - - } - - /** - * - * @returns {Promise<_Types.DatasetProcessed_t[]>} - */ - async DATASETS(): Promise<_Types.DatasetProcessed_t[]> { - const path_dataset = import.meta.env.VITE_PATH + '/models/00-tabular-classification/lymphography/' - const lymphography_info = 'lymphography.names' - const lymphography_csv = 'lymphography.csv' - const lymphography_promise_info = await fetch(path_dataset + lymphography_info) - const lymphography_container_info = await lymphography_promise_info.text() - const dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_dataset + lymphography_csv) - let dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_dataset + lymphography_csv) - /** @type {_Types.Dataset_t} */ - // Todos los atributos son categóricos (códigos 1..n): el modelo preentrenado recibe cada columna - // codificada con LabelEncoder, igual que aquí. - const dataset: _Types.Dataset_t = [ - { column_name: 'lymphatics', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'block of affere', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'bl. of lymph. c', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'bl. of lymph. s', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'by pass', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'extravasates', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'regeneration of', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'early uptake in', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'lym.nodes dimin', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'lym.nodes enlar', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'changes in lym.', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'defect in node', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'changes in node', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'changes in stru', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'special forms', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'dislocation of', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'exclusion of no', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'no. of nodes in', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'class', column_role: 'Target', column_type: 'Integer', column_missing_values: false }, - ] - /** @type {_Types.DataFrameColumnTransform_t[]} */ - const dataset_transforms = [ - ...dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder), - ] - const lymphography_encoders = DataFrameUtils.DataFrameEncoder(dataframe_original, dataset_transforms) - dataframe_processed = DataFrameUtils.DataFrameTransform(dataframe_processed, dataset_transforms) - const lymphography_target = 'class' - const lymphography_dataframe_X = dataframe_processed.drop({ columns: [lymphography_target] }) - const lymphography_dataframe_y = dataframe_original[lymphography_target] - const minMaxScaler = new dfd.MinMaxScaler() - const lymphography_minMaxScaler = minMaxScaler.fit(lymphography_dataframe_X) - const lymphography_X = lymphography_minMaxScaler.transform(lymphography_dataframe_X) - const oneHotEncoder = new dfd.OneHotEncoder() - const lymphography_oneHotEncoder = oneHotEncoder.fit(lymphography_dataframe_y) - const lymphography_y = lymphography_oneHotEncoder.transform(lymphography_dataframe_y) - const labelEncoder = new dfd.LabelEncoder() - const lymphography_labelEncoder = labelEncoder.fit(lymphography_dataframe_y.values) - const lymphography_classes = Object.keys(lymphography_labelEncoder.classes) - - return [ - { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_dataset, - info : lymphography_info, - container_info : lymphography_container_info, - csv : lymphography_csv, - dataset : dataset, - dataset_transforms : dataset_transforms, - dataframe_original : dataframe_original, - dataframe_processed : dataframe_processed, - data_processed : { - dataframe_X : lymphography_dataframe_X, - dataframe_y : lymphography_dataframe_y, - X : lymphography_X, - y : lymphography_y, - scaler : lymphography_minMaxScaler, - encoders : lymphography_encoders, - column_name_target: lymphography_target, - classes : lymphography_classes, - attributes : this.FORM, - }, - } - ] - } - - - async LOAD_LAYERS_MODEL(callbacks: LoadModelCallbacks_t) { - return await tfjs.loadLayersModel(import.meta.env.VITE_PATH + '/models/00-tabular-classification/lymphography/my-model-lymphography.json', { - onProgress: callbacks.onProgress, - }) - } - - DEFAULT_LAYERS (): _Types.Layer_t[] { - return [ - { _class: 'dense', units: 18, activation: 'sigmoid' }, - { _class: 'dense', units: 10, activation: 'relu' }, - { _class: 'dense', units: 10, activation: 'relu' }, - { _class: 'dense', units: 4, activation: 'softmax' }, - ] - } - - HTML_EXAMPLE () { - const prefix = 'datasets-models.0-tabular-classification.lymphography.html-example.' - return <> -

    -
    - -

    - - } -} diff --git a/src/pages/playground/0_TabularClassification/models/MODEL_N4L.tsx b/src/pages/playground/0_TabularClassification/models/MODEL_N4L.tsx new file mode 100644 index 0000000..7597203 --- /dev/null +++ b/src/pages/playground/0_TabularClassification/models/MODEL_N4L.tsx @@ -0,0 +1,86 @@ +import { Trans } from 'react-i18next' +import type { TFunction } from 'i18next' + +import * as _Types from '@core/types' +import { TASKS } from '@/TASKS' +import { denseLayers, n4lLabelKey, n4lLayersModels, n4lTablePrediction, n4lTaskText, n4lTableView, type N4LDataset_t, type N4LTaskView_t } from '@core/n4l/format' +import type { N4LPackage_t } from '@core/n4l/source' +import { loadN4LLayersModel } from '@core/n4l/tfjsModel' +import { prepareTabularClassification, tabularClassIndex, tabularFields } from '@core/n4l/tabularClassification' +import { N4LError } from '@core/n4l/validate' +import N4LPackageDescription from '@components/n4l/N4LPackageDescription' +import I_MODEL_TABULAR_CLASSIFICATION, { type LoadModelCallbacks_t, type TabularFormField_t } from './_model' + +/** + * Un modelo de clasificación tabular de un paquete .n4l: todo lo que antes escribía a mano cada clase (MODEL_IRIS…) + * sale de su manifiesto (su sección de clasificación tabular) y sus textos. Cumple la misma interfaz, así que las + * páginas no cambian + */ +export default class MODEL_N4L extends I_MODEL_TABULAR_CLASSIFICATION { + readonly pkg : N4LPackage_t + readonly view: N4LTaskView_t + + constructor(t: TFunction<'translation', undefined>, callbacks: () => void, pkg: N4LPackage_t) { + super(t, callbacks) + const view = n4lTableView(pkg.manifest, TASKS.TABULAR_CLASSIFICATION) + if (view === undefined) throw new N4LError(pkg.manifest.id, ['no tiene la tarea tabular-classification']) + this.pkg = pkg + this.view = view + const { section, dataset } = view + const ns = pkg.namespace + const texts = n4lTaskText(ns, section.task) + const prediction = n4lTablePrediction(section) + const examples = prediction?.examples ?? [] + this.KEY = section.key + this.TITLE = texts + 'title' + this.i18n_TITLE = texts + 'title' + this.CLASSES = (section.classes ?? []).map(({ id }) => `${ns}:classes.${n4lLabelKey(id)}`) + // Las de entrada y el objetivo, en el orden del conjunto de datos + this.TABLE_HEADER = dataset.columns.filter(({ role }) => role === 'Feature' || role === 'Target').map(({ name }) => `${ns}:columns.${n4lLabelKey(name)}`) + this.DATA_DEFAULT_KEYS = dataset.columns.filter(({ role }) => role === 'Feature').map(({ name }) => name) + this.DATA_DEFAULT = prediction?.defaults ?? {} + this.LIST_EXAMPLES = examples.map(({ values }) => values) + this.LIST_EXAMPLES_RESULTS = examples.map(({ expected }) => expected) + this.FORM = tabularFields(view, ns, t) as TabularFormField_t[] + } + + N4L_PACKAGE() { + return this.pkg + } + + MODEL_INPUT() { + return n4lLayersModels(this.view.section)[0]?.input ?? 'encoded' + } + + CLASS_INDEX(target: unknown): number { + const index = tabularClassIndex(this.view.section, target) + return index !== -1 ? index : super.CLASS_INDEX(target) + } + + DESCRIPTION() { + return + } + + async DATASETS(): Promise<_Types.DatasetProcessed_t[]> { + return prepareTabularClassification(this.pkg, this.view, this.FORM) + } + + async LOAD_LAYERS_MODEL(callbacks: LoadModelCallbacks_t) { + const [model] = n4lLayersModels(this.view.section) + return model === undefined ? null : loadN4LLayersModel(this.pkg.source, model.path, callbacks.onProgress) + } + + DEFAULT_LAYERS(): _Types.Layer_t[] { + return denseLayers(this.view.section.training?.layers).map(({ class: _class, units, activation }) => ({ _class, units, activation })) + } + + HTML_EXAMPLE() { + const texts = n4lTaskText(this.pkg.namespace, this.view.section.task) + return <> +

    +
    + +

    + + } +} diff --git a/src/pages/playground/0_TabularClassification/models/MODEL__UPLOAD.tsx b/src/pages/playground/0_TabularClassification/models/MODEL__UPLOAD.tsx index 3f26389..2f004c1 100644 --- a/src/pages/playground/0_TabularClassification/models/MODEL__UPLOAD.tsx +++ b/src/pages/playground/0_TabularClassification/models/MODEL__UPLOAD.tsx @@ -1,14 +1,14 @@ -import type { DatasetProcessed_t } from "@core/types"; -import I_MODEL_TABULAR_CLASSIFICATION from "./_model"; +import type { DatasetProcessed_t } from '@core/types'; +import I_MODEL_TABULAR_CLASSIFICATION from './_model'; import * as _Types from '@core/types' -import { DEFAULT_LAYERS_UPLOAD } from "../CONSTANTS"; -import type { TFunction } from "i18next"; +import { DEFAULT_LAYERS_UPLOAD } from '../CONSTANTS'; +import type { TFunction } from 'i18next'; import { TC_MODEL_KEYS } from '@/MODEL_KEYS' export default class MODEL__UPLOAD extends I_MODEL_TABULAR_CLASSIFICATION { static KEY = TC_MODEL_KEYS.UPLOAD - constructor(t: TFunction<"translation", undefined>, callback: () => void) { + constructor(t: TFunction<'translation', undefined>, callback: () => void) { super(t, callback) } diff --git a/src/pages/playground/0_TabularClassification/models/_model.tsx b/src/pages/playground/0_TabularClassification/models/_model.tsx index be0ec58..2974052 100644 --- a/src/pages/playground/0_TabularClassification/models/_model.tsx +++ b/src/pages/playground/0_TabularClassification/models/_model.tsx @@ -1,8 +1,8 @@ import type * as _tfjs from '@tensorflow/tfjs' -import { buildJoyride } from '@components/joyride/buildJoyride' import * as _Types from '@core/types' import type { TFunction } from 'i18next' +import type { N4LPackage_t } from '@core/n4l/source' /** Valores de una instancia del dataset, por nombre de columna */ export type TabularInstance_t = Record @@ -12,7 +12,7 @@ export type TabularFormField_t = | { type: 'int32' | 'float32', name: string } | { type: 'label-encoder', name: string, options: Array<{ value: string, text: string }> } -export type LoadModelCallbacks_t = { onProgress: (fraction: number) => void } +export type LoadModelCallbacks_t = { onProgress?: (fraction: number) => void } export default abstract class I_MODEL_TABULAR_CLASSIFICATION { KEY : string = 'I_MODEL_TABULAR_CLASSIFICATION' @@ -25,10 +25,10 @@ export default abstract class I_MODEL_TABULAR_CLASSIFICATION { FORM : TabularFormField_t[] = [] DATA_DEFAULT_KEYS : string[] = [] DATA_DEFAULT : TabularInstance_t = {} - t : TFunction<"translation", undefined> + t : TFunction<'translation', undefined> callbacks : () => void - constructor(t: TFunction<"translation", undefined>, callbacks: () => void) { + constructor(t: TFunction<'translation', undefined>, callbacks: () => void) { this.t = t this.callbacks = callbacks } @@ -37,6 +37,28 @@ export default abstract class I_MODEL_TABULAR_CLASSIFICATION { return <> } + /** El paquete .n4l del que sale el modelo (para descargarlo); null si no sale de uno */ + N4L_PACKAGE(): N4LPackage_t | null { + return null + } + + /** Lo que recibe el modelo ya entrenado: las columnas codificadas o, además, escaladas (como al entrenar aquí) */ + MODEL_INPUT(): 'encoded' | 'scaled' { + return 'encoded' + } + + /** + * Salida del modelo (posición en CLASSES) de una clase tal como aparece en el conjunto de datos; -1 si no se + * reconoce. Por defecto, la de CLASSES con ese nombre (lo que sigue al último punto de la clave) o, si no hay, la + * que termina igual ("Setosa" o "0 Iris-setosa" → "…classes.Setosa"). + */ + CLASS_INDEX(target: unknown): number { + const name = String(target).toLowerCase() + const names = this.CLASSES.map((key) => key.slice(key.lastIndexOf('.') + 1).toLowerCase()) + const exact = names.indexOf(name) + return exact !== -1 ? exact : names.findIndex((className) => className.endsWith(name) || name.endsWith(className)) + } + /** * @returns {Promise<_Types.DatasetProcessed_t[]>} */ @@ -57,17 +79,4 @@ export default abstract class I_MODEL_TABULAR_CLASSIFICATION { return <> } - JOYRIDE(): _Types.Joyride_t { - return buildJoyride(this.t, 'datasets-models.0-tabular-classification.joyride.steps.', [ - { key: 'manual', target: '.joyride-step-manual', placement: 'top' }, - { key: 'dataset-info', target: '.joyride-step-dataset-info', placement: 'top' }, - { key: 'dataset', target: '.joyride-step-dataset', placement: 'top' }, - { key: 'layer-visualizer', target: '.joyride-step-layer', placement: 'top' }, - { key: 'layer-editor', target: '.joyride-step-editor-layers', placement: 'right' }, - { key: 'params-editor', target: '.joyride-step-editor-trainer', placement: 'left-start' }, - { key: 'list-of-models', target: '.joyride-step-list-of-models', placement: 'bottom' }, - { key: 'classify-and-visualizer', target: '.joyride-step-classify-visualization', placement: 'top' }, - ]) - } - } diff --git a/src/pages/playground/0_TabularClassification/models/index.ts b/src/pages/playground/0_TabularClassification/models/index.ts index e973366..d3b68a9 100644 --- a/src/pages/playground/0_TabularClassification/models/index.ts +++ b/src/pages/playground/0_TabularClassification/models/index.ts @@ -1,15 +1,32 @@ import I_MODEL_TABULAR_CLASSIFICATION from './_model' import { TC_MODEL_KEYS } from '@/MODEL_KEYS' -import type { ModelRegistry } from '@core/models/modelRegistry' +import { TASKS } from '@/TASKS' +import { withDynamicModels, type ModelRegistry } from '@core/models/modelRegistry' +import { builtinN4LPackage, n4lPackagesOf } from '@core/n4l/catalog' +import { LOCAL_KEY_PREFIX, openLocalPackage } from '@core/n4l/localPackages' +import type { N4LPackage_t } from '@core/n4l/source' +import type { TFunction } from 'i18next' -/** Clases de modelos de clasificación tabular, cargadas bajo demanda. */ -const MAP_TC_CLASSES: ModelRegistry = { - [TC_MODEL_KEYS.UPLOAD] : () => import('./MODEL__UPLOAD').then((m) => m.default), - [TC_MODEL_KEYS.CAR] : () => import('./MODEL_CAR').then((m) => m.default), - [TC_MODEL_KEYS.IRIS] : () => import('./MODEL_IRIS').then((m) => m.default), - [TC_MODEL_KEYS.LYMPHOGRAPHY]: () => import('./MODEL_LYMPHOGRAPHY').then((m) => m.default), +/** La clase de un paquete .n4l: MODEL_N4L con ese paquete (se descarga al usarla, como las demás) */ +const n4lModelClass = (open: () => Promise) => async () => { + const [{ default: MODEL_N4L }, pkg] = await Promise.all([import('./MODEL_N4L'), open()]) + return class extends MODEL_N4L { + constructor(t: TFunction<'translation', undefined>, callbacks: () => void) { + super(t, callbacks, pkg) + } + } } +/** + * Clases de modelos de clasificación tabular, cargadas bajo demanda: subir un CSV propio, los paquetes .n4l de la + * aplicación y, como local-, los que haya abierto el usuario + */ +const MAP_TC_CLASSES: ModelRegistry = withDynamicModels({ + [TC_MODEL_KEYS.UPLOAD]: () => import('./MODEL__UPLOAD').then((m) => m.default), + ...Object.fromEntries(n4lPackagesOf(TASKS.TABULAR_CLASSIFICATION).map(({ entry, section }) => + [section.key, n4lModelClass(async () => builtinN4LPackage(entry))])), +}, (key) => (key.startsWith(LOCAL_KEY_PREFIX) ? n4lModelClass(() => openLocalPackage(key.slice(LOCAL_KEY_PREFIX.length))) : undefined)) + export { MAP_TC_CLASSES, I_MODEL_TABULAR_CLASSIFICATION, diff --git a/src/pages/playground/1_Regression/CONSTANTS.ts b/src/pages/playground/1_Regression/CONSTANTS.ts index d46d216..938646f 100644 --- a/src/pages/playground/1_Regression/CONSTANTS.ts +++ b/src/pages/playground/1_Regression/CONSTANTS.ts @@ -1,7 +1,7 @@ -import type { IdLoss_t, IdMetric_t, IdOptimizer_t } from "@/types/nn-types" +import type { IdLoss_t, IdMetric_t, IdOptimizer_t } from '@/types/nn-types' // 0 - 1 --> 0 - 100 -const DEFAULT_LEARNING_RATE = 1 +const DEFAULT_LEARNING_RATE = 0.01 // 1 - Inf(1000) const DEFAULT_NUMBER_OF_EPOCHS = (import.meta.env.VITE_ENVIRONMENT === 'development') ? 5 : 50 // 0 - 1 --> 0 - 100 @@ -19,14 +19,6 @@ const DEFAULT_LAYERS = [ { is_disabled: true, units: 1, activation: 'linear' }, ] -const LIST_TRANSFORMATIONS = [ - { value: 'int32', i18n: 'int32' }, - { value: 'float32', i18n: 'float32' }, - { value: 'string', i18n: 'string' }, - { value: 'label-encoder', i18n: 'label-encoder' }, - { value: 'drop', i18n: 'drop' }, -] - export { DEFAULT_LEARNING_RATE, DEFAULT_NUMBER_OF_EPOCHS, @@ -37,6 +29,4 @@ export { DEFAULT_ID_METRICS, DEFAULT_LAYERS, - - LIST_TRANSFORMATIONS } \ No newline at end of file diff --git a/src/pages/playground/1_Regression/ModelReviewRegression.tsx b/src/pages/playground/1_Regression/ModelReviewRegression.tsx index eec6813..b80c1c1 100644 --- a/src/pages/playground/1_Regression/ModelReviewRegression.tsx +++ b/src/pages/playground/1_Regression/ModelReviewRegression.tsx @@ -1,24 +1,36 @@ -import { useEffect, useState, useId } from "react" -import { useParams, useNavigate } from "react-router" -import { Trans, useTranslation } from "react-i18next" -import { Card, Col, Container, Form, Row } from "react-bootstrap" -import ReactGA from "react-ga4" -import * as dfd from "danfojs" -import * as tfjs from "@tensorflow/tfjs" +import { useEffect, useMemo, useState } from 'react' +import { useParams, useNavigate } from 'react-router' +import { Trans, useTranslation } from 'react-i18next' +import { Card, Col, Container, Form, Row } from 'react-bootstrap' +import * as dfd from 'danfojs' +import * as tfjs from '@tensorflow/tfjs' -import * as _Types from "@core/types" -import { VERBOSE, DEFAULT_SELECTOR_DATASET, DEFAULT_SELECTOR_MODEL, DEFAULT_SELECTOR_INSTANCE, DEFAULT_SELECTOR_DATASET_INDEX, DEFAULT_SELECTOR_MODEL_INDEX, DEFAULT_SELECTOR_INSTANCE_INDEX } from "@/CONSTANTS" -import { TABLE_PLOT_STYLE_CONFIG } from "@/CONSTANTS_DanfoJS" -import N4LSummary from "@components/summary/N4LSummary" -import DataFrameDatasetCard from "@components/dataframe/DataFrameDatasetCard" -import DataFrameScatterPlotCard from "@components/dataframe/DataFrameScatterPlotCard" -import { type I_MODEL_REGRESSION, MAP_LR_CLASSES } from "@pages/playground/1_Regression/models" -import { createReviewModelInstance } from "@core/models/createReviewModelInstance" -import ModelReviewRegressionPredict from "./ModelReviewRegressionPredict" -import { TRANSFORM_DATASET_PROCESSED_TO_STATE_PREDICTION } from "./utils" -import * as DataFrameUtils from "@core/dataframe/DataFrameUtils" -import TabularShapPanel from "@core/explainability/TabularShapPanel" -import { dataframeRowsToNumbers, dataframeRowsWithDisplay } from "@core/explainability/shapSampling" +import * as _Types from '@core/types' +import { VERBOSE, DEFAULT_SELECTOR_DATASET, DEFAULT_SELECTOR_MODEL, DEFAULT_SELECTOR_DATASET_INDEX, DEFAULT_SELECTOR_MODEL_INDEX, DEFAULT_SELECTOR_INSTANCE_INDEX } from '@/CONSTANTS' +import N4LModelSummaryButton from '@components/neural-network/N4LModelSummaryButton' +import N4LEmptyState from '@components/loading/N4LEmptyState' +import N4LVirtualSelect, { type VirtualSelectOption_t } from '@components/select/N4LVirtualSelect' +import { type I_MODEL_REGRESSION, MAP_LR_CLASSES } from '@pages/playground/1_Regression/models' +import { createReviewModelInstance } from '@core/models/createReviewModelInstance' +import ModelReviewRegressionDataset from './ModelReviewRegressionDataset' +import ModelReviewRegressionPredict from './ModelReviewRegressionPredict' +import { TRANSFORM_DATASET_PROCESSED_TO_STATE_PREDICTION } from './utils' +import TabularShapPanel from '@core/explainability/TabularShapPanel' +import N4LPageHeader from '@components/neural-network/N4LPageHeader' +import N4LTestMetrics from '@components/n4l/N4LTestMetrics' +import N4LModelCard from '@components/neural-network/N4LModelCard' +import N4LModelAside from '@components/neural-network/N4LModelAside' +import N4LDownloadProgress from '@components/loading/N4LDownloadProgress' +import { trackDownloads } from '@core/downloadProgress' +import { regressionReviewGuide } from './modelReviewGuide' +import N4LStepByStep from '@components/neural-network/stepByStep/N4LStepByStep' +import { useStepByStepEnabled } from '@components/neural-network/stepByStep/stepByStepSetting' +import { usePretrainedNetwork } from '@components/neural-network/stepByStep/usePretrainedNetwork' +import { PRETRAINED_LEARNING_RATE } from '@core/nn-utils/stepByStep' +import { dataframeRowsToNumbers, dataframeRowsWithDisplay } from '@core/explainability/shapSampling' + +// Valor de la variable objetivo para la lista de instancias: sin decimales de más +const formatTarget = (value: unknown) => (typeof value === 'number' && !Number.isInteger(value) ? String(Number(value.toFixed(4))) : String(value)) type ModelReviewRegressionProps_t = { dataset: string @@ -31,13 +43,11 @@ export default function ModelReviewRegression({ dataset }: ModelReviewRegression const { id } = useParams<{ id: string }>() const navigate = useNavigate() - const prefix = "pages.playground.1-regression." + const prefix = 'pages.playground.1-regression.' const { t } = useTranslation() - const dataframe_processed_dataset_plotID = useId() - const dataframe_processed_describe_plotID = useId() const [iModelInstance, setIModelInstance] = useState(null) - - const [dataframe_X, setDataFrame_X] = useState(new dfd.DataFrame()) + // Hasta tener los conjuntos de datos y las redes del elegido (otra vez al cambiar de conjunto) + const [isLoading, setIsLoading] = useState(true) /** * @type {ReturnType>} @@ -45,7 +55,7 @@ export default function ModelReviewRegression({ dataset }: ModelReviewRegression const [listDatasets, setDatasets] = useState<_Types.StateListDatasetProcessed_t>({ data : [], index : DEFAULT_SELECTOR_DATASET_INDEX, - dataset: "select-dataset", + dataset: 'select-dataset', }) /** @@ -54,7 +64,7 @@ export default function ModelReviewRegression({ dataset }: ModelReviewRegression const [listCustomModels, setListCustomModels] = useState<_Types.StateListCustomModel_t>({ data : [], index: DEFAULT_SELECTOR_MODEL_INDEX, - model: "select-model", + model: 'select-model', }) /** @@ -63,7 +73,7 @@ export default function ModelReviewRegression({ dataset }: ModelReviewRegression const [instances, setInstances] = useState<_Types.StateInstance_t>({ data : [], index : DEFAULT_SELECTOR_INSTANCE_INDEX, - instance: "select-instance", + instance: 'select-instance', }) /** @@ -80,36 +90,30 @@ export default function ModelReviewRegression({ dataset }: ModelReviewRegression result : [], }) - useEffect(() => { - ReactGA.send({ - hitType: "pageview", - page : `/ModelReviewRegression/${dataset}`, - title : dataset, - }) - }, [dataset]) useEffect(() => { - if (VERBOSE) console.debug("useEffect[init][ dataset, t ]") + if (VERBOSE) console.debug('useEffect[init][ dataset, t ]') const init = async () => { const _iModelInstance = await createReviewModelInstance(MAP_LR_CLASSES, dataset, (ModelClass) => new ModelClass(t, () => { }), navigate) if (_iModelInstance === null) return try { setIModelInstance(_iModelInstance) - const _datasets = await _iModelInstance.DATASETS() + // Con el progreso real de lo que se descarga + const _datasets = await trackDownloads(() => _iModelInstance.DATASETS(), 'dataset_load') setDatasets({ data : _datasets, index : 0, - dataset: "select-dataset", + dataset: 'select-dataset', }) } catch (error) { - console.error("Error", error) + console.error('Error', error) } } init().then(() => undefined) }, [dataset, t, navigate]) useEffect(() => { - if (VERBOSE) console.debug("useEffect[init][ listDatasets ]") + if (VERBOSE) console.debug('useEffect[init][ listDatasets ]') const init = async () => { await tfjs.ready() if ( @@ -117,11 +121,13 @@ export default function ModelReviewRegression({ dataset }: ModelReviewRegression listDatasets.data.length > 0 && iModelInstance ) { - const _models = await iModelInstance.MODELS(listDatasets.data[listDatasets.index].csv) + const _models = await trackDownloads(() => iModelInstance.MODELS(listDatasets.data[listDatasets.index].csv), 'model_load') + setIsLoading(false) setListCustomModels({ - data : _models, + // Un conjunto de datos sin modelos preentrenados devuelve [] (o nada, si no está en la lista) + data : _models ?? [], index: 0, - model: "select-model", + model: 'select-model', }) } } @@ -131,20 +137,21 @@ export default function ModelReviewRegression({ dataset }: ModelReviewRegression useEffect(() => { if (VERBOSE) - console.debug("useEffect[init][ datasets, datasets.data, datasets.index, models, models.data, models.index ]") + console.debug('useEffect[init][ datasets, datasets.data, datasets.index, models, models.data, models.index ]') const init = async () => { await tfjs.ready() - if (listCustomModels.index !== DEFAULT_SELECTOR_MODEL_INDEX && listCustomModels.data.length > 0) { - /**@type {_Types.DatasetProcessed_t}*/ + // Las instancias son del conjunto de datos elegido, tenga o no modelos: antes, con uno sin modelos, se quedaban + // las del anterior + if (listCustomModels.index !== DEFAULT_SELECTOR_MODEL_INDEX && listDatasets.data[listDatasets.index] !== undefined) { const dataset_processed: _Types.DatasetProcessed_t = listDatasets.data[listDatasets.index] const { dataframe_original /* data_processed */ } = dataset_processed - setDataFrame_X(dataframe_original) + // El formulario empieza con la primera instancia, y el selector lo dice setInstances((_prevState) => ({ data : dataframe_original.values as Array>, - index : DEFAULT_SELECTOR_INSTANCE_INDEX, - instance: "select-instance", + index : 0, + instance: 'select-instance', })) - const state = TRANSFORM_DATASET_PROCESSED_TO_STATE_PREDICTION(dataset_processed) + const state = TRANSFORM_DATASET_PROCESSED_TO_STATE_PREDICTION(dataset_processed, 0) setPrediction((prevState) => { return { ...prevState, @@ -169,34 +176,17 @@ export default function ModelReviewRegression({ dataset }: ModelReviewRegression listCustomModels.index, ]) - useEffect(() => { - if (VERBOSE) - console.debug( - "useEffect[ datasets, datasets.data, datasets.index, dataframe_processed_dataset_plotID, dataframe_processed_describe_plotID ]" - ) - if (listDatasets.index !== DEFAULT_SELECTOR_DATASET_INDEX && listDatasets.data.length > 0) { - const { dataframe_processed } = listDatasets.data[listDatasets.index] - dataframe_processed.plot(dataframe_processed_dataset_plotID).table({ config: TABLE_PLOT_STYLE_CONFIG }) - DataFrameUtils.DataFrameDescribePlot(dataframe_processed, dataframe_processed_describe_plotID, { - config : TABLE_PLOT_STYLE_CONFIG, - emptyText: t("dataframe.describe.no-numeric"), - transpose: true, - }) - } - }, [ - listDatasets, - listDatasets.data, - listDatasets.index, - dataframe_processed_dataset_plotID, - dataframe_processed_describe_plotID, - t, - ]) - const handleChange_Datasets_Index = (event: React.ChangeEvent) => { + setIsLoading(true) setDatasets((prevState) => ({ ...prevState, index: parseInt(event.target.value), })) + // Los modelos y la instancia eran del conjunto anterior: se vacían hasta cargar los del nuevo (si no, el + // formulario mezclaba las columnas del nuevo con la instancia del anterior y la página fallaba) + setListCustomModels({ data: [], index: DEFAULT_SELECTOR_MODEL_INDEX, model: 'select-model' }) + setInstances({ data: [], index: DEFAULT_SELECTOR_INSTANCE_INDEX, instance: 'select-instance' }) + setPrediction((prevState) => ({ ...prevState, input_1_dataframe_original: new dfd.DataFrame(), result: [] })) } const handleChange_Models_Index = async (event: React.ChangeEvent) => { @@ -206,10 +196,8 @@ export default function ModelReviewRegression({ dataset }: ModelReviewRegression })) } - const handleChange_Instance_Index = async (event: React.ChangeEvent) => { - const newInstanceIndex = parseInt(event.target.value) + const handleChange_Instance_Index = (newInstanceIndex: number) => { - /**@type {_Types.DatasetProcessed_t}*/ const dataset_processed: _Types.DatasetProcessed_t = listDatasets.data[listDatasets.index] const state = TRANSFORM_DATASET_PROCESSED_TO_STATE_PREDICTION(dataset_processed, newInstanceIndex) setPrediction((prevState) => { @@ -234,127 +222,127 @@ export default function ModelReviewRegression({ dataset }: ModelReviewRegression const explainDataProcessed = listDatasets.data[listDatasets.index]?.data_processed const explainModel = listCustomModels.data[listCustomModels.index]?.model ?? null - if (VERBOSE) console.debug("render ModelReviewRegression") + // Ya cargados los modelos del conjunto de datos elegido, no hay ninguno + const hasNoModels = listCustomModels.index !== DEFAULT_SELECTOR_MODEL_INDEX && listCustomModels.data.length === 0 + + // Selector de instancias: su número y el valor real de la variable objetivo. Puede haber miles: el desplegable solo + // pinta las que se ven + const datasetSelected = listDatasets.data[listDatasets.index] + const targetIndex = datasetSelected?.data_processed + ? datasetSelected.dataframe_original.columns.indexOf(datasetSelected.data_processed.column_name_target) + : -1 + const instanceOptions = useMemo(() => ( + instances.data.map((row, index) => ({ value: index, label: `#${index}: ${targetIndex >= 0 ? formatTarget(row[targetIndex]) : ''}` })) + ), [instances.data, targetIndex]) + // El selector solo muestra la instancia mientras el formulario no se cambie: si no, ya no es esa + const selectedRow = instances.index >= 0 ? instances.data[instances.index] : undefined + const formRow = prediction.input_1_dataframe_original.values[0] as unknown[] | undefined + const instanceMatches = selectedRow !== undefined && formRow !== undefined && + selectedRow.every((value, column) => String(value) === String(formRow[column])) + const actualValue = instanceMatches && targetIndex >= 0 ? Number(selectedRow[targetIndex]) : null + + // Guía paso a paso de la página (con voz), si el modelo la tiene: un paso por variable de entrada del conjunto elegido + const guideFields = datasetSelected?.data_processed?.dataframe_X.columns + // Paso a paso (si se ha activado en /settings), con los pesos del modelo elegido y las filas del conjunto elegido + const stepByStep = useStepByStepEnabled() + const stepNetwork = usePretrainedNetwork(explainModel, stepByStep) + const stepData = useMemo(() => ({ + X : dataframeRowsToNumbers(explainDataProcessed?.X.values), + y : ((explainDataProcessed?.y.values ?? []) as number[]).map((value) => [Number(value)]), + features: (explainDataProcessed?.X.columns ?? []) as string[], + }), [explainDataProcessed]) + + const guideSteps = useMemo(() => (iModelInstance === null + ? null + : regressionReviewGuide(t, dataset, guideFields ?? [], stepByStep)), [t, dataset, iModelInstance, guideFields, stepByStep]) + + if (VERBOSE) console.debug('render ModelReviewRegression') return ( <> - - + + } guideId={'regression.' + dataset} guideSteps={guideSteps} /> + -
    -

    - -

    -
    +
    {iModelInstance !== null && ( - - -

    - -

    -
    - - - - - - - - {listDatasets.data.map(({ csv }, index) => { - return ( - - ) - })} - - - - - - + + } + actions={}> + + + + + + + {listDatasets.data.map(({ csv }, index) => { + return ( + + ) + })} + + + + + + {/* Cómo predice con datos que no vio al entrenarlo (los de un paquete .n4l lo llevan medido) */} + {iModelInstance.DESCRIPTION()} - -
    + + - - - {/* DataFrame INFO */} - - -

    - -

    -
    - - } - info={
    } - /> - } - info={
    } - /> -
    -
    - - {/* DataFrame PLOT */} - + {/* Conjunto de datos: tal cual, procesado y su análisis (correlaciones y dispersión, entre otros) */} + {/* Model PREDICT */} - - + +

    - +

    -
    - - +
    + - - {instances.data.map((_value, index) => { - const index_format = index.toString().padStart(3, "0") - return ( - - ) - })} - - - + disabled={instances.data.length === 0 || hasNoModels} + size={'sm'} + label={t('pages.playground.generator.example-from-dataset')} + placeholder={t(instances.index >= 0 ? 'example-custom' : prefix + 'predict.list-instances')} + searchPlaceholder={t('pages.playground.generator.dynamic-form-dataset.search-entity')} + noResultsText={t('pages.playground.generator.dynamic-form-dataset.no-entity')} + countText={(shown, total) => t('pages.playground.generator.dynamic-form-dataset.entity-count', { shown, total })} /> +
    + {listCustomModels.data.map((_value, index) => { - const index_format = index.toString() + const index_format = (index + 1).toString() return ( ) })} @@ -363,18 +351,21 @@ export default function ModelReviewRegression({ dataset }: ModelReviewRegression
    - } + {!hasNoModels && + actualValue={actualValue} + />}
    0} getModel={() => explainModel} getInstance={() => (prediction.input_3_dataframe_scaling.values[0] as number[] | undefined) ?? null} getPool={() => dataframeRowsToNumbers(explainDataProcessed?.X.values)} @@ -383,6 +374,14 @@ export default function ModelReviewRegression({ dataset }: ModelReviewRegression getInstanceDisplay={() => (prediction.input_2_dataframe_encoding.values[0] as Array | undefined) ?? null} valuesAreScaled /> + + {stepByStep && stepNetwork !== undefined && ( +
    + +
    + )}
    )} diff --git a/src/pages/playground/1_Regression/ModelReviewRegressionDataset.tsx b/src/pages/playground/1_Regression/ModelReviewRegressionDataset.tsx new file mode 100644 index 0000000..0e5cd45 --- /dev/null +++ b/src/pages/playground/1_Regression/ModelReviewRegressionDataset.tsx @@ -0,0 +1,92 @@ +import { lazy, Suspense, useMemo, useState } from 'react' +import { Trans } from 'react-i18next' +import { Card, Nav, Tab } from 'react-bootstrap' + +import type * as _Types from '@core/types' +import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' +import { VERBOSE } from '@/CONSTANTS' +import N4LTablePagination from '@components/table/N4LTablePagination' +import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +// La descripción y el análisis usan Plotly (tablas y gráficos): se descargan al abrir su pestaña, no con la página +const N4LDataFrameDescribe = lazy(() => import('@components/dataframe/N4LDataFrameDescribe')) +const AnalyzeEssentials = lazy(() => import('@pages/analyze/components/AnalyzeEssentials')) + +type ModelReviewRegressionDatasetProps = { + /** undefined mientras se carga */ + dataset: _Types.DatasetProcessed_t | undefined +} + +const TABS = ['original', 'processed', 'analysis'] as const +type Tab_t = typeof TABS[number] + +/** + * El conjunto de datos del modelo en tres pestañas: tal cual (original); procesado, con cada valor categórico + * convertido en un número, y su descripción estadística; y lo más importante de su análisis exploratorio. + */ +export default function ModelReviewRegressionDataset({ dataset }: ModelReviewRegressionDatasetProps) { + const prefix = 'pages.playground.1-regression.' + const [activeTab, setActiveTab] = useState('original') + + const originalRows = useMemo(() => (dataset ? DataFrameUtils.DataFrameIterRows(dataset.dataframe_original) : []), [dataset]) + const processedRows = useMemo(() => (dataset ? DataFrameUtils.DataFrameIterRows(dataset.dataframe_processed) : []), [dataset]) + + // La variable que se predice: se resalta en las tablas y en las estadísticas + const target = dataset?.data_processed?.column_name_target ?? null + const targetIndexIn = (columns: string[]) => (target === null ? -1 : columns.indexOf(target)) + + if (VERBOSE) console.debug('render ModelReviewRegressionDataset') + return ( + + setActiveTab(TABS.find((tab) => tab === key) ?? 'original')}> + + + + + {dataset === undefined && } + {dataset && + +
    + +
    +
    + +

    + }} /> +

    +
    + +
    +
    +

    + }> + + +
    + {/* Al abrirla por primera vez: el análisis (en un worker) y sus gráficos no hacen falta antes */} + + }> + + + +
    } +
    +
    +
    + ) +} diff --git a/src/pages/playground/1_Regression/ModelReviewRegressionPredict.tsx b/src/pages/playground/1_Regression/ModelReviewRegressionPredict.tsx index fc4ba09..f86fa62 100644 --- a/src/pages/playground/1_Regression/ModelReviewRegressionPredict.tsx +++ b/src/pages/playground/1_Regression/ModelReviewRegressionPredict.tsx @@ -1,71 +1,57 @@ +import { useState } from 'react' import { Trans } from 'react-i18next' import { Button, Col, Form, Row } from 'react-bootstrap' import * as tfjs from '@tensorflow/tfjs' import * as _Types from '@core/types' +import { trackEvent } from '@core/analytics' import { VERBOSE } from '@/CONSTANTS' import ModelReviewRegressionPredictForm from './ModelReviewRegressionPredictForm' import RegressionPredictionInfo from './RegressionPredictionInfo' -/** - * @typedef ModelReviewRegressionPredictProps_t - * - * @property {_Types.CustomModel_t} customModel - * @property {_Types.DatasetProcessed_t} dataset - * @property {_Types.StatePrediction_t} prediction - * @property {React.Dispatch>} setPrediction - */ type ModelReviewRegressionPredictProps_t = { customModel : _Types.CustomModel_t, dataset : _Types.DatasetProcessed_t, prediction : _Types.StatePrediction_t, setPrediction: React.Dispatch> + /** Valor real de la instancia del formulario, si es una del conjunto de datos sin cambios */ + actualValue? : number | null } -/** - * - * @param {ModelReviewRegressionPredictProps_t} props - * @returns - */ export default function ModelReviewRegressionPredict(props: ModelReviewRegressionPredictProps_t) { const { customModel, dataset, prediction, - setPrediction + setPrediction, + actualValue = null, } = props + // El valor real de lo que se predijo: si después se edita el formulario, el resultado sigue siendo de esa instancia + const [resultActual, setResultActual] = useState(null) - - const handleSubmit_Predict = (event: React.FormEvent) => { + const handleSubmit_Predict = async (event: React.FormEvent) => { event.preventDefault() if (customModel.model === undefined) { console.error('Error: customModel.model is undefined') return } const _model = customModel.model - - const vector = prediction.input_3_dataframe_scaling.values[0] - // 2. Usamos tf.tidy para limpiar automáticamente los tensores intermedios - const result = tfjs.tidy(() => { - const tensor = tfjs.tensor2d([vector as number[]]); - - // 3. Forzamos el tipo o comprobamos si es un array - const output = _model.predict(tensor); - - // Si el modelo tiene varias salidas, output será un array. - // Si solo tiene una, lo tratamos como Tensor único. - const predictions = Array.isArray(output) - ? output[0].dataSync() - : output.dataSync(); - - // 4. Convertimos a array de JS estándar - return Array.from(predictions); - }); - + const vector = prediction.input_3_dataframe_scaling.values[0] as number[] + // Si el modelo tiene varias salidas, se usa la primera + const output = tfjs.tidy(() => { + const result = _model.predict(tfjs.tensor2d([vector])) + return Array.isArray(result) ? result[0] : result + }) + // Lectura asíncrona: con WebGPU las síncronas detienen la GPU + const result = Array.from(await output.data<'float32'>()) + output.dispose() + + setResultActual(actualValue) setPrediction((prevState) => ({ ...prevState, result: result })) + trackEvent('predict', { input: 'form' }) } if (VERBOSE) console.debug('ModelReviewLinearRegressionPredict') @@ -77,15 +63,14 @@ export default function ModelReviewRegressionPredict(props: ModelReviewRegressio prediction={prediction} setPrediction={setPrediction} /> -
    - - + -
    +
    @@ -93,8 +78,12 @@ export default function ModelReviewRegressionPredict(props: ModelReviewRegressio
    - +
    + +
    ) -} \ No newline at end of file +} diff --git a/src/pages/playground/1_Regression/ModelReviewRegressionPredictForm.tsx b/src/pages/playground/1_Regression/ModelReviewRegressionPredictForm.tsx index 29fdd58..5474e9e 100644 --- a/src/pages/playground/1_Regression/ModelReviewRegressionPredictForm.tsx +++ b/src/pages/playground/1_Regression/ModelReviewRegressionPredictForm.tsx @@ -1,20 +1,12 @@ -import styles from '@pages/playground/1_Regression/Regression.module.css' +import { useId, useMemo } from 'react' import { Row, Col, Form } from 'react-bootstrap' import { useTranslation } from 'react-i18next' -import * as dfd from 'danfojs' import * as _Types from '@core/types' import { VERBOSE } from '@/CONSTANTS' import { DataFrameSetCellValue } from '@core/dataframe/DataFrameUtils' import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' -/** - * @typedef ModelReviewRegressionPredictFormProps_t - * @property {_Types.CustomModel_t} customModel - * @property {_Types.DatasetProcessed_t} dataset - * @property {_Types.StatePrediction_t} prediction - * @property {React.Dispatch>} setPrediction - */ type ModelReviewRegressionPredictFormProps_t = { customModel : _Types.CustomModel_t, dataset : _Types.DatasetProcessed_t, @@ -22,208 +14,100 @@ type ModelReviewRegressionPredictFormProps_t = { setPrediction: React.Dispatch> } -/** - * - * @param {ModelReviewRegressionPredictFormProps_t} props - * @returns - */ +type Field_t = + | { name: string, type: 'int32' | 'float32', min: number, max: number } + | { name: string, type: 'string', options: string[] } + +/** Un campo por atributo que recibe el modelo, con su tipo y los valores que toma en el conjunto de datos */ export default function ModelReviewRegressionPredictForm(props: ModelReviewRegressionPredictFormProps_t) { const { customModel, dataset, prediction, setPrediction } = props - const { t } = useTranslation() - - // const [ready, setReady] = useState(false) + const { t, i18n } = useTranslation() + const formId = useId() - // useEffect(() => { - // setReady(!!( - // dataset - // && dataset.dataframe_processed - // && prediction - // && prediction.input_1_dataframe_original.values.length > 0 - // && customModel - // && customModel.model - // )) - // }, [dataset, prediction, customModel, setReady]) const ready = !!( - dataset && - dataset.dataframe_processed && - prediction && - prediction.input_1_dataframe_original && - prediction.input_1_dataframe_original.values && - prediction.input_1_dataframe_original.values.length > 0 && - customModel && - customModel.model + dataset?.dataframe_processed && + prediction?.input_1_dataframe_original?.values?.length > 0 && + customModel?.model ) - - - - /** - * - * @param {_Types.DatasetProcessed_t} dataset - * @param {string} column_name - * @returns - */ - const isDisabled = (dataset: _Types.DatasetProcessed_t, column_name: string) => { - if (dataset === undefined || dataset.data_processed === undefined) { - return true - } - if (dataset.data_processed.column_name_target === column_name) { - return true - } - if (dataset.dataset.some(v => v.column_name === column_name)) { - return false - } - return true - } - - /** - * - * @param {_Types.DatasetProcessed_t} dataset - * @param {string} column_name - * @returns - */ - const getColor = (dataset: _Types.DatasetProcessed_t, column_name: string) => { - if (dataset === undefined || dataset.data_processed === undefined) { - console.error('Error: dataset or dataset.data_processed is undefined') - return - } - if (dataset.data_processed.column_name_target === column_name) { - return styles.border_green - } - if (dataset.dataset.some(v => v.column_name === column_name)) { - return styles.border_blue - } - return styles.border_red - } - - const handleChange_Parameter_int32_float32 = (column_name: string, new_value: number | string) => { + // Los atributos que recibe el modelo (las columnas de X): sin la variable objetivo, que es lo que se predice, ni + // las columnas descartadas al procesar + const fields = useMemo(() => { + if (!dataset?.data_processed) return [] + return dataset.data_processed.dataframe_X.columns + .map((name): Field_t => { + const column = dataset.dataframe_original[name] + if (column.dtype === 'string') { + return { name, type: 'string', options: [...new Set((column.values as unknown[]).map((value) => String(value)))].sort() } + } + return { name, type: column.dtype === 'int32' ? 'int32' : 'float32', min: column.min(), max: column.max() } + }) + }, [dataset]) + + const updateInput = (column_name: string, new_value: number | string, new_value_encoding: number | string) => { setPrediction((prevState) => { if (dataset.data_processed === undefined) { console.error('Error: dataset.data_processed is undefined') return prevState } - const newInputDataFrameOriginal = DataFrameSetCellValue(prediction.input_1_dataframe_original, 0, column_name, new_value) - const newInputDataFrameProcessed = DataFrameSetCellValue(prediction.input_1_dataframe_processed, 0, column_name, new_value) - const newInputDataFrameEncoding = DataFrameSetCellValue(prediction.input_2_dataframe_encoding, 0, column_name, new_value) - // const newInputDataFrameScaling = DataFrameSetCellValue(prediction.input_2_dataframe_encoding, 0, column_name, new_value) - const newInputDataFrameScaling = dataset.data_processed.scaler.transform(newInputDataFrameEncoding) - + const newInputDataFrameEncoding = DataFrameSetCellValue(prevState.input_2_dataframe_encoding, 0, column_name, new_value_encoding) return { ...prevState, - input_1_dataframe_original : newInputDataFrameOriginal, - input_1_dataframe_processed: newInputDataFrameProcessed, + input_1_dataframe_original : DataFrameSetCellValue(prevState.input_1_dataframe_original, 0, column_name, new_value), + input_1_dataframe_processed: DataFrameSetCellValue(prevState.input_1_dataframe_processed, 0, column_name, new_value), input_2_dataframe_encoding : newInputDataFrameEncoding, - input_3_dataframe_scaling : newInputDataFrameScaling + input_3_dataframe_scaling : dataset.data_processed.scaler.transform(newInputDataFrameEncoding), } }) } - const handleChange_Parameter_string = (column_name: string, new_value: string) => { - setPrediction((prevState) => { - if (dataset.data_processed === undefined) { - console.error('Error: dataset.data_processed is undefined') - return prevState - } - const [new_value_encoding] = dataset.data_processed.encoders[column_name].encoder.transform([new_value]) - const newInputDataFrameOriginal = DataFrameSetCellValue(prediction.input_1_dataframe_original, 0, column_name, new_value) - const newInputDataFrameProcessed = DataFrameSetCellValue(prediction.input_1_dataframe_processed, 0, column_name, new_value) - const newInputDataFrameEncoding = DataFrameSetCellValue(prediction.input_2_dataframe_encoding, 0, column_name, new_value_encoding) - const newInputDataFrameScaling = dataset.data_processed.scaler.transform(newInputDataFrameEncoding) - return { - ...prevState, - input_1_dataframe_original : newInputDataFrameOriginal, - input_1_dataframe_processed: newInputDataFrameProcessed, - input_2_dataframe_encoding : newInputDataFrameEncoding, - input_3_dataframe_scaling : newInputDataFrameScaling - } - }) + const handleChange_Number = (column_name: string, value: string) => { + const number = value === '' ? NaN : Number(value) + updateInput(column_name, number, number) } + const handleChange_String = (column_name: string, value: string) => { + if (dataset.data_processed === undefined) return + const [value_encoding] = dataset.data_processed.encoders[column_name].encoder.transform([value]) + updateInput(column_name, value, value_encoding) + } + const numberFormat = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 3 }) + const helpText = (field: Field_t) => { + if (field.type === 'string') return t('pages.playground.form.type-categorical', { count: field.options.length }) + const type = t(field.type === 'int32' ? 'pages.playground.form.type-integer' : 'pages.playground.form.type-decimal') + return `${type}, ${t('pages.playground.form.range', { min: numberFormat.format(field.min), max: numberFormat.format(field.max) })}` + } - if (VERBOSE) console.debug('render ModelReviewLinearRegressionPredictForm') - return <> - - {!ready && <> - - } - - - {ready && <> - {dataset - .dataframe_processed - .columns - .map((column_name: string, index: number) => { - const column_type = (/** @type {_Types.DataFrameColumnType_t} */(dataset.dataframe_original[column_name].dtype)) - const column_value = prediction.input_1_dataframe_original[column_name].values[0] - - switch (column_type) { - case 'int32': { - return - - {t('pages.playground.form.parameter')}: {column_name} - handleChange_Parameter_int32_float32(column_name, $event.target.value)} /> - Dtype: {column_type} - - - } - case 'float32': { - return - - {t('pages.playground.form.parameter')}: {column_name} - handleChange_Parameter_int32_float32(column_name, $event.target.value)} /> - Dtype: {column_type} - - - } - case 'string': { - const labelEncoder = new dfd.LabelEncoder() - labelEncoder.fit(dataset.dataframe_original[column_name]) - return - - {t('pages.playground.form.parameter')}: {column_name} - handleChange_Parameter_string(column_name, e.target.value)}> - <> - {Object.entries(labelEncoder.classes) - .map(([text, _value]: [string, unknown], index_options: number) => { - return - }) - } - - - Dtype: {column_type} - - - } - default: - return <>default - } - - } - - )} - } + if (VERBOSE) console.debug('render ModelReviewRegressionPredictForm') + // La instancia tiene que ser de este conjunto de datos (al cambiar de conjunto, llega un momento después) + const instanceColumns = ready ? prediction.input_1_dataframe_original.columns : [] + if (!ready || !fields.every((field) => instanceColumns.includes(field.name))) return + return ( + + {fields.map((field, index) => { + const controlId = `${formId}-${index}` + const value = prediction.input_1_dataframe_original[field.name].values[0] + // NaN mientras se borra un número: el campo se queda vacío en vez de mostrar "NaN" + const inputValue = typeof value === 'number' && Number.isNaN(value) ? '' : value ?? '' + return ( + + + {field.name} + {field.type === 'string' + ? handleChange_String(field.name, e.target.value)}> + {field.options.map((option) => )} + + : handleChange_Number(field.name, e.target.value)} />} + {helpText(field)} + + + ) + })} - - -} \ No newline at end of file + ) +} diff --git a/src/pages/playground/1_Regression/Regression.tsx b/src/pages/playground/1_Regression/Regression.tsx index 4799826..c5d1270 100644 --- a/src/pages/playground/1_Regression/Regression.tsx +++ b/src/pages/playground/1_Regression/Regression.tsx @@ -1,16 +1,37 @@ -import { lazy, Suspense, useEffect, useRef } from 'react' -import { useParams, useNavigate, Link } from 'react-router' +import { lazy, Suspense, useEffect, useMemo } from 'react' +import { useParams, useNavigate } from 'react-router' import { Trans, useTranslation } from 'react-i18next' -import { Accordion, Button, Card, Col, Container, Form, Row } from 'react-bootstrap' -import ReactGA from 'react-ga4' +import { Accordion, Card, Col, Form, Row } from 'react-bootstrap' import * as tfjs from '@tensorflow/tfjs' -import { DEFAULT_SELECTOR_DATASET_INDEX, VERBOSE } from '@/CONSTANTS' +import { DEFAULT_SELECTOR_DATASET_INDEX, DEFAULT_SELECTOR_MODEL_INDEX, VERBOSE } from '@/CONSTANTS' import { GLOSSARY_ACTIONS } from '@/CONSTANTS_ACTIONS' import N4LDivider from '@components/divider/N4LDivider' +import N4LSectionLayout from '@components/divider/N4LSectionLayout' +import N4LTrainButton from '@components/neural-network/N4LTrainButton' +import N4LTrainingPrediction from '@components/neural-network/N4LTrainingPrediction' +import { useTrainingProgress } from '@hooks/useTrainingProgress' +import { useStoredModels } from '@hooks/useStoredModels' +import N4LStoredModelsNotice from '@components/neural-network/N4LStoredModelsNotice' +import N4LTrainingDiagnosis from '@components/neural-network/N4LTrainingDiagnosis' +import N4LModelCode from '@components/neural-network/N4LModelCode' +import { denseCodeLayers, type ModelCode_t } from '@core/nn-utils/modelCode' +import { createLoss, createMetricsList } from '@core/nn-utils/ArchitectureHelper' +import { reportTrainResult } from '@core/training/trainResult' +import { checkDenseLayers } from '@core/nn-utils/checkLayers' +import { historyFromData } from '@core/training/modelStore' +import { historyData, type TrainingHistory_t } from '@core/training/buildModels' +import { trainerGuide } from '@components/guide/trainerGuide' +import N4LStepByStep from '@components/neural-network/stepByStep/N4LStepByStep' +import { useStepByStepEnabled } from '@components/neural-network/stepByStep/stepByStepSetting' +import { dataframeRowsToNumbers } from '@core/explainability/shapSampling' +import type { TrainingSession_t } from '@core/session/trainingSession' +import { useTrainerSession } from '@hooks/useTrainerSession' +import { layersAreValid } from '@components/neural-network/alertLayerError' +import N4LPageHeader from '@components/neural-network/N4LPageHeader' +import type { IdLoss_t, IdMetric_t, IdOptimizer_t } from '@/types/nn-types' import N4LLayerDesign from '@components/neural-network/N4LLayerDesign' -import N4LJoyride from '@components/joyride/N4LJoyride' import DebugJSON from '@components/debug/DebugJSON' import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' @@ -18,12 +39,12 @@ import { MAP_LR_CLASSES } from './models' import { hasModel, loadModelClass } from '@core/models/modelRegistry' import * as _Types from '@core/types' -// import LinearRegressionModelController_Simple from '@core/controller/01-regression/LinearRegressionModelController_Simple' import { createRegressionCustomModel } from '@core/controller/01-regression/RegressionModelController' import { useRegressionContext } from '@context/useRegressionContext' import alertHelper from '@utils/alertHelper' -import { UPLOAD } from '@/TASKS' +import { TASKS, UPLOAD } from '@/TASKS' import { TRANSFORM_DATASET_PROCESSED_TO_STATE_PREDICTION } from './utils' +import N4LHelpLink from '@components/helpLink/N4LHelpLink' // Manual and datasets const RegressionManual = lazy(() => import('./RegressionManual')) @@ -34,7 +55,6 @@ const RegressionDatasetShow = lazy(() => import('./RegressionDatasetShow')) const RegressionEditorLayers = lazy(() => import('./RegressionEditorLayers')) const RegressionEditorFeaturesSelector = lazy(() => import('./RegressionEditorFeaturesSelector')) const RegressionEditorHyperparameters = lazy(() => import('./RegressionEditorHyperparameters')) -// const RegressionEditorVisor = lazy(() => import( './RegressionEditorVisor')) // Models const RegressionTableModels = lazy(() => import('./RegressionTableModels')) const RegressionPrediction = lazy(() => import('./RegressionPrediction')) @@ -43,6 +63,9 @@ type RegressionProps_t = { dataset: string } +/** Lo que se guarda de cada modelo entrenado (con el modelo): sus parámetros, el fichero con el que se entrenó y el historial */ +type StoredRegressionModel_t = Omit<_Types.CustomModelGenerated_t, 'model' | 'history' | 'dataset_processed' | 'dataframe'> & { csv: string, history: TrainingHistory_t } + export default function Regression({ dataset }: RegressionProps_t) { /** @type {ReturnType>} */ const { id: param_id } = useParams() @@ -51,6 +74,13 @@ export default function Regression({ dataset }: RegressionProps_t) { // i18n const prefix = 'pages.playground.generator.' const { t } = useTranslation() + const training = useTrainingProgress() + // Secciones de la página en orden: numeran los separadores (N4LDivider) + // Paso a paso solo si se ha activado en /settings + const stepByStep = useStepByStepEnabled() + const steps = ['hr.information', ...(dataset === UPLOAD ? ['hr.process-dataset'] : []), 'hr.dataset', 'hr.model', ...(stepByStep ? ['hr.step-by-step'] : []), 'hr.predict', 'hr.explainability'] + // La guía de la página (botón Guía): de los datos al modelo entrenado, paso a paso + const guideSteps = useMemo(() => trainerGuide(t, '1-regression', dataset, { upload: dataset === UPLOAD, datasetTable: true, testSize: 'hp-train-rate', stepByStep: stepByStep ? 'after-models' : false }), [t, dataset, stepByStep]) const { // prediction, @@ -65,6 +95,7 @@ export default function Regression({ dataset }: RegressionProps_t) { isTraining, setIsTraining, + listModels, setListModels, accordionActive, @@ -74,19 +105,78 @@ export default function Regression({ dataset }: RegressionProps_t) { setIModelInstance, } = useRegressionContext() - const joyrideButton_ref = useRef<_Types.JoyrideHandle_t>({}) + // El paso a paso (N4LStepByStep): las capas del editor y las filas ya procesadas, como las recibe la red + const stepLayers = useMemo(() => params.params_layers.map(({ units, activation }) => ({ units, activation: activation ?? 'linear' })), [params.params_layers]) + const stepProcessed = datasets.data[datasets.index]?.data_processed + // El código equivalente de la red (Ver el código): sus entradas son las columnas de los datos ya procesados + const codeSpec = useMemo((): ModelCode_t | null => (stepProcessed?.X === undefined ? null : { + inputShape : [stepProcessed.X.shape[1]], + layers : denseCodeLayers(params.params_layers), + optimizer : params.params_training.id_optimizer, + learningRate: params.params_training.learning_rate, + loss : createLoss(params.params_training.id_loss, {}), + metrics : createMetricsList(params.params_training.list_id_metrics, {}), + epochs : params.params_training.n_of_epochs, + batchSize : 32, + dataComment : t('model-code.data-regression'), + }), [stepProcessed, params, t]) + const stepData = useMemo(() => ({ + X : dataframeRowsToNumbers(stepProcessed?.X.values), + y : ((stepProcessed?.y.values ?? []) as number[]).map((value) => [Number(value)]), + features: (stepProcessed?.X.columns ?? []) as string[], + }), [stepProcessed]) + + // region SESIÓN: exportar, importar y compartir capas e hiperparámetros + + const currentSession = (): TrainingSession_t => { + const training_params = params.params_training + return { + app : 'nets4learning', + version : 1, + task : TASKS.REGRESSION, + dataset : dataset, + layers : params.params_layers, + hyperparameters: { + learningRate: training_params.learning_rate, + epochs : training_params.n_of_epochs, + testSize : training_params.test_size, + optimizer : training_params.id_optimizer, + loss : training_params.id_loss, + metrics : training_params.list_id_metrics, + }, + } + } + + const applySession = ({ layers: importedLayers, hyperparameters: h }: TrainingSession_t) => { + setParams((prevState) => ({ + ...prevState, + params_layers: importedLayers.map((layer) => ({ + units : Number(layer.units), + activation: String(layer.activation ?? 'relu'), + // La capa de salida de regresión no se puede editar + ...(layer.is_disabled === true ? { is_disabled: true } : {}), + })), + params_training: { + ...prevState.params_training, + learning_rate : h.learningRate, + n_of_epochs : h.epochs, + test_size : h.testSize, + id_optimizer : h.optimizer as IdOptimizer_t, + id_loss : h.loss as IdLoss_t, + list_id_metrics: h.metrics as IdMetric_t[], + }, + })) + } + // endregion + - useEffect(() => { - ReactGA.send({ hitType: 'pageview', page: `/Regression/${dataset}`, title: dataset }) - }, [dataset]) useEffect(() => { if (VERBOSE) console.debug('useEffect[init][ dataset, t, setIModelInstance, setAccordionActive, setDatasets, setParams, history ]') const init = async () => { await tfjs.ready() if (hasModel(MAP_LR_CLASSES, dataset)) { - /** @type {_Types.I_MODEL_REGRESSION_t} */ const _iModelInstance = new (await loadModelClass(MAP_LR_CLASSES, dataset))(t, setAccordionActive) setIModelInstance(_iModelInstance) // Al subir un CSV no hay datasets predefinidos: los aporta el usuario @@ -101,7 +191,7 @@ export default function Regression({ dataset }: RegressionProps_t) { }) } } else { - await alertHelper.alertError('Error in selection of model') + await alertHelper.alertError(t('error.model-selected')) console.error('Error, option not valid', { ID: dataset }) navigate('/404') } @@ -110,36 +200,32 @@ export default function Regression({ dataset }: RegressionProps_t) { }, [dataset, t, setIModelInstance, setAccordionActive, setDatasets, setParams, navigate]) + // Las capas por defecto de cada fichero (el vino tinto o el blanco…): al cargarlo o al elegir otro, no con cualquier + // cambio de los datos (procesarlos las borraría, y con ellas una configuración importada) + const selectedCsv = datasets.index !== DEFAULT_SELECTOR_DATASET_INDEX ? datasets.data[datasets.index]?.csv : undefined useEffect(() => { - if (dataset === UPLOAD) { - if (VERBOSE) console.debug('Regression upload csv') - } else if (hasModel(MAP_LR_CLASSES, dataset)) { - if (iModelInstance - && datasets - && datasets.data - && datasets.index != DEFAULT_SELECTOR_DATASET_INDEX - && datasets.data[datasets.index] - && datasets.data[datasets.index].csv - ) { - setParams((prevState) => ({ - ...prevState, - params_layers: iModelInstance.DEFAULT_LAYERS(datasets.data[datasets.index].csv) - })) - } - } - }, [dataset, iModelInstance, datasets, setParams]) + if (dataset === UPLOAD || !hasModel(MAP_LR_CLASSES, dataset) || iModelInstance === null || !selectedCsv) return + setParams((prevState) => ({ + ...prevState, + params_layers: iModelInstance.DEFAULT_LAYERS(selectedCsv), + })) + }, [dataset, iModelInstance, selectedCsv, setParams]) + + // Lista después de las capas por defecto del conjunto de datos (el efecto de arriba) + const { sessionVersion, importSession } = useTrainerSession(TASKS.REGRESSION, iModelInstance !== null && (dataset === UPLOAD || datasets.data.length > 0), applySession) const TrainModel = async () => { const dataset_processed = datasets.data[datasets.index] const result = await createRegressionCustomModel({ dataset_processed: dataset_processed, layerList : params.params_layers, - learningRate : params.params_training.learning_rate / 100, + learningRate : params.params_training.learning_rate, numberOfEpoch : params.params_training.n_of_epochs, testSize : params.params_training.test_size / 100, idOptimizer : params.params_training.id_optimizer, idLoss : params.params_training.id_loss, idMetrics : params.params_training.list_id_metrics, + ...training.callbacks, }) if (!result) { console.error('Error creating the model') @@ -147,7 +233,6 @@ export default function Regression({ dataset }: RegressionProps_t) { } const { model, history } = result - /** @type {_Types.CustomModelGenerated_t} */ const newModel: _Types.CustomModelGenerated_t = { model : model, history : history, @@ -163,7 +248,20 @@ export default function Regression({ dataset }: RegressionProps_t) { index: prevState.data.length } }) + storedModels.save(model, { + params_layers : newModel.params_layers, + params_training: newModel.params_training, + params_features: newModel.params_features, + csv : dataset_processed.csv, + history : historyData(history), + }) + reportTrainResult({ history: history.history, layers: newModel.params_layers }) + fillPredictionForm(dataset_processed) + training.complete() + } + /** El formulario de predicción, con la primera fila del conjunto con el que se entrenó el modelo elegido */ + const fillPredictionForm = (dataset_processed: _Types.DatasetProcessed_t) => { const newPredictionState = TRANSFORM_DATASET_PROCESSED_TO_STATE_PREDICTION(dataset_processed, 0) setPrediction((prevState) => ({ ...prevState, @@ -173,12 +271,39 @@ export default function Regression({ dataset }: RegressionProps_t) { input_2_dataframe_encoding : newPredictionState.input_2_dataframe_encoding, input_3_dataframe_scaling : newPredictionState.input_3_dataframe_scaling, })) + } + // Los modelos entrenados antes con este conjunto (guardados en el navegador): vuelven a la tabla con el fichero con el + // que se entrenaron (por su nombre). Cuando ya están cargados los datos; los de un conjunto subido no se guardan + const storedModels = useStoredModels('regression', dataset, dataset !== UPLOAD && datasets.data.length > 0, (stored) => { + const restored = stored.flatMap(({ model, data: { csv, history, ...params } }): _Types.CustomModelGenerated_t[] => { + const dataset_processed = datasets.data.find((candidate) => candidate.csv === csv) + return dataset_processed === undefined ? [] : [{ ...params, model: model as tfjs.Sequential, history: historyFromData(history), dataset_processed }] + }) + if (restored.length === 0) return + setListModels((prevState) => ({ + ...prevState, + data : [...restored, ...prevState.data], + index: prevState.index >= 0 ? prevState.index + restored.length : restored.length - 1, + })) + if (listModels.data.length === 0) fillPredictionForm(restored.at(-1)!.dataset_processed) + }) + const handleClear_StoredModels = async () => { + await storedModels.clear() + setListModels((prevState) => ({ ...prevState, data: [], index: DEFAULT_SELECTOR_MODEL_INDEX })) } const handleSubmit_TrainModel = async (event: React.FormEvent) => { event.preventDefault() + if (!(await layersAreValid(t, checkDenseLayers(params.params_layers)))) return setIsTraining(true) + training.start({ + epochs : params.params_training.n_of_epochs, + learningRate: params.params_training.learning_rate, + optimizer : params.params_training.id_optimizer, + loss : params.params_training.id_loss, + layers : params.params_layers.length, + }) try { await TrainModel() @@ -187,6 +312,7 @@ export default function Regression({ dataset }: RegressionProps_t) { console.error('Error during model training:', error) } finally { setIsTraining(false) + training.finish() } } @@ -214,44 +340,27 @@ export default function Regression({ dataset }: RegressionProps_t) { if (VERBOSE) console.debug('render Regression') return ( <> - - - - - -
    -

    - -
    - -
    + + } guideId={'train.regression.' + dataset} guideSteps={guideSteps} + getSession={currentSession} onImport={importSession} className={'mt-2 mb-3'} /> {/* INFORMATION */} - + - - accordionToggle('manual')}> -

    + + accordionToggle('manual')} as={'h3'} className={'n4l-accordion-h2'}> + }> - - accordionToggle('dataset_info')}> -

    + + accordionToggle('dataset_info')} as={'h3'} className={'n4l-accordion-h2'}> + }> @@ -263,8 +372,8 @@ export default function Regression({ dataset }: RegressionProps_t) { {/* PROCESS DATASET */} {dataset === UPLOAD && <> - - + + }> @@ -272,17 +381,17 @@ export default function Regression({ dataset }: RegressionProps_t) { } {/* SHOW DATASET */} - - + + }> {/* MODEL */} - + - + , + link1: , }} /> ]} @@ -309,48 +411,65 @@ export default function Regression({ dataset }: RegressionProps_t) {
    -
    - }> -
    - -
    - }> -
    + }> + }> - - }> + + }>
    + {/* El código equivalente de la red */} -
    - -
    + + +
    + + + + + + + + {!training.isTraining && + }

    + - + }> - + {/* Paso a paso, si se ha activado en /settings */} + {stepByStep && <> + + + + + + + } + + - + }> - + @@ -360,7 +479,7 @@ export default function Regression({ dataset }: RegressionProps_t) { -

    Debug

    +

    Debug

    @@ -388,7 +507,7 @@ export default function Regression({ dataset }: RegressionProps_t) { } -
    + ) } diff --git a/src/pages/playground/1_Regression/RegressionDataset.tsx b/src/pages/playground/1_Regression/RegressionDataset.tsx index 73a9a20..9146e63 100644 --- a/src/pages/playground/1_Regression/RegressionDataset.tsx +++ b/src/pages/playground/1_Regression/RegressionDataset.tsx @@ -1,16 +1,17 @@ import { useState } from 'react' import { useTranslation } from 'react-i18next' -import * as dfd from 'danfojs' import { DataFrameReadCSV } from '@core/dataframe/DataFrameUtils' import * as _Types from '@core/types' import { useRegressionContext } from '@context/useRegressionContext' import DragAndDrop from '@components/dragAndDrop/DragAndDrop' -import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +import N4LEmptyState from '@components/loading/N4LEmptyState' import alertHelper from '@utils/alertHelper' -import { UPLOAD } from '@/TASKS' +import { TASKS, UPLOAD } from '@/TASKS' import { VERBOSE } from '@/CONSTANTS' import type { DropEvent, FileRejection } from 'react-dropzone' +import { DATASET_ACCEPT } from '@core/dataframe/datasetFormats' +import { useProjectDatasetUpload } from '@hooks/useProjectDatasetUpload' type RegressionDatasetProps_t = { dataset: string @@ -23,8 +24,6 @@ export default function RegressionDataset({ dataset }: RegressionDatasetProps_t) datasets, setDatasets, - // datasetLocal, - // setDatasetLocal, iModelInstance, } = useRegressionContext() @@ -41,28 +40,19 @@ export default function RegressionDataset({ dataset }: RegressionDatasetProps_t) const _dataframeOriginal = await DataFrameReadCSV(file_csv) const _dataframeProcessed = await DataFrameReadCSV(file_csv) - /**@type {_Types.DatasetProcessed_t} */ + // Sin procesar: hasta pasar por el formulario de procesamiento no hay entradas ni objetivo, ni se puede entrenar + // (antes se marcaba como procesado con todo vacío y el botón de entrenar se activaba) const newDataset: _Types.DatasetProcessed_t = { is_dataset_upload : true, - is_dataset_processed: true, + is_dataset_processed: false, csv : files[0].name, path : '', info : '', container_info : '', - dataset : [/* TODO */], + dataset : [], dataframe_original : _dataframeOriginal, dataframe_processed : _dataframeProcessed, dataset_transforms : [], - data_processed : { - /* TODO */ - encoders : {}, - column_name_target: '', - scaler : new dfd.MinMaxScaler(), - dataframe_X : new dfd.DataFrame(), - dataframe_y : new dfd.DataFrame(), - X : new dfd.DataFrame(), - y : new dfd.DataFrame(), - } } setDatasets((prevState) => { return { @@ -74,16 +64,6 @@ export default function RegressionDataset({ dataset }: RegressionDatasetProps_t) index: datasets.data.length } }) - // setIndexDatasetSelected(datasets.length) - // setDatasetLocal((prevState) => ({ - // ...prevState, - // is_dataset_upload : true, - // is_dataset_processed: false, - // dataframe_original : _dataframeOriginal, - // dataframe_processed : _dataframeProcessed, - // container_info : '', - // csv : files[0].name, - // })) setShowDatasetInfo(true) await alertHelper.alertSuccess(t('alert.file-upload-success')) } catch (error) { @@ -95,20 +75,23 @@ export default function RegressionDataset({ dataset }: RegressionDatasetProps_t) if (VERBOSE) console.debug({ files }) } + // Desde «Entrenar» en /datasets (?dataset=wdbc): el CSV del proyecto, como si se hubiera arrastrado + useProjectDatasetUpload(TASKS.REGRESSION, dataset === UPLOAD, (files) => handleChange_FileUpload_CSV(files, {} as DropEvent)) + if (VERBOSE) console.debug('render RegressionDataset') return <> {dataset === UPLOAD && <> {!showDatasetInfo && <> - + } {showDatasetInfo && <>
      diff --git a/src/pages/playground/1_Regression/RegressionDatasetProcess.tsx b/src/pages/playground/1_Regression/RegressionDatasetProcess.tsx index 4c22a01..084832c 100644 --- a/src/pages/playground/1_Regression/RegressionDatasetProcess.tsx +++ b/src/pages/playground/1_Regression/RegressionDatasetProcess.tsx @@ -1,12 +1,12 @@ import { Card } from 'react-bootstrap' import { Trans } from 'react-i18next' -import { Link } from 'react-router' import { useRegressionContext } from '@context/useRegressionContext' -import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +import N4LEmptyState from '@components/loading/N4LEmptyState' import { DEFAULT_SELECTOR_DATASET_INDEX, VERBOSE } from '@/CONSTANTS' import { GLOSSARY_ACTIONS } from '@/CONSTANTS_ACTIONS' import RegressionDatasetProcessForm from './RegressionDatasetProcessForm' +import N4LHelpLink from '@components/helpLink/N4LHelpLink' export default function RegressionDatasetProcess() { @@ -28,7 +28,7 @@ export default function RegressionDatasetProcess() {

      {!showDatasetProcess() && <> - + } {showDatasetProcess() && <> @@ -39,14 +39,7 @@ export default function RegressionDatasetProcess() {

      + link1: }} />

      diff --git a/src/pages/playground/1_Regression/RegressionDatasetProcessForm.tsx b/src/pages/playground/1_Regression/RegressionDatasetProcessForm.tsx index 1767c15..148cad4 100644 --- a/src/pages/playground/1_Regression/RegressionDatasetProcessForm.tsx +++ b/src/pages/playground/1_Regression/RegressionDatasetProcessForm.tsx @@ -1,415 +1,81 @@ -import { useState, useId, useEffect } from 'react' -import { Button, Form, Row, Col } from 'react-bootstrap' -import { Trans, useTranslation } from 'react-i18next' import * as dfd from 'danfojs' import * as _Types from '@core/types' -import { DEFAULT_SCALER, DEFAULT_SELECTOR_DATASET_INDEX, E_TRANSFORMS, VERBOSE } from '@/CONSTANTS' -import { TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_1, F_TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_2 } from '@/CONSTANTS_DanfoJS' +import { DEFAULT_SELECTOR_DATASET_INDEX, VERBOSE } from '@/CONSTANTS' import { useRegressionContext } from '@context/useRegressionContext' import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' -import { LIST_TRANSFORMATIONS } from './CONSTANTS' -import { F_FILTER_Categorical, F_MAP_LabelEncoder } from '@core/nn-utils/utils' - - -/** Estado inicial del formulario para un dataframe: todas las columnas activas y el objetivo en la última. */ -function getDefaultColumns(dataframe_original: _Types.DataFrame_t) { - /** - * @type {_Types.DataFrameColumnNameTypeEnable_t[]} - */ - const _listColumnNameType: _Types.DataFrameColumnNameTypeEnable_t[] = dataframe_original.columns.map((_, index) => { - return { - column_enable : true, - column_name : dataframe_original.columns[index], - column_type : dataframe_original.dtypes[index] as _Types.DataFrameColumnType_t, - // FIX TypeScript - column_transform: dataframe_original.dtypes[index], - } - }) - const _listTransformations: _Types.DataFrameColumnTransformEnable_t[] = _listColumnNameType.map(({ column_name, column_type, column_enable }) => { - const _column_transform: _Types.ColumnTransform_t = /** @type {_Types.ColumnTransform_t} */ ((column_type === 'string') ? 'label-encoder' : column_type) - return { - column_name : column_name, - column_type : column_type, - column_enable : column_enable, - column_transform: _column_transform, - } - }) - return { - listColumnNameType : _listColumnNameType, - listColumnNameTransformations: _listTransformations, - columnNameTarget : dataframe_original.columns[dataframe_original.columns.length - 1], - } -} +import N4LDatasetProcessForm, { type DatasetProcessPlan_t } from '@components/dataframe/N4LDatasetProcessForm' +/** + * Procesa el conjunto de datos subido para la regresión (N4LDatasetProcessForm pone la interfaz): las columnas + * elegidas, codificadas y escaladas, son la entrada (X); el número que se predice se queda como está (y). + */ export default function RegressionDatasetProcessForm() { + const { datasets, setDatasets } = useRegressionContext() + const datasetSelected = datasets.index === DEFAULT_SELECTOR_DATASET_INDEX ? undefined : datasets.data[datasets.index as number] - const prefix = 'form-dataframe.' - const { t } = useTranslation() - - const plot_original_ID = useId() - const plot_processed_ID = useId() - - const { - datasets, - setDatasets, - } = useRegressionContext() - - /** - * @type {ReturnType>>} - */ - const { dataframe_original: dataframeOriginal } = datasets.data[datasets.index as number] - const [listColumnNameType, setListColumnNameTypes] = useState<_Types.DataFrameColumnNameTypeEnable_t[]>(() => getDefaultColumns(dataframeOriginal).listColumnNameType) - /** - * @type {ReturnType>} - */ - const [listColumnNameTransformations, setListColumnNameTransformations] = useState<_Types.DataFrameColumnTransformEnable_t[]>(() => getDefaultColumns(dataframeOriginal).listColumnNameTransformations) - /** - * @type {ReturnType>} - */ - const [columnNameTarget, setColumnNameTarget] = useState(() => getDefaultColumns(dataframeOriginal).columnNameTarget) - - // Al cambiar de dataset se reinicia el formulario. Se ajusta durante el render, no en un efecto: - // https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes - const [prevDataframeOriginal, setPrevDataframeOriginal] = useState(dataframeOriginal) - if (dataframeOriginal !== prevDataframeOriginal) { - const defaultColumns = getDefaultColumns(dataframeOriginal) - setPrevDataframeOriginal(dataframeOriginal) - setListColumnNameTypes(defaultColumns.listColumnNameType) - setListColumnNameTransformations(defaultColumns.listColumnNameTransformations) - setColumnNameTarget(defaultColumns.columnNameTarget) - } - - /** - * @type {ReturnType>} - */ - const [typeScaler, setTypeScaler] = useState<_Types.ScalerKey_t>(DEFAULT_SCALER) - - - const [showDetails, setShowDetails] = useState({ - show_dataframe_original : false, - show_dataframe_form : true, - show_dataframe_processed: false, - }) - - const handleSubmit_ProcessDataset = async (event: React.FormEvent) => { - event.preventDefault() - - if (datasets.index === DEFAULT_SELECTOR_DATASET_INDEX) { + const handleProcess = ({ target, scaler: typeScaler, transforms }: DatasetProcessPlan_t) => { + if (datasetSelected === undefined) { console.error('DEFAULT_SELECTOR_DATASET_INDEX') return } - const _index: number = datasets.index as number - - const { dataframe_original } = datasets.data[_index] - let { dataframe_processed } = datasets.data[_index] + const { dataframe_original } = datasetSelected + const keptColumns = new Set(transforms.filter(({ column_transform }) => column_transform !== 'drop').map(({ column_name }) => column_name)) - /** - * @type {_Types.DatasetColumn_t[]} - */ - const new_dataset: _Types.DatasetColumn_t[] = [] - for (let index = 0; index < dataframe_original.columns.length; index++) { - new_dataset[index] = { - column_name : dataframe_original.columns[index], + const new_dataset: _Types.DatasetColumn_t[] = dataframe_original.columns + .map((column_name, index) => ({ + column_name, column_type : DataFrameUtils.DataFrameColumnType_To_DatasetColumnType(dataframe_original.dtypes[index]), - column_role : dataframe_original.columns[index] === columnNameTarget ? 'Target' : 'Feature', + column_role : column_name === target ? 'Target' : 'Feature', column_missing_values: false, - } - } - const new_dataset_transforms = [ - // Los que sean de tipo String se pasan a categoricos y se filtran para añadir la función de transformación label encoder - ...new_dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder), - // listColumnNameTransformations - ] - - const dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder(dataframe_processed, new_dataset_transforms) - const new_encoders_map = dataframe_encoder.encoder_map - dataframe_processed = dataframe_encoder.dataframe_processed + } as _Types.DatasetColumn_t)) + .filter(({ column_name }) => keptColumns.has(column_name)) - const new_column_name_target = columnNameTarget - const new_dataframe_X = dataframe_processed.drop({ columns: [new_column_name_target] }).copy() - const new_dataframe_y = dataframe_original[new_column_name_target] + // Siempre desde los datos originales: si se vuelve a procesar, las columnas descartadas antes también cuentan + const dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder(DataFrameUtils.DataFrameDeepCopy(dataframe_original), transforms) + const dataframe_processed = dataframe_encoder.dataframe_processed + const new_dataframe_X = dataframe_processed.drop({ columns: [target] }).copy() + const new_dataframe_y = dataframe_original[target] - const scalers = { - 'standard-scaler': () => new dfd.StandardScaler(), - 'min-max-scaler' : () => new dfd.MinMaxScaler() - } - const scaler = scalers[typeScaler]() + const scaler = typeScaler === 'standard-scaler' ? new dfd.StandardScaler() : new dfd.MinMaxScaler() const new_scaler = scaler.fit(new_dataframe_X) const new_X = new_scaler.transform(new_dataframe_X) - const new_y = new_dataframe_y setDatasets((prevState) => { - if (prevState.index === DEFAULT_SELECTOR_DATASET_INDEX) { - console.error('DEFAULT_SELECTOR_DATASET_INDEX') - return prevState - } - const _index: number = prevState.index as number - - const new_path = prevState.data[_index].path - const new_csv = prevState.data[_index].csv - const new_info = prevState.data[_index].info - const new_container_info = prevState.data[_index].container_info - - /** - * @type {_Types.DatasetProcessed_t} - */ - const newDatasetProcessed = { + if (prevState.index === DEFAULT_SELECTOR_DATASET_INDEX) return prevState + const previous = prevState.data[prevState.index as number] + const newDatasetProcessed: _Types.DatasetProcessed_t = { is_dataset_upload : true, is_dataset_processed: true, dataframe_original : dataframe_original, dataframe_processed : dataframe_processed, dataset : new_dataset, - dataset_transforms : new_dataset_transforms, - path : new_path, - csv : new_csv, - info : new_info, - container_info : new_container_info, + dataset_transforms : transforms, + path : previous.path, + csv : previous.csv, + info : previous.info, + container_info : previous.container_info, data_processed : { dataframe_X : new_dataframe_X, dataframe_y : new_dataframe_y, X : new_X, - y : new_y, - encoders : new_encoders_map, + y : new_dataframe_y, + encoders : dataframe_encoder.encoder_map, scaler : new_scaler, - column_name_target: new_column_name_target, - } - } - - return { - ...prevState, - data: [ - ...prevState.data, - newDatasetProcessed - ], - index: prevState.data.length - } - }) - - dataframe_processed - .plot(plot_processed_ID) - .table({ - config: F_TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_2(dataframe_processed.columns, listColumnNameTransformations, columnNameTarget), - layout: { - title: t('dataframe-processed'), - }, - }) - - setShowDetails({ - show_dataframe_original : false, - show_dataframe_form : false, - show_dataframe_processed: true, - }) - } - - - - useEffect(() => { - // datasetLocal - if (datasets.index === DEFAULT_SELECTOR_DATASET_INDEX) { - console.error('DEFAULT_SELECTOR_DATASET_INDEX') - return - } - const _index: number = datasets.index as number - datasets.data[_index] - .dataframe_original - .plot(plot_original_ID) - .table({ - config: TABLE_PLOT_STYLE_CONFIG__STYLE_N4L_1, - layout: { - title: t('dataframe-original'), + column_name_target: target, }, - }) - }, [/* datasetLocal */ datasets, t, plot_original_ID/*, plot_processed_ID, listColumnNameTransformations, columnNameTarget */]) - - const handleChange_Scaler = (e: React.ChangeEvent) => { - /** - * @type {_Types.ScalerKey_t} - */ - const newTypeScaler: _Types.ScalerKey_t = e.target.value as _Types.ScalerKey_t - setTypeScaler(newTypeScaler) - } - - const handleChange_ColumnTransformEnable = (e: React.ChangeEvent, column_name: string) => { - setListColumnNameTransformations((prevState) => { - return prevState.map((oldColumn) => { - if (oldColumn.column_name === column_name) { - return { - ...oldColumn, - column_enable : e.target.checked, - column_transform: 'drop' - } - } - return { ...oldColumn } - }) + } + // En su sitio, como en la clasificación (antes se añadía otra copia y el selector de fichero salía repetido) + return { ...prevState, data: prevState.data.map((dataset, index) => (index === prevState.index ? newDatasetProcessed : dataset)) } }) } - const handleChange_ColumnTransform = (e: React.ChangeEvent, column_name: string) => { - setListColumnNameTransformations((prevState) => { - return prevState.map((oldColumn) => { - const newColumn = { - ...oldColumn, - column_transform: e.target.value as _Types.ColumnTransform_t - } - return (oldColumn.column_name === column_name) ? newColumn : oldColumn - }) - } - ) - } - - const handleChange_ColumnNameTarget = (e: React.ChangeEvent) => { - setColumnNameTarget(e.target.value) - setListColumnNameTransformations((prevState) => { - return prevState.map((oldColumn: _Types.DataFrameColumnTransformEnable_t) => { - const newColumn = { - ...oldColumn, - column_transform: E_TRANSFORMS.LABEL_ENCODER as _Types.ColumnTransform_t - } - return newColumn - }) - }) - } + if (datasetSelected === undefined) return null + const { data_processed } = datasetSelected + const processed = datasetSelected.is_dataset_processed && data_processed + ? { dataframe: datasetSelected.dataframe_processed, X: data_processed.X, target: data_processed.column_name_target, transforms: datasetSelected.dataset_transforms ?? [] } + : null if (VERBOSE) console.debug('render RegressionDatasetProcessForm') - return <> - - -
      - - - -
      - - -
      - - -
      -
      - -
      -
      - - -
      -
      - - - -
      - -

      -
      - - - - {typeScaler} - - <> - - - - - - - - - - {columnNameTarget} - - <> - {listColumnNameType.map(({ column_name, column_enable }, index) => { - return - })} - - - - - - - -
      - -

      -
      - - {listColumnNameTransformations.map(({ column_enable, column_name, column_type, column_transform, }, index) => { - return -
      - handleChange_ColumnTransformEnable(e, column_name)} - /> - - {column_name} - handleChange_ColumnTransform(e, column_name)}> - <> - {LIST_TRANSFORMATIONS.map((optionValue, optionIndex) => { - return - })} - - - Dtype: [{column_type}] -> {column_transform} - -
      - - })} -
      - -
      - - -
      - -
      - -
      -
      -
      - -
      -
      - - -
      - -
      - - -
      - - -
      -
      - -
      - -} \ No newline at end of file + return +} diff --git a/src/pages/playground/1_Regression/RegressionDatasetShow.tsx b/src/pages/playground/1_Regression/RegressionDatasetShow.tsx index e326027..07d1609 100644 --- a/src/pages/playground/1_Regression/RegressionDatasetShow.tsx +++ b/src/pages/playground/1_Regression/RegressionDatasetShow.tsx @@ -1,161 +1,59 @@ -import { useCallback, useEffect, useState, useId } from 'react' -import type { ChangeEvent } from 'react' -import { Card, Col, Form, Row } from 'react-bootstrap' +import { lazy } from 'react' +import { Card, Form } from 'react-bootstrap' import { Trans, useTranslation } from 'react-i18next' -import { DataFrame } from 'danfojs' -import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' import { DEFAULT_SELECTOR_DATASET_INDEX, VERBOSE } from '@/CONSTANTS' -import { TABLE_PLOT_STYLE_CONFIG } from '@/CONSTANTS_DanfoJS' -import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' -import N4LTablePagination from '@components/table/N4LTablePagination' +import N4LEmptyState from '@components/loading/N4LEmptyState' import N4LSummary from '@components/summary/N4LSummary' +import N4LDatasetViews from '@components/dataframe/N4LDatasetViews' import { useRegressionContext } from '@context/useRegressionContext' -import type { DatasetProcessed_t } from '@core/types' -const EMPTY_DATAFRAME = new DataFrame() +// Las estadísticas usan Plotly (1,1 MB): se descargan al abrir su apartado, no con la página +const N4LDataFrameDescribe = lazy(() => import('@components/dataframe/N4LDataFrameDescribe')) +/** + * El conjunto de datos con el que se entrena, ya procesado: tal cual, codificado y escalado (lo que recibe la red), en + * pestañas; su información y las estadísticas de cada columna. Si el conjunto tiene varios ficheros (vino tinto y + * blanco, matemáticas y portugués…), se elige cuál. + */ export default function RegressionDatasetShow() { - const { - datasets, - setDatasets, - } = useRegressionContext() - - const dataframe_processed_plotID = useId() - const dataframe_processed_describe_plotID = useId() - + const { datasets, setDatasets } = useRegressionContext() const { t } = useTranslation() - - // i18n const prefix = 'pages.playground.generator.dataset.' - const [showProcessed, setShowProcessed] = useState(false) - const datasetSelected = datasets.index !== DEFAULT_SELECTOR_DATASET_INDEX && datasets.index >= 0 ? datasets.data[datasets.index] : undefined - const showDataset = Boolean(datasetSelected?.is_dataset_processed) - const dataframe = (showProcessed ? datasetSelected?.dataframe_processed : datasetSelected?.dataframe_original) ?? EMPTY_DATAFRAME - - /** - * - * @param {React.ChangeEvent} e - */ - const handleChange_DatasetProcessed = (e: ChangeEvent) => { - setShowProcessed(e.target.checked) - } - - /** - * - * @param {React.ChangeEvent} e - */ - const handleChange_DatasetSelected = async (e: ChangeEvent) => { - const index = parseInt(e.target.value) - setDatasets((prevState) => { - return { - ...prevState, - data : [...prevState.data], - index: index - } - }) - } - - - const updateDataFrameLocal = useCallback(async (_datasetSelected: DatasetProcessed_t) => { - if (!showDataset) { - if (VERBOSE) console.debug('!showDataset') - return - } - const dataframe_processed = _datasetSelected.dataframe_processed - - dataframe_processed - .plot(dataframe_processed_plotID) - .table({ config: TABLE_PLOT_STYLE_CONFIG }) - DataFrameUtils.DataFrameDescribePlot(dataframe_processed, dataframe_processed_describe_plotID, { - config : TABLE_PLOT_STYLE_CONFIG, - emptyText: t('dataframe.describe.no-numeric'), - transpose: true, - }) - }, [showDataset, dataframe_processed_plotID, dataframe_processed_describe_plotID, t]) - - useEffect(() => { - if (VERBOSE) console.debug('useEffect [datasets, updateDataFrameLocal]') - const init = async () => { - if (datasets.data.length >= 1 && datasets.index !== DEFAULT_SELECTOR_DATASET_INDEX && datasets.index >= 0) { - await updateDataFrameLocal(datasets.data[datasets.index]) - } - } - init().then(() => undefined) - }, [datasets, updateDataFrameLocal]) + const isReady = Boolean(datasetSelected?.is_dataset_processed) + // La columna que se predice: se resalta en las tablas y en las estadísticas + const target = datasetSelected?.data_processed?.column_name_target ?? null if (VERBOSE) console.debug('render RegressionDatasetShow') - return <> + return ( - -

      -
      - handleChange_DatasetProcessed(e)} - /> - - handleChange_DatasetSelected(e)} - > - - {datasets.data - .map(({ csv }, index) => { - return - })} + +

      + {datasets.data.length > 1 && + + {t('dataset-view.file')} + { + const index = Number(event.target.value) + setDatasets((prevState) => ({ ...prevState, index })) + }}> + {datasets.data.map(({ csv }, index) => )} - -
      + }
      - {!showDataset && <> - - } - {showDataset && <> - - - - - + {!isReady && } + {isReady && datasetSelected !== undefined && <> +
      - - - {datasets.data.length >= 1 && datasets.index !== DEFAULT_SELECTOR_DATASET_INDEX && datasets.index >= 0 && !datasets.data[datasets.index].is_dataset_upload && <> - {/* TEXTO DEL DATASET car.info */} - } - info={datasets.data[datasets.index].container_info} /> - } - } - info={
      } /> - } - info={
      } /> - -
      + {!datasetSelected.is_dataset_upload && + } info={datasetSelected.container_info} />} + } /> } - - {/*} info={} />*/} - {/*} info={} />*/} - {/*} info={} />*/} -
      - -} \ No newline at end of file + ) +} diff --git a/src/pages/playground/1_Regression/RegressionEditorFeaturesSelector.tsx b/src/pages/playground/1_Regression/RegressionEditorFeaturesSelector.tsx index c085bf3..8c8e210 100644 --- a/src/pages/playground/1_Regression/RegressionEditorFeaturesSelector.tsx +++ b/src/pages/playground/1_Regression/RegressionEditorFeaturesSelector.tsx @@ -6,7 +6,7 @@ import { Trans } from 'react-i18next' import { DEFAULT_SELECTOR_DATASET_INDEX, VERBOSE } from '@/CONSTANTS' import { useRegressionContext } from '@context/useRegressionContext' -import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +import N4LEmptyState from '@components/loading/N4LEmptyState' /** * @@ -68,8 +68,11 @@ export default function RegressionEditorFeaturesSelector() { if (datasets && datasets.data.length > 0 && datasets.index !== DEFAULT_SELECTOR_DATASET_INDEX && datasets.index >= 0 && datasets.data[datasets.index].is_dataset_processed) { setParams((prevState) => { const _index: number = datasets.index as number - const Y_target = datasets.data[_index].dataframe_processed.columns[datasets.data[_index].dataframe_processed.columns.length - 1] - const X_features = new Set(datasets.data[_index].dataframe_processed.columns) + const { dataframe_processed, data_processed } = datasets.data[_index] + // Lo que de verdad usa el entrenamiento (data_processed): el objetivo no siempre es la última columna + // (California housing lo tiene en la primera) + const Y_target = data_processed?.column_name_target ?? dataframe_processed.columns[dataframe_processed.columns.length - 1] + const X_features = new Set(data_processed?.dataframe_X.columns ?? dataframe_processed.columns) X_features.delete(Y_target) return Object.assign({}, prevState, { @@ -99,18 +102,18 @@ export default function RegressionEditorFeaturesSelector() { {!show && <> - + } {show && <> - + - handleChange_FeatureSelector_Y(e)}> @@ -128,7 +131,7 @@ export default function RegressionEditorFeaturesSelector() { - + {datasets .data[datasets.index] diff --git a/src/pages/playground/1_Regression/RegressionEditorHyperparameters.tsx b/src/pages/playground/1_Regression/RegressionEditorHyperparameters.tsx index 3969671..23c5a77 100644 --- a/src/pages/playground/1_Regression/RegressionEditorHyperparameters.tsx +++ b/src/pages/playground/1_Regression/RegressionEditorHyperparameters.tsx @@ -4,14 +4,9 @@ import { Trans, useTranslation } from 'react-i18next' import alertHelper from '@utils/alertHelper' import { DEFAULT_SELECTOR_DATASET_INDEX, VERBOSE } from '@/CONSTANTS' -import { - DEFAULT_LEARNING_RATE, - DEFAULT_NUMBER_OF_EPOCHS, - DEFAULT_TEST_SIZE, -} from './CONSTANTS' -import { HyperparameterNumber, HyperparameterSelect, LossOptions, MetricsList, OptimizerOptions } from '@components/neural-network/N4LHyperparameterFields' +import { HyperparameterLearningRate, HyperparameterNumber, HyperparameterSelect, LossOptions, MetricsList, OptimizerOptions } from '@components/neural-network/N4LHyperparameterFields' import { useRegressionContext } from '@context/useRegressionContext' -import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +import N4LEmptyState from '@components/loading/N4LEmptyState' import type { IdLoss_t, IdMetric_t, IdOptimizer_t } from '@/types/nn-types' export default function RegressionEditorHyperparameters() { @@ -107,15 +102,15 @@ export default function RegressionEditorHyperparameters() { {!show && <> - + } {show && <> - + + defaultValue={params.params_training.n_of_epochs} onChange={handlerChange_NumberOfEpochs} /> + defaultValue={params.params_training.test_size} onChange={handlerChange_TestSize} />
      change_params_training('id_optimizer', value as IdOptimizer_t)}> @@ -124,7 +119,7 @@ export default function RegressionEditorHyperparameters() {
      change_params_training('id_loss', value as IdLoss_t)}> - +
      = 0 && datasets.data[datasets.index].is_dataset_processed + // La salida (una neurona, lineal) la fija la página: se miran las unidades y las activaciones de las ocultas + const issues = useMemo(() => checkDenseLayers(params.params_layers), [params.params_layers]) const handlerClick_AddLayer_Start = async () => { if (params.params_layers.length <= 10) { @@ -72,16 +81,25 @@ export default function RegressionEditorLayers() { return ( denseLayerSummary(t, layer)} + renderFields={(layer, index) => ( + handleChange_Layer(changed, { + is_disabled: params.params_layers[changed].is_disabled, + units, + activation, + })} /> + )} + // La salida de regresión (una neurona, lineal) no se borra + isLocked={(layer) => layer.is_disabled === true} + check={ setParams((prevState) => ({ ...prevState, params_layers }))} />} + flagged={flaggedLayers(issues)} onAddStart={handlerClick_AddLayer_Start} onAddEnd={handlerClick_AddLayer_End} onRemove={handlerClick_RemoveLayer} - onChange={(index, layer) => handleChange_Layer(index, { - is_disabled: params.params_layers[index].is_disabled, - units : layer.units, - activation : layer.activation, - })} + onMove={(from, to) => setParams((prevState) => ({ ...prevState, params_layers: moveLayer(prevState.params_layers, from, to) }))} + onRestore={(params_layers) => setParams((prevState) => ({ ...prevState, params_layers }))} waiting={!show} - titleAs={'h2'} + titleAs={'h3'} /> ) } \ No newline at end of file diff --git a/src/pages/playground/1_Regression/RegressionEditorVisor.tsx b/src/pages/playground/1_Regression/RegressionEditorVisor.tsx index 229ce4b..cd455ce 100644 --- a/src/pages/playground/1_Regression/RegressionEditorVisor.tsx +++ b/src/pages/playground/1_Regression/RegressionEditorVisor.tsx @@ -4,7 +4,7 @@ import { Trans, useTranslation } from 'react-i18next' import { VERBOSE } from '@/CONSTANTS' import { useRegressionContext } from '@context/useRegressionContext' -import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +import N4LEmptyState from '@components/loading/N4LEmptyState' const DEFAULT_VISOR_OPTIONS = { rmse : true, @@ -30,11 +30,7 @@ export default function RegressionEditorVisor() { } = useRegressionContext() const [visorOptions, setVisorOptions] = useState(DEFAULT_VISOR_OPTIONS) - // const [show, setShow] = useState(false) - // useEffect(() => { - // setShow(datasets.data[datasets.index].is_dataset_processed) - // }, [setShow, datasets]) const isReady = datasets.data[datasets.index]?.is_dataset_processed; useEffect(() => { @@ -67,7 +63,7 @@ export default function RegressionEditorVisor() { {!isReady && <> - + } {isReady && <> diff --git a/src/pages/playground/1_Regression/RegressionManual.tsx b/src/pages/playground/1_Regression/RegressionManual.tsx index b7cdfce..2e7904a 100644 --- a/src/pages/playground/1_Regression/RegressionManual.tsx +++ b/src/pages/playground/1_Regression/RegressionManual.tsx @@ -1,27 +1,27 @@ -import "katex/dist/katex.min.css" -import { Trans } from "react-i18next" -import { VERBOSE } from "@/CONSTANTS" -import N4LLatex from "@components/latex/N4LLatex" +import 'katex/dist/katex.min.css' +import { Trans } from 'react-i18next' +import { VERBOSE } from '@/CONSTANTS' +import N4LLatex from '@components/latex/N4LLatex' export default function RegressionManual() { - const prefixManual = "pages.playground.1-regression.generator.manual." + const prefixManual = 'pages.playground.1-regression.generator.manual.' - if (VERBOSE) console.debug("render RegressionManual") + if (VERBOSE) console.debug('render RegressionManual') return ( <>
      - - + +

      - +

      • - +
      • - +
      @@ -40,76 +40,76 @@ export default function RegressionManual() { {/*
    */}
    - - + +
    • - +
    • - +
    • - +
    • - +
    • - +
    - - + +

    - +

    - +

    - +

    - - + +

    - +

    - - + +

    - +

    - Info -
    + Info +
    - +
    - {"$$ Y(x) = b x + a $$"} + {'$$ Y(x) = b x + a $$'} - +
    - {"$$ Y(x_1, x_2, ..., x_n) = w_1 x_1 + w_2 x_2 + ... + w_n x_n + w_0 $$"} -
    + {'$$ Y(x_1, x_2, ..., x_n) = w_1 x_1 + w_2 x_2 + ... + w_n x_n + w_0 $$'} +
    ) diff --git a/src/pages/playground/1_Regression/RegressionPage.tsx b/src/pages/playground/1_Regression/RegressionPage.tsx new file mode 100644 index 0000000..4527e93 --- /dev/null +++ b/src/pages/playground/1_Regression/RegressionPage.tsx @@ -0,0 +1,14 @@ +import { RegressionProvider } from '@context/RegressionContext' +import Regression from './Regression' + +/** + * La página de entrenamiento con su contexto. Va aparte para que el contexto (que importa danfo.js) se descargue con + * ella y no con el playground: las demás tareas no lo necesitan + */ +export default function RegressionPage({ dataset }: { dataset: string }) { + return ( + + + + ) +} diff --git a/src/pages/playground/1_Regression/RegressionPrediction.tsx b/src/pages/playground/1_Regression/RegressionPrediction.tsx index bc2ebee..e9628df 100644 --- a/src/pages/playground/1_Regression/RegressionPrediction.tsx +++ b/src/pages/playground/1_Regression/RegressionPrediction.tsx @@ -1,20 +1,32 @@ -import { useState } from 'react' +import { useMemo, useState } from 'react' import { Button, Card, Col, Row, Form } from 'react-bootstrap' import { Trans, useTranslation } from 'react-i18next' import * as tfjs from '@tensorflow/tfjs' -import { DEFAULT_SELECTOR_INSTANCE, DEFAULT_SELECTOR_MODEL, DEFAULT_SELECTOR_MODEL_INDEX, VERBOSE } from '@/CONSTANTS' +import { DEFAULT_SELECTOR_MODEL, DEFAULT_SELECTOR_MODEL_INDEX, VERBOSE } from '@/CONSTANTS' import N4LSummary from '@components/summary/N4LSummary' -import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +import N4LEmptyState from '@components/loading/N4LEmptyState' +import N4LDivider from '@components/divider/N4LDivider' +import N4LVirtualSelect, { type VirtualSelectOption_t } from '@components/select/N4LVirtualSelect' import { useRegressionContext } from '@context/useRegressionContext' -import RegressionPredictionForm from '@pages/playground/1_Regression/RegressionPredictionForm' +import ModelReviewRegressionPredictForm from '@pages/playground/1_Regression/ModelReviewRegressionPredictForm' import RegressionPredictionInfo from '@pages/playground/1_Regression/RegressionPredictionInfo' import { TRANSFORM_DATASET_PROCESSED_TO_STATE_PREDICTION } from './utils' import TabularShapPanel from '@core/explainability/TabularShapPanel' import { dataframeRowsToNumbers, dataframeRowsWithDisplay } from '@core/explainability/shapSampling' +import { trackEvent } from '@core/analytics' -export default function RegressionPrediction() { +type RegressionPredictionProps = { + /** Secciones de la página (numeran el separador de la explicabilidad) */ + steps?: string[] +} + +// Valor de la variable objetivo para la lista de instancias: sin decimales de más +const formatTarget = (value: unknown) => (typeof value === 'number' && !Number.isInteger(value) ? String(Number(value.toFixed(4))) : String(value)) + +export default function RegressionPrediction({ steps }: RegressionPredictionProps) { const prefix = 'pages.playground.1-regression.predict.' + const prefixForm = 'pages.playground.generator.dynamic-form-dataset.' const { t } = useTranslation() const { @@ -26,27 +38,28 @@ export default function RegressionPrediction() { } = useRegressionContext() - /** - * @type {ReturnType>} - */ - const [indexInstance, setIndexInstance] = useState(DEFAULT_SELECTOR_INSTANCE) + // Instancia del conjunto de datos copiada al formulario (null hasta elegir una) + const [indexInstance, setIndexInstance] = useState(null) + // Valor real de lo que se predijo: si después se edita el formulario, el resultado sigue siendo de esa instancia + const [resultActual, setResultActual] = useState(null) const handleSubmit_Predict = async (e: React.FormEvent) => { e.preventDefault() const vector = prediction.input_3_dataframe_scaling.values[0] as number[] - const tensor = tfjs.tensor2d([vector]) const _indexModel: number = listModels.index as number - const model = (/**@type {tfjs.LayersModel}*/(listModels.data[_indexModel].model)) - const predictTensor = (/**@type {tfjs.Tensor}*/(model.predict(tensor)) as tfjs.Tensor) - - const result = Array.from(predictTensor.dataSync()) + const model = listModels.data[_indexModel].model + const predictTensor = tfjs.tidy(() => model.predict(tfjs.tensor2d([vector])) as tfjs.Tensor) + // Lectura asíncrona: con WebGPU las síncronas detienen la GPU + const result = Array.from(await predictTensor.data<'float32'>()) + predictTensor.dispose() + setResultActual(actualValue) setPrediction((prevState) => ({ ...prevState, result: result })) - + trackEvent('predict', { input: 'form' }) } const handleChange_Model_Index = (e: React.ChangeEvent) => { @@ -56,9 +69,7 @@ export default function RegressionPrediction() { })) } - const handleChange_Instance_Index = (e: React.ChangeEvent) => { - e.preventDefault() - const _indexInstance: number = parseInt(e.target.value) + const handleChange_Instance_Index = (_indexInstance: number) => { setIndexInstance(_indexInstance) const _indexModel: number = listModels.index as number const dataset_processed = listModels.data[_indexModel].dataset_processed @@ -80,6 +91,27 @@ export default function RegressionPrediction() { && listModels.index >= 0 const _indexModel: number = listModels.index as number + const dataProcessed = showPrediction ? listModels.data[_indexModel]?.dataset_processed?.data_processed : undefined + + // Una opción por instancia: su número y el valor real de la variable objetivo. Puede haber miles: el desplegable + // solo pinta las que se ven + const instanceOptions = useMemo(() => { + if (dataProcessed === undefined) return [] + const targets = dataProcessed.dataframe_y.values as unknown[] + return targets.map((target, index) => ({ value: index, label: `#${index}: ${formatTarget(target)}` })) + }, [dataProcessed]) + + // El valor real solo se enseña si el formulario sigue siendo la instancia elegida (sin editar) + const generatedModel = showPrediction ? listModels.data[_indexModel] : undefined + const originalRows = generatedModel?.dataset_processed.dataframe_original.values as unknown[][] | undefined + const selectedRow = indexInstance === null ? undefined : originalRows?.[indexInstance] + const formRow = prediction.input_1_dataframe_original.values[0] as unknown[] | undefined + const instanceMatches = selectedRow !== undefined && formRow !== undefined && + selectedRow.every((value, column) => String(value) === String(formRow[column])) + const actualValue = instanceMatches && indexInstance !== null + ? Number((dataProcessed?.dataframe_y.values as unknown[] | undefined)?.[indexInstance]) + : null + // Explicabilidad: el modelo recibe la instancia ESCALADA (input_3_dataframe_scaling), así que el // background sale de la X escalada del dataset del modelo seleccionado. const explainModel = listModels.data[_indexModel]?.model ?? null @@ -89,35 +121,24 @@ export default function RegressionPrediction() { return <> -

    -
    -
    - - handleChange_Instance_Index(e)}> - - <> - {showPrediction && <> - {Array(listModels.data[_indexModel].dataset_processed?.data_processed?.dataframe_X.values.length) - .fill(0) - .map((_value, index) => { - const index_format = index.toString().padStart(3, '0') - return - })} - } - - - +

    +
    +
    + t(prefixForm + 'entity-count', { shown, total })} />
    -
    +
    { - const index_format = index.toString() + const index_format = (index + 1).toString() return @@ -144,7 +165,7 @@ export default function RegressionPrediction() { {!showPrediction && <> - + } {showPrediction && <> @@ -171,18 +192,21 @@ export default function RegressionPrediction() {
    - - -
    + {/* El mismo formulario que el de los modelos preentrenados: tipo y rango de cada atributo */} + {indexInstance === null || generatedModel === undefined + ? + : } - +
    @@ -190,25 +214,25 @@ export default function RegressionPrediction() {
    - + }
    - {showPrediction && ( - explainModel} - getInstance={() => (prediction.input_3_dataframe_scaling.values[0] as number[] | undefined) ?? null} - getPool={() => dataframeRowsToNumbers(explainDataProcessed?.X.values)} - getPoolDisplay={() => dataframeRowsWithDisplay(explainDataProcessed?.X.values, explainDataProcessed?.dataframe_X?.values).display} - targetName={explainDataProcessed?.column_name_target} - getInstanceDisplay={() => (prediction.input_2_dataframe_encoding.values[0] as Array | undefined) ?? null} - valuesAreScaled - /> - )} + + explainModel} + getInstance={() => (prediction.input_3_dataframe_scaling.values[0] as number[] | undefined) ?? null} + getPool={() => dataframeRowsToNumbers(explainDataProcessed?.X.values)} + getPoolDisplay={() => dataframeRowsWithDisplay(explainDataProcessed?.X.values, explainDataProcessed?.dataframe_X?.values).display} + targetName={explainDataProcessed?.column_name_target} + getInstanceDisplay={() => (prediction.input_2_dataframe_encoding.values[0] as Array | undefined) ?? null} + valuesAreScaled + modelReady={showPrediction} + /> } diff --git a/src/pages/playground/1_Regression/RegressionPredictionForm.tsx b/src/pages/playground/1_Regression/RegressionPredictionForm.tsx deleted file mode 100644 index 2a55d4d..0000000 --- a/src/pages/playground/1_Regression/RegressionPredictionForm.tsx +++ /dev/null @@ -1,174 +0,0 @@ -import styles from '@pages/playground/1_Regression/Regression.module.css' -import { Row, Col, Form } from 'react-bootstrap' -import { useTranslation } from 'react-i18next' -import * as dfd from 'danfojs' - -import * as _Types from '@core/types' -import { VERBOSE } from '@/CONSTANTS' -import { DataFrameSetCellValue } from '@core/dataframe/DataFrameUtils' -import { useRegressionContext } from '@context/useRegressionContext' - -/** - * @typedef {Object} RegressionPredictionFormProps_t - * @property {_Types.CustomModelGenerated_t} generatedModel - * @property {Object} [dynamicObject = {}] - */ -type RegressionPredictionFormProps_t = { - generatedModel: _Types.CustomModelGenerated_t, - dynamicObject?: any -} -/** - * - * @param {RegressionPredictionFormProps_t} props - * @returns - */ -export default function RegressionPredictionForm (props: RegressionPredictionFormProps_t) { - const { generatedModel } = props - - const { - prediction, - setPrediction - } = useRegressionContext() - - const { t } = useTranslation() - - const getColor = (generatedModel: _Types.CustomModelGenerated_t, column_name: string) => { - if (generatedModel.params_features.Y_target === column_name) { - return styles.border_green - } - if (generatedModel.params_features.X_features.has(column_name)) { - return styles.border_blue - } - return styles.border_red - } - - const isDisabled = (generatedModel: _Types.CustomModelGenerated_t, column_name: string) => { - if (generatedModel.params_features.Y_target === column_name) { - return true - } - if (generatedModel.params_features.X_features.has(column_name)) { - return false - } - return true - } - - const handleChange_EditInstanceEncoding = (column_name: string, new_value: any) => { - if (generatedModel.dataset_processed.data_processed === undefined) { - console.error('Error: dataset_processed.data_processed is undefined') - return - } - const [new_value_encoding] = generatedModel.dataset_processed.data_processed.encoders[column_name].encoder.transform([new_value]) - const newInputDataFrameOriginal = DataFrameSetCellValue(prediction.input_1_dataframe_original, 0, column_name, new_value) - const newInputDataFrameProcessed = DataFrameSetCellValue(prediction.input_1_dataframe_processed, 0, column_name, new_value) - const newInputDataFrameEncoding = DataFrameSetCellValue(prediction.input_2_dataframe_encoding, 0, column_name, new_value_encoding) - const newInputDataFrameScaling = generatedModel.dataset_processed.data_processed.scaler.transform(newInputDataFrameEncoding) - - setPrediction((prevState) => { - return { - ...prevState, - input_1_dataframe_original : newInputDataFrameOriginal, - input_1_dataframe_processed: newInputDataFrameProcessed, - input_2_dataframe_encoding : newInputDataFrameEncoding, - input_3_dataframe_scaling : newInputDataFrameScaling - } - }) - } - - const handleChange_EditInstance = (column_name: string, new_value: any) => { - setPrediction((prevState) => { - if (generatedModel.dataset_processed.data_processed === undefined) { - console.error('Error: dataset_processed.data_processed is undefined') - return prevState - } - const newInputDataFrameOriginal = DataFrameSetCellValue(prediction.input_1_dataframe_original, 0, column_name, new_value) - const newInputDataFrameProcessed = DataFrameSetCellValue(prediction.input_1_dataframe_processed, 0, column_name, new_value) - const newInputDataFrameEncoding = DataFrameSetCellValue(prediction.input_2_dataframe_encoding, 0, column_name, new_value) - // const newInputDataFrameScaling = DataFrameSetCellValue(prediction.input_2_dataframe_encoding, 0, column_name, new_value) - const newInputDataFrameScaling = generatedModel.dataset_processed.data_processed.scaler.transform(newInputDataFrameEncoding) - - return { - ...prevState, - input_1_dataframe_original : newInputDataFrameOriginal, - input_1_dataframe_processed: newInputDataFrameProcessed, - input_2_dataframe_encoding : newInputDataFrameEncoding, - input_3_dataframe_scaling : newInputDataFrameScaling - } - }) - } - - if (VERBOSE) console.debug('render RegressionPredictionForm') - return - {generatedModel - .dataset_processed - .dataframe_processed - .columns - .map((column_name, index) => { - const column_type = generatedModel.dataset_processed.dataframe_original[column_name].dtype - const column_value = prediction.input_1_dataframe_original[column_name].values[0] - - switch (column_type) { - case 'int32': { - return - - {t('pages.playground.form.parameter')}: {column_name} - handleChange_EditInstance(column_name, parseInt(e.target.value))} /> - Dtype: {column_type} - - - } - case 'float32': { - return - - {t('pages.playground.form.parameter')}: {column_name} - handleChange_EditInstance(column_name, parseFloat(e.target.value))} /> - Dtype: {column_type} - - - } - case 'string': { - const labelEncoder = new dfd.LabelEncoder() - labelEncoder.fit(generatedModel.dataset_processed.dataframe_original[column_name]) - return - - {t('pages.playground.form.parameter')}: {column_name} - handleChange_EditInstanceEncoding(column_name, e.target.value)}> - <> - {Object.entries(labelEncoder.classes) - .map(([text, _value], index_options) => { - return - }) - } - - - Dtype: {column_type} - - - } - default: { - return - Error, option not valid - - } - } - })} - -} diff --git a/src/pages/playground/1_Regression/RegressionPredictionInfo.tsx b/src/pages/playground/1_Regression/RegressionPredictionInfo.tsx index 8a1d803..54abb6d 100644 --- a/src/pages/playground/1_Regression/RegressionPredictionInfo.tsx +++ b/src/pages/playground/1_Regression/RegressionPredictionInfo.tsx @@ -1,100 +1,72 @@ -import styles from "@pages/playground/1_Regression/Regression.module.css" -import { Row, Col, Form } from "react-bootstrap" -import { Trans } from "react-i18next" -import * as _Types from "@core/types" +import { useEffect } from 'react' +import { Trans, useTranslation } from 'react-i18next' +import { announce } from '@core/a11y/announce' +import * as _Types from '@core/types' +import N4LEmptyState from '@components/loading/N4LEmptyState' +import N4LSummary from '@components/summary/N4LSummary' -/** - * @typedef {Object} RegressionPredictionInfoProps - * @property {_Types.StatePrediction_t} prediction - */ type RegressionPredictionInfoProps = { - prediction: _Types.StatePrediction_t + prediction : _Types.StatePrediction_t + /** Variable que predice el modelo */ + targetName?: string + /** Valor real, si lo predicho es una instancia del conjunto de datos sin cambios */ + actual? : number | null } -/** - * - * @param {RegressionPredictionInfoProps} props - * @returns - */ -export default function RegressionPredictionInfo(props: RegressionPredictionInfoProps) { - const { prediction } = props - const ready = Boolean( - prediction && - prediction.input_1_dataframe_original && - Array.isArray(prediction.input_1_dataframe_original.values) && - prediction.input_1_dataframe_original.values.length >= 1 - ) +/** Valor predicho y, si se conoce, el real y el error; debajo, la entrada en cada paso hasta el modelo */ +export default function RegressionPredictionInfo({ prediction, targetName, actual = null }: RegressionPredictionInfoProps) { + const prefix = 'pages.playground.1-regression.predict.' + const { t, i18n } = useTranslation() + const numberFormat = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 3 }) + const percentFormat = new Intl.NumberFormat(i18n.language, { style: 'percent', maximumFractionDigits: 1 }) + + const [value] = prediction.result + const error = actual === null || value === undefined ? null : value - actual + const label = targetName ? t(prefix + 'predicted-value', { target: targetName }) : t('prediction-result') + const errorText = actual === null || error === null ? null : t(prefix + 'error', { + value : (error > 0 ? '+' : '') + numberFormat.format(error), + percent: actual === 0 ? '—' : percentFormat.format(Math.abs(error / actual)), + }) + // El resultado, también para el lector de pantalla, sin mover el foco del botón que lo ha pedido (WCAG 4.1.3) + const result = value === undefined ? '' + : [`${label}: ${numberFormat.format(value)}`, ...(actual !== null && errorText !== null ? [t(prefix + 'actual-value', { value: numberFormat.format(actual) }), errorText] : [])].join('. ') + useEffect(() => announce(result), [result]) + + if (value === undefined) return + + const steps: Array<[string, string, unknown[] | undefined]> = [ + ['prediction-input', 'prediction-input-description', prediction.input_1_dataframe_original.values[0] as unknown[]], + ['prediction-input-encoding', 'prediction-input-encoding-description', prediction.input_2_dataframe_encoding.values[0] as unknown[]], + ['prediction-input-scaling', 'prediction-input-scaling-description', prediction.input_3_dataframe_scaling.values[0] as unknown[]], + ] + const formatValue = (item: unknown) => (typeof item === 'number' ? numberFormat.format(item) : String(item)) return ( - <> - {ready && ( - <> - - - - - - - - - - - - - {/* - - - - - - - - - - - - - - - - - - - - - - - */} - - - - - - - - - - - - - - )} - +
    +
    + {label} + {numberFormat.format(value)} + {actual !== null && error !== null && <> + + {t(prefix + 'actual-value', { value: numberFormat.format(actual) })} + + {errorText} + } +
    +
    + }> +
    + {steps.map(([title, description, values]) => values && ( +
    +
    + +
    +
    {values.map(formatValue).join(', ')}
    +
    + ))} +
    +
    +
    +
    ) } diff --git a/src/pages/playground/1_Regression/RegressionTableModels.tsx b/src/pages/playground/1_Regression/RegressionTableModels.tsx index dd7f6af..8815d03 100644 --- a/src/pages/playground/1_Regression/RegressionTableModels.tsx +++ b/src/pages/playground/1_Regression/RegressionTableModels.tsx @@ -1,15 +1,23 @@ import { useState } from 'react' import { Table, Card, Button, Container, Row, Col } from 'react-bootstrap' -import { Trans } from 'react-i18next' +import { Trans, useTranslation } from 'react-i18next' import * as tfvis from '@tensorflow/tfjs-vis' import { VERBOSE } from '@/CONSTANTS' -import { parseLogs } from '@core/history/utils' +import { bestModelIndex, formatEpochs } from '@core/history/trainingSummary' +import N4LFinalMetrics, { N4LBestBadge } from '@components/neural-network/N4LFinalMetrics' +import N4LTrainingCurves from '@components/neural-network/N4LTrainingCurves' import { nnLabel } from '@core/nn-utils/ArchitectureTypesHelper' +import { layersSummary } from '@components/neural-network/layerSummary' import { useRegressionContext } from '@context/useRegressionContext' -import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +import N4LEmptyState from '@components/loading/N4LEmptyState' import type { CustomModelGenerated_t } from '@core/types' import N4LPagination from '@components/table/N4LPagination' +import { useParams } from 'react-router' +import { TASKS } from '@/TASKS' +import N4LReportButton from '@components/report/N4LReportButton' +import { historyNumbers } from '@core/report/trainingReport' +import { denseLayerSummary } from '@components/neural-network/layerSummary' export default function RegressionTableModels({ rowsPerPage = 3 }) { const prefix = 'generator.table-models.' @@ -23,6 +31,21 @@ export default function RegressionTableModels({ rowsPerPage = 3 }) { const showTable = listModels.data.length > 0 const pageCount = Math.ceil(listModels.data.length / rowsPerPage) + // Historial de cada modelo (mismo orden que la tabla) y el de menor pérdida final, si hay con quién comparar + const histories = listModels.data.map((generated) => generated.history.history) + const bestIndex = histories.length > 1 ? bestModelIndex(histories) : -1 + // Para compararlos: lo que cambia de un entrenamiento a otro (las métricas solo se miden, no cambian cómo aprende) + const { t } = useTranslation() + const { example } = useParams() + const parameters = listModels.data.map(({ params_training, params_layers }) => ({ + 'learning-rate': String(params_training.learning_rate), + 'n-of-epochs' : String(params_training.n_of_epochs), + 'test-size' : params_training.test_size + '%', + 'layers' : layersSummary(t, params_layers), + 'id-optimizer' : nnLabel(params_training.id_optimizer), + 'id-loss' : nnLabel(params_training.id_loss), + })) + const handleClick_ChangePage = (pageNumber: number) => { setActivePage(pageNumber) } @@ -41,20 +64,20 @@ export default function RegressionTableModels({ rowsPerPage = 3 }) { if (VERBOSE) console.debug('render RegressionTableModels') return <> - -

    | {listModels.data.length}

    -
    + +

    | {listModels.data.length}

    +
    @@ -63,7 +86,7 @@ export default function RegressionTableModels({ rowsPerPage = 3 }) { {!showTable && <> - + } {showTable && <> @@ -91,10 +114,10 @@ export default function RegressionTableModels({ rowsPerPage = 3 }) { .slice(activePage * rowsPerPage, (activePage * rowsPerPage) + rowsPerPage) .map((value: CustomModelGenerated_t, index: number) => { return - {(activePage * rowsPerPage) + index + 1} - {value.params_training.learning_rate}% + {(activePage * rowsPerPage) + index + 1}{(activePage * rowsPerPage) + index === bestIndex && } + {value.params_training.learning_rate} {value.params_training.test_size}% - {value.params_training.n_of_epochs} + {formatEpochs(value.history.epoch.length, value.params_training.n_of_epochs)} {value.params_layers .map((value, index2) => { @@ -116,21 +139,26 @@ export default function RegressionTableModels({ rowsPerPage = 3 }) { })} - {Object.entries(value.history.history) - .map(([key, logs], index2) => { - return - {key} {parseLogs(logs as any)}
    -
    - })} + + ({ + version : 1, + task : TASKS.REGRESSION, + dataset : example ?? '', + model : (activePage * rowsPerPage) + index + 1, + createdAt : new Date().toISOString(), + layers : value.params_layers.map((layer) => denseLayerSummary(t, layer)), + parameters: parameters[(activePage * rowsPerPage) + index], + history : historyNumbers(value.history.history), + })} /> })} @@ -143,6 +171,11 @@ export default function RegressionTableModels({ rowsPerPage = 3 }) {
    + + + + + }
    diff --git a/src/pages/playground/1_Regression/description/DescriptionRegression.tsx b/src/pages/playground/1_Regression/description/DescriptionRegression.tsx index f7e8a91..e733ed7 100644 --- a/src/pages/playground/1_Regression/description/DescriptionRegression.tsx +++ b/src/pages/playground/1_Regression/description/DescriptionRegression.tsx @@ -1,59 +1,38 @@ import { Card, Col, Container, Row } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + import N4LLatex from '@components/latex/N4LLatex' +const prefix = 'pages.regression-description.' + +/** Qué es la regresión lineal, con un ejemplo y su ecuación (/playground/description-regression) */ export default function DescriptionRegression() { + const { t } = useTranslation() + // Varios párrafos por clave; sin traducciones (cargando, en las pruebas) i18next devuelve la clave: nada que listar + const list = (key: string): string[] => { + const value: unknown = t(prefix + key, { returnObjects: true }) + return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [] + } return <> - + -

    Regresión lineal

    +

    {t(prefix + 'title')}

    -

    Descripción del problema y los modelos

    +

    {t(prefix + 'subtitle')}

    -

    Los problemas en el contexto del análisis de datos se refieren a situaciones en las que se busca predecir o estimar un valor numérico basado en variables de entrada. Los problemas de regresión lineal involucran la - utilización de un modelo matemático conocido como regresión lineal para realizar esta predicción.

    - -

    Un modelo de regresión lineal es una técnica estadística que busca establecer una relación lineal entre una variable de respuesta (o variable dependiente) y una o más variables predictoras (o variables independientes). El - objetivo del modelo es encontrar la línea recta que mejor se ajuste a los datos observados, de modo que pueda utilizarse para predecir el valor de la variable de respuesta en función de los valores de las variables - predictoras.

    - -

    El modelo de regresión lineal utiliza una función matemática para representar la relación lineal entre las variables. Esta función se basa en la fórmula de una línea recta, donde se estima el valor de la variable de - respuesta a través de una combinación lineal de los valores de las variables predictoras. Los coeficientes de la ecuación lineal, también conocidos como coeficientes de regresión, se determinan mediante técnicas estadísticas - que buscan minimizar la diferencia entre los valores observados y los valores predichos por el modelo.

    - -

    Una vez que se ha ajustado el modelo de regresión lineal, puede utilizarse para hacer predicciones sobre el valor de la variable de respuesta cuando se conocen los valores de las variables predictoras. También permite - identificar la contribución relativa de cada variable predictora en la explicación de la variabilidad de la variable de respuesta.

    - -

    En resumen, los modelos de regresión lineal son herramientas estadísticas utilizadas para predecir valores numéricos basados en variables predictoras, estableciendo una relación lineal entre ellas. Estos modelos pueden ser - útiles en diversos campos, como la economía, la ciencia, la ingeniería y la investigación social, entre otros.

    + {list('paragraphs').map((text) =>

    {text}

    )}
    - -

    - - Supongamos que queremos predecir el precio de una casa (variable de respuesta, denotada por $Y$) basándonos en el tamaño de la casa en metros cuadrados (variable predictora, denotada por $x$). Podemos expresar la relación - entre - estas dos variables mediante la siguiente ecuación de regresión lineal: - -

    +

    {t(prefix + 'example')}

    {'$$ Y = \\beta_0 + \\beta_1 * x + \\epsilon $$'} - - Donde: - -
      -
    1. $Y$ representa el precio de la casa.
    2. -
    3. X representa el tamaño de la casa.
    4. -
    5. $\beta_0$ es el intercepto, que indica el valor de Y cuando X es igual a cero.
    6. -
    7. $\beta_1$ es la pendiente de la línea de regresión, que representa el cambio en el precio de la casa asociado a un incremento unitario en el tamaño de la casa.
    8. -
    9. $\epsilon$ es el término de error, que representa la variabilidad no explicada por el modelo.
    10. -
    -

    El objetivo del modelo de regresión lineal es estimar los valores de los coeficientes $\beta_0$ y $\beta_1$ a partir de los datos observados para obtener una línea recta que mejor se ajuste a los puntos en el gráfico - de dispersión de las variables.

    -

    Una vez que el modelo está ajustado, podemos utilizarlo para predecir el precio de una casa desconocida dada su área en metros cuadrados. Simplemente debemos sustituir el valor de $x$ en la ecuación y calcular el - valor predicho de $Y$.

    -

    Cabe destacar que este ejemplo es un caso simplificado de regresión lineal simple, y en la práctica los modelos pueden involucrar múltiples variables predictoras y considerar interacciones entre ellas.

    +

    {t(prefix + 'where')}

    +
      + {list('terms').map((text) =>
    • {text}
    • )} +
    + {list('closing').map((text) =>

    {text}

    )}
    diff --git a/src/pages/playground/1_Regression/modelReviewGuide.ts b/src/pages/playground/1_Regression/modelReviewGuide.ts new file mode 100644 index 0000000..9a4def8 --- /dev/null +++ b/src/pages/playground/1_Regression/modelReviewGuide.ts @@ -0,0 +1,57 @@ +import { LR_MODEL_KEYS } from '@/MODEL_KEYS' +import type { GuideStep_t } from '@components/guide/N4LGuide' +import { buildGuideSteps, centerStep, guideStep, type GuideStepSpec_t, type GuideTranslate_t } from '@components/guide/buildGuideSteps' + +type RegressionGuide_t = { + /** Un paso por variable de entrada (fields.); si son muchas, uno para todo el formulario (form) */ + fieldSteps: boolean + /** Pasos propios del modelo, detrás del paso con esa clave */ + extra? : Record +} + +/** + * Modelos con guía en su página de prueba (/playground/regression/model/). Sus textos van en guide.1-regression. + * y, lo que es igual en todos, en guide.1-regression.common. + */ +const GUIDES: Record = { + [LR_MODEL_KEYS.AUTO_MPG] : { fieldSteps: true }, + // Sin G1 ni G2 (las notas de los trimestres): en su formulario se echan en falta y un paso explica por qué + [LR_MODEL_KEYS.STUDENT_PERFORMANCE]: { fieldSteps: false, extra: { form: [guideStep('grades', 'form')] } }, + [LR_MODEL_KEYS.WINE] : { fieldSteps: false }, + // Dos conjuntos con columnas distintas: un paso para todo el formulario + [LR_MODEL_KEYS.SALARY] : { fieldSteps: false }, + [LR_MODEL_KEYS.HOUSING_PRICES] : { fieldSteps: false }, +} + +export const REGRESSION_REVIEW_GUIDES = Object.keys(GUIDES) + +/** + * Los pasos de la guía de la página de un modelo de regresión (null si no tiene): qué predice, el modelo y sus + * conjuntos de datos (tal cual, procesados y su análisis), el formulario, la predicción y su explicación. `fields` + * son las variables de entrada del conjunto elegido. + */ +export function regressionReviewGuide(t: GuideTranslate_t, modelKey: string, fields: string[], stepByStep = false): GuideStep_t[] | null { + const guide = GUIDES[modelKey] + if (guide === undefined) return null + const specs: GuideStepSpec_t[] = [ + centerStep('intro'), + guideStep('model', 'model'), + guideStep('model-summary', 'model-summary'), + guideStep('dataset-select', 'dataset-select'), + guideStep('dataset', 'dataset'), + guideStep('dataset-processed', 'dataset-processed', 'bottom'), + guideStep('dataset-analysis', 'dataset-analysis', 'bottom'), + guideStep('instances', 'instances', 'bottom'), + guideStep('models', 'models', 'bottom'), + ...(guide.fieldSteps + ? fields.map((field) => guideStep('fields.' + field, 'field-' + field, 'bottom')) + : [guideStep('form', 'form')]), + guideStep('predict', 'predict'), + guideStep('result', 'result'), + guideStep('explain', 'explain'), + // Paso a paso, solo si se ha activado en /settings + ...(stepByStep ? [guideStep('step-by-step', 'step-by-step')] : []), + centerStep('end'), + ] + return buildGuideSteps(t, 'guide.1-regression', modelKey, specs.flatMap((spec) => [spec, ...(guide.extra?.[spec.key] ?? [])])) +} diff --git a/src/pages/playground/1_Regression/models/MODEL_1_SALARY.tsx b/src/pages/playground/1_Regression/models/MODEL_1_SALARY.tsx deleted file mode 100644 index d9c96e7..0000000 --- a/src/pages/playground/1_Regression/models/MODEL_1_SALARY.tsx +++ /dev/null @@ -1,218 +0,0 @@ -import { Trans } from 'react-i18next' -import * as tfjs from '@tensorflow/tfjs' -import * as dfd from 'danfojs' - -import * as _Types from '@core/types' -import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' -import I_MODEL_REGRESSION from './_model' -import { F_FILTER_Categorical, F_MAP_LabelEncoder } from '@core/nn-utils/utils' -import { LR_MODEL_KEYS } from '@/MODEL_KEYS' - -export default class MODEL_1_SALARY extends I_MODEL_REGRESSION { - static KEY = LR_MODEL_KEYS.SALARY - - URL_SALARY = 'https://www.kaggle.com/datasets/saquib7hussain/experience-salary-dataset/data' - URL_SALARY_EXTRA = 'https://www.kaggle.com/datasets/rkiattisak/salaly-prediction-for-beginer' - i18n_TITLE = 'datasets-models.1-regression.salary.title' - _KEY = 'SALARY' - - DESCRIPTION () { - const prefix = 'datasets-models.1-regression.salary.description.' - return <> -

    -

    -

    - link, - }} /> -

    -
    - -
      -
    1. -
    2. -
    -
    -
    - -
      -
    1. -
    -
    -
    - -
      -
    1. - - - -
    2. -
    3. - - - -
    4. -
    -
    - - } - - /** - * - * @returns {Promise<_Types.DatasetProcessed_t[]>} - */ - async DATASETS () : Promise<_Types.DatasetProcessed_t[]> { - const path_datasets = import.meta.env.VITE_PATH + '/datasets/01-regression/salary/' - const salary_info = 'salary.names' - const salary_csv = 'salary.csv' - - const dataset_promise_info = await fetch(path_datasets + salary_info) - const salary_container_info = await dataset_promise_info.text() - /** @type {_Types.Dataset_t} */ - const salary_dataset: _Types.Dataset_t = [ - { column_name: 'YearsExperience', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'Salary', column_role: 'Target', column_type: 'Continuous', column_missing_values: false }, - ] - const salary_dataset_transforms = [ - ...salary_dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder), - // { column_name: 'Salary', column_type: 'drop' } - ] - const salary_dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_datasets + salary_csv) - let salary_dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_datasets + salary_csv) - const salary_dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder(salary_dataframe_processed, salary_dataset_transforms) - const salary_encoders_map = salary_dataframe_encoder.encoder_map - salary_dataframe_processed = salary_dataframe_encoder.dataframe_processed - const salary_target = 'Salary' - const salary_dataframe_X = salary_dataframe_processed.drop({ columns: [salary_target] }).copy() - const salary_dataframe_y = salary_dataframe_original[salary_target] - const minMaxScaler = new dfd.MinMaxScaler() - const salary_scaler = minMaxScaler.fit(salary_dataframe_X) - const salary_X = salary_scaler.transform(salary_dataframe_X) - const salary_y = salary_dataframe_y - - - // SALARY EXTRA - - const salary_extra_info = 'salary-extra.names' - const salary_extra_csv = 'salary-extra.csv' - - const salary_extra_dataset_promise_info = await fetch(path_datasets + salary_extra_info) - const salary_extra_container_info = await salary_extra_dataset_promise_info.text() - /** @type {_Types.Dataset_t} */ - const salary_extra_dataset: _Types.Dataset_t = [ - { column_name: 'Age', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'Gender', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'Education Level', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'Job Title', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'Years of Experience', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'Salary', column_role: 'Target', column_type: 'Integer', column_missing_values: false }, - ] - const salary_extra_dataset_transforms = [ - ...salary_extra_dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder), - // { column_name: 'Salary', column_type: 'drop' } - ] - const salary_extra_dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_datasets + salary_extra_csv) - let salary_extra_dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_datasets + salary_extra_csv) - const salary_extra_dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder(salary_extra_dataframe_processed, salary_extra_dataset_transforms) - const salary_extra_encoders_map = salary_extra_dataframe_encoder.encoder_map - salary_extra_dataframe_processed = salary_extra_dataframe_encoder.dataframe_processed - const salary_extra_target = 'Salary' - const salary_extra_dataframe_X = salary_extra_dataframe_processed.drop({ columns: [salary_extra_target] }).copy() - const salary_extra_dataframe_y = salary_extra_dataframe_original[salary_extra_target] - const minMaxScaler2 = new dfd.MinMaxScaler() - const salary_extra_scaler = minMaxScaler2.fit(salary_extra_dataframe_X) - const salary_extra_X = salary_extra_scaler.transform(salary_extra_dataframe_X) - const salary_extra_y = salary_extra_dataframe_y - - return [ - { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_datasets, - info : salary_info, - csv : salary_csv, - container_info : salary_container_info, - dataset : salary_dataset, - dataset_transforms : salary_dataset_transforms, - dataframe_original : salary_dataframe_original, // Antes de aplicar los transformers - dataframe_processed : salary_dataframe_processed, // Despues de aplicar los transformers - data_processed : { - dataframe_X : salary_dataframe_X, // Antes de hacer el escalado y sin el target - dataframe_y : salary_dataframe_y, - X : salary_X, // Despues de hacer el escalado y sin el target - y : salary_y, - scaler : salary_scaler, - encoders : salary_encoders_map, - column_name_target: salary_target, - } - }, - - { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_datasets, - info : salary_extra_info, - csv : salary_extra_csv, - container_info : salary_extra_container_info, - dataset : salary_extra_dataset, - dataset_transforms : salary_extra_dataset_transforms, - dataframe_original : salary_extra_dataframe_original, - dataframe_processed : salary_extra_dataframe_processed, - data_processed : { - dataframe_X : salary_extra_dataframe_X, - dataframe_y : salary_extra_dataframe_y, - X : salary_extra_X, - y : salary_extra_y, - scaler : salary_extra_scaler, - encoders : salary_extra_encoders_map, - column_name_target: salary_extra_target, - } - } - ] - } - - /** - * - * @param {string} [dataset=''] - * @return {Promise<_Types.CustomModel_t[]>} - */ - async MODELS (dataset: string): Promise<_Types.CustomModel_t[]> { - const path = import.meta.env.VITE_PATH + '/models/01-regression/salary' - const model_salary = await tfjs.loadLayersModel(path + '/2/lr-model-2.json') - const models: { [key: string]: _Types.CustomModel_t[] } = { - 'salary-extras.csv': [], - 'salary.csv' : [ - { - model : model_salary, - model_path: path + '/0/lr-model-0.json', - X : ['YearsExperience'], - y : 'Salary' - }, - ] - } - return models[dataset] - } - - COMPILE () { - const model = new tfjs.Sequential() - model.compile({ - optimizer: tfjs.train.rmsprop(0.01), - loss : 'meanSquaredError', - metrics : ['meanSquaredError', 'meanAbsoluteError'] - }) - return model - } - - DEFAULT_LAYERS (_dataset: _Types.Dataset_t|string = ''): _Types.CustomParamsLayerModel_t[] { - return [ - { is_disabled: false, units: 10, activation: 'sigmoid' }, - { is_disabled: false, units: 20, activation: 'relu' }, - { is_disabled: true, units: 1, activation: 'linear' } - ] - } - - ATTRIBUTE_INFORMATION () { - return <> - } -} diff --git a/src/pages/playground/1_Regression/models/MODEL_2_AUTO_MPG.tsx b/src/pages/playground/1_Regression/models/MODEL_2_AUTO_MPG.tsx deleted file mode 100644 index 65d256a..0000000 --- a/src/pages/playground/1_Regression/models/MODEL_2_AUTO_MPG.tsx +++ /dev/null @@ -1,196 +0,0 @@ -import * as tfjs from '@tensorflow/tfjs' -import * as dfd from 'danfojs' -import { Trans } from 'react-i18next' - -import * as _Types from '@core/types' -import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' -import I_MODEL_REGRESSION from './_model' -import { F_FILTER_Categorical, F_MAP_LabelEncoder } from '@core/nn-utils/utils' -import { LR_MODEL_KEYS } from '@/MODEL_KEYS' - -export default class MODEL_2_AUTO_MPG extends I_MODEL_REGRESSION { - - static KEY = LR_MODEL_KEYS.AUTO_MPG - static URL = 'https://archive.ics.uci.edu/ml/datasets/auto+mpg' - - URL = 'https://archive.ics.uci.edu/ml/datasets/auto+mpg' - i18n_TITLE = 'datasets-models.1-regression.auto-mpg.title' - _KEY = 'AUTO_MPG' - - DESCRIPTION () { - const prefix = 'datasets-models.1-regression.auto-mpg.description.' - return <> -

    -

    -

    - link, - }} /> -

    -
    - -
      -
    1. -
    2. -
    3. -
    4. -
    5. -
    6. -
    7. -
    8. -
    9. -
    -
    -
    - -
      -
    1. -
    2. -
    3. -
    4. -
    5. -
    6. -
    7. -
    8. -
    9. -
    -
    -
    - -
      -
    1. -
    -
    -
    - -
      -
    1. link, - }} />
    2. -
    -
    -
    - BibTeX -
    -{`
    -@misc{misc_auto_mpg_9,
    -  author       = {Quinlan,R.},
    -  title        = {{Auto MPG}},
    -  year         = {1993},
    -  howpublished = {UCI Machine Learning Repository},
    -  note         = {{DOI}: https://doi.org/10.24432/C5859H}
    -}
    -`}
    -        
    -
    - - } - - /** - * - * @returns {Promise<_Types.DatasetProcessed_t[]>} - */ - async DATASETS (): Promise<_Types.DatasetProcessed_t[]> { - const path_datasets = import.meta.env.VITE_PATH + '/datasets/01-regression/auto-mpg/' - const auto_info = 'auto-mpg.names' - const auto_csv = 'auto-mpg.csv' - - const auto_promise_info = await fetch(path_datasets + auto_info) - const auto_container_info = await auto_promise_info.text() - const auto_dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_datasets + auto_csv) - let auto_dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_datasets + auto_csv) - /** @type {_Types.Dataset_t} */ - const auto_dataset: _Types.Dataset_t = [ - { column_name: 'cylinders', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'displacement', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'horsepower', column_role: 'Feature', column_type: 'Continuous', column_missing_values: true }, - { column_name: 'weight', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'acceleration', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'model-year', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - // { column_name: 'origin', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'mpg', column_role: 'Target', column_type: 'Continuous', column_missing_values: false }, - // { column_name: 'car_name', column_role: 'ID', column_type: 'Categorical', column_missing_values: false }, - ] - const auto_dataset_transforms = [ - ...auto_dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder), - // { column_name: 'mpg', column_type: 'drop' } - ] - const auto_target = 'mpg' - const auto_dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder(auto_dataframe_processed, auto_dataset_transforms) - const auto_encoders_map = auto_dataframe_encoder.encoder_map - auto_dataframe_processed = auto_dataframe_encoder.dataframe_processed - const auto_dataframe_X = auto_dataframe_processed.drop({ columns: [auto_target] }).copy() - const auto_dataframe_y = auto_dataframe_original[auto_target] - const minMaxScaler = new dfd.MinMaxScaler() - const auto_minMaxScaler = minMaxScaler.fit(auto_dataframe_X) - const auto_X = auto_minMaxScaler.transform(auto_dataframe_X) - const auto_y = auto_dataframe_y - - return [ - { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_datasets, - csv : auto_csv, - info : auto_info, - container_info : auto_container_info, - dataset : auto_dataset, - dataset_transforms : auto_dataset_transforms, - dataframe_original : auto_dataframe_original, - dataframe_processed : auto_dataframe_processed, - data_processed : { - dataframe_X : auto_dataframe_X, - dataframe_y : auto_dataframe_y, - X : auto_X, - y : auto_y, - scaler : auto_minMaxScaler, - encoders : auto_encoders_map, - column_name_target: auto_target, - } - } - ] - } - - /** - * - * @param {string} [dataset=''] - * @return {Promise<_Types.CustomModel_t[]>} - */ - async MODELS (dataset: string = ''): Promise<_Types.CustomModel_t[]> { - const path = import.meta.env.VITE_PATH + '/models/01-regression/auto-mpg' - const model = await tfjs.loadLayersModel(path + '/0/lr-model-0.json') - const models: { [key: string]: _Types.CustomModel_t[] } = { - 'auto-mpg.csv': [ - { - model : model, - model_path: path + '/0/lr-model-0.json', - }, - ] - } - return models[dataset] - } - - DEFAULT_LAYERS (): _Types.Layer_t[] { - return [ - { is_disabled: false, units: 64, activation: 'relu', _class: 'dense' }, - { is_disabled: false, units: 64, activation: 'relu', _class: 'dense' }, - { is_disabled: true, units: 1, activation: 'linear', _class: 'dense' } - ] - } - - COMPILE () { - const model = new tfjs.Sequential() - model.compile({ - optimizer: tfjs.train.rmsprop(0.01), - loss : 'meanSquaredError', - metrics : ['meanSquaredError', 'meanAbsoluteError'] - }) - return model - } - - ATTRIBUTE_INFORMATION () { - return <> - } -} diff --git a/src/pages/playground/1_Regression/models/MODEL_3_HOUSING_PRICES.tsx b/src/pages/playground/1_Regression/models/MODEL_3_HOUSING_PRICES.tsx deleted file mode 100644 index ad15350..0000000 --- a/src/pages/playground/1_Regression/models/MODEL_3_HOUSING_PRICES.tsx +++ /dev/null @@ -1,305 +0,0 @@ -import * as tfjs from '@tensorflow/tfjs' -import * as dfd from 'danfojs' -import { Trans } from 'react-i18next' - -import * as _Types from '@core/types' -import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' -import I_MODEL_REGRESSION from './_model' -import { F_FILTER_Categorical, F_MAP_LabelEncoder } from '@core/nn-utils/utils' -import { LR_MODEL_KEYS } from '@/MODEL_KEYS' - -export default class MODEL_3_HOUSING_PRICES extends I_MODEL_REGRESSION { - - static KEY = LR_MODEL_KEYS.HOUSING_PRICES - static URL = 'https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html' - - // CALIFORNIA_URL = 'https://www.kaggle.com/datasets/fedesoriano/california-housing-prices-data-extra-features' - - BOSTON_URL = 'https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html' - BOSTON_URL_MEDIUM = 'https://medium.com/@docintangible/racist-data-destruction-113e3eff54a8' - - - i18n_TITLE = 'datasets-models.1-regression.housing-prices.title' - _KEY = 'HOUSING_PRICES' - - DESCRIPTION() { - const prefix = 'datasets-models.1-regression.housing-prices.description.' - return <> -

    -

    -

    - link, - }} /> -

    - {/* -
    - -
      - {Object.entries(this.t(prefix + 'details-input.california.list', { returnObjects: true, defaultValue: [] })) - .map((value, index) => { - return
    1. - })} -
    -
    -
    - -
      - {Object.entries(this.t(prefix + 'details-output.california.list', { returnObjects: true, defaultValue: [] })) - .map((value, index) => { - return
    1. - })} -
    -
    -
    - -
      -
    1. - link, - }} /> -
    2. - -
    -
    - -
    - - */} - -
    - -
      - {Object.entries(this.t(prefix + 'details-input.boston.list', { returnObjects: true, defaultValue: [] })) - .map((_value, index) => { - return
    1. - })} -
    -
    -
    - -
      - {Object.entries(this.t(prefix + 'details-output.boston.list', { returnObjects: true, defaultValue: [] })) - .map((_value, index) => { - return
    1. - })} -
    -
    -
    - -
      -
    1. - link, - }} /> -
    2. -
    -
    - - - } - - /** - * - * @returns {Promise<_Types.DatasetProcessed_t[]>} - */ - async DATASETS(): Promise<_Types.DatasetProcessed_t[]> { - const path_datasets = import.meta.env.VITE_PATH + '/datasets/01-regression/housing-prices/' - - // ------------------------ - // #region Boston housing - const boston_info = 'boston-housing.names' - const boston_csv = 'boston-housing-2020.csv' - const boston_dataset_promise_info = await fetch(path_datasets + boston_info) - const boston_container_info = await boston_dataset_promise_info.text() - const boston_dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_datasets + boston_csv) - let boston_dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_datasets + boston_csv) - /** @type {_Types.Dataset_t} */ - const boston_dataset: _Types.Dataset_t = [ - { column_name: 'CRIM', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'ZN', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'INDUS', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'CHAS', column_type: 'Binary', column_role: 'Feature', column_missing_values: false }, - { column_name: 'NOX', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'RM', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'AGE', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'DIS', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'RAD', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'TAX', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'PTRATIO', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'B', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'LSTAT', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'MEDV', column_type: 'Continuous', column_role: 'Target', column_missing_values: false } - ] - /** @type {_Types.DataFrameColumnTransform_t[]} */ - const boston_dataset_transforms: _Types.DataFrameColumnTransform_t[] = [ - ...boston_dataset.filter(F_FILTER_Categorical).map(v => F_MAP_LabelEncoder(v) as _Types.DataFrameColumnTransform_t), - // { column_name: 'B', column_transform: 'drop' }, - // { column_name: 'MEDV', column_transform: 'drop' }, - ] - const boston_target = 'MEDV' - const boston_dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder(boston_dataframe_processed, boston_dataset_transforms) - const boston_encoders_map = boston_dataframe_encoder.encoder_map - boston_dataframe_processed = boston_dataframe_encoder.dataframe_processed - const boston_dataframe_X = boston_dataframe_processed.drop({ columns: [boston_target] }).copy() - const boston_dataframe_y = boston_dataframe_original[boston_target] - const minMaxScaler = new dfd.MinMaxScaler() - const boston_scaler = minMaxScaler.fit(boston_dataframe_X) - const boston_X = boston_scaler.transform(boston_dataframe_X) - const boston_y = boston_dataframe_y - // #endregion - - // #endregion California - // const california_info = 'california-housing.names' - // const california_csv = 'california-housing-2024.csv' - // const promise_info = await fetch(path_datasets + california_info) - // const california_container_info = await promise_info.text() - // let california_dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_datasets + california_csv) - // let california_dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_datasets + california_csv) - // /** @type {_Types.Dataset_t} */ - // const california_dataset = [ - // { column_name: 'Median_Income', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Median_Age', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Tot_Rooms', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Tot_Bedrooms', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Population', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Households', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Latitude', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Longitude', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Distance_to_coast', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Distance_to_LA', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Distance_to_SanDiego', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Distance_to_SanJose', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Distance_to_SanFrancisco', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'Median_House_Value', column_type: 'Continuous', column_role: 'Target', column_missing_values: false }, - // ] - // /** @type {_Types.DataFrameColumnTransform_t[]} */ - // const california_dataset_transforms = [ - // ...california_dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder), - // // { column_transform: 'label-encoder', column_name: 'Tot_Rooms' }, - // // { column_transform: 'label-encoder', column_name: 'Tot_Bedrooms' }, - // // { column_transform: 'label-encoder', column_name: 'Population' }, - // // { column_transform: 'label-encoder', column_name: 'Households' }, - // // { column_transform: 'drop', column_name: 'Latitude' }, - // // { column_transform: 'drop', column_name: 'Longitude' }, - // { column_transform: 'drop', column_name: 'Distance_to_coast' }, - // { column_transform: 'drop', column_name: 'Distance_to_LA' }, - // { column_transform: 'drop', column_name: 'Distance_to_SanDiego' }, - // { column_transform: 'drop', column_name: 'Distance_to_SanJose' }, - // { column_transform: 'drop', column_name: 'Distance_to_SanFrancisco' }, - // // { column_transform: 'drop', column_name: 'Median_House_Value' } - // ] - // const california_target = 'Median_House_Value' - // const california_dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder(california_dataframe_processed, california_dataset_transforms) - // const california_encoders_map = california_dataframe_encoder.encoder_map - // california_dataframe_processed = california_dataframe_encoder.dataframe_processed - // const california_dataframe_X = california_dataframe_processed.drop({ columns: [california_target] }).copy() - // const california_dataframe_y = california_dataframe_original[california_target] - // const standardScaler = new dfd.StandardScaler() - // const california_scaler = standardScaler.fit(california_dataframe_X) - // const california_X = california_scaler.transform(california_dataframe_X) - // const california_y = california_dataframe_y - // #endregion - - return [ - { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_datasets, - csv : boston_csv, - info : boston_info, - container_info : boston_container_info, - dataset : boston_dataset, - dataset_transforms : boston_dataset_transforms, - dataframe_original : boston_dataframe_original, - dataframe_processed : boston_dataframe_processed, - data_processed : { - dataframe_X : boston_dataframe_X, - dataframe_y : boston_dataframe_y, - X : boston_X, - y : boston_y, - scaler : boston_scaler, - encoders : boston_encoders_map, - column_name_target: boston_target, - } - }, - // { - // is_dataset_upload : false, - // is_dataset_processed: true, - // path : path_datasets, - // csv : california_csv, - // info : california_info, - // container_info : california_container_info, - // dataset : california_dataset, - // dataframe_original : california_dataframe_original, - // dataframe_processed : california_dataframe_processed, - // dataset_transforms : california_dataset_transforms, - // data_processed : { - // dataframe_X : california_dataframe_X, - // dataframe_y : california_dataframe_y, - // X : california_X, - // y : california_y, - // scaler : california_scaler, - // encoders : california_encoders_map, - // column_name_target: california_target, - // } - // } - ] - } - - /** - * - * @param {string} [dataset=''] - * @return {Promise<_Types.CustomModel_t[]>} - */ - async MODELS(dataset: string = ''): Promise<_Types.CustomModel_t[]> { - const path = import.meta.env.VITE_PATH + '/models/01-regression/housing-dataset' - const model = await tfjs.loadLayersModel(path + '/0/lr-model-0.json') - const models: { [key: string]: _Types.CustomModel_t[] } = { - 'boston-housing-2020.csv': [ - { - model : model, - model_path: path + '/0/lr-model-0.json', - X : ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'LSTAT'], - y : 'MEDV', - }, - ], - 'california-housing-2024.csv': [], - } - return models[dataset] - } - - DEFAULT_LAYERS(dataset: string = ''): _Types.Layer_t[] { - const models: { [key: string]: _Types.Layer_t[] } = { - 'california-housing-2024.csv': [ - { _class: 'dense', is_disabled: false, units: 20, activation: 'sigmoid' }, - { _class: 'dense', is_disabled: true, units: 1, activation: 'linear' }, - ], - 'boston-housing-2020.csv': [ - { _class: 'dense', is_disabled: false, units: 32, activation: 'sigmoid' }, - { _class: 'dense', is_disabled: false, units: 16, activation: 'sigmoid' }, - { _class: 'dense', is_disabled: true, units: 1, activation: 'linear' } - ] - } - return models[dataset] - } - - COMPILE() { - // https://towardsdatascience.com/regression-on-boston-housing-dataset-f409b7e4a155 - const model = new tfjs.Sequential() - model.compile({ - optimizer: tfjs.train.rmsprop(0.01), - loss : 'meanSquaredError', - metrics : ['meanSquaredError', 'meanAbsoluteError'] - }) - return model - } - - ATTRIBUTE_INFORMATION() { - return <> - } - -} diff --git a/src/pages/playground/1_Regression/models/MODEL_4_BREAST_CANCER.tsx b/src/pages/playground/1_Regression/models/MODEL_4_BREAST_CANCER.tsx deleted file mode 100644 index 372dea5..0000000 --- a/src/pages/playground/1_Regression/models/MODEL_4_BREAST_CANCER.tsx +++ /dev/null @@ -1,440 +0,0 @@ -import * as dfd from 'danfojs' -import { Trans } from 'react-i18next' - -import * as _Types from '@core/types' -import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' -import I_MODEL_REGRESSION from './_model' -import { F_FILTER_Categorical, F_MAP_LabelEncoder } from '@core/nn-utils/utils' -import { LR_MODEL_KEYS } from '@/MODEL_KEYS' - -export default class MODEL_4_BREAST_CANCER extends I_MODEL_REGRESSION { - - static KEY = LR_MODEL_KEYS.BREAST_CANCER - static URL = 'https://archive.ics.uci.edu/dataset/15/breast+cancer+wisconsin+original' - static URL_2 = 'https://archive.ics.uci.edu/dataset/16/breast+cancer+wisconsin+prognostic' - static URL_3 = 'https://archive.ics.uci.edu/dataset/17/breast+cancer+wisconsin+diagnostic' - - URL = 'https://archive.ics.uci.edu/dataset/15/breast+cancer+wisconsin+original' - URL_2 = 'https://archive.ics.uci.edu/dataset/16/breast+cancer+wisconsin+prognostic' - URL_3 = 'https://archive.ics.uci.edu/dataset/17/breast+cancer+wisconsin+diagnostic' - URL_IMAGE = 'https://www.cs.wisc.edu/~street/images/' - - i18n_TITLE = 'datasets-models.1-regression.breast-cancer.title' - _KEY = 'BREAST_CANCER' - - wdbc_columns_X = [ - 'Time', - 'radius1', - 'texture1', - 'perimeter1', - 'area1', - 'smoothness1', - 'compactness1', - 'concavity1', - 'concave_points1', - 'symmetry1', - 'fractal_dimension1', - 'radius2', - 'texture2', - 'perimeter2', - 'area2', - 'smoothness2', - 'compactness2', - 'concavity2', - 'concave_points2', - 'symmetry2', - 'fractal_dimension2', - 'radius3', - 'texture3', - 'perimeter3', - 'area3', - 'smoothness3', - 'compactness3', - 'concavity3', - 'concave_points3', - 'symmetry3', - 'fractal_dimension3', - 'tumor_size', - 'lymph_node_status', - ] - - DESCRIPTION () { - const prefix = 'datasets-models.1-regression.breast-cancer.description.' - return <> -

    -

    -

    - link, - }} - /> -

    -

    -

    - link, - }} - /> -

    -
    - -
      - {Object.entries(this.t(prefix + 'details-1-input.list', { returnObjects: true, defaultValue: [] })) - .map((_value, index) => { - return
    1. - })} -
    -
    -
    - -
      - {Object.entries(this.t(prefix + 'details-2-output.list', { returnObjects: true, defaultValue: [] })) - .map((_value, index) => { - return
    1. - })} -
    -
    -
    - -
      -
    1. - TEXT - }} /> -
    2. -
    3. - TEXT - }} /> -
    4. -
    5. - TEXT - }} /> -
    6. -
    -
    -
    - BibTeX -
    -{`
    -@misc{misc_breast_cancer_wisconsin_(prognostic)_16,
    -  author       = {Wolberg,William, Street,W., and Mangasarian,Olvi},
    -  title        = {{Breast Cancer Wisconsin (Prognostic)}},
    -  year         = {1995},
    -  howpublished = {UCI Machine Learning Repository},
    -  note         = {{DOI}: https://doi.org/10.24432/C5GK50}
    -}
    -`}
    -          {`
    -@misc{misc_breast_cancer_wisconsin_(diagnostic)_17,
    -  author       = {Wolberg,William, Mangasarian,Olvi, Street,Nick, and Street,W.},
    -  title        = {{Breast Cancer Wisconsin (Diagnostic)}},
    -  year         = {1995},
    -  howpublished = {UCI Machine Learning Repository},
    -  note         = {{DOI}: https://doi.org/10.24432/C5DW2B}
    -}
    -`}
    -        
    -
    - - } - - /** - * - * @returns {Promise<_Types.DatasetProcessed_t[]>} - */ - async DATASETS () { - const path_datasets = import.meta.env.VITE_PATH + '/datasets/01-regression/breast-cancer/' - const bcw_info = 'breast-cancer-wisconsin.names' - const bcw_csv = 'breast-cancer-wisconsin.csv' - const wdbc_info = 'wdbc.names' - const wdbc_csv = 'wdbc.csv' - const wpbc_info = 'wpbc.names' - const wpbc_csv = 'wpbc.csv' - - const [bcw_promise_info, wdbc_promise_info, wpbc_promise_info] = await Promise.all([ - fetch(path_datasets + bcw_info), - fetch(path_datasets + wdbc_info), - fetch(path_datasets + wpbc_info), - ]) - const [bcw_container_info, wdbc_container_info, wpbc_container_info] = await Promise.all([ - bcw_promise_info.text(), - wdbc_promise_info.text(), - wpbc_promise_info.text(), - ]) - - // -------------------- - // #region Dataset Breast cancer wisconsin (Original) - const bcw_dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_datasets + bcw_csv) - let bcw_dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_datasets + bcw_csv) - - /** @type {_Types.Dataset_t} */ - const bcw_dataset: _Types.Dataset_t = [ - { column_name: 'Sample_code_number', column_role: 'ID', column_type: 'Categorical', column_missing_values: false }, - { column_name: 'Clump_thickness', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'Uniformity_of_cell_size', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'Uniformity_of_cell_shape', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'Marginal_adhesion', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'Single_epithelial_cell_size', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'Bare_nuclei', column_role: 'Feature', column_type: 'Integer', column_missing_values: true, column_missing_values_key: '?' }, - { column_name: 'Bland_chromatin', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'Normal_nucleoli', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'Mitoses', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'Class', column_role: 'Target', column_type: 'Binary', column_missing_values: false }, - ] - /** @type {_Types.DataFrameColumnTransform_t[]} */ - const bcw_dataset_transforms: _Types.DataFrameColumnTransform_t[] = [ - ...bcw_dataset.filter(F_FILTER_Categorical).map(v => F_MAP_LabelEncoder(v) as _Types.DataFrameColumnTransform_t), - { column_name: 'Sample_code_number', column_transform: 'drop' }, - { column_name: 'Bare_Nuclei', column_transform: 'drop' }, - // { column_name: 'Bare_Nuclei', column_transform: 'replace_?_NaN' }, - // { column_name: 'Bare_Nuclei', column_transform: 'dropNa' }, - // { column_name: 'Class', column_transform: 'drop' }, - ] - const bcw_target = 'Class' - const bcw_dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder(bcw_dataframe_processed, bcw_dataset_transforms) - const bcw_encoders_map = bcw_dataframe_encoder.encoder_map - bcw_dataframe_processed = bcw_dataframe_encoder.dataframe_processed - const bcw_dataframe_X = bcw_dataframe_processed.drop({ columns: [bcw_target] }).copy() - const bcw_dataframe_y = bcw_dataframe_original[bcw_target] - const minMaxScaler_1 = new dfd.MinMaxScaler() - const bcw_scaler = minMaxScaler_1.fit(bcw_dataframe_X) - const bcw_X = bcw_scaler.transform(bcw_dataframe_X) - const bcw_y = bcw_dataframe_y - // #endregion - - - // -------------------- - // #region Breast Cancer Wisconsin (Diagnostic) - const wdbc_dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_datasets + wdbc_csv) - let wdbc_dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_datasets + wdbc_csv) - /**@type {_Types.Dataset_t} */ - const wdbc_dataset: _Types.Dataset_t = [ - { column_name: 'ID', column_type: 'Categorical', column_role: 'ID', column_missing_values: false }, - { column_name: 'radius1', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'texture1', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'perimeter1', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'area1', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'smoothness1', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'compactness1', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'concavity1', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'concave_points1', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'symmetry1', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'fractal_dimension1', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'radius2', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'texture2', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'perimeter2', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'area2', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'smoothness2', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'compactness2', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'concavity2', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'concave_points2', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'symmetry2', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'fractal_dimension2', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'radius3', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'texture3', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'perimeter3', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'area3', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'smoothness3', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'compactness3', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'concavity3', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'concave_points3', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'symmetry3', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'fractal_dimension3', column_type: 'Continuous', column_role: 'Feature', column_missing_values: false }, - { column_name: 'Diagnosis', column_type: 'Categorical', column_role: 'Target', column_missing_values: false }, - ] - /** @type {_Types.DataFrameColumnTransform_t[]} */ - const wdbc_dataset_transforms = [ - ...wdbc_dataset.filter(F_FILTER_Categorical).map(v => F_MAP_LabelEncoder(v) as _Types.DataFrameColumnTransform_t), - // { column_name: 'ID', column_transform: 'drop' }, - // { column_name: 'Diagnosis', column_transform: 'drop' }, - - ] - const wdbc_target = 'Diagnosis' - const wdbc_dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder(wdbc_dataframe_processed, wdbc_dataset_transforms) - const wdbc_encoders_map = wdbc_dataframe_encoder.encoder_map - wdbc_dataframe_processed = wdbc_dataframe_encoder.dataframe_processed - const wdbc_dataframe_X = wdbc_dataframe_processed.drop({ columns: [wdbc_target] }).copy() - const wdbc_dataframe_y = wdbc_dataframe_original[wdbc_target] - const minMaxScaler_2 = new dfd.MinMaxScaler() - const wdbc_scaler = minMaxScaler_2.fit(wdbc_dataframe_X) - const wdbc_X = wdbc_scaler.transform(wdbc_dataframe_X) - const wdbc_y = wdbc_dataframe_y - // #endregion - - // -------------------- - // #region Breast Cancer Wisconsin (Prognostic) - const wpbc_dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_datasets + wpbc_csv) - let wpbc_dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_datasets + wpbc_csv) - /** @type {_Types.Dataset_t} */ - const wpbc_dataset: _Types.Dataset_t = [ - { column_name: 'ID', column_role: 'ID', column_type: 'Integer', column_missing_values: false }, - { column_name: 'Time', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, // empiezan los 3 ciclos - { column_name: 'radius1', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'texture1', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'perimeter1', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'area1', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'smoothness1', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'compactness1', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'concavity1', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'concave_points1', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'symmetry1', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'fractal_dimension1', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'radius2', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'texture2', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'perimeter2', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'area2', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'smoothness2', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'compactness2', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'concavity2', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'concave_points2', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'symmetry2', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'fractal_dimension2', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'radius3', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'texture3', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'perimeter3', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'area3', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, - { column_name: 'smoothness3', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'compactness3', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'concavity3', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'concave_points3', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'symmetry3', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'fractal_dimension3', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, // Fin 3 ciclos - { column_name: 'tumor_size', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, - { column_name: 'lymph_node_status', column_role: 'Feature', column_type: 'Integer', column_missing_values: true, column_missing_values_key: '?' }, - { column_name: 'Outcome', column_role: 'Target', column_type: 'Categorical', column_missing_values: false }, - ] - /** @type {_Types.DataFrameColumnTransform_t[]} */ - const wpbc_dataset_transforms: _Types.DataFrameColumnTransform_t[] = [ - ...wpbc_dataset.filter(F_FILTER_Categorical).map(v => F_MAP_LabelEncoder(v) as _Types.DataFrameColumnTransform_t) -, - { column_name: 'ID', column_transform: 'drop' }, - { column_name: 'lymph_node_status', column_transform: 'drop' }, - // { column_name: 'lymph_node_status', column_transform: 'replace_?_NaN' }, - // { column_name: 'lymph_node_status', column_transform: 'dropNa' }, - // { column_name: 'lymph_node_status', column_transform: 'drop' }, - // { column_name: 'Outcome', column_transform: 'drop' }, - ] - const wpbc_target = 'Outcome' - const wpbc_dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder(wpbc_dataframe_processed, wpbc_dataset_transforms) - const wpbc_encoders_map = wpbc_dataframe_encoder.encoder_map - wpbc_dataframe_processed = wpbc_dataframe_encoder.dataframe_processed - const wpbc_dataframe_X = wpbc_dataframe_processed.drop({ columns: [wpbc_target] }).copy() - const wpbc_dataframe_y = wpbc_dataframe_original[wpbc_target] - const minMaxScaler_3 = new dfd.MinMaxScaler() - const wpbc_scaler = minMaxScaler_3.fit(wpbc_dataframe_X) - const wpbc_X = wpbc_scaler.transform(wpbc_dataframe_X) - const wpbc_y = wpbc_dataframe_y - // #endregion - - - return [ - { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_datasets, - info : bcw_info, - csv : bcw_csv, - container_info : bcw_container_info, - dataset : bcw_dataset, - dataset_transforms : bcw_dataset_transforms, - dataframe_original : bcw_dataframe_original, - dataframe_processed : bcw_dataframe_processed, - data_processed : { - dataframe_X : bcw_dataframe_X, - dataframe_y : bcw_dataframe_y, - X : bcw_X, - y : bcw_y, - scaler : bcw_scaler, - encoders : bcw_encoders_map, - column_name_target: bcw_target, - } - }, - { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_datasets, - csv : wdbc_csv, - info : wdbc_info, - container_info : wdbc_container_info, - dataset : wdbc_dataset, - dataset_transforms : wdbc_dataset_transforms, - dataframe_original : wdbc_dataframe_original, - dataframe_processed : wdbc_dataframe_processed, - data_processed : { - dataframe_X : wdbc_dataframe_X, - dataframe_y : wdbc_dataframe_y, - X : wdbc_X, - y : wdbc_y, - scaler : wdbc_scaler, - encoders : wdbc_encoders_map, - column_name_target: wdbc_target, - } - }, - { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_datasets, - info : wpbc_info, - csv : wpbc_csv, - container_info : wpbc_container_info, - dataset : wpbc_dataset, - dataset_transforms : wpbc_dataset_transforms, - dataframe_original : wpbc_dataframe_original, - dataframe_processed : wpbc_dataframe_processed, - data_processed : { - dataframe_X : wpbc_dataframe_X, - dataframe_y : wpbc_dataframe_y, - X : wpbc_X, - y : wpbc_y, - scaler : wpbc_scaler, - encoders : wpbc_encoders_map, - column_name_target: wpbc_target, - } - } - ] - } - - DEFAULT_LAYERS () { - return [ - { is_disabled: false, units: 32, activation: 'relu' }, - { is_disabled: false, units: 16, activation: 'relu' }, - { is_disabled: true, units: 1, activation: 'linear' } - ] - } - - /** - * - * @param {string} [dataset=''] - * @return {Promise<_Types.CustomModel_t[]>} - */ - async MODELS (dataset: string = ''): Promise<_Types.CustomModel_t[]> { - const path = import.meta.env.VITE_PATH + '/models/01-regression/breast-cancer' - // const model = await tfjs.loadLayersModel(path + '/0/lr-model-0.json') - - const models: { [key: string]: _Types.CustomModel_t[] } = { - 'breast-cancer-wisconsin.csv': [], - 'wpbc.csv' : [], - 'wdbc.csv' : [ - { - model_path: path + '/0/lr-model-0.json', - X : this.wdbc_columns_X, - y : 'Outcome' - } - ], - } - return models[dataset] - } - - ATTRIBUTE_INFORMATION () { - return <> - } -} diff --git a/src/pages/playground/1_Regression/models/MODEL_5_STUDENT_PERFORMANCE.tsx b/src/pages/playground/1_Regression/models/MODEL_5_STUDENT_PERFORMANCE.tsx deleted file mode 100644 index 87dd790..0000000 --- a/src/pages/playground/1_Regression/models/MODEL_5_STUDENT_PERFORMANCE.tsx +++ /dev/null @@ -1,300 +0,0 @@ -import * as dfd from 'danfojs' -import * as tfjs from '@tensorflow/tfjs' -import { Trans } from 'react-i18next' - -import * as _Types from '@core/types' -import * as DataFrameUtils from '@core/dataframe/DataFrameUtils' -import I_MODEL_REGRESSION from './_model' -import { F_FILTER_Categorical, F_MAP_LabelEncoder } from '@core/nn-utils/utils' -import { LR_MODEL_KEYS } from '@/MODEL_KEYS' - -export default class MODEL_5_STUDENT_PERFORMANCE extends I_MODEL_REGRESSION { - - static KEY = LR_MODEL_KEYS.STUDENT_PERFORMANCE - static URL = 'https://archive.ics.uci.edu/dataset/320/student+performance' - - URL = 'https://archive.ics.uci.edu/dataset/320/student+performance' - i18n_TITLE = 'datasets-models.1-regression.student-performance.title' - _KEY = 'STUDENT_PERFORMANCE' - - student_performance_columns_X = [ - 'school', - 'sex', - 'age', - 'address', - 'famsize', - 'Pstatus', - 'Medu', - 'Fedu', - 'Mjob', - 'Fjob', - 'reason', - 'guardian', - 'traveltime', - 'studytime', - 'failures', - 'schoolsup', - 'famsup', - 'paid', - 'activities', - 'nursery', - 'higher', - 'internet', - 'romantic', - 'famrel', - 'freetime', - 'goout', - 'Dalc', - 'Walc', - 'health', - 'absences' - ] - - DESCRIPTION () { - const prefix = 'datasets-models.1-regression.student-performance.description.' - return <> -

    -

    -

    -

    -

    - link, - }} /> -

    -
    - -
      - {Object.entries(this.t(prefix + 'details-1-input.list', { returnObjects: true, defaultValue: [] })) - .map((_value, index) => { - return
    1. - })} -
    -
    -
    - -
      - {Object.entries(this.t(prefix + 'details-2-output.list', { returnObjects: true, defaultValue: [] })) - .map((_value, index) => { - return
    1. - })} -
    -
    -
    - -
      -
    1. TEXT - }} />
    2. -
    -
    -
    - BibTeX -
    -{`
    -@misc{misc_student_performance_320,
    -  author       = {Cortez,Paulo},
    -  title        = {{Student Performance}},
    -  year         = {2014},
    -  howpublished = {UCI Machine Learning Repository},
    -  note         = {{DOI}: https://doi.org/10.24432/C5TG7T}
    -}
    -`}
    -        
    -
    - - } - - /** - * - * @returns {Promise<_Types.DatasetProcessed_t[]>} - */ - async DATASETS (): Promise<_Types.DatasetProcessed_t[]> { - const path_datasets = import.meta.env.VITE_PATH + '/datasets/01-regression/student-performance/' - const student_info = 'student.names' - const mat_csv = 'student-mat-2024.csv' - const por_csv = 'student-por-2024.csv' - - const dataset_fetch_info = await fetch(path_datasets + student_info) - const student_container_info = await dataset_fetch_info.text() - - /** - * @type {_Types.Dataset_t} - */ - const dataset: _Types.Dataset_t = [ - { column_name: 'school', column_type: 'Categorical', column_role: 'Feature', column_missing_values: false }, - { column_name: 'sex', column_type: 'Binary', column_role: 'Feature', column_missing_values: false }, - { column_name: 'age', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'address', column_type: 'Categorical', column_role: 'Feature', column_missing_values: false }, - { column_name: 'famsize', column_type: 'Categorical', column_role: 'Feature', column_missing_values: false }, - { column_name: 'Pstatus', column_type: 'Categorical', column_role: 'Feature', column_missing_values: false }, - { column_name: 'Medu', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'Fedu', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'Mjob', column_type: 'Categorical', column_role: 'Feature', column_missing_values: false }, - { column_name: 'Fjob', column_type: 'Categorical', column_role: 'Feature', column_missing_values: false }, - { column_name: 'reason', column_type: 'Categorical', column_role: 'Feature', column_missing_values: false }, - { column_name: 'guardian', column_type: 'Categorical', column_role: 'Feature', column_missing_values: false }, - { column_name: 'traveltime', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'studytime', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'failures', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'schoolsup', column_type: 'Binary', column_role: 'Feature', column_missing_values: false }, - { column_name: 'famsup', column_type: 'Binary', column_role: 'Feature', column_missing_values: false }, - { column_name: 'paid', column_type: 'Binary', column_role: 'Feature', column_missing_values: false }, - { column_name: 'activities', column_type: 'Binary', column_role: 'Feature', column_missing_values: false }, - { column_name: 'nursery', column_type: 'Binary', column_role: 'Feature', column_missing_values: false }, - { column_name: 'higher', column_type: 'Binary', column_role: 'Feature', column_missing_values: false }, - { column_name: 'internet', column_type: 'Binary', column_role: 'Feature', column_missing_values: false }, - { column_name: 'romantic', column_type: 'Binary', column_role: 'Feature', column_missing_values: false }, - { column_name: 'famrel', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'freetime', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'goout', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'Dalc', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'Walc', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'health', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - { column_name: 'absences', column_type: 'Integer', column_role: 'Feature', column_missing_values: false }, - // { column_name: 'G1', column_type: 'Categorical', column_role: 'Target', column_missing_values: false }, - // { column_name: 'G2', column_type: 'Categorical', column_role: 'Target', column_missing_values: false }, - { column_name: 'G3', column_type: 'Integer', column_role: 'Target', column_missing_values: false }, - ] - - // #region Student Mat - const mat_dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_datasets + mat_csv) - let mat_dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_datasets + mat_csv) - /** @type {_Types.DataFrameColumnTransform_t[]} */ - const mat_dataset_transforms = [ - ...dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder), - // { column_name: 'G1', column_transform: 'drop' }, - // { column_name: 'G2', column_transform: 'drop' }, - // { column_name: 'G3', column_transform: 'drop' }, - ] - const mat_target = 'G3' // G1;G2;G3 - const mat_dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder(mat_dataframe_processed, mat_dataset_transforms) - const mat_encoders_map = mat_dataframe_encoder.encoder_map - mat_dataframe_processed = mat_dataframe_encoder.dataframe_processed - const mat_dataframe_X = mat_dataframe_processed.drop({ columns: ['G3'] }).copy() - /**@type {_Types.Series_t}*/ - const mat_dataframe_y = mat_dataframe_original[mat_target] - const minMaxScaler1 = new dfd.MinMaxScaler() - const mat_scaler = minMaxScaler1.fit(mat_dataframe_X) - const mat_X = mat_scaler.transform(mat_dataframe_X) - const mat_y = mat_dataframe_y - // #endregion - - - // #region Student Por - const por_dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_datasets + por_csv) - let por_dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_datasets + por_csv) - /** @type {_Types.DataFrameColumnTransform_t[]} */ - const por_dataset_transforms: _Types.DataFrameColumnTransform_t[] = [ - ...dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder), - // { column_name: 'G1', column_transform: 'drop' }, - // { column_name: 'G2', column_transform: 'drop' }, - // { column_name: 'G3', column_transform: 'drop' }, - ] - const por_target = 'G3' // G1;G2;G3 - const por_dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder(por_dataframe_processed, por_dataset_transforms) - const por_encoders_map = por_dataframe_encoder.encoder_map - por_dataframe_processed = por_dataframe_encoder.dataframe_processed - const por_dataframe_X = por_dataframe_processed.drop({ columns: ['G3'] }).copy() - /**@type {_Types.Series_t}*/ - const por_dataframe_y = por_dataframe_original[por_target] - const minMaxScaler2 = new dfd.MinMaxScaler() - const por_minMaxScaler = minMaxScaler2.fit(por_dataframe_X) - /**@type {_Types.DataFrame_t}*/ - const por_X = por_minMaxScaler.transform(por_dataframe_X) - const por_y = por_dataframe_y - // #endregion - - - return [ - { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_datasets, - info : student_info, - container_info : student_container_info, - csv : mat_csv, - dataset : dataset, - dataset_transforms : mat_dataset_transforms, - dataframe_original : mat_dataframe_original, - dataframe_processed : mat_dataframe_processed, - data_processed : { - dataframe_X : mat_dataframe_X, - dataframe_y : mat_dataframe_y, - X : mat_X, - y : mat_y, - scaler : mat_scaler, - encoders : mat_encoders_map, - column_name_target: mat_target, - } - }, - { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_datasets, - info : student_info, - container_info : student_container_info, - csv : por_csv, - dataset : dataset, - dataset_transforms : por_dataset_transforms, - dataframe_original : por_dataframe_original, - dataframe_processed : por_dataframe_processed, - data_processed : { - dataframe_X : por_dataframe_X, - dataframe_y : por_dataframe_y, - X : por_X, - y : por_y, - scaler : por_minMaxScaler, - encoders : por_encoders_map, - column_name_target: por_target, - } - } - ] - } - - /** - * - * @param {string} [dataset=''] - * @return {Promise<_Types.CustomModel_t[]>} - */ - async MODELS (dataset: string = ''): Promise<_Types.CustomModel_t[]> { - const path = import.meta.env.VITE_PATH + '/models/01-regression/student-performance' - const mat_model_0 = await tfjs.loadLayersModel(path + '/0/lr-model-mat.json') - const por_model_0 = await tfjs.loadLayersModel(path + '/0/lr-model-por.json') - const models: { [key: string]: _Types.CustomModel_t[] } = { - 'student-mat-2024.csv': [ - { - model : mat_model_0, - model_path: path + '/0/lr-model-mat.json', - X : this.student_performance_columns_X, - y : 'G3' - }, - ], - 'student-por-2024.csv': [ - { - model : por_model_0, - model_path: path + '/0/lr-model-por.json', - X : this.student_performance_columns_X, - y : 'G3' - }, - ] - } - return models[dataset] - } - - DEFAULT_LAYERS () { - return [ - { is_disabled: false, units: 32, activation: 'sigmoid' }, - { is_disabled: false, units: 16, activation: 'sigmoid' }, - { is_disabled: true, units: 1, activation: 'linear' } - ] - } - - ATTRIBUTE_INFORMATION () { - return <> - - - } -} diff --git a/src/pages/playground/1_Regression/models/MODEL_6_WINE.tsx b/src/pages/playground/1_Regression/models/MODEL_6_WINE.tsx deleted file mode 100644 index 41d11b5..0000000 --- a/src/pages/playground/1_Regression/models/MODEL_6_WINE.tsx +++ /dev/null @@ -1,358 +0,0 @@ -import * as dfd from "danfojs" -import { Trans } from "react-i18next" -import * as tfjs from "@tensorflow/tfjs" - -import * as _Types from "@core/types" -import * as DataFrameUtils from "@core/dataframe/DataFrameUtils" -import I_MODEL_REGRESSION from "./_model" -import { F_FILTER_Categorical, F_MAP_LabelEncoder } from "@core/nn-utils/utils" -import { LR_MODEL_KEYS } from '@/MODEL_KEYS' - -export default class MODEL_WINE extends I_MODEL_REGRESSION { - static KEY = LR_MODEL_KEYS.WINE - static URL = "https://archive.ics.uci.edu/dataset/186/wine+quality" - - URL = "https://archive.ics.uci.edu/dataset/186/wine+quality" - i18n_TITLE = "datasets-models.1-regression.wine.title" - _KEY = "WINE" - - wine_columns_X = [ - "fixed_acidity", - "volatile_acidity", - "citric_acid", - "residual_sugar", - "chlorides", - "free_sulfur_dioxide", - "total_sulfur_dioxide", - "density", - "pH", - "sulphates", - "alcohol", - ] - - DESCRIPTION() { - const prefix = "datasets-models.1-regression.wine.description." - return ( - <> -

    - -

    -

    - -

    -

    - -

    -

    - - link - - ), - }} - /> -

    -
    - - - -
      - {Object.entries( - this.t(prefix + "details-1-input.list", { - returnObjects: true, - defaultValue : [], - }) - ).map((_value, index) => { - return ( -
    1. - -
    2. - ) - })} -
    -
    -
    - - - -
      - {Object.entries( - this.t(prefix + "details-2-output.list", { - returnObjects: true, - defaultValue : [], - }) - ).map((_value, index) => { - return ( -
    1. - -
    2. - ) - })} -
    -
    -
    - - - -
      -
    1. - - TEXT - - ), - }} - /> -
    2. -
    -
    -
    - BibTeX -
    -            {`
    -@misc{misc_wine_quality_186,
    -  author       = {Cortez,Paulo, Cerdeira,A., Almeida,F., Matos,T., and Reis,J.},
    -  title        = {{Wine Quality}},
    -  year         = {2009},
    -  howpublished = {UCI Machine Learning Repository},
    -  note         = {{DOI}: https://doi.org/10.24432/C56S3T}
    -}
    -`}
    -          
    -
    - - ) - } - - /** - * - * @returns {Promise<_Types.DatasetProcessed_t[]>} - */ - async DATASETS(): Promise<_Types.DatasetProcessed_t[]> { - const path_datasets = import.meta.env.VITE_PATH + "/datasets/01-regression/wine-quality/" - - const info = "wine-quality.names" - const red_dataset_csv = "wine-quality-red.csv" - const white_dataset_csv = "wine-quality-white.csv" - - const dataset_fetch_info = await fetch(path_datasets + info) - const container_info = await dataset_fetch_info.text() - - /** @type {_Types.Dataset_t} */ - const dataset: _Types.Dataset_t = [ - { - column_name : "fixed_acidity", - column_role : "Feature", - column_type : "Continuous", - column_missing_values: false, - }, - { - column_name : "volatile_acidity", - column_role : "Feature", - column_type : "Continuous", - column_missing_values: false, - }, - { - column_name : "citric_acid", - column_role : "Feature", - column_type : "Continuous", - column_missing_values: false, - }, - { - column_name : "residual_sugar", - column_role : "Feature", - column_type : "Continuous", - column_missing_values: false, - }, - { - column_name : "chlorides", - column_role : "Feature", - column_type : "Continuous", - column_missing_values: false, - }, - { - column_name : "free_sulfur_dioxide", - column_role : "Feature", - column_type : "Continuous", - column_missing_values: false, - }, - { - column_name : "total_sulfur_dioxide", - column_role : "Feature", - column_type : "Continuous", - column_missing_values: false, - }, - { - column_name : "density", - column_role : "Feature", - column_type : "Continuous", - column_missing_values: false, - }, - { - column_name : "pH", - column_role : "Feature", - column_type : "Continuous", - column_missing_values: false, - }, - { - column_name : "sulphates", - column_role : "Feature", - column_type : "Continuous", - column_missing_values: false, - }, - { - column_name : "alcohol", - column_role : "Feature", - column_type : "Continuous", - column_missing_values: false, - }, - { - column_name : "quality", - column_role : "Target", - column_type : "Integer", - column_missing_values: false, - }, - // { - // column_name: "color", - // column_role: "Other", - // column_type: "Categorical", - // column_missing_values: false, - // }, - ] - - // #region Wine Red - const red_dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_datasets + red_dataset_csv) - let red_dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_datasets + red_dataset_csv) - /** @type {_Types.DataFrameColumnTransform_t[]} */ - const red_dataset_transforms: _Types.DataFrameColumnTransform_t[] = [ - ...dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder), - // { column_name: 'quality', column_transform: 'drop' }, - ] - const red_target = "quality" - const red_dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder( - red_dataframe_processed, - red_dataset_transforms - ) - const red_encoders_map = red_dataframe_encoder.encoder_map - red_dataframe_processed = red_dataframe_encoder.dataframe_processed - const red_dataframe_X = red_dataframe_processed.drop({ columns: [red_target] }).copy() - const red_dataframe_y = red_dataframe_original[red_target] - const minMaxScaler_1 = new dfd.MinMaxScaler() - const red_scaler = minMaxScaler_1.fit(red_dataframe_X) - const red_X = red_scaler.transform(red_dataframe_X) - const red_y = red_dataframe_y - // #endregion - - // #region Wine White - const white_dataframe_original = await DataFrameUtils.DataFrameReadCSV(path_datasets + white_dataset_csv) - let white_dataframe_processed = await DataFrameUtils.DataFrameReadCSV(path_datasets + white_dataset_csv) - /** @type {_Types.DataFrameColumnTransform_t[]} */ - const white_dataset_transforms = [ - ...dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder), - // { column_name: 'quality', column_transform: 'drop' }, - ] - const white_target = "quality" - const white_dataframe_encoder = DataFrameUtils.DataFrameTransformAndEncoder( - white_dataframe_processed, - white_dataset_transforms - ) - const white_encoders_map = white_dataframe_encoder.encoder_map - white_dataframe_processed = white_dataframe_encoder.dataframe_processed - const white_dataframe_X = white_dataframe_processed.drop({ columns: [white_target] }).copy() - const white_dataframe_y = white_dataframe_original[white_target] - const minMaxScaler_2 = new dfd.MinMaxScaler() - const white_scaler = minMaxScaler_2.fit(white_dataframe_X) - const white_X = white_scaler.transform(white_dataframe_X) - const white_y = white_dataframe_y - // #endregion - - return [ - { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_datasets, - info : info, - container_info : container_info, - csv : red_dataset_csv, - dataset : dataset, - dataset_transforms : red_dataset_transforms, - dataframe_original : red_dataframe_original, - dataframe_processed : red_dataframe_processed, - data_processed : { - dataframe_X : red_dataframe_X, - dataframe_y : red_dataframe_y, - X : red_X, - y : red_y, - column_name_target: red_target, - scaler : red_scaler, - encoders : red_encoders_map, - }, - }, - { - is_dataset_upload : false, - is_dataset_processed: true, - path : path_datasets, - info : info, - container_info : container_info, - csv : white_dataset_csv, - dataset : dataset, - dataset_transforms : white_dataset_transforms, - dataframe_original : white_dataframe_original, - dataframe_processed : white_dataframe_processed, - data_processed : { - dataframe_X : white_dataframe_X, - dataframe_y : white_dataframe_y, - X : white_X, - y : white_y, - scaler : white_scaler, - encoders : white_encoders_map, - column_name_target: white_target, - }, - }, - ] - } - - DEFAULT_LAYERS() { - return [ - { is_disabled: true, units: 11, activation: "relu" }, - { is_disabled: false, units: 32, activation: "relu" }, - { is_disabled: false, units: 16, activation: "relu" }, - { is_disabled: true, units: 1, activation: "linear" }, - ] - } - - async MODELS(dataset: string): Promise<_Types.CustomModel_t[]> { - const path = import.meta.env.VITE_PATH + "/models/01-regression/wine" - const red_model_0 = await tfjs.loadLayersModel(path + "/0/lr-model-red.json") - const white_model_0 = await tfjs.loadLayersModel(path + "/0/lr-model-white.json") - const models: { [key: string]: _Types.CustomModel_t[] } = { - "wine-quality-red.csv": [ - { - model : red_model_0, - model_path: path + "/0/lr-model-red.json", - X : this.wine_columns_X, - y : "quality", - }, - ], - "wine-quality-white.csv": [ - { - model : white_model_0, - model_path: path + "/0/lr-model-white.json", - X : this.wine_columns_X, - y : "quality", - }, - ], - } - return models[dataset] - } - - ATTRIBUTE_INFORMATION() { - return <> - } -} diff --git a/src/pages/playground/1_Regression/models/MODEL_N4L.tsx b/src/pages/playground/1_Regression/models/MODEL_N4L.tsx new file mode 100644 index 0000000..212e5f4 --- /dev/null +++ b/src/pages/playground/1_Regression/models/MODEL_N4L.tsx @@ -0,0 +1,68 @@ +import type { TFunction } from 'i18next' + +import * as _Types from '@core/types' +import { TASKS } from '@/TASKS' +import { denseLayers, n4lLayersModels, n4lTaskText, n4lTableView, type N4LDataset_t, type N4LTaskView_t } from '@core/n4l/format' +import { prepareRegression } from '@core/n4l/regression' +import type { N4LPackage_t } from '@core/n4l/source' +import { fileName } from '@core/n4l/tabularData' +import { loadN4LLayersModel } from '@core/n4l/tfjsModel' +import { N4LError } from '@core/n4l/validate' +import N4LPackageDescription from '@components/n4l/N4LPackageDescription' +import I_MODEL_REGRESSION from './_model' + +/** + * Un modelo de regresión de un paquete .n4l: sus conjuntos, sus modelos ya entrenados (los de cada CSV) y la red por + * defecto salen de su manifiesto (su sección de regresión) y sus textos. Cumple la misma interfaz que las clases de + * antes, así que las páginas no cambian + */ +export default class MODEL_N4L extends I_MODEL_REGRESSION { + readonly pkg : N4LPackage_t + readonly view: N4LTaskView_t + + constructor(t: TFunction<'translation', undefined>, setAccordionActive: React.Dispatch>, pkg: N4LPackage_t) { + super(t, setAccordionActive) + const view = n4lTableView(pkg.manifest, TASKS.REGRESSION) + if (view === undefined) throw new N4LError(pkg.manifest.id, ['no tiene la tarea regression']) + this.pkg = pkg + this.view = view + this._KEY = view.section.key + this.i18n_TITLE = n4lTaskText(pkg.namespace, TASKS.REGRESSION) + 'title' + this.URL_DATASET = pkg.manifest.source?.url ?? '' + } + + /** El paquete del que sale (para descargarlo) */ + N4L_PACKAGE() { + return this.pkg + } + + DESCRIPTION() { + return + } + + /** La misma red para todos sus conjuntos; las capas «locked» no se pueden cambiar (la salida, que da un número) */ + DEFAULT_LAYERS(_dataset: string): _Types.CustomParamsLayerModel_t[] { + return denseLayers(this.view.section.training?.layers).map(({ units, activation, locked }) => ({ units, activation, is_disabled: locked ?? false })) + } + + async DATASETS(): Promise<_Types.DatasetProcessed_t[]> { + return prepareRegression(this.pkg, this.view) + } + + TEST_METRICS(dataset: string) { + const ids = this.view.datasets.filter(({ file }) => fileName(file) === dataset).map(({ id }) => id) + const metrics = this.view.section.models.find((model) => ids.includes(model.dataset))?.metrics + const { test_r2, test_mae, test_baseline_mae } = metrics ?? {} + return test_r2 === undefined || test_mae === undefined || test_baseline_mae === undefined ? null : { test_r2, test_mae, test_baseline_mae } + } + + /** Los modelos ya entrenados con el CSV `dataset` (por su nombre de fichero) */ + async MODELS(dataset = ''): Promise<_Types.CustomModel_t[]> { + const ids = this.view.datasets.filter(({ file }) => fileName(file) === dataset).map(({ id }) => id) + const models = n4lLayersModels(this.view.section).filter((model) => ids.includes(model.dataset)) + return Promise.all(models.map(async ({ path }) => ({ + model : await loadN4LLayersModel(this.pkg.source, path), + model_path: this.pkg.source.url(path) ?? path, + }))) + } +} diff --git a/src/pages/playground/1_Regression/models/_model.tsx b/src/pages/playground/1_Regression/models/_model.tsx index cf6efea..70cb99f 100644 --- a/src/pages/playground/1_Regression/models/_model.tsx +++ b/src/pages/playground/1_Regression/models/_model.tsx @@ -1,17 +1,16 @@ -import * as _Types from "@core/types" -import { buildJoyride } from '@components/joyride/buildJoyride' -import type { TFunction } from "i18next" +import * as _Types from '@core/types' +import type { TFunction } from 'i18next' export default abstract class I_MODEL_REGRESSION { - _KEY = "" - i18n_TITLE = "" - URL_DATASET = "" + _KEY = '' + i18n_TITLE = '' + URL_DATASET = '' - t : TFunction<"translation", undefined> + t : TFunction<'translation', undefined> setAccordionActive: React.Dispatch> - constructor(_t: TFunction<"translation", undefined>, _setAccordionActive: React.Dispatch>) { + constructor(_t: TFunction<'translation', undefined>, _setAccordionActive: React.Dispatch>) { this.t = _t this.setAccordionActive = _setAccordionActive } @@ -30,13 +29,21 @@ export default abstract class I_MODEL_REGRESSION { */ DEFAULT_LAYERS(dataset: string): _Types.CustomParamsLayerModel_t[] { const list_map: { [key: string]: _Types.CustomParamsLayerModel_t[] } = { - "": [], + '': [], } return list_map[dataset] || [] } COMPILE() {} + /** + * Cómo predice el modelo ya entrenado del CSV `dataset` con datos que no vio al entrenarlo (los de un paquete .n4l, + * medidos al entrenarlos); null si no se sabe + */ + TEST_METRICS(_dataset: string): { test_r2: number, test_mae: number, test_baseline_mae: number } | null { + return null + } + /** * * @return {Promise>} @@ -49,37 +56,7 @@ export default abstract class I_MODEL_REGRESSION { * @param {string} [_dataset=''] * @return {Promise<_Types.CustomModel_t[]>} */ - async MODELS(_dataset = ""): Promise<_Types.CustomModel_t[]> { + async MODELS(_dataset = ''): Promise<_Types.CustomModel_t[]> { return [] } - - /** - * callback: (e) => { - * e.action : "start" | "update", - * e.controlled: boolean, - * e.index : number, - * e.lifecycle : "init" | "ready" | "beacon" | "tooltip" | "complete", - * e.size : 3, - * e.status : "running", - * e.type :"tour:start" - * } - * - * @return {_Types.Joyride_t} - */ - JOYRIDE(): _Types.Joyride_t { - // Cada paso abre las secciones del acordeón donde está su elemento - const openManual = () => this.setAccordionActive(['manual']) - const openDatasetInfo = () => this.setAccordionActive(['manual', 'dataset_info']) - return buildJoyride(this.t, 'datasets-models.1-regression.joyride.steps.', [ - { key: 'manual', target: '.joyride-step-1-manual', placement: 'top', onShow: openManual }, - { key: 'dataset-info', target: '.joyride-step-2-dataset-info', placement: 'top', onShow: openDatasetInfo }, - { key: 'pre-process-dataset', target: '.joyride-step-3-pre-process-dataset', placement: 'top', onShow: openDatasetInfo }, - { key: 'dataset', target: '.joyride-step-4-dataset', placement: 'top', onShow: openDatasetInfo }, - { key: 'layer-visualizer', target: '.joyride-step-5-layer', placement: 'top', onShow: openDatasetInfo }, - { key: 'layer-editor', target: '.joyride-step-6-editor-layers', placement: 'right', onShow: openDatasetInfo }, - { key: 'params-editor', target: '.joyride-step-7-editor-trainer', placement: 'left-start', onShow: openDatasetInfo }, - { key: 'list-of-models', target: '.joyride-step-8-list-of-models', placement: 'bottom', onShow: openDatasetInfo }, - { key: 'predict-and-visualizer', target: '.joyride-step-9-predict-visualization', placement: 'top', onShow: openDatasetInfo }, - ]) - } } diff --git a/src/pages/playground/1_Regression/models/index.ts b/src/pages/playground/1_Regression/models/index.ts index 9300168..4a7aa40 100644 --- a/src/pages/playground/1_Regression/models/index.ts +++ b/src/pages/playground/1_Regression/models/index.ts @@ -1,18 +1,32 @@ import I_MODEL_REGRESSION from './_model' import { LR_MODEL_KEYS } from '@/MODEL_KEYS' -import type { ModelRegistry } from '@core/models/modelRegistry' +import { TASKS } from '@/TASKS' +import { withDynamicModels, type ModelRegistry } from '@core/models/modelRegistry' +import { builtinN4LPackage, n4lPackagesOf } from '@core/n4l/catalog' +import { LOCAL_KEY_PREFIX, openLocalPackage } from '@core/n4l/localPackages' +import type { N4LPackage_t } from '@core/n4l/source' +import type { TFunction } from 'i18next' -/** Clases de modelos de regresión, cargadas bajo demanda. */ -const MAP_LR_CLASSES: ModelRegistry = { - [LR_MODEL_KEYS.UPLOAD] : () => import('./MODEL__UPLOAD').then((m) => m.default), - [LR_MODEL_KEYS.SALARY] : () => import('./MODEL_1_SALARY').then((m) => m.default), - [LR_MODEL_KEYS.AUTO_MPG] : () => import('./MODEL_2_AUTO_MPG').then((m) => m.default), - [LR_MODEL_KEYS.HOUSING_PRICES] : () => import('./MODEL_3_HOUSING_PRICES').then((m) => m.default), - [LR_MODEL_KEYS.BREAST_CANCER] : () => import('./MODEL_4_BREAST_CANCER').then((m) => m.default), - [LR_MODEL_KEYS.STUDENT_PERFORMANCE]: () => import('./MODEL_5_STUDENT_PERFORMANCE').then((m) => m.default), - [LR_MODEL_KEYS.WINE] : () => import('./MODEL_6_WINE').then((m) => m.default), +/** La clase de un paquete .n4l: MODEL_N4L con ese paquete (se descarga al usarla, como las demás) */ +const n4lModelClass = (open: () => Promise) => async () => { + const [{ default: MODEL_N4L }, pkg] = await Promise.all([import('./MODEL_N4L'), open()]) + return class extends MODEL_N4L { + constructor(t: TFunction<'translation', undefined>, setAccordionActive: React.Dispatch>) { + super(t, setAccordionActive, pkg) + } + } } +/** + * Clases de modelos de regresión, cargadas bajo demanda: subir un CSV propio, los paquetes .n4l de la aplicación y, + * como local-, los que haya abierto el usuario + */ +const MAP_LR_CLASSES: ModelRegistry = withDynamicModels({ + [LR_MODEL_KEYS.UPLOAD]: () => import('./MODEL__UPLOAD').then((m) => m.default), + ...Object.fromEntries(n4lPackagesOf(TASKS.REGRESSION).map(({ entry, section }) => + [section.key, n4lModelClass(async () => builtinN4LPackage(entry))])), +}, (key) => (key.startsWith(LOCAL_KEY_PREFIX) ? n4lModelClass(() => openLocalPackage(key.slice(LOCAL_KEY_PREFIX.length))) : undefined)) + export { MAP_LR_CLASSES, I_MODEL_REGRESSION, diff --git a/src/pages/playground/1_Regression/utils.ts b/src/pages/playground/1_Regression/utils.ts index a42f63e..e22ecd2 100644 --- a/src/pages/playground/1_Regression/utils.ts +++ b/src/pages/playground/1_Regression/utils.ts @@ -30,7 +30,8 @@ export function TRANSFORM_DATASET_PROCESSED_TO_STATE_PREDICTION (dataset_process const prediction_input_X = _X.values[index_row] const df_void_input_original = new dfd.DataFrame([], { columns: _dataframe_original.columns, dtypes: _dataframe_original.dtypes }) - const df_void_input_processed = new dfd.DataFrame([], { columns: _dataframe_processed.columns, dtypes: _dataframe_original.dtypes }) + // Con sus propios tipos: si se descartaron columnas al procesar, el procesado tiene menos que el original + const df_void_input_processed = new dfd.DataFrame([], { columns: _dataframe_processed.columns, dtypes: _dataframe_processed.dtypes }) const df_void_dataframe_X = new dfd.DataFrame([], { columns: _dataframe_X.columns, dtypes: _dataframe_X.dtypes }) const df_void_X = new dfd.DataFrame([], { columns: _X.columns, dtypes: _X.dtypes }) diff --git a/src/pages/playground/2_ObjectDetection/ModelReviewObjectDetection.tsx b/src/pages/playground/2_ObjectDetection/ModelReviewObjectDetection.tsx index 04a62ee..e7dfa70 100644 --- a/src/pages/playground/2_ObjectDetection/ModelReviewObjectDetection.tsx +++ b/src/pages/playground/2_ObjectDetection/ModelReviewObjectDetection.tsx @@ -1,21 +1,25 @@ import 'bootstrap/dist/css/bootstrap.min.css' -import { useCallback, useEffect, useRef, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { Card, Col, Container, Form, Row, Button } from 'react-bootstrap' import { Camera as IconCamera } from 'react-bootstrap-icons' -import ReactGA from 'react-ga4' import Webcam from 'react-webcam' import { Trans, useTranslation } from 'react-i18next' import { useNavigate } from 'react-router' -import * as tfjs from '@tensorflow/tfjs' import { VERBOSE } from '@/CONSTANTS' -import { UPLOAD } from '@/TASKS' +import { TASKS, UPLOAD } from '@/TASKS' import DragAndDrop from '@components/dragAndDrop/DragAndDrop' -import FakeProgressBar from '@components/loading/FakeProgressBar' +import N4LDownloadProgress from '@components/loading/N4LDownloadProgress' +import { trackDownloads } from '@core/downloadProgress' +import { askBeforeDownload } from '@core/models/downloadConsent' +import N4LMaximizeButton from '@components/maximize/N4LMaximizeButton' +import { useMaximize } from '@components/maximize/useMaximize' import { MAP_OD_CLASSES } from '@pages/playground/2_ObjectDetection/models' import { createReviewModelInstance } from '@core/models/createReviewModelInstance' +import { restoreTFBackend } from '@core/tfBackend' import alertHelper from '@utils/alertHelper' import type I_MODEL_OBJECT_DETECTION from './models/_model' +import { DetectionSmoother } from './models/smoothing' import { delay } from '@utils/utils' import { ImageExplainResults, @@ -24,18 +28,33 @@ import { } from '@core/explainability/ImageExplainPanel' import { DEFAULT_SHAP_IMAGE_OPTIONS } from '@core/explainability/shapImageOptions' import { explainErrorKey } from '@core/explainability/explainError' +import { trackEvent } from '@core/analytics' import { runObjectDetectionExplain } from './explainPrediction/runObjectDetectionExplain' +import WebcamDeviceInfo, { type DetectionStats_t } from './WebcamDeviceInfo' +import N4LPageHeader from '@components/neural-network/N4LPageHeader' +import N4LModelCard from '@components/neural-network/N4LModelCard' +import N4LModelAside from '@components/neural-network/N4LModelAside' +import { objectDetectionReviewGuide } from './modelReviewGuide' +import { detectionSummary, detectionText, type DetectedItem_t } from './detectionSummary' +import { announce } from '@core/a11y/announce' -const WebcamComponent = (Webcam as unknown) as React.FC; +// Cada cuánto se actualiza el texto de lo que ve la cámara +const LIVE_SUMMARY_MS = 2000 -tfjs.setBackend('webgl').then(() => { - if (VERBOSE) console.debug('setBackend: WebGL') -}) +const WebcamComponent = (Webcam as unknown) as React.FC; -/** - * @typedef {'ratio-9x16'|'ratio-2x3'|'ratio-3x4'|'ratio-1x1'|'ratio-4x3'|'ratio-3x2'|'ratio-16x9'} Ratio_t - */ -type Ratio_t = 'ratio-9x16' | 'ratio-2x3' | 'ratio-3x4' | 'ratio-1x1' | 'ratio-4x3' | 'ratio-3x2' | 'ratio-16x9' +// El vídeo de la cámara y el lienzo con las detecciones ocupan todo #webcamContainer y se encajan igual dentro, sin +// recortar (contain): las detecciones caen sobre el vídeo aunque el contenedor no tenga su proporción (maximizado) +// Predicciones por segundo con la cámara, como mucho +const DETECTION_FPS = 20 + +const WEBCAM_LAYER_STYLE: React.CSSProperties = { + position : 'absolute', + inset : 0, + width : '100%', + height : '100%', + objectFit: 'contain', +} type ModelReviewObjectDetectionProps = { dataset: string @@ -44,7 +63,7 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec const { dataset } = props const isWebView = navigator.userAgent.toLowerCase().indexOf('wv') !== -1 - const { t } = useTranslation() + const { t, i18n } = useTranslation() const navigate = useNavigate() const [isLoading, setLoading] = useState(true) @@ -62,10 +81,17 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec const [devices, setDevices] = useState([]) const [iModelInstance, setIModelInstance] = useState(null) - /** - * @type {ReturnType>} - */ - const [ratioCamera, setRatioCamera] = useState('ratio-16x9') + // Proporción (ancho / alto) de los fotogramas de la cámara: la toma su contenedor, así el vídeo lo llena sin bandas. + // Sale del propio vídeo y no de getSettings().aspectRatio, que Firefox no da (el contenedor quedaba cuadrado) + const [cameraAspect, setCameraAspect] = useState(16 / 9) + // La tarjeta de la cámara, a pantalla completa + const webcamMaximize = useMaximize() + // Predicciones hechas con la cámara y lo que han tardado: los lee la información del dispositivo + const detectionStats_ref = useRef({ predictions: 0, totalMs: 0 }) + // La carga del modelo (ENABLE_MODEL), para esperarla si se sube una imagen antes de que termine + const modelReady_ref = useRef | null>(null) + // Guía paso a paso de la página (con voz): solo con el botón "Guía" + const guideSteps = useMemo(() => (iModelInstance === null ? null : objectDetectionReviewGuide(t, dataset)), [t, dataset, iModelInstance]) /** * @type {ReturnType>} @@ -98,14 +124,15 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec // === Explicabilidad (SHAP) === const imgData_ref = useRef(null) + // Lo detectado en texto: en la foto subida, al terminar; con la cámara, cada pocos segundos (sin anunciarlo solo: + // saturaría el lector), y se anuncia al pulsar «Decir lo que se detecta» + const [imageDetections, setImageDetections] = useState(null) + const [liveDetections, setLiveDetections] = useState(null) const [explainResult, setExplainResult] = useState(null) const [showExplain, setShowExplain] = useState(false) const [isCalculo, setIsCalculo] = useState(false) const [shapOptions, setShapOptions] = useState({ ...DEFAULT_SHAP_IMAGE_OPTIONS, maskValue: 0 }) - useEffect(() => { - ReactGA.send({ hitType: 'pageview', page: `/ModelReviewObjectDetection/${dataset}`, title: dataset }) - }, [dataset]) const handleDevices = useCallback(async () => { if (VERBOSE) console.debug('useCallback[handleDevices]') @@ -171,16 +198,17 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec useEffect(() => { if (VERBOSE) console.debug('useEffect[init][ dataset, t, history ]') async function init() { - await tfjs.ready() - if (tfjs.getBackend() !== 'webgl') { - console.error('Error tensorflow backend webgl not installed in your browser') - return - } + // Los modelos de pose (pose-detection) registran WebGPU con más prioridad: se vuelve al backend elegido en el menú + await restoreTFBackend() const _iModelInstance = await createReviewModelInstance(MAP_OD_CLASSES, dataset, (ModelClass) => new ModelClass(t), navigate) if (_iModelInstance === null) return try { setIModelInstance(_iModelInstance) - await _iModelInstance.ENABLE_MODEL() + // Con ahorro de datos o conexión lenta, antes se pregunta; luego, con el progreso real (COCO-SSD pesa unos 18 MB) + await askBeforeDownload(TASKS.OBJECT_DETECTION, dataset) + const ready = trackDownloads(() => _iModelInstance.ENABLE_MODEL(), 'model_load') + modelReady_ref.current = ready + await ready setLoading(false) await alertHelper.alertSuccess(t('model-loaded-successfully')) } catch (error) { @@ -212,13 +240,12 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec // Get Video Properties const video = WebCam_ref.current.video - // Set canvas width - canvas_ref.current.width = WebCam_ref.current.video.videoWidth - canvas_ref.current.height = WebCam_ref.current.video.videoHeight + // Set canvas width (solo si cambia: asignarlo, aunque sea el mismo valor, vuelve a crear el lienzo) + if (canvas_ref.current.width !== video.videoWidth) canvas_ref.current.width = video.videoWidth + if (canvas_ref.current.height !== video.videoHeight) canvas_ref.current.height = video.videoHeight const ctx = canvas_ref.current.getContext('2d') as CanvasRenderingContext2D ctx.clearRect(0, 0, canvas_ref.current.width, canvas_ref.current.height) - // ctx.setTransform(-1, 0, 0, 1, canvas_ref.current.width, 0) return { ctx, video } }, []) @@ -234,9 +261,10 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec input_img_or_video: ImageData | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement, config: { flipHorizontal: boolean } ) => { - if (iModelInstance === null) return + if (iModelInstance === null) return [] const predictions = await iModelInstance.PREDICTION(input_img_or_video, config) iModelInstance.RENDER(ctx, predictions) + return predictions }, [iModelInstance]) useEffect(() => { @@ -248,21 +276,55 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec } } + // La predicción puede acabar después de apagar la cámara o cambiar de modelo: entonces no se pinta + let isCancelled = false try { - const fps = 20 + const fps = DETECTION_FPS let fpsInterval: number, now: number, then: number, elapsed: number + // Una predicción cada vez: si la anterior no ha terminado se salta el fotograma. Si no, mientras el modelo + // espera a la GPU (lecturas asíncronas) empezaban predicciones nuevas que se pisaban y el vídeo iba a saltos. + let isPredicting = false + let summarizedAt = 0 + // Las detecciones, seguidas de un fotograma al siguiente y suavizadas (si el modelo dice cómo): sin temblar ni + // parpadear. Si su RENDER solo dibuja, se dibujan en cada fotograma de la pantalla, acercándose a la última + // predicción, en vez de a saltos con cada una + const smoother = iModelInstance?.SMOOTHING ? new DetectionSmoother(iModelInstance.SMOOTHING) : null + const renderEveryFrame = iModelInstance?.RENDER_EVERY_FRAME ?? false const animate = async () => { if (isCameraEnable) { requestAnimation_ref.current = requestAnimationFrame(animate) + if (smoother !== null && renderEveryFrame && iModelInstance !== null) { + const _processWebcam = processWebcam() + if (_processWebcam !== null) iModelInstance.RENDER(_processWebcam.ctx, smoother.frame(performance.now())) + } now = Date.now() elapsed = now - then - if (elapsed > fpsInterval) { + const video = WebCam_ref.current?.video + if (elapsed > fpsInterval && !isPredicting && iModelInstance !== null && video?.readyState === 4) { then = now - (elapsed % fpsInterval) - const _processWebcam = processWebcam() - if (_processWebcam !== null) { - if (_processWebcam.ctx !== null && _processWebcam.video !== null) { - await processData(_processWebcam.ctx, _processWebcam.video, { flipHorizontal: iModelInstance?.mirror ?? false }) + isPredicting = true + try { + const start = performance.now() + const predictions = await iModelInstance.PREDICTION(video, { flipHorizontal: iModelInstance.mirror ?? false }) + detectionStats_ref.current.predictions += 1 + detectionStats_ref.current.totalMs += performance.now() - start + if (isCancelled) return + smoother?.update(predictions, performance.now()) + // Lo que se ve: el texto de lo detectado dice lo mismo que la pantalla + const shown = smoother === null ? predictions : smoother.latest() + if (smoother === null || !renderEveryFrame) { + // El canvas se limpia justo antes de pintar: limpiarlo antes de predecir lo dejaba vacío mientras tanto + const _processWebcam = processWebcam() + if (_processWebcam !== null) iModelInstance.RENDER(_processWebcam.ctx, shown) } + if (now - summarizedAt >= LIVE_SUMMARY_MS) { + summarizedAt = now + setLiveDetections(detectionSummary(iModelInstance, shown)) + } + } catch (error) { + console.error(error) + } finally { + isPredicting = false } } } @@ -285,15 +347,25 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec // Limpia la animación cuando el componente se desmonta return () => { if (VERBOSE) console.debug(`delete AnimationFrame(${requestAnimation_ref.current});`) + isCancelled = true if (requestAnimation_ref.current !== null) { cancelAnimationFrame(requestAnimation_ref.current) } } - }, [isCameraEnable, iModelInstance, processWebcam, processData]) + }, [isCameraEnable, iModelInstance, processWebcam]) + + // Analíticas: cuánto tiempo se usa la cámara en tiempo real + useEffect(() => { + if (!isCameraEnable) return + const startedAt = performance.now() + trackEvent('webcam_start') + return () => trackEvent('webcam_end', { duration_sec: Math.round((performance.now() - startedAt) / 1000) }) + }, [isCameraEnable]) const handleChange_Camera = (e: React.ChangeEvent) => { const webcamChecked = e.target.checked setCameraEnable(!!webcamChecked) + setLiveDetections(null) } const handleChange_Device = (e: React.ChangeEvent) => { @@ -301,26 +373,19 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec setDeviceId(_deviceId) } - const onUserMediaEvent = (mediaStream: MediaStream) => { - const aspectRatio = mediaStream.getVideoTracks()[0].getSettings().aspectRatio || 1 - if (aspectRatio >= 0.5 && aspectRatio < 0.6) { - setRatioCamera('ratio-9x16') - } else if (aspectRatio >= 0.6 && aspectRatio < 0.7) { - setRatioCamera('ratio-2x3') - } else if (aspectRatio >= 0.7 && aspectRatio < 0.8) { - setRatioCamera('ratio-3x4') - } else if (aspectRatio === 1) { - setRatioCamera('ratio-1x1') - } else if (aspectRatio >= 1.3 && aspectRatio < 1.4) { - setRatioCamera('ratio-4x3') - } else if (aspectRatio >= 1.4 && aspectRatio < 1.6) { - setRatioCamera('ratio-3x2') - } else if (aspectRatio >= 1.7 && aspectRatio < 1.8) { - setRatioCamera('ratio-16x9') - } else { - setRatioCamera('ratio-1x1') - } - // mediaStream.scale(-1, 1) + // La cámara ya emite: el permiso está concedido aunque permissions.query no lo diga (Firefox, con el permiso dado + // solo para esta visita, sigue diciendo "prompt": el selector pedía permisos y la lista de cámaras se quedaba vacía) + const handleUserMedia = async () => { + setCameraPermission('granted') + if (!navigator?.mediaDevices?.enumerateDevices) return + const mediaDevices = await navigator.mediaDevices.enumerateDevices() + setDevices(mediaDevices.filter(({ kind }) => kind === 'videoinput')) + } + + // Al llegar los primeros fotogramas y cada vez que cambian de tamaño (otra cámara, el móvil girado) + const handleVideoSize = (event: React.SyntheticEvent) => { + const { videoWidth, videoHeight } = event.currentTarget + if (videoWidth > 0 && videoHeight > 0) setCameraAspect(videoWidth / videoHeight) } const onUserMediaErrorEvent = (error: any) => { @@ -364,7 +429,7 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec const resultCanvas = canvasImage_ref.current; if (!originalCanvas || !resultCanvas || !processCanvas) { - console.error("Canvas references not found"); + console.error('Canvas references not found'); return; } @@ -372,17 +437,20 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec const resultCtx = resultCanvas.getContext('2d'); if (!originalCtx || !resultCtx) { - console.error("Canvas 2D context not available"); + console.error('Canvas 2D context not available'); return; } if (iModelInstance === null) { - console.error("Model not loaded"); + console.error('Model not loaded'); return; } - // 2. Reload Model - await iModelInstance.ENABLE_MODEL(); + // 2. El modelo de la página, cuando termine de cargarse si aún se está cargando, sin lo que siguió en la webcam. No se + // vuelve a cargar: se creaba otro detector en cada imagen (sin liberar el anterior) y, si se subía mientras el de la + // página aún se cargaba, los dos de MediaPipe se pisaban y abortaba (Module.arguments has been replaced…) + await modelReady_ref.current + iModelInstance.RESET(); const objectUrl = URL.createObjectURL(_files[0]); const img = new Image(); @@ -415,13 +483,17 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec // Process detection // Una imagen subida no se muestra en espejo (la webcam sí): nunca se refleja. - await processData(resultCtx, imgData, { flipHorizontal: false }); + const predictions = await processData(resultCtx, imgData, { flipHorizontal: false }); + trackEvent('predict', { input: 'image' }) + const detected = detectionSummary(iModelInstance, predictions) + setImageDetections(detected) + announce(detectionText(t, detected, i18n.language)) await delay(2000); // Artificial delay if needed for UI/UX setProcessImage({ isProcessing: false, isProcessed: true }); } catch (error) { - console.error("Processing failed:", error); + console.error('Processing failed:', error); setProcessImage({ isProcessing: false, isProcessed: false }); } finally { // 3. Clean up memory @@ -465,6 +537,7 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec return } + trackEvent('explain', { method: 'shap' }) setIsCalculo(true) try { const result = await runObjectDetectionExplain({ @@ -500,39 +573,23 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec if (VERBOSE) console.debug('render ModelReviewObjectDetection') return ( <> - - - -

    - -

    - -
    + + } guideId={'object-detection.' + dataset} guideSteps={guideSteps} className={'mt-2'} /> - + -
    - - -

    - {iModelInstance !== null && } -

    -
    - - {dataset !== UPLOAD && iModelInstance?.DESCRIPTION()} - -
    - - {/* Panel narrativo del método (idéntico patrón al review tabular). OD usa SHAP. */} - + + }> + {dataset !== UPLOAD && iModelInstance?.DESCRIPTION()} + + {/* Cómo se explica la predicción (SHAP) */} +

    @@ -542,173 +599,167 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec

    {t('ui.explain.about-shap')}

    -

    + - - -
    -

    - -

    -
    - -
    - -
    - + +

    + +

    +
    + +
    + +
    + + - - {isWebView && ( - <> + {isWebView && ( + <> + + + )} + {!isWebView && ( + <> + {cameraPermission === 'granted' && ( - - )} - {!isWebView && ( - <> - {cameraPermission === 'granted' && ( + )} + {(cameraPermission === 'prompt' || + cameraPermission === 'denied') && ( )} - {(cameraPermission === 'prompt' || - cameraPermission === 'denied') && ( - - )} - - )} - {devices.map((device, index) => { - return ( - - ) - })} - - - -
    + + )} + {devices.map((device, index) => { + return ( + + ) + })} + +
    + +
    - + {/* Con la cámara encendida sobra: ya se ve */} + {!isCameraEnable && - - - - {isCameraEnable && ( - <> -
    - - -
    - - )} - -
    +
    } + {/* Directamente en el cuerpo de la tarjeta: maximizada, la cámara ocupa el alto que queda y el vídeo y + el lienzo (con su tamaño y object-fit: contain) se encajan igual dentro */} + {isCameraEnable && ( +
    + + +
    + )} + {isCameraEnable && +
    +

    + {liveDetections === null ? t('datasets-models.2-object-detection.interface.detections.waiting') : detectionText(t, liveDetections, i18n.language)} +

    + +
    }
    - -
    - {t('Device info')} -
      - {devices.map((device, index) => { - return ( -
    1. - {device.kind} | {device.label} -
    2. - ) - })} -
    -
    + + WebCam_ref.current?.video} + devices={devices} + cameraPermission={cameraPermission} + isWebView={isWebView} + mirrored={iModelInstance?.mirror ?? false} + model={iModelInstance ? t(iModelInstance.TITLE) : '—'} + fpsLimit={DETECTION_FPS} + stats={detectionStats_ref} /> - +

    + {processImage.isProcessed && imageDetections !== null && +

    {detectionText(t, imageDetections, i18n.language)}

    } - +

    {t('ui.explain.title')}

    @@ -804,7 +859,7 @@ export default function ModelReviewObjectDetection(props: ModelReviewObjectDetec -

    - - + + } guideId={'train.image-classification.' + dataset} guideSteps={guideSteps} + getSession={currentSession} onImport={importSession} className={'mt-3'} /> - + - -

    Manual

    + + + + - - -

    + + + {iModelInstance.DESCRIPTION()} @@ -330,13 +509,13 @@ export default function ImageClassification(props: ImageClassificationProps_t) {
    - + {/* EDITOR */}
    - + @@ -346,12 +525,19 @@ export default function ImageClassification(props: ImageClassificationProps_t) { + setLayers={setLayers} + classes={iModelInstance?.CLASS_LABELS.length ?? 10} /> {/* GENERAL PARAMETERS */} + {/* El código equivalente de la red */} - + + + + + + + {/* BLOCK BUTTON */} -
    - -
    + + + + + {!training.isTraining && + }
    - + + {/* GENERATED MODELS */} - + - + {/* BLOCK 2 */} - + {/* EXPLAINABILITY (LRP) */} + + - +

    {t('pages.playground.0-tabular-classification.general.explain-panel-title')} (LRP)

    {showExplain && explainResult && } + {!hasExplainInput && }
    - */} - -
    - - - - {Layers.map((_item, index: number) => { - return - - - - -
    - -
    - - {/* CLASS */} - - Clase de la capa - handleChange_Class(e, index)}> - {TYPE_CLASS.map(({ key, label }, index) => { - return () - })} - - - -
    - - -
    -
    - })} -
    -
    - + return ( + layerSummaryParts(t, layer).join(', ')} + isLocked={(layer) => layer._protected === true} + renderFields={(layer, index) => <> + + + handleChange_Class(e, index)}> + {TYPE_CLASS.map(({ key, label }) => )} + + +
    + + } + check={} + flagged={flaggedLayers(issues)} + onAddEnd={handleClick_AddLayer_End} + onRemove={handleClick_RemoveLayer} + onMove={(from, to) => setLayers((current) => moveLayer(current, from, to))} + onRestore={setLayers} + footer={

    - - }} /> + }} />

    -
    -
    - -} \ No newline at end of file + } + /> + ) +} diff --git a/src/pages/playground/3_ImageClassification/ImageClassificationEditorLayersItem.tsx b/src/pages/playground/3_ImageClassification/ImageClassificationEditorLayersItem.tsx index d2e6a5c..ed25f62 100644 --- a/src/pages/playground/3_ImageClassification/ImageClassificationEditorLayersItem.tsx +++ b/src/pages/playground/3_ImageClassification/ImageClassificationEditorLayersItem.tsx @@ -2,12 +2,12 @@ import { Col, Form, Row } from 'react-bootstrap' import { Trans, useTranslation } from 'react-i18next' import { TYPE_ACTIVATION } from '@core/nn-utils/ArchitectureTypesHelper' import { VERBOSE } from '@/CONSTANTS' -import type { Layer_t } from '@/types/types' +import type { ImageLayer_t } from '@/types/types' type Props = { - item : Layer_t, + item : ImageLayer_t, indexLayer : number, - handleChange_Attr: (e: React.ChangeEvent, indexLayer: number, _param_name_: keyof Layer_t) => void + handleChange_Attr: (e: React.ChangeEvent, indexLayer: number, _param_name_: keyof ImageLayer_t) => void } export default function ImageClassificationEditorLayersItem(props: Props) { diff --git a/src/pages/playground/3_ImageClassification/ImageClassificationTableModels.tsx b/src/pages/playground/3_ImageClassification/ImageClassificationTableModels.tsx index 80f1c13..a3c8ab5 100644 --- a/src/pages/playground/3_ImageClassification/ImageClassificationTableModels.tsx +++ b/src/pages/playground/3_ImageClassification/ImageClassificationTableModels.tsx @@ -1,18 +1,34 @@ import { useState } from 'react' import { Table, Card, Button, Container, Row, Col } from 'react-bootstrap' -import { Trans } from 'react-i18next' +import { Trans, useTranslation } from 'react-i18next' import * as tfvis from '@tensorflow/tfjs-vis' import { VERBOSE } from '@/CONSTANTS' -import { parseLogs } from '@core/history/utils' +import { bestModelIndex, formatEpochs } from '@core/history/trainingSummary' +import N4LFinalMetrics, { N4LBestBadge } from '@components/neural-network/N4LFinalMetrics' +import N4LTrainingCurves from '@components/neural-network/N4LTrainingCurves' +import N4LConfusionMatrix from '@components/neural-network/N4LConfusionMatrix' import { nnLabel } from '@core/nn-utils/ArchitectureTypesHelper' -import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +import { layersSummary } from '@components/neural-network/layerSummary' +import N4LEmptyState from '@components/loading/N4LEmptyState' import type { ImageClassificationGeneratedModel_t } from '@core/types' import N4LPagination from '@components/table/N4LPagination' +import { useParams } from 'react-router' +import { TASKS } from '@/TASKS' +import N4LReportButton from '@components/report/N4LReportButton' +import { historyNumbers } from '@core/report/trainingReport' +import { layerSummaryParts } from '@components/neural-network/layerSummary' +import N4LDownloadTrained from '@components/n4l/N4LDownloadTrained' +import type { N4LPackage_t } from '@core/n4l/source' +import { n4lLayersOf } from './models/n4lLayers' type ImageClassificationTableModelsProps = { GeneratedModels: ImageClassificationGeneratedModel_t[], rowsPerPage : number + /** El paquete .n4l del conjunto: cada modelo se puede guardar en uno (con el conjunto y sus textos) */ + pkg? : N4LPackage_t | null + /** Las clases, en el orden de las salidas */ + classes? : string[] } const DEFAULT_PROPS: ImageClassificationTableModelsProps = { GeneratedModels: [], @@ -22,7 +38,9 @@ export default function ImageClassificationTableModels(props: ImageClassificatio const { GeneratedModels, - rowsPerPage + rowsPerPage, + pkg = null, + classes = [], } = props const prefix = 'generator.table-models.' @@ -32,6 +50,21 @@ export default function ImageClassificationTableModels(props: ImageClassificatio const showTable = GeneratedModels.length > 0 const pageCount = Math.ceil(GeneratedModels.length / rowsPerPage) + // Historial de cada modelo (mismo orden que la tabla) y el de menor pérdida final, si hay con quién comparar + const histories = GeneratedModels.map((generated) => generated.history.history) + const bestIndex = histories.length > 1 ? bestModelIndex(histories) : -1 + // Para compararlos: lo que cambia de un entrenamiento a otro (las métricas solo se miden, no cambian cómo aprende) + const { t } = useTranslation() + const { example } = useParams() + const parameters = GeneratedModels.map(({ params }) => ({ + 'learning-rate': String(params.learning_rate), + 'n-epochs' : String(params.n_epochs), + 'test-size' : params.test_size + '%', + 'layers' : layersSummary(t, params.layers), + 'id-optimizer' : nnLabel(params.id_optimizer), + 'id-loss' : nnLabel(params.id_loss), + })) + const handleClick_ChangePage = (pageNumber: number) => { setActivePage(pageNumber) } @@ -50,18 +83,18 @@ export default function ImageClassificationTableModels(props: ImageClassificatio if (VERBOSE) console.debug('render ImageClassificationTableModels') return <> - +

    | {GeneratedModels.length}

    -
    +
    @@ -70,7 +103,7 @@ export default function ImageClassificationTableModels(props: ImageClassificatio {!showTable && <> - + } {showTable && <> @@ -97,10 +130,10 @@ export default function ImageClassificationTableModels(props: ImageClassificatio .slice(activePage * rowsPerPage, (activePage * rowsPerPage) + rowsPerPage) .map((value, index) => { return - {(activePage * rowsPerPage) + index + 1} - {value.params.learning_rate}% + {(activePage * rowsPerPage) + index + 1}{(activePage * rowsPerPage) + index === bestIndex && } + {value.params.learning_rate} {value.params.test_size}% - {value.params.n_epochs} + {formatEpochs(value.history.epoch.length, value.params.n_epochs)} {value.params.layers .map((value, index2) => { @@ -119,20 +152,28 @@ export default function ImageClassificationTableModels(props: ImageClassificatio })} - {Object.entries(value.history.history) - .map(([key, logs], index2) => { - const logsArray = logs as Array - return - {key} {parseLogs(logsArray)}
    -
    - })} + + } + number={(activePage * rowsPerPage) + index + 1} /> + ({ + version : 1, + task : TASKS.IMAGE_CLASSIFICATION, + dataset : example ?? '', + model : (activePage * rowsPerPage) + index + 1, + createdAt : new Date().toISOString(), + layers : value.params.layers.map((layer) => layerSummaryParts(t, layer).join(', ')), + parameters: parameters[(activePage * rowsPerPage) + index], + history : historyNumbers(value.history.history), + ...(value.evaluation !== undefined) && { evaluation: value.evaluation }, + })} /> })} @@ -145,6 +186,12 @@ export default function ImageClassificationTableModels(props: ImageClassificatio
    + + + GeneratedModels[index].evaluation !== undefined && } /> + + }
    diff --git a/src/pages/playground/3_ImageClassification/ModelReviewImageClassification.tsx b/src/pages/playground/3_ImageClassification/ModelReviewImageClassification.tsx index 466abb2..b76732b 100644 --- a/src/pages/playground/3_ImageClassification/ModelReviewImageClassification.tsx +++ b/src/pages/playground/3_ImageClassification/ModelReviewImageClassification.tsx @@ -1,80 +1,82 @@ -import { useEffect, useRef, useState } from "react" -import { Button, Card, Col, Container, Modal, Row } from "react-bootstrap" -import { useNavigate } from "react-router" -import * as _chartjs from "chart.js" -import * as tfjs from "@tensorflow/tfjs" -import { BarElement, CategoryScale, Chart as ChartJS, Legend, LinearScale, Title, Tooltip } from "chart.js" -import { Bar } from "react-chartjs-2" -import { Trans, useTranslation } from "react-i18next" -import ReactGA from "react-ga4" - - -import type I_MODEL_IMAGE_CLASSIFICATION from "./models/_model" -import { VERBOSE } from "@/CONSTANTS" -import { UPLOAD } from "@/TASKS" -import alertHelper from "@utils/alertHelper" -import FakeProgressBar from "@components/loading/FakeProgressBar" -import DragAndDrop from "@components/dragAndDrop/DragAndDrop" - -import ModelReviewImageClassificationDraw from "@pages/playground/3_ImageClassification/ModelReviewImageClassificationDraw" -import { MAP_IC_CLASSES } from "@pages/playground/3_ImageClassification/models" -import { createReviewModelInstance } from "@core/models/createReviewModelInstance" -import { DEFAULT_BAR_DATA, type BarChartData_t } from "@pages/playground/3_ImageClassification/CONSTANTS" -import { UTILS_image } from "@pages/playground/3_ImageClassification/utils/utils" -import type { BarOptions_t } from "@/types/types" +import { useEffect, useMemo, useRef, useState } from 'react' +import { Button, Card, Col, Container, Row, Spinner } from 'react-bootstrap' +import { useNavigate } from 'react-router' +import * as tfjs from '@tensorflow/tfjs' +import { Trans, useTranslation } from 'react-i18next' + +import type I_MODEL_IMAGE_CLASSIFICATION from './models/_model' +import type { ImageClassificationResult_t } from './models/_model' +import type { SpriteImageDataset } from './models/SpriteImageDataset' +import { VERBOSE } from '@/CONSTANTS' +import { TASKS, UPLOAD } from '@/TASKS' +import alertHelper from '@utils/alertHelper' +import N4LDownloadProgress from '@components/loading/N4LDownloadProgress' +import { trackDownloads } from '@core/downloadProgress' +import { askBeforeDownload } from '@core/models/downloadConsent' +import DragAndDrop from '@components/dragAndDrop/DragAndDrop' + +import ModelReviewImageClassificationDraw from '@pages/playground/3_ImageClassification/ModelReviewImageClassificationDraw' +import { MAP_IC_CLASSES } from '@pages/playground/3_ImageClassification/models' +import { createReviewModelInstance } from '@core/models/createReviewModelInstance' +import { spriteToImageData, UTILS_image } from '@pages/playground/3_ImageClassification/utils/utils' import { ImageExplainResults, ShapImageControls, type ImageExplainResult_t, -} from "@core/explainability/ImageExplainPanel" -import { DEFAULT_SHAP_IMAGE_OPTIONS } from "@core/explainability/shapImageOptions" -import { explainErrorKey } from "@core/explainability/explainError" +} from '@core/explainability/ImageExplainPanel' +import { DEFAULT_SHAP_IMAGE_OPTIONS } from '@core/explainability/shapImageOptions' +import { explainErrorKey } from '@core/explainability/explainError' +import N4LModelSummaryButton from '@components/neural-network/N4LModelSummaryButton' +import N4LPageHeader from '@components/neural-network/N4LPageHeader' +import N4LModelCard from '@components/neural-network/N4LModelCard' +import N4LModelAside from '@components/neural-network/N4LModelAside' +import N4LDownloadPackage from '@components/n4l/N4LDownloadPackage' +import { imageClassificationReviewGuide } from './modelReviewGuide' +import N4LClassificationChart from '@components/neural-network/N4LClassificationChart' +import N4LVirtualSelect, { type VirtualSelectOption_t } from '@components/select/N4LVirtualSelect' +import { warmUpModel } from '@core/nn-utils/warmUpModel' +import { trackEvent } from '@core/analytics' +import N4LEmptyState from '@components/loading/N4LEmptyState' +import { CharacterFormsExamples } from '@pages/playground/3_ImageClassification/components/N4LCharacterForms' +import { FEATURED_FORMS } from '@pages/playground/3_ImageClassification/models/characterForms' +import { prefersReducedMotion } from '@core/a11y/displaySettings' import { runImageClassificationExplain, runImageClassificationExplainLrp, + warmUpLrp, supportsLrp, -} from "@pages/playground/3_ImageClassification/explainPrediction/runImageClassificationExplain" +} from '@pages/playground/3_ImageClassification/explainPrediction/runImageClassificationExplain' -ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend) +/** Lo clasificado: la salida del modelo y, si es una imagen del conjunto de test, su clase real */ +type Result_t = ImageClassificationResult_t & { actualIndex: number | null } - - -const DEFAULT_INFO: { image_src: string | null; image_upload: File | null; modal_image: File | null } = { - image_src : null, - image_upload: null, - modal_image : null, -} type ModelReviewImageClassificationProps = { dataset: string } export default function ModelReviewImageClassification({ dataset }: ModelReviewImageClassificationProps) { const { t } = useTranslation() const navigate = useNavigate() + const prefix = 'datasets-models.3-image-classifier.interface.' + const prefixForm = 'pages.playground.generator.dynamic-form-dataset.' const [iModelInstance, setIModelInstance] = useState(null) const [model, setModel] = useState(null) + const [isLoading, setIsLoading] = useState(true) - const iChartRef_modal = useRef<_chartjs.Chart<"bar">>(null) - const iChartRef_image = useRef<_chartjs.Chart<"bar">>(null) - - /** - * @type {ReturnType>} - */ + // Imagen clasificada (también es la base del mapa de calor de la explicación) + // Compilar los shaders de LRP tras cargar el modelo (warmUpLrp) + const lrpWarmUp_ref = useRef>(Promise.resolve()) const canvas_original_image_ref = useRef(null) - /** - * @type {ReturnType>} - */ - const canvas_modal_image_ref = useRef(null) + const result_ref = useRef(null) + const [result, setResult] = useState(null) - const [isLoading, setIsLoading] = useState(true) + const [imageUpload, setImageUpload] = useState(null) - const [isImageUploaded, setIsImageUploaded] = useState(false) - const [isModalShow, setIsModelShow] = useState(false) - const [info, setInfo] = useState(DEFAULT_INFO) - - const [barDataImage, setBarDataImage] = useState(DEFAULT_BAR_DATA) - const [barDataModal, setBarDataModal] = useState(DEFAULT_BAR_DATA) + // MNIST, KMNIST, CIFAR-10…: sus imágenes de test se pueden clasificar desde un selector (se descargan al pedirlo) + const [testDataset, setTestDataset] = useState(null) + const [isLoadingTestDataset, setIsLoadingTestDataset] = useState(false) + const [selectedInstance, setSelectedInstance] = useState(null) // === Explicabilidad (SHAP / LRP) === // Imagen clasificada que se explicará (misma ImageData que recibió el modelo). @@ -84,156 +86,156 @@ export default function ModelReviewImageClassification({ dataset }: ModelReviewI const [showExplain, setShowExplain] = useState(false) const [isCalculo, setIsCalculo] = useState(false) // Los modelos de dibujos (MNIST, KMNIST) solo ofrecen LRP; el resto elige entre SHAP y LRP (si el modelo implementa LRP). - const [explainMethod, setExplainMethod] = useState<"shap" | "lrp">("shap") + const [explainMethod, setExplainMethod] = useState<'shap' | 'lrp'>('shap') const [lrpAvailable, setLrpAvailable] = useState(false) const [shapOptions, setShapOptions] = useState(DEFAULT_SHAP_IMAGE_OPTIONS) - /** - * @type {*|BarOptions_t} - */ - const bar_option: BarOptions_t = { - responsive: true, - plugins : { - legend: { - position: "top", - }, - title: { - display: true, - text : t("prediction"), - }, - }, - } useEffect(() => { - ReactGA.send({ hitType: "pageview", page: `/ModelReviewImageClassification/${dataset}`, title: dataset }) - }, [dataset]) - - useEffect(() => { - if (VERBOSE) console.debug("useEffect[init][ dataset, t, history ]") + if (VERBOSE) console.debug('useEffect[init][ dataset, t, history ]') const init = async () => { const _iModelInstance = await createReviewModelInstance(MAP_IC_CLASSES, dataset, (ModelClass) => new ModelClass(t), navigate) if (_iModelInstance === null) return try { setIModelInstance(_iModelInstance) - setModel(await _iModelInstance.ENABLE_MODEL() as tfjs.LayersModel) + // Con ahorro de datos o conexión lenta, antes se pregunta; luego, con el progreso real (MobileNet pesa unos 16 MB) + await askBeforeDownload(TASKS.IMAGE_CLASSIFICATION, dataset) + const _model = await trackDownloads(() => _iModelInstance.ENABLE_MODEL(), 'model_load') as tfjs.LayersModel + // Shaders compilados antes de poder clasificar: la primera clasificación ya no bloquea la página + if (_model instanceof tfjs.LayersModel) await warmUpModel(_model) + setModel(_model) setLrpAvailable(supportsLrp(_iModelInstance)) setIsLoading(false) - await alertHelper.alertSuccess(t("model-loaded-successfully")) + // Los de LRP, mientras tanto (ya se puede clasificar); "Explicar" espera a que acaben + if (_model instanceof tfjs.LayersModel) lrpWarmUp_ref.current = warmUpLrp(_iModelInstance, _model) + await alertHelper.alertSuccess(t('model-loaded-successfully')) } catch (error) { - console.error("Error", error) + console.error('Error', error) } } init().then() }, [dataset, t, navigate]) - useEffect(() => { - if (VERBOSE) console.debug("useEffect [barDataModal]") - if (iChartRef_modal.current) { - iChartRef_modal.current.update() - } - }, [barDataModal]) - - useEffect(() => { - if (VERBOSE) console.debug("useEffect [barDataImage]") - if (iChartRef_image.current) { - iChartRef_image.current.update() - } - }, [barDataImage]) - + // KMNIST: los ejemplos enseñan cada carácter de hoy junto a sus formas antiguas + const characterForms = iModelInstance?.CHARACTER_FORMS() ?? null // MNIST y KMNIST: se puede dibujar la entrada y la explicación es siempre con LRP const isDrawable = iModelInstance?.DRAWABLE ?? false - - const handleClick_ImageByExamples_OpenDrawAndPredict = (image_src: string) => { - setInfo((prevState) => { - return { - ...prevState, - image_src: image_src, - } - }) - - setIsModelShow(true) - } - - const handleFileUpload_Image = (files: File[]) => { - try { - const blob = files[0] - setInfo((prevState) => { - return { - ...prevState, - image_upload: new File([blob], blob.name, { type: blob.type }), - } - }) - setIsImageUploaded(true) - } catch (error) { - console.error(error) - } + // Las imágenes de un conjunto (no MobileNet): tienen imágenes de test, y los ejemplos son pequeños + const spriteImage = iModelInstance?.IMAGE ?? null + // La clase de cada ejemplo, para que su botón diga lo mismo que ve quien mira la imagen + const exampleLabels = iModelInstance?.LIST_IMAGES_EXAMPLES_LABELS() ?? [] + const hasTestImages = iModelInstance?.TEST_IMAGES ?? false + // Guía paso a paso de la página (con voz): solo con el botón "Guía" + const hasSummary = model instanceof tfjs.LayersModel + const guideSteps = useMemo(() => (iModelInstance === null + ? null + : imageClassificationReviewGuide(t, dataset, { drawable: isDrawable, summary: hasSummary, testImages: hasTestImages })), [t, dataset, iModelInstance, isDrawable, hasSummary, hasTestImages]) + + // region CLASIFICACIÓN + /** Clasifica la entrada del modelo y la deja como entrada de la explicación */ + const classify = async (imageData: ImageData, actualIndex: number | null = null) => { + if (iModelInstance === null || model === null) return + const { predictions } = await iModelInstance.CLASSIFY_IMAGE(model, imageData) + setResult({ ...iModelInstance.PREDICTION_RESULT(predictions), actualIndex }) + setExplainInput(imageData) } - const handleModal_Close = () => { - setIsModelShow(false) + // El resultado queda debajo de las imágenes de ejemplo: se lleva a la vista al clasificar desde ahí + const scrollToResult = () => { + const reduceMotion = prefersReducedMotion() + result_ref.current?.scrollIntoView({ behavior: reduceMotion ? 'auto' : 'smooth', block: 'nearest' }) } - const handleModal_Exited = () => { } - const handleModal_Entered = async () => { - // Hasta que termina la carga no hay modelo con el que clasificar - if (iModelInstance === null || model === null) return - // const canvas = document.getElementById('modal_canvas_image') - const canvas = canvas_modal_image_ref.current as HTMLCanvasElement - const canvas_modal_ctx = canvas.getContext("2d") as CanvasRenderingContext2D - canvas_modal_ctx.clearRect(0, 0, canvas.width, canvas.height) + /** Pinta una imagen en el canvas del resultado y clasifica lo que se ve en él */ + const classifyImage = (src: string) => new Promise((resolve) => { + const canvas = canvas_original_image_ref.current + if (canvas === null || iModelInstance === null) { + resolve() + return + } const image = new Image() - image.src = info.image_src! image.addEventListener('error', (e: Event) => { UTILS_image.failed(e) + resolve() }) image.onload = async () => { + const canvas_ctx = canvas.getContext('2d') as CanvasRenderingContext2D + canvas_ctx.clearRect(0, 0, canvas.width, canvas.height) UTILS_image.drawImageInCanvasWithContainer(image, canvas) - const imageData = await iModelInstance.GET_IMAGE_DATA(canvas, canvas_modal_ctx) - const { predictions } = await iModelInstance.CLASSIFY_IMAGE(model, imageData) - const barDataPrediction = await iModelInstance.PREDICTION_FORMAT(predictions) - - // La pintamos también en el canvas original (id "originalImage"), que es la imagen base - // del heatmap; si no, al explicar un ejemplo el mapa de calor se ve sobre blanco. - if (canvas_original_image_ref.current) { - UTILS_image.drawImageInCanvasWithContainer(image, canvas_original_image_ref.current) - } - setExplainInput(imageData) - - setBarDataModal(barDataPrediction) + await classify(await iModelInstance.GET_IMAGE_DATA(canvas, canvas_ctx)) + resolve() } + image.src = src + }) + + const handleClick_Example = async (image_src: string) => { + setSelectedInstance(null) + await classifyImage(image_src) + trackEvent('predict', { input: 'sample' }) + scrollToResult() + } + + const handleFileUpload_Image = (files: File[]) => { + const blob = files[0] + if (blob) setImageUpload(new File([blob], blob.name, { type: blob.type })) } const handleClick_ImageUploaded_Predict = async () => { - if (iModelInstance === null || model === null) return - if (!isImageUploaded || !info.image_upload) { - await alertHelper.alertError(t("error.need-to-upload-image")) + if (imageUpload === null) { + await alertHelper.alertError(t('error.need-to-upload-image')) return } - const image = new Image() - image.src = URL.createObjectURL(info.image_upload) - image.addEventListener('error', (e: Event) => { - UTILS_image.failed(e) - }) + setSelectedInstance(null) + await classifyImage(URL.createObjectURL(imageUpload)) + trackEvent('predict', { input: 'image' }) + } - const canvas = canvas_original_image_ref.current - if (!(canvas instanceof HTMLCanvasElement)) { - throw new Error("HTMLCanvasElement") - } + const handleClassify_Drawing = async (imageData: ImageData) => { + setSelectedInstance(null) + await classify(imageData) + trackEvent('predict', { input: 'drawing' }) + } - const canvas_ctx = canvas.getContext("2d") as CanvasRenderingContext2D - canvas_ctx.clearRect(0, 0, canvas.width, canvas.height) - image.onload = async () => { - UTILS_image.drawImageInCanvasWithContainer(image, canvas) - const imageData = await iModelInstance.GET_IMAGE_DATA(canvas, canvas_ctx) - const { predictions } = await iModelInstance.CLASSIFY_IMAGE(model, imageData) - const barDataPrediction = await iModelInstance.PREDICTION_FORMAT(predictions) + const handleClick_LoadTestDataset = async () => { + if (iModelInstance === null) return + setIsLoadingTestDataset(true) + try { + setTestDataset(await iModelInstance.LOAD_DATASET()) + } catch (error) { + console.error(error) + await alertHelper.alertError(t('error.load-dataset')) + } finally { + setIsLoadingTestDataset(false) + } + } - setExplainInput(imageData) + const testOptions = useMemo(() => { + if (testDataset === null || iModelInstance === null) return [] + return testDataset.testClasses().map((label, index) => ({ value: index, label: `#${index}: ${iModelInstance.CLASS_LABELS[label] ?? label}` })) + }, [testDataset, iModelInstance]) - setBarDataImage(barDataPrediction) - } + /** Una imagen de test tal cual (la entrada exacta del modelo), ampliada en el canvas del resultado */ + const handleChange_TestImage = async (index: number) => { + const canvas = canvas_original_image_ref.current + if (testDataset === null || canvas === null) return + const { pixels, label } = testDataset.testExample(index) + const imageData = spriteToImageData(pixels, testDataset.image) + const small = document.createElement('canvas') + small.width = imageData.width + small.height = imageData.height + small.getContext('2d')?.putImageData(imageData, 0, 0) + canvas.width = 200 + canvas.height = 200 + const canvas_ctx = canvas.getContext('2d') as CanvasRenderingContext2D + canvas_ctx.imageSmoothingEnabled = false + canvas_ctx.drawImage(small, 0, 0, canvas.width, canvas.height) + setSelectedInstance(index) + await classify(imageData, label) + trackEvent('predict', { input: 'test_sample' }) + scrollToResult() } + // endregion // Nueva imagen clasificada: pasa a ser la entrada de la explicabilidad y se descarta // la explicación anterior. @@ -258,24 +260,27 @@ export default function ModelReviewImageClassification({ dataset }: ModelReviewI const imageData = imgData_ref.current const modelInstance = model if (!imageData || !modelInstance || iModelInstance === null) { - await alertHelper.alertInfo(t("info.insert-input")) + await alertHelper.alertInfo(t('info.insert-input')) return } - const useLrp = isDrawable || explainMethod === "lrp" + const useLrp = isDrawable || explainMethod === 'lrp' if (useLrp && !lrpAvailable) { - await alertHelper.alertError(t("ui.explain.lrp-not-available")) + await alertHelper.alertError(t('ui.explain.lrp-not-available')) return } + trackEvent('explain', { method: useLrp ? 'lrp' : 'shap' }) setIsCalculo(true) try { + // Hasta que acaba el calentamiento, los programas de LRP no se pueden usar + if (useLrp) await lrpWarmUp_ref.current const result = useLrp ? await runImageClassificationExplainLrp({ iModel: iModelInstance, modelInstance, imageData }) : await runImageClassificationExplain({ iModel: iModelInstance, modelInstance, imageData, ...shapOptions }) setExplainResult({ - method : useLrp ? "lrp" : "shap", + method : useLrp ? 'lrp' : 'shap', values : result.shapValues, labels : result.selectedLabels, // Con MNIST/KMNIST las etiquetas son índices; MobileNet ya devuelve el nombre de la clase @@ -290,200 +295,185 @@ export default function ModelReviewImageClassification({ dataset }: ModelReviewI }) setShowExplain(true) } catch (error) { - console.error("Error calculating explainability", { error }) + console.error('Error calculating explainability', { error }) await alertHelper.alertError(t(explainErrorKey(error))) } finally { setIsCalculo(false) } } - if (VERBOSE) console.debug("render ModelReviewImageClassification") + if (VERBOSE) console.debug('render ModelReviewImageClassification') return ( <> - - - -
    -

    - -

    -
    - -
    + + } guideId={'image-classification.' + dataset} guideSteps={guideSteps} className={'mt-2'} /> - + -
    - + + } + actions={<> + + + }> + {dataset !== UPLOAD && iModelInstance?.DESCRIPTION()} + + {/* Cómo se explica la predicción (SHAP o LRP) */} + -

    - {iModelInstance !== null && } -

    -
    - {dataset !== UPLOAD && iModelInstance?.DESCRIPTION()} -
    - - {/* Panel narrativo del método de explicabilidad (idéntico patrón al review tabular). */} - - -

    - +

    +

    -

    - {isDrawable || explainMethod === "lrp" - ? t("ui.explain.about-lrp") - : t("ui.explain.about-shap")} +

    + {isDrawable || explainMethod === 'lrp' + ? t('ui.explain.about-lrp') + : t('ui.explain.about-shap')}

    -

    + - + {/* IMÁGENES DE EJEMPLO (y las del conjunto de test, si son las de un conjunto) */} + + +

    + +

    + {hasTestImages && testDataset === null && + } + {hasTestImages && testDataset !== null && +
    + t(prefixForm + 'entity-count', { shown, total })} /> +
    } +
    + + {/* KMNIST: cada carácter como se escribe hoy junto a formas antiguas del conjunto */} + {characterForms !== null && <> +

    + + } + {characterForms === null && <> +

    + {/* Las imágenes de un conjunto (dibujos de 28×28, fotos de 32×32): una fila de miniaturas; fotos grandes + (MobileNet): tres por fila */} +
    + {(iModelInstance?.LIST_IMAGES_EXAMPLES() ?? []).map((image, index) => ( + + ))} +
    + } +
    +
    + + {/* SUBIR UNA IMAGEN Y DIBUJAR */} - - - -

    - -

    -
    - - - - {(iModelInstance?.LIST_IMAGES_EXAMPLES() ?? []).map((image, index) => { - const path_image = import.meta.env.VITE_PATH + "/assets/" + image - return ( - - {image} { - await handleClick_ImageByExamples_OpenDrawAndPredict(path_image) - }} - /> - - ) - })} - - - -
    - -
    - - - + +

    - +

    - + -
    -
    {isDrawable && ( - <> - - + )}
    - + {/* CLASIFICACIÓN */} +

    - +

    - - - - - - - - - - - - - - - - + {result === null && } + {/* El canvas siempre está montado: las imágenes se pintan en él antes de clasificarlas */} + + + + + + {result !== null && + } + +
    - + -

    {t("pages.playground.0-tabular-classification.general.explain-panel-title")} ({isDrawable || explainMethod === "lrp" ? "LRP" : "SHAP"})

    +

    {t('pages.playground.0-tabular-classification.general.explain-panel-title')} ({isDrawable || explainMethod === 'lrp' ? 'LRP' : 'SHAP'})

    {!isDrawable && (
    - {t("ui.explain.method")}: + {t('ui.explain.method')}:
    @@ -517,44 +508,6 @@ export default function ModelReviewImageClassification({ dataset }: ModelReviewI - - - - - - - - - - - -
    - -
    - - -
    - -
    - -
    -
    -
    - - - -
    ) } diff --git a/src/pages/playground/3_ImageClassification/ModelReviewImageClassificationDraw.tsx b/src/pages/playground/3_ImageClassification/ModelReviewImageClassificationDraw.tsx index de4a075..7c3c59e 100644 --- a/src/pages/playground/3_ImageClassification/ModelReviewImageClassificationDraw.tsx +++ b/src/pages/playground/3_ImageClassification/ModelReviewImageClassificationDraw.tsx @@ -2,58 +2,35 @@ import { Trans } from 'react-i18next' import { Card, Col } from 'react-bootstrap' import CustomCanvasDrawer from '@pages/playground/3_ImageClassification/components/customCanvasDrawer' import { toImageData } from '@pages/playground/3_ImageClassification/utils/utils' -import type * as tfjs from '@tensorflow/tfjs' -import type I_MODEL_IMAGE_CLASSIFICATION from './models/_model' type Props = { - iModelInstance : I_MODEL_IMAGE_CLASSIFICATION | null, - model : tfjs.LayersModel | null, - iChartRef_image : React.RefObject, - setBarDataImage : React.Dispatch>, - /** Canvas de resultado donde se muestra el dibujo. */ - canvasResultRef : React.RefObject, - onImageDataReady?: (imageData: ImageData) => void, - onResetExplain? : () => void, + /** Canvas del resultado, donde se muestra el dibujo clasificado (y la base del mapa de calor) */ + canvasResultRef: React.RefObject, + /** Recibe la entrada del modelo (28×28) para clasificarla */ + onClassify : (imageData: ImageData) => void | Promise, + onResetExplain?: () => void, } -/** Lienzo para dibujar la entrada de los modelos de 28x28 en escala de grises (MNIST, KMNIST). */ -export default function ModelReviewImageClassificationDraw (props: Props) { - const { - iModelInstance, - model, - iChartRef_image, - setBarDataImage, - canvasResultRef, - onImageDataReady, - onResetExplain - } = props - const handleCanvasDraw_Clear = async () => { - const canvas = canvasResultRef.current - canvas?.getContext('2d')?.clearRect(0, 0, canvas.width, canvas.height) - } +/** Lienzo para dibujar la entrada de los modelos de 28x28 en escala de grises (MNIST, KMNIST). */ +export default function ModelReviewImageClassificationDraw ({ canvasResultRef, onClassify, onResetExplain }: Props) { - const handleCanvasDraw_Submit = async (draw_canvas: HTMLCanvasElement, _draw_canvas_ctx: CanvasRenderingContext2D, canvas_small?: HTMLCanvasElement) => { - // Mostramos el dibujo en el canvas de resultado y reducimos a 28×28 en un canvas aparte: - // antes la miniatura se pintaba encima del dibujo grande y se leían los dos mezclados. + const handleCanvasDraw_Submit = async (draw_canvas: HTMLCanvasElement, canvas_small: HTMLCanvasElement | null) => { + // El dibujo se muestra en el canvas del resultado (cuadrado, como el lienzo) y se reduce a 28×28 en un canvas + // aparte: antes la miniatura se pintaba encima del dibujo grande y se leían los dos mezclados. const canvas = canvasResultRef.current - canvas?.getContext('2d')?.drawImage(draw_canvas, 0, 0, canvas.width, canvas.height) + if (canvas !== null) { + canvas.width = 200 + canvas.height = 200 + canvas.getContext('2d')?.drawImage(draw_canvas, 0, 0, canvas.width, canvas.height) + } const imageData = toImageData(draw_canvas, 28, 28) // Miniatura 28×28: lo que realmente recibe el modelo (CustomCanvasDrawer la deja vacía si no se pinta aquí). canvas_small?.getContext('2d')?.putImageData(imageData, 0, 0) - if (iModelInstance === null || model === null) return - const { predictions } = await iModelInstance.CLASSIFY(model, imageData) - setBarDataImage(await iModelInstance.PREDICTION_FORMAT(predictions)) - iChartRef_image.current.update() - - // Notificamos la imagen dibujada al padre para la explicabilidad - if (typeof onImageDataReady === 'function') { - onImageDataReady(imageData) - } + await onClassify(imageData) } return <> - +

    @@ -62,16 +39,12 @@ export default function ModelReviewImageClassificationDraw (props: Props) { { if (canvas === null || canvas_ctx === null) { - console.error("canvas or canvas_ctx is null") + console.error('canvas or canvas_ctx is null') return } - await handleCanvasDraw_Clear() - await handleCanvasDraw_Submit(canvas, canvas_ctx, canvas_small ?? undefined) - }} - clearFunction={async () => { - await handleCanvasDraw_Clear() - onResetExplain?.() + await handleCanvasDraw_Submit(canvas, canvas_small) }} + clearFunction={() => onResetExplain?.()} onDrawStart={() => onResetExplain?.()}/>
    diff --git a/src/pages/playground/3_ImageClassification/components/ImagePicker.tsx b/src/pages/playground/3_ImageClassification/components/ImagePicker.tsx new file mode 100644 index 0000000..42fc2ae --- /dev/null +++ b/src/pages/playground/3_ImageClassification/components/ImagePicker.tsx @@ -0,0 +1,74 @@ +import { useEffect, useRef, useState } from 'react' +import { Button } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' + +import DragAndDrop from '@components/dragAndDrop/DragAndDrop' +import { UTILS_image } from '@pages/playground/3_ImageClassification/utils/utils' + +const PREVIEW_SIZE = 200 + +type ImagePickerProps = { + /** Imagen elegida del conjunto de prueba (la entrada exacta del modelo): se enseña ampliada */ + image : ImageData | null + /** Clasificar lo que se ve: la imagen subida (o la del conjunto) en el canvas de la vista previa */ + onClassify: (canvas: HTMLCanvasElement) => void | Promise + /** Al subir una imagen (deja de ser la del conjunto) */ + onUpload? : () => void +} + +/** + * En lugar del lienzo de dibujo, para las imágenes en color (CIFAR-10…): una vista previa con la imagen elegida del + * conjunto o una subida, que se clasifica con el botón + */ +export default function ImagePicker({ image, onClassify, onUpload }: ImagePickerProps) { + const { t } = useTranslation() + const prefix = 'datasets-models.3-image-classifier.interface.' + const canvas_ref = useRef(null) + const [hasImage, setHasImage] = useState(false) + + // Una imagen del conjunto: ampliada sin suavizar (se ven sus píxeles, como los ve la red) + useEffect(() => { + const canvas = canvas_ref.current + if (canvas === null || image === null) return + const small = document.createElement('canvas') + small.width = image.width + small.height = image.height + small.getContext('2d')?.putImageData(image, 0, 0) + canvas.width = PREVIEW_SIZE + canvas.height = PREVIEW_SIZE + const context = canvas.getContext('2d') as CanvasRenderingContext2D + context.imageSmoothingEnabled = false + context.drawImage(small, 0, 0, PREVIEW_SIZE, PREVIEW_SIZE) + setHasImage(true) + }, [image]) + + const handleDrop = (files: File[]) => { + const canvas = canvas_ref.current + if (files.length === 0 || canvas === null) return + onUpload?.() + const picture = new Image() + picture.onload = () => { + UTILS_image.drawImageInCanvasWithContainer(picture, canvas) + setHasImage(true) + URL.revokeObjectURL(picture.src) + } + picture.src = URL.createObjectURL(files[0]) + } + + return ( +
    +
    + +
    + +
    + +
    +
    + ) +} diff --git a/src/pages/playground/3_ImageClassification/components/N4LCharacterForms.tsx b/src/pages/playground/3_ImageClassification/components/N4LCharacterForms.tsx new file mode 100644 index 0000000..a158e03 --- /dev/null +++ b/src/pages/playground/3_ImageClassification/components/N4LCharacterForms.tsx @@ -0,0 +1,94 @@ +import { Table } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import type { CharacterForms_t } from '../models/characterForms' + +/** + * Cada carácter como se escribe hoy (con cómo se lee y el kanji del que viene) junto a todas sus formas antiguas, cada + * una con su kanji. Para la información del modelo: cabe también en la columna estrecha de la página del modelo + */ +export function CharacterFormsTable({ characters, prefix }: { characters: CharacterForms_t[], prefix: string }) { + const { t } = useTranslation() + return ( +
    + + + + + + + + + + {characters.map(({ char, reading, origin, old }) => ( + + + + + ))} + +
    {t(prefix + 'title')}
    {t(prefix + 'modern')}{t(prefix + 'old')}
    + {char} + {reading}, {origin} + +
    + {old.map(({ image, origin: from }) => ( +
    + {t(prefix +
    {from}
    +
    + ))} +
    +
    +
    {t(prefix + 'note')}
    +
    + ) +} + +type CharacterFormsExamplesProps = { + characters: CharacterForms_t[] + /** Cuántas formas antiguas de cada carácter (las primeras) */ + forms : number + prefix : string + disabled : boolean + onClassify: (src: string) => void +} + +/** Las imágenes de ejemplo, carácter a carácter: la de hoy y algunas antiguas, y cada una se clasifica al pulsarla */ +export function CharacterFormsExamples({ characters, forms, prefix, disabled, onClassify }: CharacterFormsExamplesProps) { + const { t } = useTranslation() + return ( +
    + {characters.map(({ char, reading, modern, old }) => ( +
    +
    + {char}, {reading} +
    +
    +
    + +
    {t(prefix + 'modern')}
    +
    +
    +
    + {old.slice(0, forms).map(({ image, origin }) => ( +
    + +
    {origin}
    +
    + ))} +
    +
    {t(prefix + 'old')}
    +
    +
    +
    + ))} +
    + ) +} diff --git a/src/pages/playground/3_ImageClassification/components/customCanvasDrawer.css b/src/pages/playground/3_ImageClassification/components/customCanvasDrawer.css index bb45aa1..fc26c80 100644 --- a/src/pages/playground/3_ImageClassification/components/customCanvasDrawer.css +++ b/src/pages/playground/3_ImageClassification/components/customCanvasDrawer.css @@ -29,4 +29,19 @@ .container-canvas { display: flex; justify-content: center; -} \ No newline at end of file +} + +/* + * Lienzo de dibujo: tan grande como quepa (hasta 260 px) junto a la miniatura de 28×28. Con el dedo dibuja en vez de + * mover la página. + */ +.n4l-draw-canvas { + width: min(260px, calc(100% - 36px)); + aspect-ratio: 1; + border: 1px solid black; + background: white; + touch-action: none; + user-select: none; + -webkit-user-select: none; + cursor: crosshair; +} diff --git a/src/pages/playground/3_ImageClassification/components/customCanvasDrawer.tsx b/src/pages/playground/3_ImageClassification/components/customCanvasDrawer.tsx index fe554e8..1540754 100644 --- a/src/pages/playground/3_ImageClassification/components/customCanvasDrawer.tsx +++ b/src/pages/playground/3_ImageClassification/components/customCanvasDrawer.tsx @@ -1,8 +1,12 @@ -import "./customCanvasDrawer.css" -import { useEffect, useRef, useState, type FormEvent } from "react" -import { Button } from "react-bootstrap" -import { Trans } from "react-i18next" -import { VERBOSE } from '@/CONSTANTS' +import './customCanvasDrawer.css' +import { useEffect, useRef, type PointerEvent } from 'react' +import { Button } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' + +// El dibujo va en coordenadas de 0 a 200 (el grosor del trazo, 20, es una décima parte del lienzo) sobre un lienzo de +// 600×600 píxeles, que se muestra con el tamaño que quepa en la pantalla +const DRAW_SIZE = 200 +const CANVAS_PIXELS = 600 /** * @typedef {Object} CustomCanvasDrawerProps @@ -13,6 +17,8 @@ type CustomCanvasDrawerProps = { submitFunction: (canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, canvas_small: HTMLCanvasElement) => void | Promise, clearFunction : () => void, onDrawStart ?: () => void, + /** Imagen de 28×28 que se pinta en el lienzo (p. ej. una del dataset); se puede seguir dibujando encima */ + image ?: ImageData | null, } /** @@ -25,8 +31,9 @@ export default function CustomCanvasDrawer(props: CustomCanvasDrawerProps) { submitFunction, clearFunction, onDrawStart, + image, } = props - const [isDrawing, setIsDrawing] = useState(false) + const { t } = useTranslation() /** * * @type {React.MutableRefObject} @@ -35,154 +42,157 @@ export default function CustomCanvasDrawer(props: CustomCanvasDrawerProps) { const context_ref = useRef(null) const canvas_small_ref = useRef(null) + // Último punto del trazo que se está dibujando (null: no se está dibujando) + const last_point_ref = useRef<[number, number] | null>(null) - function handleTouchStart(e: TouchEvent) { - e.preventDefault() - } - - function handleTouchMove(e: TouchEvent) { - if (canvas_ref.current === null || context_ref.current === null) { - console.error("canvasRef or contextRef is null") - return - } + useEffect(() => { + if (canvas_ref.current === null) return + const canvas = canvas_ref.current + canvas.width = CANVAS_PIXELS + canvas.height = CANVAS_PIXELS - const rect = canvas_ref.current.getBoundingClientRect() - const cssX = e.touches[0].clientX - rect.left - const cssY = e.touches[0].clientY - rect.top - //* canvasRef.current.width / rect.width - //* canvasRef.current.height / rect.height - // contextRef.current.fillStyle = `hsl(${performance.now() % 360 | 0},100%,50%)` - context_ref.current.fillRect(cssX - 20, cssY - 20, 20, 20) - } + const context = canvas.getContext('2d') as CanvasRenderingContext2D + // Se dibuja en coordenadas de 0 a DRAW_SIZE sea cual sea el tamaño en pantalla (setTransform y no scale: el + // efecto puede repetirse, en StrictMode, y scale se acumularía) + const scale = CANVAS_PIXELS / DRAW_SIZE + context.setTransform(scale, 0, 0, scale, 0, 0) + context.lineCap = 'round' + context.lineJoin = 'round' + context.strokeStyle = 'black' + context.lineWidth = 20 + context_ref.current = context + }, []) + // Imagen nueva: ampliada (sin suavizar, se ven los píxeles) en el lienzo y tal cual en la miniatura useEffect(() => { - if (canvas_ref !== null) { - const canvas = canvas_ref.current as HTMLCanvasElement - canvas.width = 600 - canvas.height = 600 - canvas.style.width = "200px" - canvas.style.height = "200px" - - const context = canvas.getContext("2d") as CanvasRenderingContext2D - context.scale(3, 3) - context.lineCap = "round" - context.strokeStyle = "black" - context.lineWidth = 20 - context_ref.current = context + const context = context_ref.current + const canvas_small = canvas_small_ref.current + if (image === null || image === undefined || context === null || canvas_small === null) return + canvas_small.getContext('2d')?.putImageData(image, 0, 0) + context.save() + context.setTransform(1, 0, 0, 1, 0, 0) + context.imageSmoothingEnabled = false + context.clearRect(0, 0, context.canvas.width, context.canvas.height) + context.drawImage(canvas_small, 0, 0, context.canvas.width, context.canvas.height) + context.restore() + }, [image]) - // React to touch events on the canvas - canvas.addEventListener("touchstart", handleTouchStart, { passive: false }) - canvas.addEventListener("touchmove", handleTouchMove) - return () => { - canvas.removeEventListener("touchstart", handleTouchStart) - canvas.removeEventListener("touchmove", handleTouchMove) - } - } - }, []) + /** Punto del puntero en las coordenadas del dibujo (el lienzo se muestra más o menos grande según la pantalla) */ + const drawPoint = (event: PointerEvent): [number, number] => { + const canvas = event.currentTarget + const { offsetX, offsetY } = event.nativeEvent + return [offsetX * DRAW_SIZE / canvas.clientWidth, offsetY * DRAW_SIZE / canvas.clientHeight] + } - const startDrawing = (_event: React.MouseEvent) => { - if (context_ref.current === null) { - console.error("Context is null") + // Ratón, dedo o lápiz: los eventos de puntero sirven para los tres + const startDrawing = (event: PointerEvent) => { + const context = context_ref.current + if (context === null) { + console.error('Context is null') return } - const { nativeEvent } = _event - const { offsetX, offsetY } = nativeEvent - context_ref.current.beginPath() - context_ref.current.moveTo(offsetX, offsetY) - setIsDrawing(true) + if (event.pointerType === 'mouse' && event.button !== 0) return + event.preventDefault() + // El trazo sigue aunque el dedo o el ratón salgan del lienzo + event.currentTarget.setPointerCapture?.(event.pointerId) + const point = drawPoint(event) + // Un toque sin moverse también deja un punto + context.beginPath() + context.moveTo(...point) + context.lineTo(...point) + context.stroke() + last_point_ref.current = point // Al empezar a escribir un número nuevo, limpiamos el heatmap anterior. onDrawStart?.() } - const finishDrawing = (_event: React.MouseEvent) => { - if (context_ref.current === null) { - console.error("Context is null") - return - } - context_ref.current.closePath() - setIsDrawing(false) + const draw = (event: PointerEvent) => { + const context = context_ref.current + const last_point = last_point_ref.current + if (context === null || last_point === null) return + const point = drawPoint(event) + // Solo el tramo nuevo: volver a pintar todo el trazo en cada movimiento va cada vez más lento + context.beginPath() + context.moveTo(...last_point) + context.lineTo(...point) + context.stroke() + last_point_ref.current = point } - const draw = ($event: React.MouseEvent) => { - if (context_ref.current === null) { - console.error("Context is null") - return - } - const { nativeEvent } = $event - if (isDrawing) { - const { offsetX, offsetY } = nativeEvent - context_ref.current.lineTo(offsetX, offsetY) - context_ref.current.stroke() - } + const finishDrawing = () => { + last_point_ref.current = null } const clear = () => { if (context_ref.current === null) { - console.error("Context is null") + console.error('Context is null') return } - context_ref.current.clearRect(0, 0, 200, 200) - } - - const onChange = (event: FormEvent) => { - if (VERBOSE) console.debug("onChange event:", event) - event.preventDefault() + context_ref.current.clearRect(0, 0, DRAW_SIZE, DRAW_SIZE) + const canvas_small = canvas_small_ref.current + canvas_small?.getContext('2d')?.clearRect(0, 0, canvas_small.width, canvas_small.height) } return ( <> -
    +
    + {/* Dibujar exige arrastrar (WCAG 2.5.7): la alternativa, con un clic o el teclado, son los ejemplos y las + imágenes de prueba de la página, y lo dice el texto de debajo */} startDrawing(event)} - onMouseUp={(event) => finishDrawing(event)} - onMouseMove={(event) => draw(event)} - onChange={(event) => onChange(event)} + className={'n4l-draw-canvas'} + role={'img'} + aria-label={t('custom-canvas-drawer.canvas')} + aria-describedby={'canvas-alternative'} + onPointerDown={startDrawing} + onPointerMove={draw} + onPointerUp={finishDrawing} + onPointerCancel={finishDrawing} >
    +

    {t('custom-canvas-drawer.alternative')}

    diff --git a/src/pages/playground/3_ImageClassification/custom/trainImageClassifier.ts b/src/pages/playground/3_ImageClassification/custom/trainImageClassifier.ts index 2856f64..c8c04cb 100644 --- a/src/pages/playground/3_ImageClassification/custom/trainImageClassifier.ts +++ b/src/pages/playground/3_ImageClassification/custom/trainImageClassifier.ts @@ -1,11 +1,15 @@ import * as tfvis from '@tensorflow/tfjs-vis' import * as tfjs from '@tensorflow/tfjs' -import { createOptimizer, createLoss, createMetricsList } from '@core/nn-utils/ArchitectureHelper' -import { isActivation } from '@core/nn-utils/ArchitectureTypesHelper' import { TAB_03_IMAGE_CLASSIFICATION } from '@/CONSTANTS' import type { IdLoss_t, IdMetric_t, IdOptimizer_t } from '@/types/nn-types' -import type { Layer_t } from '@/types/types' -import { SpriteImageDataset, type SpriteDatasetConfig_t } from '../models/SpriteImageDataset' +import { forwardProgress, type ClassificationEvaluation_t } from '@core/controller/trainDenseModel' +import type { ImageLayer_t } from '@/types/types' +import { getActiveTFBackend } from '@core/tfBackend' +import { showTrainingVisor } from '@core/nn-utils/trainingVisor' +import { ModelDefinitionError, buildImageModel, compileModel, modelFromArtifacts } from '@core/training/buildModels' +import { TrainingWorkerUnavailableError, trainInWorker } from '@core/training/trainingClient' +import { loadSpriteDataset, type SpriteImageDataset, type SpriteDatasetConfig_t } from '../models/SpriteImageDataset' +import { shouldOpenVisor } from '@core/a11y/displaySettings' export type ParamsTrainImage_t = { learningRate : number, @@ -14,24 +18,35 @@ export type ParamsTrainImage_t = { idLoss : IdLoss_t, idOptimizer : IdOptimizer_t, idMetricsList: IdMetric_t[], - layers : Layer_t[], + layers : ImageLayer_t[], +} + +/** Progreso del entrenamiento: aviso al acabar cada época (desde 1) y petición de parar */ +export type TrainProgress_t = { + onEpochEnd?: (epoch: number, totalEpochs: number) => void + shouldStop?: () => boolean } -const IMAGE_WIDTH = 28 -const IMAGE_HEIGHT = 28 const BATCH_SIZE = 512 -// Imágenes que se usan en cada entrenamiento (se sacan barajadas del dataset) +// Imágenes que se usan en cada entrenamiento como mucho (se sacan barajadas del dataset) const TRAIN_DATA_SIZE = 11000 const TEST_DATA_SIZE = 2000 +/** Cuántas imágenes de entrenamiento y de validación se usan: como mucho las que tiene el conjunto */ +const dataSizes = ({ numElements, numTrain }: SpriteDatasetConfig_t) => ({ + trainSize: Math.min(TRAIN_DATA_SIZE, numTrain), + testSize : Math.min(TEST_DATA_SIZE, numElements - numTrain), +}) + async function showExamples(data: SpriteImageDataset) { const surface = tfvis.visor().surface({ name: 'Data set: Examples', tab: TAB_03_IMAGE_CLASSIFICATION }) + const { width, height, channels } = data.image const examples = data.nextTestBatch(20) for (let i = 0; i < examples.xs.shape[0]; i++) { - const imageTensor = tfjs.tidy(() => examples.xs.slice([i, 0], [1, examples.xs.shape[1]]).reshape([IMAGE_HEIGHT, IMAGE_WIDTH, 1])) as tfjs.Tensor3D + const imageTensor = tfjs.tidy(() => examples.xs.slice([i, 0], [1, examples.xs.shape[1]]).reshape([height, width, channels])) as tfjs.Tensor3D const canvas = document.createElement('canvas') - canvas.width = IMAGE_WIDTH - canvas.height = IMAGE_HEIGHT + canvas.width = width + canvas.height = height canvas.style.margin = '4px' await tfjs.browser.toPixels(imageTensor, canvas) surface.drawArea.appendChild(canvas) @@ -39,116 +54,150 @@ async function showExamples(data: SpriteImageDataset) { } } -async function train(model: tfjs.Sequential, data: SpriteImageDataset, numberOfEpoch: number) { - const fitCallbacks = tfvis.show.fitCallbacks( - { name: 'Training: Train Model', tab: TAB_03_IMAGE_CLASSIFICATION }, - ['loss', 'val_loss', 'acc', 'val_acc'], - ) +/** + * Entrena y devuelve, además del historial, la clase real y la predicha de cada imagen de validación (las mismas con las + * que se calcula val_loss): son la matriz de confusión de la tabla de modelos. + */ +async function train(model: tfjs.Sequential, data: SpriteImageDataset, sizes: ReturnType, numberOfEpoch: number, progress: TrainProgress_t, fitCallbacks: VisCallbacks_t): Promise<{ history: tfjs.History, evaluation: ClassificationEvaluation_t }> { + const { width, height, channels } = data.image const [trainXs, trainYs] = tfjs.tidy(() => { - const d = data.nextTrainBatch(TRAIN_DATA_SIZE) - return [d.xs.reshape([TRAIN_DATA_SIZE, IMAGE_HEIGHT, IMAGE_WIDTH, 1]), d.labels] + const d = data.nextTrainBatch(sizes.trainSize) + return [d.xs.reshape([sizes.trainSize, height, width, channels]), d.labels] }) const [testXs, testYs] = tfjs.tidy(() => { - const d = data.nextTestBatch(TEST_DATA_SIZE) - return [d.xs.reshape([TEST_DATA_SIZE, IMAGE_HEIGHT, IMAGE_WIDTH, 1]), d.labels] - }) - return await model.fit(trainXs, trainYs, { - batchSize : BATCH_SIZE, - validationData: [testXs, testYs], - epochs : numberOfEpoch, - shuffle : true, - callbacks : fitCallbacks, + const d = data.nextTestBatch(sizes.testSize) + return [d.xs.reshape([sizes.testSize, height, width, channels]), d.labels] }) + const progressCallbacks: tfjs.CustomCallbackArgs = { + onBatchEnd: async () => { + if (progress.shouldStop?.()) model.stopTraining = true + }, + onEpochEnd: async (epoch) => { + progress.onEpochEnd?.(epoch + 1, numberOfEpoch) + if (progress.shouldStop?.()) model.stopTraining = true + }, + } + try { + const history = await model.fit(trainXs, trainYs, { + batchSize : BATCH_SIZE, + validationData: [testXs, testYs], + epochs : numberOfEpoch, + shuffle : true, + callbacks : [fitCallbacks, progressCallbacks], + }) + const [labels, predictions] = tfjs.tidy((): [tfjs.Tensor, tfjs.Tensor] => [ + testYs.argMax(-1), + (model.predict(testXs, { batchSize: BATCH_SIZE }) as tfjs.Tensor).argMax(-1), + ]) + // Lecturas asíncronas: con WebGPU las síncronas detienen la GPU + const evaluation = { labels: Array.from(await labels.data<'int32'>()), predictions: Array.from(await predictions.data<'int32'>()) } + tfjs.dispose([labels, predictions]) + return { history, evaluation } + } finally { + // Las imágenes ya no hacen falta: el modelo guarda sus pesos y el historial guarda números + tfjs.dispose([trainXs, trainYs, testXs, testYs]) + } } -function doPrediction(model: tfjs.Sequential, data: SpriteImageDataset, testDataSize = 500): [tfjs.Tensor1D, tfjs.Tensor1D] { - const testData = data.nextTestBatch(testDataSize) - const testXs = testData.xs.reshape([testDataSize, IMAGE_HEIGHT, IMAGE_WIDTH, 1]) - const labels = testData.labels.argMax(-1) as tfjs.Tensor1D - const prediction = (model.predict(testXs) as tfjs.Tensor).argMax(-1) as tfjs.Tensor1D - testXs.dispose() - return [prediction, labels] +/** Precisión por clase y matriz de confusión en el visor, con las mismas imágenes de validación */ +async function showEvaluation({ labels, predictions }: ClassificationEvaluation_t, classNames: string[]) { + const labelsTensor = tfjs.tensor1d(labels, 'int32') + const predictionsTensor = tfjs.tensor1d(predictions, 'int32') + try { + const classAccuracy = await tfvis.metrics.perClassAccuracy(labelsTensor, predictionsTensor, classNames.length) + await tfvis.show.perClassAccuracy({ name: 'Evaluation: Accuracy', tab: TAB_03_IMAGE_CLASSIFICATION }, classAccuracy, classNames) + const confusionMatrix = await tfvis.metrics.confusionMatrix(labelsTensor, predictionsTensor, classNames.length) + await tfvis.render.confusionMatrix({ name: 'Evaluation: Confusion Matrix', tab: TAB_03_IMAGE_CLASSIFICATION }, { + values : confusionMatrix, + tickLabels: classNames, + }) + } finally { + tfjs.dispose([labelsTensor, predictionsTensor]) + } } -async function showEvaluation(model: tfjs.Sequential, data: SpriteImageDataset, classNames: string[]) { - const [preds, labels] = doPrediction(model, data) - const classAccuracy = await tfvis.metrics.perClassAccuracy(labels, preds) - await tfvis.show.perClassAccuracy({ name: 'Evaluation: Accuracy', tab: TAB_03_IMAGE_CLASSIFICATION }, classAccuracy, classNames) - const confusionMatrix = await tfvis.metrics.confusionMatrix(labels, preds) - await tfvis.render.confusionMatrix({ name: 'Evaluation: Confusion Matrix', tab: TAB_03_IMAGE_CLASSIFICATION }, { - values : confusionMatrix, - tickLabels: classNames, - }) - labels.dispose() - preds.dispose() +type VisCallbacks_t = ReturnType + +/** La red de las capas del editor, compilada (momento de 0,99 en el optimizador, como siempre en imágenes) */ +function getModel(layerList: ImageLayer_t[], idOptimizer: IdOptimizer_t, idLoss: IdLoss_t, idMetrics_list: IdMetric_t[], learningRate: number) { + const model = buildImageModel(layerList) + compileModel(model, { idOptimizer, idLoss, idMetrics: idMetrics_list, learningRate, momentum: 0.99 }) + return model } -function getModel(layerList: Layer_t[], idOptimizer: IdOptimizer_t, idLoss: IdLoss_t, idMetrics_list: IdMetric_t[], learningRate: number) { - const model = tfjs.sequential() - const optimizer = createOptimizer(idOptimizer, { learningRate: (learningRate / 100), momentum: 0.99 }) - const loss = createLoss(idLoss, {}) - const metrics = createMetricsList(idMetrics_list, {}) +/** + * Entrena una red convolucional con un dataset de imágenes guardado como sprite (MNIST, KMNIST, CIFAR-10…) + * y muestra en el visor ejemplos, el entrenamiento y la evaluación por clase. Devuelve también la clase real y la + * predicha de cada imagen de validación. + */ +export async function trainImageClassifier(dataset: SpriteDatasetConfig_t, classNames: string[], params: ParamsTrainImage_t, progress: TrainProgress_t = {}) { + const { layers } = params + + // Abierto en escritorio; en el móvil se dibuja cerrado (se abre con "Abrir visor") + showTrainingVisor() + // Los ejemplos del visor salen de las imágenes de test (el conjunto entero lo decodifica quien entrena) + await showExamples(await loadSpriteDataset(dataset, { testOnly: true })) + + // El resumen del visor con la misma red (sin entrenar) antes de empezar + const summaryModel = buildImageModel(layers) + await tfvis.show.modelSummary({ name: 'Model summary', tab: TAB_03_IMAGE_CLASSIFICATION }, summaryModel) + summaryModel.dispose() + tfvis.visor().setActiveTab(TAB_03_IMAGE_CLASSIFICATION) + // Se abre al crearlo: si se ha elegido en /settings, se cierra (sus gráficas siguen ahí, por si se abre a mano) + if (!shouldOpenVisor()) tfvis.visor().close() + const fitCallbacks = tfvis.show.fitCallbacks( + { name: 'Training: Train Model', tab: TAB_03_IMAGE_CLASSIFICATION }, + ['loss', 'val_loss', 'acc', 'val_acc'], + ) - for (const [index, layer] of layerList.entries()) { - const activation = layer.activation ?? undefined - if (activation !== undefined && !isActivation(activation)) { - throw new Error(`Layer ${index + 1} activation is not valid (${activation})`) - } - switch (layer._class) { - case 'conv2d': { - if (layer.kernelSize === undefined || layer.filters === undefined) { - throw new Error(`Layer ${index + 1}: conv2d needs kernelSize and filters`) - } - model.add(tfjs.layers.conv2d({ - ...(layer._protected ? { inputShape: layer.inputShape } : {}), - kernelSize: layer.kernelSize, - filters : layer.filters, - activation, - })) - break - } - case 'maxPooling2d': { - model.add(tfjs.layers.maxPooling2d({ poolSize: layer.poolSize, strides: layer.strides })) - break - } - case 'flatten': { - model.add(tfjs.layers.flatten({})) - break - } - case 'dense': { - if (layer.units === undefined) { - throw new Error(`Layer ${index + 1}: dense needs units`) - } - model.add(tfjs.layers.dense({ units: layer.units, activation })) - break - } - default: { - console.error('Error, layer not valid', { layer }) - break - } - } + let result: { model: tfjs.Sequential, history: tfjs.History, evaluation: ClassificationEvaluation_t } | null = null + try { + result = await trainImageClassifierInWorker(dataset, params, progress, fitCallbacks) + } catch (error) { + if (error instanceof ModelDefinitionError || !(error instanceof TrainingWorkerUnavailableError)) throw error + console.warn('Training in the main thread:', error.message) } - model.compile({ optimizer, loss, metrics }) - return model + result ??= await trainImageClassifierInMainThread(dataset, params, progress, fitCallbacks) + await showEvaluation(result.evaluation, classNames) + return result } /** - * Entrena una red convolucional con un dataset de imágenes de 28x28 guardado como sprite (MNIST, KMNIST…) - * y muestra en el visor ejemplos, el entrenamiento y la evaluación por clase. + * En un worker (TODO-worker.md): descarga y decodifica el sprite y entrena allí, así la página no se bloquea. El + * progreso llega por mensajes al visor y a la página */ -export async function trainImageClassifier(dataset: SpriteDatasetConfig_t, classNames: string[], params: ParamsTrainImage_t) { +async function trainImageClassifierInWorker(dataset: SpriteDatasetConfig_t, params: ParamsTrainImage_t, progress: TrainProgress_t, fitCallbacks: VisCallbacks_t) { const { learningRate, numberEpochs, idOptimizer, idLoss, idMetricsList, layers } = params + const result = await trainInWorker('trainImages', { + backend : getActiveTFBackend(), + imagesUrl : new URL(dataset.imagesUrl, document.baseURI).href, + labelsUrl : new URL(dataset.labelsUrl, document.baseURI).href, + numElements : dataset.numElements, + numTrain : dataset.numTrain, + numClasses : dataset.numClasses, + image : dataset.image, + layers, + compile : { idOptimizer, idLoss, idMetrics: idMetricsList, learningRate, momentum: 0.99 }, + numberOfEpoch: numberEpochs, + ...dataSizes(dataset), + batchSize : BATCH_SIZE, + }, { + shouldStop: progress.shouldStop, + onProgress: forwardProgress(fitCallbacks, progress.onEpochEnd), + }) + if (result.evaluation === undefined) throw new Error('The worker did not return the evaluation') + return { + model : await modelFromArtifacts(result.artifacts), + history : result.history as unknown as tfjs.History, + evaluation: result.evaluation, + } +} - tfvis.visor().open() - const data = new SpriteImageDataset(dataset) - await data.load() - await showExamples(data) - +/** Sin worker: todo aquí, como antes */ +async function trainImageClassifierInMainThread(dataset: SpriteDatasetConfig_t, params: ParamsTrainImage_t, progress: TrainProgress_t, fitCallbacks: VisCallbacks_t) { + const { learningRate, numberEpochs, idOptimizer, idLoss, idMetricsList, layers } = params + const data = await loadSpriteDataset(dataset) const model = getModel(layers, idOptimizer, idLoss, idMetricsList, learningRate) - await tfvis.show.modelSummary({ name: 'Model summary', tab: TAB_03_IMAGE_CLASSIFICATION }, model) - tfvis.visor().setActiveTab(TAB_03_IMAGE_CLASSIFICATION) - - const history = await train(model, data, numberEpochs) - await showEvaluation(model, data, classNames) - return { model, history } + const { history, evaluation } = await train(model, data, dataSizes(dataset), numberEpochs, progress, fitCallbacks) + return { model, history, evaluation } } diff --git a/src/pages/playground/3_ImageClassification/explainPrediction/modelEmbeddingActivations.ts b/src/pages/playground/3_ImageClassification/explainPrediction/modelEmbeddingActivations.ts index fb06a58..f28e745 100644 --- a/src/pages/playground/3_ImageClassification/explainPrediction/modelEmbeddingActivations.ts +++ b/src/pages/playground/3_ImageClassification/explainPrediction/modelEmbeddingActivations.ts @@ -165,7 +165,7 @@ function stabilize(z: tfjs.Tensor, epsilon: number): tfjs.Tensor { * (Montavon et al. 2019, §10.2.2): * * z = forward(x) s = R_out / z (constante) - * c = ∇_x Σ(forward(x) · s) + * c = ∇_x Σ(forward(x) × s) * R_in = x ⊙ c * * Sirve para cualquier capa lineal (Dense, Conv2D, AvgPool) y, con MaxPool, @@ -181,7 +181,7 @@ function lrpBackward( return x.mul(c); } -/** Regla epsilon genérica: R_i = Σ_j x_i·w_ij / (z_j + ε·sign(z_j)) · R_j */ +/** Regla epsilon genérica: R_i = Σ_j x_i × w_ij / (z_j + ε × sign(z_j)) × R_j */ function lrpEpsilon( forward: Forward, x: tfjs.Tensor, @@ -196,7 +196,7 @@ function lrpEpsilon( /** * Regla alpha-beta genérica (con α − β = 1): - * R_i = Σ_j ( α · (x_i·w⁺_ij)/z⁺_j − β · (x_i·w⁻_ij)/z⁻_j ) · R_j + * R_i = Σ_j ( α × (x_i × w⁺_ij)/z⁺_j − β × (x_i × w⁻_ij)/z⁻_j ) × R_j * Supone entradas no negativas (salida de ReLU o píxeles en [0, 1]). */ function lrpAlphaBeta( diff --git a/src/pages/playground/3_ImageClassification/explainPrediction/runImageClassificationExplain.ts b/src/pages/playground/3_ImageClassification/explainPrediction/runImageClassificationExplain.ts index 4ce9f3b..95f06e9 100644 --- a/src/pages/playground/3_ImageClassification/explainPrediction/runImageClassificationExplain.ts +++ b/src/pages/playground/3_ImageClassification/explainPrediction/runImageClassificationExplain.ts @@ -6,6 +6,7 @@ import { createImageClassificationAdapter } from '@core/explainability/adapters/ import { buildMaskedBackground, minShapSamples } from '@core/explainability/shapSampling'; import { computeSLICzeroMap } from '@utils/slic0'; import { ExplainError } from '@core/explainability/explainError'; +import { compileShaders } from '@core/nn-utils/warmUpModel'; export interface ExplainParams { iModel : any; @@ -171,6 +172,44 @@ export async function runImageClassificationExplain( /** * Ejecuta el flujo de explicabilidad para LRP (Layer-wise Relevance Propagation). */ +/** Las capas que recorre LRP (todas menos la de entrada) */ +const lrpLayerNames = (modelInstance: tfjs.LayersModel): string[] => + modelInstance.layers + .filter((layer) => layer.getClassName() !== 'InputLayer') + .map((layer) => layer.name); + +const withBatch = (shape: Array): number[] => [1, ...shape.slice(1).map((size) => size ?? 1)]; + +/** + * Compila los shaders de LRP (gradientes de cada capa, argMax, oneHot…) antes de la primera explicación, que si no + * bloquea unos 300 ms compilándolos (TODO-worker.md, fase 0). Se propaga la relevancia con activaciones a cero de la + * forma de cada capa (la forma sale del modelo, sin calcular nada) en modo solo compilar: ver `compileShaders`. + */ +export async function warmUpLrp(iModel: any, modelInstance: tfjs.LayersModel): Promise { + if (!supportsLrp(iModel)) return; + const inputShape = modelInstance.inputs[0]?.shape; + if (!inputShape) return; + const layers: Record = {}; + const add = (name: string, shape: Array) => { + const full = withBatch(shape); + layers[name] = { data: new Float32Array(full.reduce((a, b) => a * b, 1)), shape: full }; + }; + add('__input__', inputShape); + const names = lrpLayerNames(modelInstance); + for (const name of names) { + const outputShape = modelInstance.getLayer(name).outputShape; + // Capas con varias salidas: no las hay en estos modelos; si las hubiera, no se calienta + if (!Array.isArray(outputShape) || Array.isArray(outputShape[0])) return; + add(name, outputShape as Array); + } + await compileShaders(() => iModel.CALCULATE_LRP_PROPAGATION( + modelInstance, + null, + { layers, order: ['__input__', ...names] }, + { rule: 'epsilon', epsilon: 0.01, winnerTakesAll: true }, + )); +} + export async function runImageClassificationExplainLrp( params: ExplainLrpParams, ): Promise { @@ -195,9 +234,7 @@ export async function runImageClassificationExplainLrp( ); } - const layerNames = modelInstance.layers - .filter((layer: any) => layer?.getClassName?.() !== 'InputLayer') - .map((layer: any) => layer.name); + const layerNames = lrpLayerNames(modelInstance); const activations = await iModel.GET_ACTIVATIONS_IMAGE( modelInstance, @@ -219,8 +256,13 @@ export async function runImageClassificationExplainLrp( }, ); + // En color, la de cada píxel es la suma de la de sus tres canales: el mapa de calor tiene un valor por píxel + const perPixel: tfjs.Tensor = relevanceTensor.rank === 4 && relevanceTensor.shape[3]! > 1 + ? tfjs.tidy(() => relevanceTensor.sum(-1, true)) + : relevanceTensor; try { - const relevanceValues: number[] = Array.from(relevanceTensor.dataSync()); + // Lectura asíncrona: dataSync detiene el hilo principal hasta que la GPU termina + const relevanceValues: number[] = Array.from(await perPixel.data()); const { index: predictedIndex, predictions } = await iModel.CLASSIFY_IMAGE( modelInstance, imageData, @@ -235,9 +277,10 @@ export async function runImageClassificationExplainLrp( segmentationMapArray: null, numSegments : relevanceValues.length, backgroundData : [], - relevanceShape : Array.from(relevanceTensor.shape), + relevanceShape : Array.from(perPixel.shape), }; } finally { + if (perPixel !== relevanceTensor) perPixel.dispose(); if (relevanceTensor?.dispose) relevanceTensor.dispose(); } } diff --git a/src/pages/playground/3_ImageClassification/layersGuide.ts b/src/pages/playground/3_ImageClassification/layersGuide.ts new file mode 100644 index 0000000..3dbad5e --- /dev/null +++ b/src/pages/playground/3_ImageClassification/layersGuide.ts @@ -0,0 +1,61 @@ +import type { TFunction } from 'i18next' + +import type { GuideStep_t } from '@components/guide/N4LGuide' +import { imageLayerShapes } from '@core/nn-utils/checkLayers' +import { TYPE_ACTIVATION } from '@core/nn-utils/ArchitectureTypesHelper' +import type { ImageLayer_t } from '@/types/types' + +const prefix = 'guide.train.3-image-classification.' + +/** + * Un paso de la guía por cada capa del editor (en el entrenador de imágenes): qué hace esa capa con sus números de + * verdad, lo que recibe y lo que sale, sus filtros y los pesos que aprende. Se rehacen al cambiar las capas. Textos en + * guide.train.3-image-classification..layer.* (cómo se llama cada clase: dígito, carácter…) y, lo demás, en + * .common.layer.* + */ +export function layersGuide(t: TFunction, language: string, dataset: string, layers: ImageLayer_t[]): GuideStep_t[] { + const shapes = imageLayerShapes(layers) + const text = (key: string, values: Record = {}) => + t([`${prefix}${dataset}.layer.${key}`, `${prefix}common.layer.${key}`], values) + const format = new Intl.NumberFormat(language) + const activationLabel = (key: string) => TYPE_ACTIVATION.find((option) => option.key === key)?.label ?? key + const className = text('class-name') + let convolutions = 0 + + return layers.map((layer, index) => { + const shape = shapes[index] + const target = `[data-guide="layer-${index}"]` + const number = index + 1 + if (shape === null) return { target, placement: 'auto', title: text('broken.title', { number }), content: text('broken.content') } + + const isOutput = index === layers.length - 1 && layer._class === 'dense' + const kind = isOutput ? 'output' + : layer._class === 'conv2d' ? (convolutions++ === 0 ? 'conv-first' : 'conv') + : layer._class === 'maxPooling2d' ? 'pool' + : layer._class === 'flatten' ? 'flatten' : 'dense' + const [inputHeight, inputWidth, inputChannels] = shape.input + const [outputHeight, outputWidth, outputChannels] = shape.output + const values = { + number, + class : className, + inputSize : `${inputHeight}×${inputWidth}`, + inputChannels : inputChannels ?? '', + inputValues : format.format(inputHeight), + outputSize : `${outputHeight}×${outputWidth}`, + outputChannels: outputChannels ?? '', + values : format.format(outputHeight), + params : format.format(shape.params), + kernel : layer.kernelSize ?? '', + filters : layer.filters ?? '', + pool : layer.poolSize ?? '', + strides : layer.strides ?? '', + units : layer.units ?? '', + activation : activationLabel(layer.activation ?? 'linear'), + } + // La salida, con softmax o no (entonces el aviso del editor lo dice); las demás capas con activación, cuál es + const content = kind === 'output' + ? text(layer.activation === 'softmax' ? 'output.content' : 'output.content-other', values) + : [text(kind + '.content', values), ...(kind === 'pool' || kind === 'flatten' ? [] : [text(layer.activation === 'relu' ? 'relu' : 'activation', values)])].join(' ') + return { target, placement: 'auto', title: text(kind + '.title', values), content } + }) +} diff --git a/src/pages/playground/3_ImageClassification/modelReviewGuide.ts b/src/pages/playground/3_ImageClassification/modelReviewGuide.ts new file mode 100644 index 0000000..b14dec8 --- /dev/null +++ b/src/pages/playground/3_ImageClassification/modelReviewGuide.ts @@ -0,0 +1,31 @@ +import { IC_MODEL_KEYS } from '@/MODEL_KEYS' +import type { GuideStep_t } from '@components/guide/N4LGuide' +import { buildGuideSteps, centerStep, guideStep, type GuideTranslate_t } from '@components/guide/buildGuideSteps' + +/** + * Modelos con guía en su página (/playground/image-classification/model/). Sus textos van en + * guide.3-image-classification. y, lo que es igual en todos, en guide.3-image-classification.common. + */ +export const IMAGE_CLASSIFICATION_REVIEW_GUIDES: string[] = [IC_MODEL_KEYS.MNIST, IC_MODEL_KEYS.KMNIST, IC_MODEL_KEYS.CIFAR10, IC_MODEL_KEYS.MOBILENET] + +/** + * Los pasos de la guía de la página de un modelo de clasificación de imágenes (null si no tiene). Con las imágenes de + * un conjunto (MNIST, KMNIST, CIFAR-10), también sus imágenes de test; con las que se pueden dibujar (en gris), el + * dibujo; el resumen del modelo, solo si lo tiene (MobileNet no: no es un LayersModel). + */ +export function imageClassificationReviewGuide(t: GuideTranslate_t, modelKey: string, { drawable, summary, testImages }: { drawable: boolean, summary: boolean, testImages: boolean }): GuideStep_t[] | null { + if (!IMAGE_CLASSIFICATION_REVIEW_GUIDES.includes(modelKey)) return null + return buildGuideSteps(t, 'guide.3-image-classification', modelKey, [ + centerStep('intro'), + guideStep('model', 'model'), + ...(summary ? [guideStep('model-summary', 'model-summary')] : []), + guideStep('explain-about', 'explain-about'), + guideStep('examples', 'examples'), + ...(testImages ? [guideStep('test-images', 'test-images', 'bottom')] : []), + guideStep('upload', 'upload'), + ...(drawable ? [guideStep('draw', 'draw')] : []), + guideStep('result', 'result'), + guideStep('explain', 'explain'), + centerStep('end'), + ]) +} diff --git a/src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_KMNIST.tsx b/src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_KMNIST.tsx deleted file mode 100644 index 4416214..0000000 --- a/src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_KMNIST.tsx +++ /dev/null @@ -1,76 +0,0 @@ -import { Trans } from 'react-i18next' -import * as tfjs from '@tensorflow/tfjs' -import I_MODEL_IMAGE_28X28 from './_model_28x28' -import { KMNIST_DATASET } from './SpriteImageDataset' -import { IC_MODEL_KEYS } from '@/MODEL_KEYS' - -// Modelo preentrenado con Scripts/train_kmnist_model.cjs y su precisión con las 10.000 imágenes de test -// (la que guarda el script en model.json como testAccuracy) -const PRETRAINED_MODEL_URL = import.meta.env.VITE_PATH + '/models/03-image-classification/kmnist/model.json' -export const KMNIST_PRETRAINED_TEST_ACCURACY = 0.9825 - -// Cada carácter (en el orden de CLASS_LABELS) escrito con la fuente Noto Sans CJK JP; las genera -// Scripts/build_kmnist_examples.py -export const LIST_OF_IMAGES_KMNIST: string[] = Array.from({ length: 10 }, (_, label) => `kmnist/${label}.png`) - -export default class MODEL_IMAGE_KMNIST extends I_MODEL_IMAGE_28X28 { - static KEY = IC_MODEL_KEYS.KMNIST - TITLE = 'datasets-models.3-image-classifier.kmnist.title' - i18n_TITLE = 'datasets-models.3-image-classifier.kmnist.title' - DATASET = KMNIST_DATASET - // Los 10 caracteres hiragana de KMNIST (kmnist_classmap.csv) - CLASS_LABELS = ['お', 'き', 'す', 'つ', 'な', 'は', 'ま', 'や', 'れ', 'を'] - - DESCRIPTION() { - const prefix = 'datasets-models.3-image-classifier.kmnist.description.' - return <> -

    -

    -

    - -
    - -
      -
    1. -
    -
    -
    - -
      -
    1. -
    -
    -
    - -
      -
    1. -
    2. -
    -
    -
    - BibTeX -
    -          {`
    -@online{clanuwat2018deep,
    -  author       = {Tarin Clanuwat and Mikel Bober-Irizar and Asanobu Kitamoto and Alex Lamb and Kazuaki Yamamoto and David Ha},
    -  title        = {Deep Learning for Classical Japanese Literature},
    -  date         = {2018-12-03},
    -  year         = {2018},
    -  eprintclass  = {cs.CV},
    -  eprinttype   = {arXiv},
    -  eprint       = {cs.CV/1812.01718},
    -}
    -`}
    -        
    -
    - - } - - LIST_IMAGES_EXAMPLES(): string[] { - return LIST_OF_IMAGES_KMNIST - } - - async ENABLE_MODEL() { - return await tfjs.loadLayersModel(PRETRAINED_MODEL_URL) - } -} diff --git a/src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_MNIST.tsx b/src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_MNIST.tsx deleted file mode 100644 index babec38..0000000 --- a/src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_MNIST.tsx +++ /dev/null @@ -1,78 +0,0 @@ -import { Trans } from 'react-i18next' -import * as tfjs from '@tensorflow/tfjs' -import I_MODEL_IMAGE_28X28 from './_model_28x28' -import { MNIST_DATASET } from './SpriteImageDataset' -import { IC_MODEL_KEYS } from '@/MODEL_KEYS' - -export const LIST_OF_IMAGES_MNIST: string[] = [ - '0_new.png', - '1_new.png', - '2_new.png', - '3_new.png', - '4_new.png', - '5_new.png', - '6_new.png', - '7_new.png', - '8_new.png', - '9_new.png' -] - -export default class MODEL_IMAGE_MNIST extends I_MODEL_IMAGE_28X28 { - static KEY = IC_MODEL_KEYS.MNIST - TITLE = 'datasets-models.3-image-classifier.mnist.title' - i18n_TITLE = 'datasets-models.3-image-classifier.mnist.title' - DATASET = MNIST_DATASET - CLASS_LABELS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] - - DESCRIPTION() { - const prefix = 'datasets-models.3-image-classifier.mnist.description.' - return <> -

    -

    -

    - -
    - -
      -
    1. -
    -
    -
    - -
      -
    1. -
    -
    -
    - BibTeX -
    -          {`
    -@article{deng2012mnist,
    -  title={The mnist database of handwritten digit images for machine learning research},
    -  author={Deng, Li},
    -  journal={IEEE Signal Processing Magazine},
    -  volume={29},
    -  number={6},
    -  pages={141--142},
    -  year={2012},
    -  publisher={IEEE}
    -}
    -`}
    -        
    -
    - - } - - LIST_IMAGES_EXAMPLES(): string[] { - return LIST_OF_IMAGES_MNIST - } - - /** - * - * @returns {Promise} - */ - async ENABLE_MODEL() { - const model = await tfjs.loadLayersModel(import.meta.env.VITE_PATH + '/models/03-image-classification/keras-mnist/model.json') - return model - } -} diff --git a/src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_MOBILENET.tsx b/src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_MOBILENET.tsx deleted file mode 100644 index ff83869..0000000 --- a/src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_MOBILENET.tsx +++ /dev/null @@ -1,96 +0,0 @@ -import I_MODEL_IMAGE_CLASSIFICATION from './_model' -import { Trans } from 'react-i18next' -import * as tf_mobilenet from '@tensorflow-models/mobilenet' -import { DEFAULT_BAR_DATA, type BarChartData_t } from '@pages/playground/3_ImageClassification/CONSTANTS' - -/** Una clase predicha por MobileNet con su probabilidad */ -type MobileNetPrediction_t = { className: string, probability: number } -import { IC_MODEL_KEYS } from '@/MODEL_KEYS' - -export const LIST_OF_IMAGES_MOBILENET = [ - 'beef-burger.jpg', - 'bulldog.jpg', - 'butterfly.jpg', - 'cat.jpg', - 'cheetah.jpg', - 'cruise.jpg', - 'duck.jpg', - 'elephant.jpg', - 'lion.jpg', -] -export default class MODEL_IMAGE_MOBILENET extends I_MODEL_IMAGE_CLASSIFICATION { - static KEY = IC_MODEL_KEYS.MOBILENET - TITLE = 'datasets-models.3-image-classifier.mobilenet.title' - i18n_TITLE = 'datasets-models.3-image-classifier.mobilenet.title' - - DESCRIPTION() { - const prefix = 'datasets-models.3-image-classifier.mobilenet.description.' - return <> -

    -

    - -
    - -
      -
    1. -
    -
    -
    - -
      -
    1. - Text - }} /> -
    2. -
    -
    -
    - -

    -
      -
    1. - Text - }} /> -
    2. -
    -
    - - } - - async ENABLE_MODEL(): Promise { - return await tf_mobilenet.load() - } - - async CLASSIFY(model: tf_mobilenet.MobileNet, imageData: ImageData): Promise<{predictions: MobileNetPrediction_t[], index: number}> { - const predictions = await model.classify(imageData) - return { predictions, index: 0 } - } - - async CLASSIFY_IMAGE(model: tf_mobilenet.MobileNet, imageData: ImageData): Promise<{predictions: MobileNetPrediction_t[], index: number}> { - const predictions = await model.classify(imageData) - return { predictions, index: 0 } - } - - async PREDICTION_FORMAT(predictions: MobileNetPrediction_t[]): Promise { - return { - labels : [''], - datasets: predictions.map((v, i) => { - return { - label : v.className, - data : [v.probability], - backgroundColor: DEFAULT_BAR_DATA.datasets[0].backgroundColor[i % 7], - borderColor : DEFAULT_BAR_DATA.datasets[0].borderColor[i % 7], - borderWidth : DEFAULT_BAR_DATA.datasets[0].borderWidth, - } - }), - } - } - - LIST_IMAGES_EXAMPLES(): string[] { - return LIST_OF_IMAGES_MOBILENET - } -} diff --git a/src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_RESNET.tsx b/src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_RESNET.tsx deleted file mode 100644 index d6f868c..0000000 --- a/src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_RESNET.tsx +++ /dev/null @@ -1,46 +0,0 @@ -import I_MODEL_IMAGE_CLASSIFICATION from './_model' -import { IC_MODEL_KEYS } from '@/MODEL_KEYS' - -// TODO -export default class MODEL_IMAGE_RESNET extends I_MODEL_IMAGE_CLASSIFICATION { - static KEY = IC_MODEL_KEYS.RESNET - TITLE = '' - i18n_TITLE = '' - - DESCRIPTION () { - return <> -

    - ResNet V2 es una familiar de redes de arquitecturas para la clasificación de imágenes con un número variable de capas. -

    -

    - Están basadas en la arquitectura ResNet original publicada por Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun: - "Deep Residual Learning for Image Recognition", 2015. -

    -

    - La variación "V2" utilizada en el modelo que vamos a usar fue realizada por Kaiming He, Xiangyu Zhang, - Shaoqing Ren, Jian Sun:{' '} - "Identity Mappings in Deep Residual Networks", 2016. -

    -

    - La diferencia con ResNet V1 es el uso de la normalización por lotes antes de cada capa de peso. El modelo - cargado usa un total de 50 capas. -

    - -
    - Datos de entrada -
      -
    1. Imagen con valores de color entre [0,1] de 224 x 224 píxeles.
    2. -
    -
    -
    - Datos de salida -
      -
    1. Un número de 0 a 1001 que son cada una de las categorías de esta{' '} - lista -
    2. -
    -
    - - } -} diff --git a/src/pages/playground/3_ImageClassification/models/MODEL_N4L.tsx b/src/pages/playground/3_ImageClassification/models/MODEL_N4L.tsx new file mode 100644 index 0000000..e504af6 --- /dev/null +++ b/src/pages/playground/3_ImageClassification/models/MODEL_N4L.tsx @@ -0,0 +1,111 @@ +import type { TFunction } from 'i18next' + +import { TASKS } from '@/TASKS' +import type { ImageLayer_t } from '@/types/types' +import { n4lLabelKey, n4lTaskText } from '@core/n4l/format' +import { n4lFileUrls, n4lImageExamples, type N4LImageRuntime_t } from '@core/n4l/imageClassification' +import type { N4LPackage_t } from '@core/n4l/source' +import { loadN4LLayersModel } from '@core/n4l/tfjsModel' +import { N4LError } from '@core/n4l/validate' +import N4LPackageDescription from '@components/n4l/N4LPackageDescription' +import { CharacterFormsTable } from '../components/N4LCharacterForms' +import I_MODEL_IMAGE_SPRITE from './_model_sprite' +import { n4lCharacterForms, type CharacterForms_t } from './characterForms' +import { imageLayersOf } from './n4lLayers' +import type { SpriteDatasetConfig_t } from './SpriteImageDataset' + +type SpriteRuntime_t = Extract + +// Las direcciones del sprite de cada paquete: las de un .n4l abierto se crean una vez (así el sprite se descarga y se +// decodifica una sola vez por visita, como el de un paquete servido) +const spriteUrls = new WeakMap>>() + +/** + * Un clasificador de las imágenes de un paquete .n4l (MNIST, KMNIST, CIFAR-10…): sus clases, su sprite, su modelo ya + * entrenado, sus imágenes de ejemplo y su red por defecto salen del manifiesto y sus textos. `urls`: la dirección de + * cada imagen de ejemplo + */ +export default class MODEL_N4L extends I_MODEL_IMAGE_SPRITE { + readonly pkg : N4LPackage_t + readonly runtime : SpriteRuntime_t + DATASET_NAME : string + private readonly urls : Record + private readonly forms: CharacterForms_t[] | null + + constructor(t: TFunction<'translation', undefined>, pkg: N4LPackage_t, runtime: SpriteRuntime_t, urls: Record) { + super(t, runtime.dataset.image) + const texts = n4lTaskText(pkg.namespace, TASKS.IMAGE_CLASSIFICATION) + this.pkg = pkg + this.runtime = runtime + this.urls = urls + this.TITLE = texts + 'title' + this.i18n_TITLE = texts + 'title' + this.DATASET_NAME = runtime.dataset.id.toUpperCase() + this.CLASS_IDS = (runtime.section.classes ?? []).map(({ id }) => id) + // Su nombre en los textos del paquete («avión»); si no lo tiene, el del conjunto («7», «お») + this.CLASS_LABELS = this.CLASS_IDS.map((id) => t(`${pkg.namespace}:classes.${n4lLabelKey(id)}`, { defaultValue: id })) + this.forms = n4lCharacterForms(runtime.section, (file) => urls[file] ?? '') + } + + /** El paquete del que sale (para descargarlo) */ + N4L_PACKAGE() { + return this.pkg + } + + async SPRITE(): Promise { + const { source } = this.pkg + const { dataset } = this.runtime + if (!spriteUrls.has(source)) spriteUrls.set(source, n4lFileUrls(source, [dataset.file, dataset.labels])) + const urls = await spriteUrls.get(source)! + return { + name : this.DATASET_NAME, + imagesUrl : urls[dataset.file], + labelsUrl : urls[dataset.labels], + numElements: dataset.rows, + numTrain : dataset.train, + numClasses : this.CLASS_IDS.length, + image : dataset.image, + } + } + + DESCRIPTION() { + const texts = n4lTaskText(this.pkg.namespace, TASKS.IMAGE_CLASSIFICATION) + return ( + + {this.forms !== null && } + + ) + } + + /** Las imágenes de ejemplo (sin las formas antiguas de los caracteres: esas van con CHARACTER_FORMS) */ + LIST_IMAGES_EXAMPLES(): string[] { + return n4lImageExamples(this.runtime.section).filter(({ old }) => old !== true).map(({ file }) => this.urls[file]) + } + + LIST_IMAGES_EXAMPLES_LABELS(): Array { + const classes = this.runtime.section.classes ?? [] + return n4lImageExamples(this.runtime.section).filter(({ old }) => old !== true).map(({ expected }) => { + const index = classes.findIndex(({ id, aliases }) => id === expected || (aliases ?? []).includes(expected ?? '')) + return index === -1 ? undefined : this.CLASS_LABELS[index] + }) + } + + CHARACTER_FORMS() { + return this.forms + } + + DEFAULT_TRAINING() { + const { learningRate, epochs } = this.runtime.section.training ?? {} + return { learningRate, epochs } + } + + DEFAULT_LAYERS(): ImageLayer_t[] { + return imageLayersOf(this.runtime.section.training?.layers ?? [], this.IMAGE) + } + + async ENABLE_MODEL() { + const { model } = this.runtime + if (model === undefined) throw new N4LError(this.pkg.manifest.id, ['image-classification: no tiene un modelo ya entrenado']) + return loadN4LLayersModel(this.pkg.source, model.path) + } +} diff --git a/src/pages/playground/3_ImageClassification/models/MODEL_N4L_MOBILENET.tsx b/src/pages/playground/3_ImageClassification/models/MODEL_N4L_MOBILENET.tsx new file mode 100644 index 0000000..34eb4ab --- /dev/null +++ b/src/pages/playground/3_ImageClassification/models/MODEL_N4L_MOBILENET.tsx @@ -0,0 +1,79 @@ +import type { TFunction } from 'i18next' +import * as tf_mobilenet from '@tensorflow-models/mobilenet' + +import { TASKS } from '@/TASKS' +import { n4lTaskText } from '@core/n4l/format' +import { n4lImageExamples, type N4LImageRuntime_t } from '@core/n4l/imageClassification' +import type { N4LPackage_t } from '@core/n4l/source' +import N4LPackageDescription from '@components/n4l/N4LPackageDescription' +import { DEFAULT_BAR_DATA, type BarChartData_t } from '@pages/playground/3_ImageClassification/CONSTANTS' +import I_MODEL_IMAGE_CLASSIFICATION, { type ImageClassificationResult_t } from './_model' + +type MobileNetRuntime_t = Extract + +/** Una clase predicha por MobileNet con su probabilidad */ +type MobileNetPrediction_t = { className: string, probability: number } + +/** + * MobileNet en un paquete .n4l (el de ImageNet): la librería lo descarga en la versión y el ancho del manifiesto; sus + * textos y sus fotos de ejemplo son los del paquete. `urls`: la dirección de cada foto + */ +export default class MODEL_N4L_MOBILENET extends I_MODEL_IMAGE_CLASSIFICATION { + readonly pkg : N4LPackage_t + readonly runtime : MobileNetRuntime_t + private readonly urls: Record + + constructor(t: TFunction<'translation', undefined>, pkg: N4LPackage_t, runtime: MobileNetRuntime_t, urls: Record) { + super(t) + const texts = n4lTaskText(pkg.namespace, TASKS.IMAGE_CLASSIFICATION) + this.pkg = pkg + this.runtime = runtime + this.urls = urls + this.TITLE = texts + 'title' + this.i18n_TITLE = texts + 'title' + } + + /** El paquete del que sale (para descargarlo) */ + N4L_PACKAGE() { + return this.pkg + } + + DESCRIPTION() { + return + } + + async ENABLE_MODEL(): Promise { + const { version, alpha } = this.runtime.model + return tf_mobilenet.load({ version, alpha: alpha as tf_mobilenet.MobileNetAlpha }) + } + + async CLASSIFY(model: tf_mobilenet.MobileNet, imageData: ImageData): Promise<{ predictions: MobileNetPrediction_t[], index: number }> { + const predictions = await model.classify(imageData) + return { predictions, index: 0 } + } + + async CLASSIFY_IMAGE(model: tf_mobilenet.MobileNet, imageData: ImageData): Promise<{ predictions: MobileNetPrediction_t[], index: number }> { + return this.CLASSIFY(model, imageData) + } + + PREDICTION_RESULT(predictions: MobileNetPrediction_t[]): ImageClassificationResult_t { + return { values: predictions.map((p) => p.probability), labels: predictions.map((p) => p.className), topK: true } + } + + async PREDICTION_FORMAT(predictions: MobileNetPrediction_t[]): Promise { + return { + labels : [''], + datasets: predictions.map((v, i) => ({ + label : v.className, + data : [v.probability], + backgroundColor: DEFAULT_BAR_DATA.datasets[0].backgroundColor[i % 7], + borderColor : DEFAULT_BAR_DATA.datasets[0].borderColor[i % 7], + borderWidth : DEFAULT_BAR_DATA.datasets[0].borderWidth, + })), + } + } + + LIST_IMAGES_EXAMPLES(): string[] { + return n4lImageExamples(this.runtime.section).map(({ file }) => this.urls[file]) + } +} diff --git a/src/pages/playground/3_ImageClassification/models/SpriteImageDataset.ts b/src/pages/playground/3_ImageClassification/models/SpriteImageDataset.ts index fce7935..e2ea9cd 100644 --- a/src/pages/playground/3_ImageClassification/models/SpriteImageDataset.ts +++ b/src/pages/playground/3_ImageClassification/models/SpriteImageDataset.ts @@ -3,16 +3,14 @@ * (Copyright 2018 Google LLC, Apache License 2.0), generalizado para cualquier sprite con el mismo formato. */ import * as tf from '@tensorflow/tfjs' - -const IMAGE_SIZE = 28 * 28 -const NUM_CLASSES = 10 -// Filas del sprite que se leen de cada vez a través del canvas -const CHUNK_SIZE = 5000 +import { createWorkerClient } from '@core/workers/workerClient' +import { CHUNK_SIZE, copyChannels, spriteImageValues, type SpriteImage_t } from './spriteDecode' +import type { SpriteWorkerApi_t } from './sprite.worker' /** - * Dataset de imágenes de 28x28 en escala de grises guardado como sprite: - * - `imagesUrl`: PNG con una imagen por fila (784 px de ancho), primero las de entrenamiento. - * - `labelsUrl`: etiquetas en one-hot, NUM_CLASSES bytes por imagen, en el mismo orden. + * Dataset de imágenes guardado como sprite (el de un paquete .n4l, kind image-sprite), en gris o en color (`image`): + * - `imagesUrl`: PNG con una imagen aplanada por fila (784 px de ancho las de 28×28), primero las de entrenamiento. + * - `labelsUrl`: etiquetas en one-hot, `numClasses` bytes por imagen, en el mismo orden. */ export type SpriteDatasetConfig_t = { name : string @@ -20,64 +18,80 @@ export type SpriteDatasetConfig_t = { labelsUrl : string numElements: number numTrain : number -} - -export const MNIST_DATASET: SpriteDatasetConfig_t = { - name : 'MNIST', - imagesUrl : 'https://storage.googleapis.com/learnjs-data/model-builder/mnist_images.png', - labelsUrl : 'https://storage.googleapis.com/learnjs-data/model-builder/mnist_labels_uint8', - numElements: 65000, - numTrain : 55000, -} - -// Generado con Scripts/build_kmnist_sprite.py: 2.000 imágenes por carácter para entrenar y 500 para test -export const KMNIST_DATASET: SpriteDatasetConfig_t = { - name : 'KMNIST', - imagesUrl : import.meta.env.VITE_PATH + '/datasets/03-image-classification/kmnist/kmnist_images.png', - labelsUrl : import.meta.env.VITE_PATH + '/datasets/03-image-classification/kmnist/kmnist_labels_uint8', - numElements: 25000, - numTrain : 20000, + numClasses : number + image : SpriteImage_t } /** Descarga el sprite y las etiquetas y devuelve lotes barajados de entrenamiento y de test. */ export class SpriteImageDataset { - private readonly config: SpriteDatasetConfig_t - private trainImages = new Float32Array(0) - private testImages = new Float32Array(0) - private trainLabels = new Uint8Array(0) - private testLabels = new Uint8Array(0) - private trainIndices : Uint32Array = new Uint32Array(0) - private testIndices : Uint32Array = new Uint32Array(0) + private readonly config : SpriteDatasetConfig_t + private readonly numClasses: number + /** Valores de cada imagen */ + private readonly imageSize : number + private trainImages : Float32Array = new Float32Array(0) + private testImages : Float32Array = new Float32Array(0) + private trainLabels : Uint8Array = new Uint8Array(0) + private testLabels : Uint8Array = new Uint8Array(0) + private trainIndices : Uint32Array = new Uint32Array(0) + private testIndices : Uint32Array = new Uint32Array(0) private shuffledTrainIndex = 0 private shuffledTestIndex = 0 constructor(config: SpriteDatasetConfig_t) { this.config = config + this.numClasses = config.numClasses + this.imageSize = spriteImageValues(config.image) + } + + /** Cómo son sus imágenes */ + get image(): SpriteImage_t { + return this.config.image } - async load() { + /** Todo el conjunto o, con `testOnly`, solo las imágenes de test (las de entrenamiento no se decodifican) */ + async load({ testOnly = false } = {}) { const { numElements, numTrain } = this.config - const [images, labels] = await Promise.all([this.loadImages(), this.loadLabels()]) - if (labels.length !== numElements * NUM_CLASSES) { - throw new Error(`Labels file has ${labels.length} bytes, expected ${numElements * NUM_CLASSES}`) + const firstRow = testOnly ? numTrain : 0 + const [images, labels] = await Promise.all([this.loadImages(firstRow, numElements - firstRow), this.loadLabels()]) + if (labels.length !== numElements * this.numClasses) { + throw new Error(`Labels file has ${labels.length} bytes, expected ${numElements * this.numClasses}`) } - this.trainIndices = tf.util.createShuffledIndices(numTrain) + // subarray y no slice: comparten memoria en vez de copiarla (MNIST entero son 204 MB de Float32Array) + const trainRows = numTrain - firstRow + this.trainIndices = tf.util.createShuffledIndices(Math.max(trainRows, 0)) this.testIndices = tf.util.createShuffledIndices(numElements - numTrain) - this.trainImages = images.slice(0, IMAGE_SIZE * numTrain) - this.testImages = images.slice(IMAGE_SIZE * numTrain) - this.trainLabels = labels.slice(0, NUM_CLASSES * numTrain) - this.testLabels = labels.slice(NUM_CLASSES * numTrain) + this.trainImages = images.subarray(0, this.imageSize * Math.max(trainRows, 0)) + this.testImages = images.subarray(this.imageSize * Math.max(trainRows, 0)) + this.trainLabels = labels.subarray(firstRow * this.numClasses, this.numClasses * numTrain) + this.testLabels = labels.subarray(this.numClasses * numTrain) } - // Lee el sprite por trozos en un canvas; al ser gris basta con el canal rojo (0-255 → 0-1) - private loadImages(): Promise { - const { imagesUrl, numElements } = this.config + /** + * Las filas [firstRow, firstRow + numRows) del sprite. En un worker (decodificar MNIST bloqueaba el hilo principal + * ~320 ms); si no se puede (sin workers u OffscreenCanvas), aquí mismo + */ + private async loadImages(firstRow: number, numRows: number): Promise { + const url = new URL(this.config.imagesUrl, document.baseURI).href + const worker = createWorkerClient(() => new Worker(new URL('./sprite.worker.ts', import.meta.url), { type: 'module' })) + try { + return await worker.call('decode', { url, firstRow, numRows, image: this.config.image }) + } catch (error) { + console.warn('Sprite decoded in the main thread:', error) + return this.loadImagesInMainThread(firstRow, numRows) + } finally { + worker.terminate() + } + } + + // Lee el sprite por trozos en un canvas (0-255 → 0-1; en gris basta con el canal rojo) + private loadImagesInMainThread(firstRow: number, numRows: number): Promise { + const { imagesUrl, image } = this.config return new Promise((resolve, reject) => { const img = new Image() img.crossOrigin = '' img.onerror = () => reject(new Error(`Could not load dataset images: ${imagesUrl}`)) img.onload = () => { - const images = new Float32Array(numElements * IMAGE_SIZE) + const images = new Float32Array(numRows * this.imageSize) const canvas = document.createElement('canvas') const ctx = canvas.getContext('2d', { willReadFrequently: true }) if (ctx === null) { @@ -85,15 +99,11 @@ export class SpriteImageDataset { return } canvas.width = img.naturalWidth - for (let row = 0; row < numElements; row += CHUNK_SIZE) { - const rows = Math.min(CHUNK_SIZE, numElements - row) + for (let row = 0; row < numRows; row += CHUNK_SIZE) { + const rows = Math.min(CHUNK_SIZE, numRows - row) canvas.height = rows - ctx.drawImage(img, 0, row, img.naturalWidth, rows, 0, 0, img.naturalWidth, rows) - const { data } = ctx.getImageData(0, 0, canvas.width, rows) - const offset = row * IMAGE_SIZE - for (let j = 0; j < data.length / 4; j++) { - images[offset + j] = data[j * 4] / 255 - } + ctx.drawImage(img, 0, firstRow + row, img.naturalWidth, rows, 0, 0, img.naturalWidth, rows) + copyChannels(ctx.getImageData(0, 0, canvas.width, rows).data, images, row * this.imageSize, image.channels) } resolve(images) } @@ -121,17 +131,62 @@ export class SpriteImageDataset { }) } + /** Imágenes de test: las que nunca se usan para entrenar (de ellas sale la validación) */ + get numTest() { + return this.testLabels.length / this.numClasses + } + + /** Clase de cada imagen de test */ + testClasses(): number[] { + return Array.from({ length: this.numTest }, (_, index) => this.classOf(this.testLabels, index)) + } + + /** Una imagen de test: sus valores (0–1; en gris, 0 fondo y 1 trazo) y su clase */ + testExample(index: number): { pixels: Float32Array, label: number } { + return { + pixels: this.testImages.slice(index * this.imageSize, (index + 1) * this.imageSize), + label : this.classOf(this.testLabels, index), + } + } + + // Las etiquetas están en one-hot + private classOf(labels: Uint8Array, index: number) { + const oneHot = labels.subarray(index * this.numClasses, (index + 1) * this.numClasses) + return oneHot.indexOf(Math.max(...oneHot)) + } + private nextBatch(batchSize: number, images: Float32Array, labels: Uint8Array, index: () => number) { - const batchImages = new Float32Array(batchSize * IMAGE_SIZE) - const batchLabels = new Uint8Array(batchSize * NUM_CLASSES) + const batchImages = new Float32Array(batchSize * this.imageSize) + const batchLabels = new Uint8Array(batchSize * this.numClasses) for (let i = 0; i < batchSize; i++) { const idx = index() - batchImages.set(images.subarray(idx * IMAGE_SIZE, (idx + 1) * IMAGE_SIZE), i * IMAGE_SIZE) - batchLabels.set(labels.subarray(idx * NUM_CLASSES, (idx + 1) * NUM_CLASSES), i * NUM_CLASSES) + batchImages.set(images.subarray(idx * this.imageSize, (idx + 1) * this.imageSize), i * this.imageSize) + batchLabels.set(labels.subarray(idx * this.numClasses, (idx + 1) * this.numClasses), i * this.numClasses) } return { - xs : tf.tensor2d(batchImages, [batchSize, IMAGE_SIZE]), - labels: tf.tensor2d(batchLabels, [batchSize, NUM_CLASSES]), + xs : tf.tensor2d(batchImages, [batchSize, this.imageSize]), + labels: tf.tensor2d(batchLabels, [batchSize, this.numClasses]), } } } + +// Un sprite por dataset y visita: el entrenamiento y el selector de imágenes de test comparten la descarga. Se guarda +// el conjunto entero y, aparte, el de solo test (el selector de la página del modelo no necesita las de entrenamiento) +const loadedDatasets = new Map>() + +/** + * El dataset ya cargado (lo descarga la primera vez). Con `testOnly` basta con las imágenes de test y, si el entero + * ya está, se usa ese. Si la descarga falla, la siguiente llamada lo vuelve a intentar + */ +export function loadSpriteDataset(config: SpriteDatasetConfig_t, { testOnly = false } = {}): Promise { + const fullKey = config.imagesUrl + '#all' + const key = testOnly ? config.imagesUrl + '#test' : fullKey + let loading = loadedDatasets.get(key) ?? (testOnly ? loadedDatasets.get(fullKey) : undefined) + if (loading === undefined) { + const dataset = new SpriteImageDataset(config) + loading = dataset.load({ testOnly }).then(() => dataset) + loading.catch(() => loadedDatasets.delete(key)) + loadedDatasets.set(key, loading) + } + return loading +} diff --git a/src/pages/playground/3_ImageClassification/models/_model.tsx b/src/pages/playground/3_ImageClassification/models/_model.tsx index d4b435a..00803c8 100644 --- a/src/pages/playground/3_ImageClassification/models/_model.tsx +++ b/src/pages/playground/3_ImageClassification/models/_model.tsx @@ -1,17 +1,25 @@ import type * as _tfjs from '@tensorflow/tfjs' -import { buildJoyride } from '@components/joyride/buildJoyride' import type {MobileNet} from '@tensorflow-models/mobilenet' import type * as _Types from '@core/types' -import type { Layer_t } from '@/types/types' +import type { ImageLayer_t } from '@/types/types' import type { IdLoss_t, IdMetric_t, IdOptimizer_t } from '@/types/nn-types' import type { BarChartData_t } from '../CONSTANTS' import type { TFunction } from 'i18next' +import type { TrainProgress_t } from '@pages/playground/3_ImageClassification/custom/trainImageClassifier' +import type { ClassificationEvaluation_t } from '@core/controller/trainDenseModel' +import type { SpriteImageDataset } from './SpriteImageDataset' +import type { CharacterForms_t } from './characterForms' +import type { SpriteImage_t } from './spriteDecode' +import type { N4LPackage_t } from '@core/n4l/source' /** Modelo que clasifica las imágenes: uno entrenado con tfjs o MobileNet */ export type ImageClassifierModel_t = _tfjs.LayersModel | MobileNet /** Parámetros de entrenamiento que recoge la página de clasificación de imágenes */ +/** Resultado de clasificar una imagen, listo para N4LClassificationChart */ +export type ImageClassificationResult_t = { values: number[], labels: string[], topK: boolean } + export type ImageTrainParams_t = { learningRate : number numberEpochs : number @@ -19,19 +27,25 @@ export type ImageTrainParams_t = { idLoss : IdLoss_t | IdMetric_t idOptimizer : IdOptimizer_t idMetricsList: Array - layers : Layer_t[] + layers : ImageLayer_t[] } export default abstract class I_MODEL_IMAGE_CLASSIFICATION { TITLE : string = '' i18n_TITLE : string = '' - /** Nombre de cada clase, en el orden de las salidas del modelo (p. ej. '0'…'9') */ + /** Nombre de cada clase (en el idioma de la página), en el orden de las salidas del modelo (p. ej. '0'…'9') */ CLASS_LABELS: string[] = [] - /** Clasifica dibujos de 28x28 en escala de grises: la revisión del modelo ofrece el lienzo y explica con LRP */ + /** Su identificador en el conjunto de datos (en el mismo orden), si no es el nombre: 'airplane' para «avión» */ + CLASS_IDS : string[] = [] + /** Clasifica dibujos en escala de grises: la revisión del modelo ofrece el lienzo y explica con LRP */ DRAWABLE = false - t : TFunction<"translation", undefined> + /** Cómo son las imágenes que recibe, si son las de un conjunto (null: cualquier foto, como MobileNet) */ + IMAGE : SpriteImage_t | null = null + /** Sus imágenes de prueba se pueden clasificar desde un selector (LOAD_DATASET) */ + TEST_IMAGES = false + t : TFunction<'translation', undefined> - constructor (_t: TFunction<"translation", undefined>) { + constructor (_t: TFunction<'translation', undefined>) { this.t = _t } @@ -39,10 +53,20 @@ export default abstract class I_MODEL_IMAGE_CLASSIFICATION { return <> } - DEFAULT_LAYERS (): Layer_t[] { + /** El paquete .n4l del que sale, para descargarlo (null si no sale de uno) */ + N4L_PACKAGE (): N4LPackage_t | null { + return null + } + + DEFAULT_LAYERS (): ImageLayer_t[] { return [] } + /** La tasa de aprendizaje y las épocas con las que se empieza a entrenar, si el conjunto las propone */ + DEFAULT_TRAINING (): { learningRate?: number, epochs?: number } { + return {} + } + /** * * @returns {Promise<_tfjs.LayersModel | MobileNet | null>} @@ -51,10 +75,24 @@ export default abstract class I_MODEL_IMAGE_CLASSIFICATION { return null } + /** Las direcciones de las imágenes de ejemplo */ LIST_IMAGES_EXAMPLES (): string[] { return [] } + /** + * La clase de cada imagen de ejemplo (en el mismo orden), ya traducida, si se sabe: con ella el botón del ejemplo dice + * qué es («Clasificar el ejemplo 3: 7»), lo mismo que ve quien mira la imagen + */ + LIST_IMAGES_EXAMPLES_LABELS (): Array { + return [] + } + + /** Caracteres que se escribían de varias formas (KMNIST): los ejemplos enseñan la de hoy junto a las antiguas */ + CHARACTER_FORMS (): CharacterForms_t[] | null { + return null + } + async CLASSIFY (_model: ImageClassifierModel_t, _imageData: ImageData): Promise<{predictions: unknown[], index: number}> { return { predictions: [], index: 0 } } @@ -63,6 +101,14 @@ export default abstract class I_MODEL_IMAGE_CLASSIFICATION { return { predictions: [], index: 0 } } + /** + * La predicción como la muestra N4LClassificationChart: un valor por clase y su nombre. `topK` si son solo las + * clases más probables de muchas (MobileNet devuelve las 3 primeras de 1000) + */ + PREDICTION_RESULT (_predictions: unknown[]): ImageClassificationResult_t { + return { values: [], labels: [], topK: false } + } + async PREDICTION_FORMAT (_predictions: unknown[]): Promise { return { labels : [], @@ -72,9 +118,14 @@ export default abstract class I_MODEL_IMAGE_CLASSIFICATION { /** * - * @returns {Promise<{model: _tfjs.Sequential, history: _tfjs.History} | null>} + * @returns {Promise<{model: _tfjs.Sequential, history: _tfjs.History, evaluation?: ClassificationEvaluation_t} | null>} */ - async TRAIN_MODEL (_params: ImageTrainParams_t): Promise<{model: _tfjs.Sequential, history: _tfjs.History} | null> { + /** Dataset de imágenes con el que se entrena (null si el modelo no se entrena en N4L) */ + async LOAD_DATASET (): Promise { + return null + } + + async TRAIN_MODEL (_params: ImageTrainParams_t, _progress?: TrainProgress_t): Promise<{model: _tfjs.Sequential, history: _tfjs.History, evaluation?: ClassificationEvaluation_t} | null> { return new Promise((resolve) => { setTimeout(() => { resolve(null) @@ -82,18 +133,6 @@ export default abstract class I_MODEL_IMAGE_CLASSIFICATION { }) } - JOYRIDE (): _Types.Joyride_t { - return buildJoyride(this.t, 'datasets-models.3-image-classification.joyride.steps.', [ - { key: 'manual', target: '.joyride-step-1-manual', placement: 'top' }, - { key: 'dataset-info', target: '.joyride-step-2-dataset-info', placement: 'top' }, - { key: 'layer-visualizer', target: '.joyride-step-5-layer', placement: 'top' }, - { key: 'layer-editor', target: '.joyride-step-6-editor-layers', placement: 'right' }, - { key: 'params-editor', target: '.joyride-step-7-editor-trainer', placement: 'left-start' }, - { key: 'list-of-models', target: '.joyride-step-8-list-of-models', placement: 'bottom' }, - { key: 'classify', target: '.joyride-step-9-classify', placement: 'top' }, - ]) - } - /** Imagen que recibe el modelo; por defecto, el canvas entero */ async GET_IMAGE_DATA (canvas: HTMLCanvasElement, canvas_ctx: CanvasRenderingContext2D): Promise { return canvas_ctx.getImageData(0, 0, canvas.width, canvas.height) diff --git a/src/pages/playground/3_ImageClassification/models/_model_28x28.tsx b/src/pages/playground/3_ImageClassification/models/_model_sprite.tsx similarity index 56% rename from src/pages/playground/3_ImageClassification/models/_model_28x28.tsx rename to src/pages/playground/3_ImageClassification/models/_model_sprite.tsx index 5462056..381a00e 100644 --- a/src/pages/playground/3_ImageClassification/models/_model_28x28.tsx +++ b/src/pages/playground/3_ImageClassification/models/_model_sprite.tsx @@ -1,33 +1,48 @@ import * as tfjs from '@tensorflow/tfjs' -import I_MODEL_IMAGE_CLASSIFICATION from './_model' -import type { SpriteDatasetConfig_t } from './SpriteImageDataset' -import { trainImageClassifier, type ParamsTrainImage_t } from '@pages/playground/3_ImageClassification/custom/trainImageClassifier' +import I_MODEL_IMAGE_CLASSIFICATION, { type ImageClassificationResult_t } from './_model' +import { loadSpriteDataset, type SpriteDatasetConfig_t, type SpriteImageDataset } from './SpriteImageDataset' +import { trainImageClassifier, type ParamsTrainImage_t, type TrainProgress_t } from '@pages/playground/3_ImageClassification/custom/trainImageClassifier' import { DEFAULT_BAR_DATA, type BarChartData_t } from '@pages/playground/3_ImageClassification/CONSTANTS' -import { imageDataToMnistTensor4d, toImageData } from '@pages/playground/3_ImageClassification/utils/utils' -import type { Layer_t } from '@/types/types' +import { imageDataToTensor4d, toImageData } from '@pages/playground/3_ImageClassification/utils/utils' +import type { SpriteImage_t } from './spriteDecode' +import type { ClassificationEvaluation_t } from '@core/controller/trainDenseModel' import { createActivationsHelpers, applyLRP, } from '@pages/playground/3_ImageClassification/explainPrediction/modelEmbeddingActivations' -const _activationsHelpers = createActivationsHelpers({ - imageDataToTensor4d: imageDataToMnistTensor4d, -}) - /** - * Clasificador de imágenes de 28x28 en escala de grises con 10 clases (MNIST, KMNIST…). - * Cada dataset solo define su sprite (`DATASET`), el nombre de sus clases y su descripción: - * el entrenamiento, la clasificación y la explicación con LRP son comunes. + * Clasificador de las imágenes de un sprite, en gris (MNIST, KMNIST…) o en color (CIFAR-10…). Cada conjunto solo da + * cómo son sus imágenes (`IMAGE`), su sprite (`SPRITE`), el nombre de sus clases y su descripción: el entrenamiento, la + * clasificación y la explicación con LRP son comunes. Las de gris se pueden dibujar */ -export default abstract class I_MODEL_IMAGE_28X28 extends I_MODEL_IMAGE_CLASSIFICATION { - abstract DATASET: SpriteDatasetConfig_t - DRAWABLE = true +export default abstract class I_MODEL_IMAGE_SPRITE extends I_MODEL_IMAGE_CLASSIFICATION { + /** El nombre del conjunto (en la gráfica de la predicción) */ + abstract DATASET_NAME: string + TEST_IMAGES = true + private readonly activations: ReturnType + declare IMAGE : SpriteImage_t + + /** `image`: cómo son las imágenes del conjunto */ + constructor(t: ConstructorParameters[0], image: SpriteImage_t) { + super(t) + this.IMAGE = image + this.DRAWABLE = image.channels === 1 + this.activations = createActivationsHelpers({ imageDataToTensor4d: (imageData: ImageData) => imageDataToTensor4d(imageData, image.channels) }) + } + + /** El sprite del conjunto (sus direcciones pueden necesitar leer el paquete: se pide al usarlo) */ + abstract SPRITE(): Promise + + PREDICTION_RESULT(predictions: number[]): ImageClassificationResult_t { + return { values: predictions, labels: this.CLASS_LABELS, topK: false } + } async PREDICTION_FORMAT(predictions: number[]): Promise { return { labels : this.CLASS_LABELS, datasets: [{ - label : this.DATASET.name, + label : this.DATASET_NAME, data : predictions, backgroundColor: DEFAULT_BAR_DATA.datasets[0].backgroundColor, borderColor : DEFAULT_BAR_DATA.datasets[0].borderColor, @@ -37,10 +52,10 @@ export default abstract class I_MODEL_IMAGE_28X28 extends I_MODEL_IMAGE_CLASSIFI } async CLASSIFY(model: tfjs.LayersModel, imageData: ImageData): Promise<{ predictions: number[]; index: number }> { - const predictions = Array.from(tfjs.tidy(() => { - const predTensor = model.predict(imageDataToMnistTensor4d(imageData)) as tfjs.Tensor - return predTensor.dataSync() - })) + const predTensor = tfjs.tidy(() => model.predict(imageDataToTensor4d(imageData, this.IMAGE.channels)) as tfjs.Tensor) + // Lectura asíncrona: dataSync detiene el hilo principal hasta que la GPU termina + const predictions = Array.from(await predTensor.data()) + predTensor.dispose() const index = predictions.indexOf(Math.max(...predictions)) return { predictions, index } } @@ -49,9 +64,9 @@ export default abstract class I_MODEL_IMAGE_28X28 extends I_MODEL_IMAGE_CLASSIFI return this.CLASSIFY(model, imageData) } - /** Imagen del canvas reducida a 28×28 (entrada del modelo), sin dibujar en el canvas. */ + /** Imagen del canvas reducida al tamaño de las del conjunto (entrada del modelo), sin dibujar en el canvas */ async GET_IMAGE_DATA(canvas: HTMLCanvasElement, _canvas_ctx: CanvasRenderingContext2D): Promise { - return toImageData(canvas, 28, 28) + return toImageData(canvas, this.IMAGE.width, this.IMAGE.height) } /** @@ -63,7 +78,7 @@ export default abstract class I_MODEL_IMAGE_28X28 extends I_MODEL_IMAGE_CLASSIFI imageData: ImageData, options: { layerNames?: string[]; includeInput?: boolean } = {}, ) { - return _activationsHelpers.GET_ACTIVATIONS_IMAGE(model, imageData, options) + return this.activations.GET_ACTIVATIONS_IMAGE(model, imageData, options) } /** @@ -94,7 +109,7 @@ export default abstract class I_MODEL_IMAGE_28X28 extends I_MODEL_IMAGE_CLASSIFI // LRP se inicializa con el LOGIT pre-softmax de la clase objetivo, // no con las probabilidades (Montavon et al. 2019, §10.2.1). - // Como la softmax va fusionada en la última Dense, recalculamos z = x·W + b. + // Como la softmax va fusionada en la última Dense, recalculamos z = x × W + b. const lastLayer = model.getLayer(lastLayerName) const prevData = activations.layers[orderReversed[1]] const xLast = tfjs.tensor(prevData.data, prevData.shape) @@ -137,63 +152,13 @@ export default abstract class I_MODEL_IMAGE_28X28 extends I_MODEL_IMAGE_CLASSIFI }) } - async TRAIN_MODEL(params: ParamsTrainImage_t): Promise<{ model: tfjs.Sequential, history: tfjs.History }> { - return trainImageClassifier(this.DATASET, this.CLASS_LABELS, params) + /** Dataset (ya descargado si se ha entrenado): sus imágenes de test se pueden clasificar desde el selector */ + async LOAD_DATASET(): Promise { + // Solo las imágenes de test: es lo que enseña el selector (si el entero ya se cargó al entrenar, se usa ese) + return loadSpriteDataset(await this.SPRITE(), { testOnly: true }) } - DEFAULT_LAYERS(): Layer_t[] { - return [ - { - _class : 'conv2d', - _protected: true, - inputShape: [28, 28, 1], - kernelSize: 3, - filters : 16, - activation: 'relu', - }, - { - _class : 'maxPooling2d', - _protected: false, - poolSize : 2, - strides : 2, - }, - { - _class : 'conv2d', - _protected: false, - - kernelSize: 3, - filters : 32, - activation: 'relu' - }, - { - _class : 'maxPooling2d', - _protected: false, - poolSize : 2, - strides : 2, - }, - { - _class : 'conv2d', - _protected: false, - kernelSize: 3, - filters : 32, - activation: 'relu' - }, - { - _class : 'flatten', - _protected: false, - }, - { - _class : 'dense', - _protected: false, - units : 64, - activation: 'relu' - }, - { - _class : 'dense', - _protected: false, - units : 10, - activation: 'softmax' - } - ] + async TRAIN_MODEL(params: ParamsTrainImage_t, progress: TrainProgress_t = {}): Promise<{ model: tfjs.Sequential, history: tfjs.History, evaluation: ClassificationEvaluation_t }> { + return trainImageClassifier(await this.SPRITE(), this.CLASS_LABELS, params, progress) } } diff --git a/src/pages/playground/3_ImageClassification/models/characterForms.ts b/src/pages/playground/3_ImageClassification/models/characterForms.ts new file mode 100644 index 0000000..c687a34 --- /dev/null +++ b/src/pages/playground/3_ImageClassification/models/characterForms.ts @@ -0,0 +1,48 @@ +import type { N4LTask_t } from '@core/n4l/format' +import { n4lImageExamples } from '@core/n4l/imageClassification' + +/** Una forma antigua de un carácter: su imagen y el kanji del que viene */ +export type OldForm_t = { + /** Dirección de la imagen */ + image : string + origin: string +} + +/** Un carácter que se escribía de varias formas: cómo es hoy y sus formas antiguas, para enseñarlas juntas */ +export type CharacterForms_t = { + /** El carácter de hoy */ + char : string + /** Cómo se lee (en rōmaji) */ + reading: string + /** El kanji del que viene la forma de hoy */ + origin : string + /** Dirección de la imagen del carácter de hoy */ + modern : string + /** Formas antiguas: las FEATURED_FORMS primeras se enseñan en los ejemplos; todas, en la información del modelo */ + old : OldForm_t[] +} + +/** Formas antiguas de cada carácter en los ejemplos */ +export const FEATURED_FORMS = 3 + +/** + * Los caracteres de un paquete con formas antiguas (KMNIST): sus clases con cómo se leen (`reading`) y, de sus imágenes + * de ejemplo, la de hoy y las antiguas (`old`), en su orden. null si sus clases no son caracteres. `urlOf`: la + * dirección de cada imagen + */ +export function n4lCharacterForms(section: N4LTask_t, urlOf: (file: string) => string): CharacterForms_t[] | null { + const classes = section.classes ?? [] + if (!classes.some(({ reading }) => reading !== undefined)) return null + const images = n4lImageExamples(section) + return classes.map(({ id, reading = '', origin = '' }) => { + const own = images.filter(({ expected }) => expected === id) + const modern = own.find(({ old }) => old !== true) + return { + char : id, + reading, + origin, + modern: modern === undefined ? '' : urlOf(modern.file), + old : own.filter(({ old }) => old === true).map(({ file, origin: from = '' }) => ({ image: urlOf(file), origin: from })), + } + }) +} diff --git a/src/pages/playground/3_ImageClassification/models/index.ts b/src/pages/playground/3_ImageClassification/models/index.ts index 2bce455..c944695 100644 --- a/src/pages/playground/3_ImageClassification/models/index.ts +++ b/src/pages/playground/3_ImageClassification/models/index.ts @@ -1,15 +1,48 @@ import I_MODEL_IMAGE_CLASSIFICATION from './_model' -import { IC_MODEL_KEYS } from '@/MODEL_KEYS' -import type { ModelRegistry } from '@core/models/modelRegistry' +import { TASKS } from '@/TASKS' +import { withDynamicModels, type ModelRegistry } from '@core/models/modelRegistry' +import { builtinN4LPackage, n4lPackagesOf } from '@core/n4l/catalog' +import { n4lFileUrls, n4lImageExamples, n4lImageRuntime } from '@core/n4l/imageClassification' +import { LOCAL_KEY_PREFIX, openLocalPackage } from '@core/n4l/localPackages' +import type { N4LPackage_t } from '@core/n4l/source' +import type { TFunction } from 'i18next' -/** Clases de modelos de clasificación de imágenes, cargadas bajo demanda. */ -const MAP_IC_CLASSES: ModelRegistry = { - [IC_MODEL_KEYS.MNIST] : () => import('./MODEL_IMAGE_MNIST').then((m) => m.default), - [IC_MODEL_KEYS.KMNIST] : () => import('./MODEL_IMAGE_KMNIST').then((m) => m.default), - [IC_MODEL_KEYS.MOBILENET]: () => import('./MODEL_IMAGE_MOBILENET').then((m) => m.default), - [IC_MODEL_KEYS.RESNET] : () => import('./MODEL_IMAGE_RESNET').then((m) => m.default), +/** + * La clase de un paquete .n4l, según cómo se usa: MODEL_N4L (un modelo de TF.js con su sprite de imágenes) o + * MODEL_N4L_MOBILENET, con ese paquete y la dirección de sus imágenes de ejemplo (se descarga al usarla, como las demás) + */ +const n4lModelClass = (open: () => Promise) => async () => { + const pkg = await open() + const runtime = n4lImageRuntime(pkg.manifest) + const urls = await n4lFileUrls(pkg.source, n4lImageExamples(runtime.section).map(({ file }) => file)) + if (runtime.kind === 'mobilenet') { + const mobilenet = runtime + const { default: MODEL_N4L_MOBILENET } = await import('./MODEL_N4L_MOBILENET') + return class extends MODEL_N4L_MOBILENET { + constructor(t: TFunction<'translation', undefined>) { + super(t, pkg, mobilenet, urls) + } + } + } + const sprite = runtime + const { default: MODEL_N4L } = await import('./MODEL_N4L') + return class extends MODEL_N4L { + constructor(t: TFunction<'translation', undefined>) { + super(t, pkg, sprite, urls) + } + } } +/** + * Clases de modelos de clasificación de imágenes, cargadas bajo demanda: los paquetes .n4l de la aplicación y, como + * local-, los que haya abierto el usuario + */ +const MAP_IC_CLASSES: ModelRegistry = withDynamicModels( + Object.fromEntries(n4lPackagesOf(TASKS.IMAGE_CLASSIFICATION).map(({ entry, section }) => + [section.key, n4lModelClass(async () => builtinN4LPackage(entry))])), + (key) => (key.startsWith(LOCAL_KEY_PREFIX) ? n4lModelClass(() => openLocalPackage(key.slice(LOCAL_KEY_PREFIX.length))) : undefined), +) + export { MAP_IC_CLASSES, I_MODEL_IMAGE_CLASSIFICATION, diff --git a/src/pages/playground/3_ImageClassification/models/n4lLayers.ts b/src/pages/playground/3_ImageClassification/models/n4lLayers.ts new file mode 100644 index 0000000..05642e6 --- /dev/null +++ b/src/pages/playground/3_ImageClassification/models/n4lLayers.ts @@ -0,0 +1,44 @@ +import type { N4LLayer_t } from '@core/n4l/format' +import type { ImageLayer_t } from '@/types/types' +import type { SpriteImage_t } from './spriteDecode' + +/** + * Las capas del manifiesto como las edita la aplicación: la primera recibe las imágenes del conjunto (`image`); las + * «locked», protegidas + */ +export function imageLayersOf(layers: N4LLayer_t[], { width, height, channels }: SpriteImage_t): ImageLayer_t[] { + return layers.flatMap((layer, index): ImageLayer_t[] => { + // Las recurrentes son de las series temporales: una red de imágenes no las tiene + if (layer.class === 'simpleRNN' || layer.class === 'lstm' || layer.class === 'gru') return [] + const base: ImageLayer_t = { _class: layer.class, _protected: layer.locked ?? false, ...(index === 0 && { inputShape: [height, width, channels] }) } + switch (layer.class) { + case 'conv2d': + return [{ ...base, filters: layer.filters, kernelSize: layer.kernelSize, activation: layer.activation }] + case 'maxPooling2d': + return [{ ...base, poolSize: layer.poolSize, strides: layer.strides }] + case 'dense': + return [{ ...base, units: layer.units, activation: layer.activation }] + default: + return [base] + } + }) +} + +/** Las capas del editor como en el manifiesto (para guardar un modelo entrenado en un .n4l) */ +export function n4lLayersOf(layers: ImageLayer_t[]): N4LLayer_t[] { + return layers.flatMap((layer): N4LLayer_t[] => { + const locked = layer._protected === true ? { locked: true } : {} + switch (layer._class) { + case 'conv2d': + return [{ class: 'conv2d', filters: layer.filters ?? 1, kernelSize: layer.kernelSize ?? 1, activation: layer.activation ?? 'linear', ...locked }] + case 'maxPooling2d': + return [{ class: 'maxPooling2d', poolSize: layer.poolSize ?? 2, strides: layer.strides ?? 2, ...locked }] + case 'flatten': + return [{ class: 'flatten', ...locked }] + case 'dense': + return [{ class: 'dense', units: layer.units ?? 1, activation: layer.activation ?? 'linear', ...locked }] + default: + return [] + } + }) +} diff --git a/src/pages/playground/3_ImageClassification/models/sprite.worker.ts b/src/pages/playground/3_ImageClassification/models/sprite.worker.ts new file mode 100644 index 0000000..f703362 --- /dev/null +++ b/src/pages/playground/3_ImageClassification/models/sprite.worker.ts @@ -0,0 +1,8 @@ +// Worker que decodifica los sprites de imágenes fuera del hilo principal (TODO-worker.md, fase 3) +import { exposeWorker } from '@core/workers/exposeWorker' +import { decodeSpriteRows } from './spriteDecode' + +export const spriteWorkerApi = { decode: decodeSpriteRows } +export type SpriteWorkerApi_t = typeof spriteWorkerApi + +exposeWorker(spriteWorkerApi) diff --git a/src/pages/playground/3_ImageClassification/models/spriteDecode.ts b/src/pages/playground/3_ImageClassification/models/spriteDecode.ts new file mode 100644 index 0000000..484a4a9 --- /dev/null +++ b/src/pages/playground/3_ImageClassification/models/spriteDecode.ts @@ -0,0 +1,47 @@ +// Decodificación de los sprites de imágenes (una imagen aplanada por fila del PNG: 784 px de ancho las de 28×28, 1024 +// las de 32×32), común al worker y al camino del hilo principal. + +/** Cómo es cada imagen del sprite: ancho y alto en píxeles y canales (1, gris; 3, color RGB) */ +export type SpriteImage_t = { width: number, height: number, channels: number } + +/** Valores de cada imagen (lo que recibe la red por imagen) */ +export const spriteImageValues = ({ width, height, channels }: SpriteImage_t) => width * height * channels + +// Filas del sprite que se leen de cada vez a través del canvas (un canvas no puede medir 65 000 px de alto) +export const CHUNK_SIZE = 5000 + +/** + * Píxeles RGBA de un trozo del sprite → valores 0–1: en gris basta con el canal rojo; en color, R, G y B de cada píxel + * seguidos (como los espera la red: alto, ancho y canal) + */ +export function copyChannels(rgba: Uint8ClampedArray, target: Float32Array, offset: number, channels: number) { + const pixels = rgba.length / 4 + for (let j = 0; j < pixels; j++) { + for (let c = 0; c < channels; c++) target[offset + j * channels + c] = rgba[j * 4 + c] / 255 + } +} + +export type SpriteRows_t = { url: string, firstRow: number, numRows: number, image: SpriteImage_t } + +/** Las filas [firstRow, firstRow + numRows) del sprite, decodificadas en un worker con OffscreenCanvas */ +export async function decodeSpriteRows({ url, firstRow, numRows, image }: SpriteRows_t): Promise { + const response = await fetch(url) + if (!response.ok) throw new Error(`Could not load dataset images: ${url} (${response.status})`) + const bitmap = await createImageBitmap(await response.blob(), { colorSpaceConversion: 'none', premultiplyAlpha: 'none' }) + try { + const values = spriteImageValues(image) + const images = new Float32Array(numRows * values) + const canvas = new OffscreenCanvas(bitmap.width, Math.min(CHUNK_SIZE, numRows)) + const context = canvas.getContext('2d', { willReadFrequently: true }) + if (context === null) throw new Error('OffscreenCanvas 2D context not available') + for (let row = 0; row < numRows; row += CHUNK_SIZE) { + const rows = Math.min(CHUNK_SIZE, numRows - row) + context.clearRect(0, 0, canvas.width, canvas.height) + context.drawImage(bitmap, 0, firstRow + row, bitmap.width, rows, 0, 0, bitmap.width, rows) + copyChannels(context.getImageData(0, 0, bitmap.width, rows).data, images, row * values, image.channels) + } + return images + } finally { + bitmap.close() + } +} diff --git a/src/pages/playground/3_ImageClassification/utils/imagePrediction.ts b/src/pages/playground/3_ImageClassification/utils/imagePrediction.ts new file mode 100644 index 0000000..c4ead32 --- /dev/null +++ b/src/pages/playground/3_ImageClassification/utils/imagePrediction.ts @@ -0,0 +1,15 @@ +import { argMax } from '@core/nn-utils/classificationOutput' + +/** Resultado de clasificar un dibujo con uno de los modelos entrenados */ +export type ImagePrediction_t = { + /** Salida del modelo para cada clase */ + values : number[] + /** Clase elegida: la de mayor valor */ + index : number + /** Modelo de la tabla (desde 0) que ha hecho la predicción */ + modelIndex: number +} + +export function makeImagePrediction(values: number[], modelIndex: number): ImagePrediction_t { + return { values, index: argMax(values), modelIndex } +} diff --git a/src/pages/playground/3_ImageClassification/utils/utils.ts b/src/pages/playground/3_ImageClassification/utils/utils.ts index a898065..072bda6 100644 --- a/src/pages/playground/3_ImageClassification/utils/utils.ts +++ b/src/pages/playground/3_ImageClassification/utils/utils.ts @@ -1,5 +1,7 @@ import * as tfjs from '@tensorflow/tfjs' +import type { SpriteImage_t } from '../models/spriteDecode' + export const UTILS_image = { failed : (event: Event) => console.error(event), /** @@ -113,9 +115,69 @@ export function thresholdImageData(image: ImageData, threshold = 100): ImageData return result } +/** + * Imagen de un dataset de 28×28 (valores 0 fondo, 1 trazo) como ImageData opaca con el trazo oscuro sobre fondo + * claro, como los dibujos: `imageDataToMnistTensor4d` la vuelve a dar exactamente con esos valores. + */ +export function grayscaleToImageData(pixels: Float32Array, width: number, height: number): ImageData { + const result = createImageData(width, height) + for (let i = 0; i < pixels.length; i++) { + const value = Math.round(255 * (1 - pixels[i])) + result.data.set([value, value, value, 255], i * 4) + } + return result +} + +/** + * Imagen de un sprite (sus valores 0–1) como ImageData opaca: en gris, con el trazo oscuro sobre fondo claro, como los + * dibujos (grayscaleToImageData); en color, tal cual. `imageDataToTensor4d` la vuelve a dar exactamente + */ +export function spriteToImageData(pixels: Float32Array, { width, height, channels }: SpriteImage_t): ImageData { + if (channels === 1) return grayscaleToImageData(pixels, width, height) + const result = createImageData(width, height) + for (let i = 0; i < width * height; i++) { + for (let c = 0; c < 3; c++) result.data[i * 4 + c] = Math.round(255 * pixels[i * channels + Math.min(c, channels - 1)]) + result.data[i * 4 + 3] = 255 + } + return result +} + +/** + * Entrada de una red en color (1×alto×ancho×3): RGB entre 0 y 1. Lo transparente cuenta como blanco (sobre el fondo + * blanco de la página) + */ +export function imageDataToRgbTensor4d(imageData: ImageData): tfjs.Tensor4D { + const { data, width, height } = imageData + const values = new Float32Array(width * height * 3) + for (let i = 0, p = 0; p < data.length; i++, p += 4) { + const alpha = data[p + 3] / 255 + for (let c = 0; c < 3; c++) values[i * 3 + c] = (data[p + c] / 255) * alpha + (1 - alpha) + } + return tfjs.tensor4d(values, [1, height, width, 3]) +} + +/** Entrada de una red de imágenes según sus canales: en gris, como MNIST; en color, RGB */ +export const imageDataToTensor4d = (imageData: ImageData, channels: number): tfjs.Tensor4D => + (channels === 1 ? imageDataToMnistTensor4d(imageData) : imageDataToRgbTensor4d(imageData)) + +/** ImageData ampliada (sin suavizar) como data URL, p. ej. para la imagen base de la explicación */ +export function imageDataToDataUrl(imageData: ImageData, size: number): string { + const source = document.createElement('canvas') + source.width = imageData.width + source.height = imageData.height + source.getContext('2d')?.putImageData(imageData, 0, 0) + const canvas = document.createElement('canvas') + canvas.width = size + canvas.height = size + const ctx = canvas.getContext('2d') as CanvasRenderingContext2D + ctx.imageSmoothingEnabled = false + ctx.drawImage(source, 0, 0, size, size) + return canvas.toDataURL() +} + /** * Entrada de los modelos MNIST/KMNIST (1×28×28×1), sin modificar `imageData`. - * El modelo espera el trazo en blanco (1) sobre fondo negro (0): valor = (1 − rojo) · alfa. + * El modelo espera el trazo en blanco (1) sobre fondo negro (0): valor = (1 − rojo) × alfa. * - Imagen opaca con dígito oscuro sobre fondo claro → 1 − rojo. * - Dibujo en el lienzo (trazo negro sobre fondo transparente) → alfa. */ diff --git a/src/pages/playground/4_Clustering/Clustering.tsx b/src/pages/playground/4_Clustering/Clustering.tsx new file mode 100644 index 0000000..ed82573 --- /dev/null +++ b/src/pages/playground/4_Clustering/Clustering.tsx @@ -0,0 +1,328 @@ +import { useEffect, useEffectEvent, useMemo, useState } from 'react' +import { Alert, Badge, Button, Card, Col, Container, Form, Row, Table } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' + +import { TASKS, UPLOAD } from '@/TASKS' +import { taskOptions } from '@/TASK_OPTIONS' +import { DataFrameReadCSV } from '@core/dataframe/DataFrameUtils' +import { DATASET_ACCEPT } from '@core/dataframe/datasetFormats' +import { readDatasetInWorker } from '@core/dataframe/datasetReaderClient' +import { compareWithLabels, elbow, kmeans, pca2, silhouette, standardize, type KMeansResult_t } from '@core/clustering/kmeans' +import { trackEvent } from '@core/analytics' +import { variableTables } from '@pages/datasets/datasetVariables' +import { datasetKey, projectDatasetByKey } from '@pages/analyze/projectDatasets' +import { useProjectDatasetUpload } from '@hooks/useProjectDatasetUpload' +import DragAndDrop from '@components/dragAndDrop/DragAndDrop' +import N4LPageHeader from '@components/neural-network/N4LPageHeader' +import N4LEmptyState from '@components/loading/N4LEmptyState' +import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +import N4LNumberField from '@components/form/N4LNumberField' +import { ClusterScatter, ElbowChart } from './ClusteringCharts' +import ClusteringComparison from './ClusteringComparison' +import { clusterColor } from './clusterColors' +import { useTheme } from '@hooks/useTheme' + +const prefix = 'pages.playground.clustering.' +/** k del codo: de 1 a 8 grupos */ +const ELBOW_KS = [1, 2, 3, 4, 5, 6, 7, 8] +const MIN_K = 2 +const MAX_K = 10 + +/** Los datos: nombres de columna, filas (texto tal cual) y qué columnas son numéricas */ +type Table_t = { columns: string[], rows: unknown[][], numeric: boolean[] } + +type Run_t = { + result : KMeansResult_t + /** Las filas usadas (sin las que tenían algún valor vacío en las columnas elegidas) */ + used : number[] + /** Puntos con los que se agrupó (escalados o no) */ + points : number[][] + silhouette : number + elbow : { k: number, inertia: number }[] + features : string[] + labelColumn: string | null +} + +/** + * Agrupar (clustering) con k-means: se eligen las columnas y el número de grupos (k), y se ven los grupos en 2D, cómo se + * forman iteración a iteración, la silueta, el codo y, si el conjunto trae las clases reales, cuánto se parecen. + */ +export default function Clustering({ dataset }: { dataset: string }) { + const { t, i18n } = useTranslation() + const theme = useTheme() + const option = taskOptions(TASKS.CLUSTERING, 'dataset').find(({ value }) => value === dataset) + const file = option?.info?.files?.[0] + const [table, setTable] = useState(null) + // El nombre del fichero subido (o cargado desde /datasets), para el título + const [uploadedName, setUploadedName] = useState(null) + const [error, setError] = useState(false) + + // Las columnas que se usan, si se escalan, la de las etiquetas reales (opcional), k y la semilla + const [features, setFeatures] = useState([]) + const [labelColumn, setLabelColumn] = useState(null) + const [scale, setScale] = useState(true) + const [k, setK] = useState(3) + const [seed, setSeed] = useState(1) + const [run, setRun] = useState(null) + const [step, setStep] = useState(0) + const [isPlaying, setIsPlaying] = useState(false) + + const number = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 3 }), [i18n.language]) + + /** Al tener los datos: columnas numéricas de entrada y, según su ficha, la de las clases reales */ + const loadTable = (columns: string[], rows: unknown[][], dtypes: string[], sourceFile?: string) => { + const numeric = dtypes.map((dtype) => dtype === 'float32' || dtype === 'int32') + const variables = sourceFile === undefined ? undefined : variableTables([sourceFile])[0]?.variables + const roleOf = (column: string) => variables?.find(({ name }) => name === column.trim())?.role + // La de las clases: la que su ficha describe como objetivo o, si no, la última de texto con pocos valores + const distinct = (column: string) => new Set(rows.map((row) => String(row[columns.indexOf(column)]))).size + const target = columns.find((column) => roleOf(column) === 'Target') + ?? [...columns].reverse().find((column) => !numeric[columns.indexOf(column)] && distinct(column) >= MIN_K && distinct(column) <= MAX_K) + ?? null + setTable({ columns, rows, numeric }) + setLabelColumn(target) + setFeatures(columns.filter((column, index) => numeric[index] && column !== target && roleOf(column) !== 'ID')) + if (target !== null) setK(Math.min(MAX_K, distinct(target))) + setRun(null) + } + + const onLoaded = useEffectEvent(loadTable) + useEffect(() => { + if (dataset === UPLOAD || file === undefined) return + let isCancelled = false + DataFrameReadCSV(import.meta.env.VITE_PATH + '/' + file) + .then((dataframe) => { + if (!isCancelled) onLoaded(dataframe.columns, dataframe.values as unknown[][], dataframe.dtypes as string[], file) + }) + .catch((reason: unknown) => { + console.error(reason) + if (!isCancelled) setError(true) + }) + return () => { isCancelled = true } + }, [dataset, file]) + + const handleUpload = async (files: File[]) => { + if (files.length !== 1) return + try { + const { columns, rows, dtypes } = await readDatasetInWorker(files[0]) + // Un CSV del proyecto (desde /datasets, o descargado y vuelto a subir): con su ficha, sin agrupar por su identificador + loadTable(columns, rows, dtypes, projectDatasetByKey(datasetKey(files[0].name))?.file) + setUploadedName(files[0].name) + setError(false) + } catch (reason) { + console.error(reason) + setError(true) + } + } + + // Desde «Agrupar» en /datasets (?dataset=wdbc): se carga como si se hubiera subido + useProjectDatasetUpload(TASKS.CLUSTERING, dataset === UPLOAD, (files) => { void handleUpload(files) }) + + // La columna de las clases no se usa para agrupar, aunque sea numérica y estuviera marcada + const chosen = features.filter((feature) => feature !== labelColumn) + const handleRun = (withSeed = seed) => { + if (table === null || chosen.length === 0) return + const indices = chosen.map((feature) => table.columns.indexOf(feature)) + const used: number[] = [] + const raw: number[][] = [] + table.rows.forEach((row, index) => { + const values = indices.map((column) => Number(row[column])) + if (values.every(Number.isFinite)) { + used.push(index) + raw.push(values) + } + }) + if (raw.length < k) return + const points = scale ? standardize(raw) : raw + const result = kmeans(points, { k, seed: withSeed }) + setRun({ + result, used, points, features : chosen, labelColumn, + silhouette: silhouette(points, result.assignments, { seed: withSeed }), + elbow : elbow(points, ELBOW_KS.filter((value) => value <= raw.length), withSeed), + }) + setStep(result.steps.length - 1) + setIsPlaying(false) + trackEvent('cluster_run', { k, features: chosen.length, scaled: scale, rows: raw.length }) + } + + // Ver cómo se forman los grupos: de la iteración 0 (los centroides iniciales) a la última + // Se para sola al llegar a la última + const isAnimating = isPlaying && run !== null && step < run.result.steps.length - 1 + useEffect(() => { + if (!isAnimating) return + const timer = window.setTimeout(() => setStep((current) => current + 1), 700) + return () => window.clearTimeout(timer) + }, [isAnimating, step]) + + const projection = useMemo(() => (run === null ? null : pca2(run.points)), [run]) + const projected = useMemo(() => (run === null || projection === null ? [] : run.points.map(projection.project)), [run, projection]) + const comparison = useMemo(() => { + if (run === null || run.labelColumn === null || table === null) return null + const column = table.columns.indexOf(run.labelColumn) + return compareWithLabels(run.result.assignments, run.used.map((index) => String(table.rows[index][column])), run.result.centroids.length) + }, [run, table]) + // Cómo es cada grupo: cuántas filas y la media de cada columna, en sus unidades (sin escalar) + const profiles = useMemo(() => { + if (run === null || table === null) return [] + return run.result.centroids.map((_centroid, cluster) => { + const members = run.used.filter((_index, position) => run.result.assignments[position] === cluster) + const means = run.features.map((feature) => { + const column = table.columns.indexOf(feature) + return members.reduce((sum, index) => sum + Number(table.rows[index][column]), 0) / Math.max(1, members.length) + }) + return { size: members.length, means } + }) + }, [run, table]) + + const silhouetteLevel = run === null ? null : run.silhouette > 0.5 ? 'good' : run.silhouette > 0.25 ? 'fair' : 'weak' + const toggleFeature = (feature: string) => + setFeatures((current) => (current.includes(feature) ? current.filter((item) => item !== feature) : [...current, feature])) + const datasetTitle = uploadedName ?? (option !== undefined ? t(option.i18n) : dataset) + + return ( + + } guideId={'clustering.' + dataset} guideSteps={null} className={'mt-2'} /> +

    {t(prefix + 'intro')}

    + + {dataset === UPLOAD && + +

    {t(prefix + 'upload')}

    + + + +
    } + {error && {t('error.file-upload')}} + {table === null && dataset !== UPLOAD && !error && } + + {table !== null && + + +

    {datasetTitle}

    + +

    {t(prefix + 'rows', { count: table.rows.length })}

    +
    + {t(prefix + 'features')} + {table.columns.map((column, index) => table.numeric[index] && column !== labelColumn && ( + toggleFeature(column)} /> + ))} + {t(prefix + 'features-help')} +
    + + {t(prefix + 'label')} + setLabelColumn(event.target.value === '' ? null : event.target.value)}> + + {table.columns.map((column) => )} + + {t(prefix + 'label-help')} + + setScale(!scale)} /> + {t(prefix + 'scale-help')} + +
    + + {run !== null && + } +
    +
    +
    + + + + {run === null && } + {run !== null && projection !== null && <> + + + +
    {t(prefix + 'groups')}
    {run.result.centroids.length}
    +
    {t(prefix + 'iterations')}
    {run.result.steps.length - 1}
    +
    {t(prefix + 'inertia')}
    {number.format(run.result.inertia)}
    +
    {t(prefix + 'silhouette')}
    {number.format(run.silhouette)}
    +
    +

    {t(prefix + 'silhouette-' + silhouetteLevel)}

    +
    +
    + + + +

    {t(prefix + 'scatter-title')}

    +
    + + { + setIsPlaying(false) + setStep(Number(event.target.value)) + }} /> + {t(prefix + 'iteration', { number: step })} +
    +
    + + +

    {t(prefix + 'scatter-help')}

    +
    +
    + + {comparison !== null && } + + + + +

    {t(prefix + 'elbow-title')}

    + + +

    {t(prefix + 'elbow-help')}

    +
    +
    + + + +

    {t(prefix + 'profiles-title')}

    + + {/* Una fila por columna y una columna por grupo: con muchas columnas (el vino tiene 13) cabe igual */} + {/* Con muchos grupos se desplaza: con el teclado también */} +
    + + + + + {profiles.map((_profile, cluster) => ( + + ))} + + + + + + {profiles.map(({ size }, cluster) => )} + + {run.features.map((feature, index) => ( + + + {profiles.map(({ means }, cluster) => )} + + ))} + +
    {t(prefix + 'variable')} + + {t(prefix + 'cluster', { number: cluster + 1 })} +
    {t(prefix + 'size')}{size}
    {feature}{number.format(means[index])}
    +
    +

    {t(prefix + 'profiles-help')}

    +
    +
    + +
    + } + +
    } +
    + ) +} diff --git a/src/pages/playground/4_Clustering/ClusteringCharts.tsx b/src/pages/playground/4_Clustering/ClusteringCharts.tsx new file mode 100644 index 0000000..e0cc78e --- /dev/null +++ b/src/pages/playground/4_Clustering/ClusteringCharts.tsx @@ -0,0 +1,103 @@ +import { useMemo } from 'react' +import { Line, Scatter } from 'react-chartjs-2' +import { useTranslation } from 'react-i18next' + +import type { KMeansStep_t, Point_t } from '@core/clustering/kmeans' +import { useTheme } from '@hooks/useTheme' + +import { chartColor, withAlpha } from '@core/chartColors' +import N4LChartData from '@components/chart/N4LChartData' + +import { clusterColor } from './clusterColors' +import { prefersReducedMotion } from '@core/a11y/displaySettings' + +const prefix = 'pages.playground.clustering.' + +// Una forma de punto por grupo, además del color (WCAG 1.4.1); la cruz es de los centroides +const POINT_STYLES = ['circle', 'triangle', 'rect', 'rectRot', 'star', 'rectRounded', 'cross', 'dash', 'line', 'circle'] as const + +type ScatterProps = { + /** Los puntos ya proyectados a 2D */ + points : [number, number][] + step : KMeansStep_t + project : (point: Point_t) => [number, number] + /** Varianza que recoge cada eje (PCA) */ + explained: [number, number] +} + +/** Los puntos en 2D (PCA), coloreados por grupo en una iteración, con sus centroides */ +export function ClusterScatter({ points, step, project, explained }: ScatterProps) { + const { t, i18n } = useTranslation() + const theme = useTheme() + // Los centroides, del color del texto: negros en claro y casi blancos en oscuro + const centroidColor = theme === 'dark' ? '#dee2e6' : '#000000' + const percent = useMemo(() => new Intl.NumberFormat(i18n.language, { style: 'percent', maximumFractionDigits: 0 }), [i18n.language]) + const k = step.centroids.length + const datasets = [ + ...Array.from({ length: k }, (_value, cluster) => ({ + label : t(prefix + 'cluster', { number: cluster + 1 }), + data : points.filter((_point, index) => step.assignments[index] === cluster).map(([x, y]) => ({ x, y })), + backgroundColor: withAlpha(clusterColor(cluster, theme), 0.67), + borderColor : clusterColor(cluster, theme), + pointStyle : POINT_STYLES[cluster % POINT_STYLES.length], + pointRadius : 4, + })), + { + label : t(prefix + 'centroids'), + data : step.centroids.map((centroid) => project(centroid)).map(([x, y]) => ({ x, y })), + backgroundColor: centroidColor, + borderColor : centroidColor, + pointStyle : 'crossRot' as const, + pointRadius : 9, + borderWidth : 3, + }, + ] + // Para quien no ve la gráfica: cuántas filas tiene cada grupo + const description = Array.from({ length: k }, (_value, cluster) => + `${t(prefix + 'cluster', { number: cluster + 1 })}: ${t(prefix + 'rows', { count: step.assignments.filter((assigned) => assigned === cluster).length })}`).join(', ') + const axis = (number: number) => t(prefix + 'axis', { number, variance: percent.format(explained[number - 1]) }) + return <> + + {/* Los grupos con sus filas y dónde queda su centroide en la gráfica */} + { + const [x, y] = project(centroid) + return [t(prefix + 'cluster', { number: cluster + 1 }), step.assignments.filter((assigned) => assigned === cluster).length, x, y] + })} /> + +} + +/** El codo: la inercia para cada k, con la elegida resaltada */ +export function ElbowChart({ values, k }: { values: { k: number, inertia: number }[], k: number }) { + const { t, i18n } = useTranslation() + const theme = useTheme() + const number = new Intl.NumberFormat(i18n.language, { maximumSignificantDigits: 4 }) + const description = values.map((value) => `k = ${value.k}: ${number.format(value.inertia)}`).join(', ') + return <> + value.k), + datasets: [{ + label : t(prefix + 'inertia'), + data : values.map((value) => value.inertia), + borderColor : chartColor('blue', theme), + backgroundColor: chartColor('blue', theme), + pointRadius : values.map((value) => (value.k === k ? 7 : 3)), + }], + }} options={{ + animation : false, + responsive: true, + scales : { x: { title: { display: true, text: 'k' } }, y: { title: { display: true, text: t(prefix + 'inertia') } } }, + }} /> + [value.k, value.inertia])} /> + +} diff --git a/src/pages/playground/4_Clustering/ClusteringComparison.tsx b/src/pages/playground/4_Clustering/ClusteringComparison.tsx new file mode 100644 index 0000000..d55ec44 --- /dev/null +++ b/src/pages/playground/4_Clustering/ClusteringComparison.tsx @@ -0,0 +1,112 @@ +import { useMemo } from 'react' +import { Badge, Card, Table } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import type { LabelComparison_t } from '@core/clustering/kmeans' +import HelpTerm from '@components/helpLink/N4LHelpTerm' + +import { clusterColor } from './clusterColors' +import { useTheme } from '@hooks/useTheme' + +const prefix = 'pages.playground.clustering.' + +/** Cómo leer el índice de Rand ajustado: a partir de qué valor cada frase */ +const ARI_LEVELS: [number, string][] = [[0.8, 'high'], [0.5, 'medium'], [0.2, 'low']] + +/** Fondo de una celda: más intenso cuanto mayor parte del grupo es de esa clase */ +const cellBackground = (count: number, size: number) => + count === 0 || size === 0 ? undefined : `rgba(var(--bs-success-rgb), ${(0.1 + 0.5 * (count / size)).toFixed(2)})` + +type ClusteringComparisonProps = { + comparison : LabelComparison_t + /** La columna con las clases reales */ + labelColumn: string +} + +/** + * Los grupos frente a las clases reales, como una matriz de confusión: cuántas filas de cada clase hay en cada grupo y + * qué parte del grupo son, la clase mayoritaria de cada grupo (y si es una mezcla), los totales, la pureza y el índice + * de Rand ajustado con lo que quieren decir + */ +export default function ClusteringComparison({ comparison, labelColumn }: ClusteringComparisonProps) { + const { t, i18n } = useTranslation() + const theme = useTheme() + const percent = useMemo(() => new Intl.NumberFormat(i18n.language, { style: 'percent', maximumFractionDigits: 0 }), [i18n.language]) + const percentPrecise = useMemo(() => new Intl.NumberFormat(i18n.language, { style: 'percent', maximumFractionDigits: 1 }), [i18n.language]) + const number = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 3 }), [i18n.language]) + const { classes, table, classTotals, groups, purity, ari } = comparison + const rows = classTotals.reduce((sum, total) => sum + total, 0) + const ariLevel = ARI_LEVELS.find(([minimum]) => ari >= minimum)?.[1] ?? 'none' + const title = t(prefix + 'comparison-title', { column: labelColumn }) + + return ( + +

    {title}

    + +

    {t(prefix + 'comparison-help')}

    + +
    +
    +
    +
    {percentPrecise.format(purity)}
    +
    +
    +
    +
    {number.format(ari)}
    +
    +

    {t(prefix + 'ari-' + ariLevel)}

    +
    + + {/* Con muchas clases se desplaza: con el teclado también */} +
    + + + + + + + + + {classes.map((name) => )} + + + {table.map((row, cluster) => { + const { size, majority, share, isMixed } = groups[cluster] + return ( + + + {row.map((count, column) => ( + + ))} + + + + ) + })} + + + + + {classTotals.map((total, column) => )} + + + + +
    {t(prefix + 'group')}{labelColumn}{t(prefix + 'size')}{t(prefix + 'majority')}
    {name}
    + + {t(prefix + 'cluster', { number: cluster + 1 })} + + {count} + {count > 0 && {percent.format(count / size)}} + {size} + {size === 0 ? '—' : <> + {classes[majority]} ({percent.format(share)}) + {isMixed && {t(prefix + 'mixed')}} + } +
    {t(prefix + 'total')}{total}{rows}{t(prefix + 'purity')}: {percentPrecise.format(purity)}
    +
    +

    {t(prefix + 'comparison-legend')}

    +
    +
    + ) +} diff --git a/src/pages/playground/4_Clustering/clusterColors.ts b/src/pages/playground/4_Clustering/clusterColors.ts new file mode 100644 index 0000000..d6f3ab9 --- /dev/null +++ b/src/pages/playground/4_Clustering/clusterColors.ts @@ -0,0 +1,7 @@ +import { categoryColor, type ChartColor_t } from '@core/chartColors' +import type { Theme_t } from '@core/theme' + +/** Un color por grupo (los mismos en todas las gráficas y tablas del agrupamiento), en el tono del tema */ +const CLUSTER_ORDER: readonly ChartColor_t[] = ['blue', 'orange', 'green', 'pink', 'purple', 'teal', 'red', 'yellow', 'cyan', 'gray'] + +export const clusterColor = (cluster: number, theme: Theme_t) => categoryColor(CLUSTER_ORDER, cluster, theme) diff --git a/src/pages/playground/5_TimeSeries/ModelReviewTimeSeries.tsx b/src/pages/playground/5_TimeSeries/ModelReviewTimeSeries.tsx new file mode 100644 index 0000000..2013c57 --- /dev/null +++ b/src/pages/playground/5_TimeSeries/ModelReviewTimeSeries.tsx @@ -0,0 +1,118 @@ +import { useEffect, useMemo, useState } from 'react' +import { Alert, Col, Container, Row } from 'react-bootstrap' +import { Link } from 'react-router' +import { Trans, useTranslation } from 'react-i18next' + +import { TASKS } from '@/TASKS' +import { taskOptions } from '@/TASK_OPTIONS' +import { builtinN4LPackage, n4lPackageByKey } from '@core/n4l/catalog' +import { n4lLayersModels, n4lNamespace } from '@core/n4l/format' +import { loadN4LLayersModel } from '@core/n4l/tfjsModel' +import { trackDownloads } from '@core/downloadProgress' +import { prepareSeries } from '@core/timeSeries/series' +import { evaluateSeriesModel } from '@core/timeSeries/seriesModel' +import N4LPageHeader from '@components/neural-network/N4LPageHeader' +import N4LModelAside from '@components/neural-network/N4LModelAside' +import N4LModelCard from '@components/neural-network/N4LModelCard' +import N4LModelSummaryButton from '@components/neural-network/N4LModelSummaryButton' +import N4LPackageDescription from '@components/n4l/N4LPackageDescription' +import N4LDownloadPackage from '@components/n4l/N4LDownloadPackage' +import N4LDownloadProgress from '@components/loading/N4LDownloadProgress' + +import ModelReviewTimeSeriesDataset from './ModelReviewTimeSeriesDataset' +import ModelReviewTimeSeriesPredict from './ModelReviewTimeSeriesPredict' +import TimeSeriesForecast from './TimeSeriesForecast' +import TimeSeriesTestMetrics from './TimeSeriesTestMetrics' +import { usePackageSeries } from './usePackageSeries' +import { initialPrep, prefix, type ForecastModel_t } from './timeSeriesConfig' +import { timeSeriesReviewGuide } from './modelReviewGuide' + +/** + * El modelo ya entrenado de una serie de un paquete, como las páginas de los modelos de las demás tareas: a la + * izquierda su ficha (el resumen de la red, el paquete, cómo predice lo que no vio y la descripción) y a la derecha la + * serie (tal cual, en una gráfica y preparada para la red), predecir un valor con los anteriores y cómo predice toda + * la parte de prueba y lo que viene después + */ +export default function ModelReviewTimeSeries({ dataset }: { dataset: string }) { + const { t } = useTranslation() + const pkg = useMemo(() => n4lPackageByKey(TASKS.TIME_SERIES, dataset), [dataset]) + const option = useMemo(() => taskOptions(TASKS.TIME_SERIES, 'dataset').find(({ value }) => value === dataset), [dataset]) + const { series, error } = usePackageSeries(pkg, option?.info?.files?.[0]) + const entry = pkg === undefined ? undefined : n4lLayersModels(pkg.section)[0] + const forecast = pkg?.section.forecast + const [loaded, setLoaded] = useState(null) + const [loadError, setLoadError] = useState(false) + const guideSteps = useMemo(() => timeSeriesReviewGuide(t, dataset), [t, dataset]) + + // El modelo (con el progreso de la descarga) y cómo predice la prueba de su serie, preparada como al entrenarlo + useEffect(() => { + if (pkg === undefined || entry === undefined || series === null) return + let isCancelled = false + const run = async () => { + const model = await trackDownloads(() => loadN4LLayersModel(builtinN4LPackage(pkg.entry).source, entry.path), 'model_load') + const prepared = prepareSeries(series.values, initialPrep(series.values.length, series.frequency, forecast).prep) + if (isCancelled) return + setLoaded({ model, prepared, evaluation: null }) + const evaluation = await evaluateSeriesModel(model, series.values, prepared) + if (!isCancelled) setLoaded({ model, prepared, evaluation }) + } + run().catch((reason: unknown) => { + console.error(reason) + if (!isCancelled) setLoadError(true) + }) + return () => { isCancelled = true } + }, [pkg, entry, series, forecast]) + + if (pkg === undefined || entry === undefined) return {t('error.model-selected')} + const ns = n4lNamespace(pkg.entry.id) + const name = t(`${ns}:tasks.time-series.name`) + + return ( + <> + + } guideId={'time-series.' + dataset} guideSteps={guideSteps} className={'mt-2'} /> + + + + + + + + + {(error || loadError) && {t('error.file-upload')}} + + + + + + + + {t(prefix + 'model.train-yours')} + + }> + + + + + + + + {/* La serie: tal cual, en una gráfica con la prueba marcada y preparada para la red */} + + + {series !== null && loaded !== null && + } + + {/* Toda la prueba (a un paso o seguida) frente a las predicciones sencillas, y lo que viene después */} + {series !== null && loaded !== null && +
    + {}} season={forecast?.season} + modelName={t(prefix + 'model.name')} /> +
    } + +
    +
    + + ) +} diff --git a/src/pages/playground/5_TimeSeries/ModelReviewTimeSeriesDataset.tsx b/src/pages/playground/5_TimeSeries/ModelReviewTimeSeriesDataset.tsx new file mode 100644 index 0000000..bda5052 --- /dev/null +++ b/src/pages/playground/5_TimeSeries/ModelReviewTimeSeriesDataset.tsx @@ -0,0 +1,100 @@ +import { useEffect, useMemo, useState } from 'react' +import { Card, Nav, Tab } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' + +import { testStartOf, type PreparedSeries_t } from '@core/timeSeries/series' +import N4LTablePagination from '@components/table/N4LTablePagination' +import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' + +import TimeSeriesChart from './TimeSeriesChart' +import TimeSeriesWindows from './TimeSeriesWindows' +import { prefix, seriesSummary, type LoadedSeries_t } from './timeSeriesConfig' +import { announce } from '@core/a11y/announce' + +type ModelReviewTimeSeriesDatasetProps = { + /** null mientras se carga */ + series : LoadedSeries_t | null + /** Cómo se preparó para el modelo (null hasta tener el modelo) */ + prepared: PreparedSeries_t | null + name : string +} + +const TABS = ['original', 'chart', 'windows'] as const +type Tab_t = typeof TABS[number] + +/** + * La serie del modelo en tres pestañas, como el conjunto de datos de las demás tareas: tal cual (sus fechas y sus + * valores), en una gráfica con la parte de prueba marcada y preparada para la red (las ventanas que recibe y su escala) + */ +export default function ModelReviewTimeSeriesDataset({ series, prepared, name }: ModelReviewTimeSeriesDatasetProps) { + const { t, i18n } = useTranslation() + const [activeTab, setActiveTab] = useState('original') + // Al cargar la serie, lo que tiene (también para el lector de pantalla: WCAG 4.1.3) + const summary = series === null ? '' : seriesSummary(t, series) + useEffect(() => announce(summary), [summary]) + const number = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumSignificantDigits: 4 }), [i18n.language]) + const rows = useMemo(() => (series === null ? [] : series.dates.map((date, i) => [date, series.values[i]])), [series]) + const testStart = series === null || prepared === null ? 0 : testStartOf(series.values.length, prepared.prep.testSize) + const range = (from: number, to: number) => (series === null ? '' : t(prefix + 'data.range', { first: series.dates[from], last: series.dates[to - 1], count: to - from })) + + return ( + + setActiveTab(TABS.find((tab) => tab === key) ?? 'original')}> + + + + + {series === null && } + {series !== null && + +

    + {summary} +

    +
    + +
    +
    + + + {prepared !== null && +

    + +

    } +
    + + {prepared === null && } + {prepared !== null && <> +

    + +

    + + } +
    +
    } +
    +
    +
    + ) +} diff --git a/src/pages/playground/5_TimeSeries/ModelReviewTimeSeriesPredict.tsx b/src/pages/playground/5_TimeSeries/ModelReviewTimeSeriesPredict.tsx new file mode 100644 index 0000000..bd06dfd --- /dev/null +++ b/src/pages/playground/5_TimeSeries/ModelReviewTimeSeriesPredict.tsx @@ -0,0 +1,167 @@ +import { useMemo, useState } from 'react' +import { Button, Card, Col, Form, Row } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' +import type * as tfjs from '@tensorflow/tfjs' + +import { trackEvent } from '@core/analytics' +import { firstTarget, testStartOf, toValue, windowAt, type PreparedSeries_t } from '@core/timeSeries/series' +import { predictWindows } from '@core/timeSeries/seriesModel' +import N4LVirtualSelect, { type VirtualSelectOption_t } from '@components/select/N4LVirtualSelect' +import N4LEmptyState from '@components/loading/N4LEmptyState' +import N4LSummary from '@components/summary/N4LSummary' + +import { prefix as seriesPrefix, type LoadedSeries_t } from './timeSeriesConfig' + +const prefix = seriesPrefix + 'review.' + +type ModelReviewTimeSeriesPredictProps = { + model : tfjs.LayersModel + series : LoadedSeries_t + prepared: PreparedSeries_t +} + +/** Lo que se predijo: con qué valores, el resultado y, si eran los de la serie sin cambiar, el valor real */ +type Result_t = { target: number, inputs: number[], vector: number[], value: number, actual: number | null } + +/** + * Predecir un valor de la serie, como el formulario de las demás tareas: se elige un valor de la serie y el formulario + * se rellena con los anteriores (la ventana; al diferenciar, uno más, para calcular los cambios), que se pueden cambiar. + * Debajo, lo que recibe la red (escalado) y el resultado, con el valor real si los valores son los de la serie + */ +export default function ModelReviewTimeSeriesPredict({ model, series, prepared }: ModelReviewTimeSeriesPredictProps) { + const { t, i18n } = useTranslation() + const { prep, scale } = prepared + const { dates, values } = series + const number = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 3 }), [i18n.language]) + const percent = useMemo(() => new Intl.NumberFormat(i18n.language, { style: 'percent', maximumFractionDigits: 1 }), [i18n.language]) + const testStart = testStartOf(values.length, prep.testSize) + const first = firstTarget(prep) + // Los valores que necesita: la ventana y, al diferenciar, el anterior a ella + const size = prep.window + (prep.difference ? 1 : 0) + const inputsOf = (target: number) => values.slice(target - size, target) + + // El valor elegido de la serie (de entrada, el primero de la prueba, que la red no vio) y el formulario + const [target, setTarget] = useState(testStart) + const [inputs, setInputs] = useState(() => inputsOf(testStart)) + const [result, setResult] = useState(null) + + const options = useMemo(() => Array.from({ length: values.length - first }, (_value, i) => { + const position = first + i + return { value: position, label: `${dates[position]}: ${number.format(values[position])}${position >= testStart ? ' (' + t(prefix + 'test') + ')' : ''}` } + }), [dates, values, first, testStart, number, t]) + + // El formulario es el de ese valor mientras no se cambie: solo entonces se sabe el valor real + const original = inputsOf(target) + const isUnchanged = inputs.every((value, i) => value === original[i]) + const isValid = inputs.every(Number.isFinite) + const vector = isValid ? windowAt(inputs, inputs.length, prep, scale) : [] + + const handleChange_Target = (position: number) => { + setTarget(position) + setInputs(inputsOf(position)) + } + + const handleSubmit_Predict = async (event: React.FormEvent) => { + event.preventDefault() + if (!isValid) return + const [predicted] = await predictWindows(model, [vector], prep.window) + setResult({ target, inputs: [...inputs], vector, value: toValue(predicted, inputs[inputs.length - 1], prep, scale), actual: isUnchanged ? values[target] : null }) + trackEvent('predict', { input: isUnchanged ? 'sample' : 'form' }) + } + + const error = result === null || result.actual === null ? null : result.value - result.actual + const changes = result === null || !prep.difference ? null : result.inputs.slice(1).map((value, i) => value - result.inputs[i]) + + return ( + + +

    +
    +
    + t('pages.playground.generator.dynamic-form-dataset.entity-count', { shown, total })} /> +
    + + {}}> + + + +
    +
    + +

    {t(prefix + 'choose-instance', { count: size })}

    +
    + + {inputs.map((value, i) => { + const position = target - size + i + return ( + + + {dates[position]} + setInputs((current) => current.map((item, k) => (k === i ? (event.target.value === '' ? NaN : Number(event.target.value)) : item)))} /> + + + ) + })} + + + {t(prefix + 'vector')} + number.format(item)).join(', ')} /> + {t(prefix + (prep.difference ? 'vector-help-difference' : 'vector-help'))} + +
    + +
    +
    + +
    + +
    + {result === null && } + {result !== null && +
    +
    + {t(prefix + 'predicted-value', { target: series.valueColumn, date: dates[result.target] })} + {number.format(result.value)} + {result.actual !== null && error !== null && <> + {t(prefix + 'actual-value', { value: number.format(result.actual) })} + + {t(prefix + 'error', { + value : (error > 0 ? '+' : '') + number.format(error), + percent: result.actual === 0 ? '—' : percent.format(Math.abs(error / result.actual)), + })} + + } +
    +
    + }> +
    + {([ + ['step-values', result.inputs], + ...(changes === null ? [] : [['step-changes', changes] as const]), + ['step-scaled', result.vector], + ] as const).map(([key, items]) => ( +
    +
    {t(prefix + key + '.title')} {t(prefix + key + '.text')}
    +
    {items.map((item) => number.format(item)).join(', ')}
    +
    + ))} +
    +
    +
    +
    } +
    +
    +
    + ) +} diff --git a/src/pages/playground/5_TimeSeries/TimeSeries.tsx b/src/pages/playground/5_TimeSeries/TimeSeries.tsx new file mode 100644 index 0000000..4af2eb4 --- /dev/null +++ b/src/pages/playground/5_TimeSeries/TimeSeries.tsx @@ -0,0 +1,316 @@ +import { useMemo, useState } from 'react' +import { Accordion, Alert, Col, Form, Row } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' + +import { TASKS, UPLOAD } from '@/TASKS' +import { GLOSSARY_ACTIONS } from '@/CONSTANTS_ACTIONS' +import { taskOptions } from '@/TASK_OPTIONS' +import { n4lPackageByKey } from '@core/n4l/catalog' +import { n4lNamespace } from '@core/n4l/format' +import { canPrepare, prepareSeries, type SeriesPrep_t } from '@core/timeSeries/series' +import { evaluateSeriesModel } from '@core/timeSeries/seriesModel' +import { SERIES_LAYER_CLASSES, type SeriesLayer_t } from '@core/timeSeries/seriesLayers' +import { trainSeriesModel } from '@core/controller/trainSeriesModel' +import { historyData } from '@core/training/buildModels' +import { reportTrainResult } from '@core/training/trainResult' +import { checkSeriesLayers } from '@core/nn-utils/checkLayers' +import { SessionError, type TrainingSession_t } from '@core/session/trainingSession' +import { useTrainingProgress } from '@hooks/useTrainingProgress' +import { useStoredModels } from '@hooks/useStoredModels' +import { useTrainerSession } from '@hooks/useTrainerSession' +import alertHelper from '@utils/alertHelper' +import N4LDivider from '@components/divider/N4LDivider' +import N4LSectionLayout from '@components/divider/N4LSectionLayout' +import N4LPageHeader from '@components/neural-network/N4LPageHeader' +import N4LTrainButton from '@components/neural-network/N4LTrainButton' +import N4LTrainingPrediction from '@components/neural-network/N4LTrainingPrediction' +import N4LTrainingDiagnosis from '@components/neural-network/N4LTrainingDiagnosis' +import N4LStoredModelsNotice from '@components/neural-network/N4LStoredModelsNotice' +import N4LPackageDescription from '@components/n4l/N4LPackageDescription' +import { layersAreValid } from '@components/neural-network/alertLayerError' +import WaitingPlaceholder from '@components/loading/WaitingPlaceholder' +import N4LHelpLink from '@components/helpLink/N4LHelpLink' +import type { IdLoss_t, IdOptimizer_t } from '@/types/nn-types' + +import TimeSeriesUpload from './TimeSeriesUpload' +import TimeSeriesPreparation from './TimeSeriesPreparation' +import TimeSeriesModels from './TimeSeriesModels' +import TimeSeriesForecast from './TimeSeriesForecast' +import { usePackageSeries } from './usePackageSeries' +import { timeSeriesTrainerGuide } from './trainerGuide' +import { TimeSeriesEditorLayers, TimeSeriesHyperparameters } from './TimeSeriesEditor' +import N4LModelCode from '@components/neural-network/N4LModelCode' +import { seriesCodeLayers, type ModelCode_t } from '@core/nn-utils/modelCode' +import { createLoss, createMetricsList } from '@core/nn-utils/ArchitectureHelper' +import { + DEFAULT_HYPER, + DEFAULT_LAYERS, + initialPrep, + prefix, + SERIES_METRICS, + seriesLayersOf, + type LoadedSeries_t, + type SeriesHyper_t, + type StoredSeriesModel_t, + type TrainedSeriesModel_t, +} from './timeSeriesConfig' + +/** Las partes de «Cómo funciona» */ +const MANUAL = ['windows', 'split', 'scale', 'modes', 'baselines', 'networks'] + +/** + * Series temporales: predecir los siguientes valores de una serie con los anteriores. Se elige cuántos valores mira la + * red (la ventana) y cuántos se apartan al final para probar, se monta y entrena la red (dense o recurrente) y se ve + * cómo predice la prueba, a un paso o seguida, frente a las predicciones más sencillas, y lo que viene después + */ +export default function TimeSeries({ dataset }: { dataset: string }) { + const { t } = useTranslation() + const isUpload = dataset === UPLOAD + const option = useMemo(() => taskOptions(TASKS.TIME_SERIES, 'dataset').find(({ value }) => value === dataset), [dataset]) + // Una vez: el catálogo da un objeto nuevo en cada llamada, y la serie se carga cuando cambia + const pkg = useMemo(() => (isUpload ? undefined : n4lPackageByKey(TASKS.TIME_SERIES, dataset)), [isUpload, dataset]) + const training = useTrainingProgress() + const steps = ['hr.information', ...(isUpload ? ['hr.process-dataset'] : []), 'hr.dataset', 'hr.model', 'hr.predict'] + const guideSteps = useMemo(() => timeSeriesTrainerGuide(t, dataset, isUpload), [t, dataset, isUpload]) + + const [series, setSeries] = useState(null) + const [prep, setPrep] = useState({ window: 12, testSize: 20, difference: false }) + const [season, setSeason] = useState(undefined) + const [layers, setLayers] = useState(() => (pkg?.section.training ? seriesLayersOf(pkg.section.training.layers) : DEFAULT_LAYERS)) + const [hyper, setHyper] = useState(() => ({ + ...DEFAULT_HYPER, + ...(pkg?.section.training?.learningRate !== undefined && { learningRate: pkg.section.training.learningRate }), + ...(pkg?.section.training?.epochs !== undefined && { epochs: pkg.section.training.epochs }), + })) + // El código equivalente de la red (Ver el código): recibe la ventana de valores anteriores + const codeSpec = useMemo((): ModelCode_t => ({ + inputShape : [prep.window], + layers : seriesCodeLayers(layers, prep.window), + optimizer : hyper.optimizer, + learningRate: hyper.learningRate, + loss : createLoss(hyper.loss, {}), + metrics : createMetricsList(SERIES_METRICS, {}), + epochs : hyper.epochs, + batchSize : hyper.batchSize, + dataComment : t('model-code.data-series', { window: prep.window }), + }), [layers, prep.window, hyper, t]) + const [models, setModels] = useState([]) + // El modelo que se enseña en «Predecir»; null, el último entrenado + const [chosen, setChosen] = useState(null) + const selected = chosen !== null && chosen < models.length ? chosen : models.length - 1 + + /** Una serie nueva: su preparación (la del paquete o según su frecuencia) y sin los modelos de la anterior */ + const loadSeries = (loaded: LoadedSeries_t | null) => { + setSeries(loaded) + setModels([]) + setChosen(null) + if (loaded === null) return + const initial = initialPrep(loaded.values.length, loaded.frequency, pkg?.section.forecast) + setPrep(initial.prep) + setSeason(initial.season) + } + + // Los conjuntos de los paquetes: su serie, que se prepara al llegar + const { error } = usePackageSeries(pkg, option?.info?.files?.[0], loadSeries) + + /** Mide cómo predice un modelo (a un paso y seguido) y lo apunta en su fila */ + const evaluate = async (entry: TrainedSeriesModel_t, values: number[]) => { + try { + const evaluation = await evaluateSeriesModel(entry.model, values, entry.prepared) + setModels((current) => current.map((item) => (item.model === entry.model ? { ...item, evaluation } : item))) + } catch (reason) { + console.error(reason) + } + } + + // Los modelos entrenados antes con este conjunto (guardados en el navegador); los de un fichero subido, no + const storedModels = useStoredModels(TASKS.TIME_SERIES, dataset, !isUpload && series !== null, (stored) => { + if (series === null) return + const restored = stored.flatMap(({ model, data }): TrainedSeriesModel_t[] => (canPrepare(series.values.length, data.prep) + ? [{ ...data, model, prepared: prepareSeries(series.values, data.prep), evaluation: null }] + : [])) + if (restored.length === 0) return + setModels((current) => [...restored, ...current]) + setChosen((current) => (current === null ? null : current + restored.length)) + void restored.reduce((previous, entry) => previous.then(() => evaluate(entry, series.values)), Promise.resolve()) + }) + + // region Sesión: exportar, importar y compartir la red, los hiperparámetros y la preparación + const getSession = (): TrainingSession_t => ({ + app : 'nets4learning', + version : 1, + task : TASKS.TIME_SERIES, + dataset, + layers : layers, + hyperparameters: { + learningRate: hyper.learningRate, + epochs : hyper.epochs, + testSize : prep.testSize, + optimizer : hyper.optimizer, + loss : hyper.loss, + metrics : SERIES_METRICS, + }, + series: { window: prep.window, difference: prep.difference, batchSize: hyper.batchSize }, + }) + const applySession = ({ layers: imported, hyperparameters: h, series: s }: TrainingSession_t) => { + const valid = imported.every((layer) => (SERIES_LAYER_CLASSES as readonly unknown[]).includes(layer._class) && Number.isFinite(Number(layer.units))) + && (s === undefined || (Number.isInteger(s.window) && s.window > 0 && typeof s.difference === 'boolean')) + if (!valid) throw new SessionError('session.error-not-session') + setLayers(imported.map((layer) => ({ + _class : layer._class as SeriesLayer_t['_class'], + units : Number(layer.units), + activation: String(layer.activation ?? 'relu'), + ...(layer.is_disabled === true && { is_disabled: true }), + }))) + setHyper((current) => ({ + ...current, + learningRate: h.learningRate, + epochs : h.epochs, + optimizer : h.optimizer as IdOptimizer_t, + loss : h.loss as IdLoss_t, + ...(s?.batchSize !== undefined && { batchSize: s.batchSize }), + })) + setPrep((current) => ({ ...current, testSize: h.testSize, ...(s !== undefined && { window: s.window, difference: s.difference }) })) + } + const { sessionVersion, importSession } = useTrainerSession(TASKS.TIME_SERIES, series !== null, applySession) + // endregion + + const isValid = series !== null && canPrepare(series.values.length, prep) + + const handleSubmit_Train = async (event: React.FormEvent) => { + event.preventDefault() + if (series === null || !isValid) return + if (!(await layersAreValid(t, checkSeriesLayers(layers)))) return + const prepared = prepareSeries(series.values, prep) + const trained = { layers: [...layers], prep: { ...prep }, hyper: { ...hyper } } + training.start({ epochs: hyper.epochs, learningRate: hyper.learningRate, optimizer: hyper.optimizer, loss: hyper.loss, layers: layers.length }) + try { + const { model, history } = await trainSeriesModel({ + prepared, + layerList : trained.layers, + learningRate : hyper.learningRate, + numberOfEpoch: hyper.epochs, + batchSize : hyper.batchSize, + idOptimizer : hyper.optimizer, + idLoss : hyper.loss, + idMetrics : SERIES_METRICS, + ...training.callbacks, + }) + const entry: TrainedSeriesModel_t = { ...trained, model, history: historyData(history), prepared, evaluation: null } + setModels((current) => [...current, entry]) + setChosen(null) + storedModels.save(model, { layers: entry.layers, prep: entry.prep, hyper: entry.hyper, history: entry.history }) + reportTrainResult({ history: history.history, layers: entry.layers }) + training.complete() + void alertHelper.alertSuccess(t('alert.model-train-success')) + await evaluate(entry, series.values) + } catch (reason) { + console.error('Error during model training:', reason) + } finally { + training.finish() + } + } + + const handleClear_StoredModels = async () => { + await storedModels.clear() + setModels([]) + setChosen(null) + } + + if (!isUpload && (option === undefined || pkg === undefined)) return {t('error.model-selected')} + const title = series === null ? '' : isUpload ? series.name : t(series.name) + + return ( + +
    + } guideId={'train.time-series.' + dataset} guideSteps={guideSteps} + getSession={getSession} onImport={importSession} className={'mt-2 mb-3'} /> + + {/* INFORMACIÓN: cómo funciona y el conjunto de datos */} + + + + + + {MANUAL.map((part) => ( +
    +

    {t(prefix + 'manual.' + part + '.title')}

    +

    +
    + ))} +

    + }} /> +

    +
    +
    + + + {isUpload ? : t(option!.i18n)} + + + {pkg !== undefined + ? + :

    {t(prefix + 'upload.info')}

    } +
    +
    +
    + + {/* SUBIR UNA SERIE */} + {isUpload && <> + +
    + } + + {/* LA SERIE Y SU PREPARACIÓN */} + + {error && {t('error.file-upload')}} + {series === null && !isUpload && !error && } + {series === null && isUpload &&

    {t(prefix + 'upload.waiting')}

    } + {series !== null && + } + + {/* LA RED */} + +
    + + + + + + + + + {/* El código equivalente de la red */} + + + + + + + + + + + + {!training.isTraining && } + + +
    +
    + +
    + +
    + + {/* PREDECIR */} + +
    + {series !== null && } +
    +
    +
    + ) +} diff --git a/src/pages/playground/5_TimeSeries/TimeSeriesChart.tsx b/src/pages/playground/5_TimeSeries/TimeSeriesChart.tsx new file mode 100644 index 0000000..83c7864 --- /dev/null +++ b/src/pages/playground/5_TimeSeries/TimeSeriesChart.tsx @@ -0,0 +1,131 @@ +import { useMemo } from 'react' +import { Line } from 'react-chartjs-2' +import type { Plugin } from 'chart.js' +import { useTranslation } from 'react-i18next' + +import { useTheme } from '@hooks/useTheme' +import N4LChartData from '@components/chart/N4LChartData' + +import { prefix, seriesColors } from './timeSeriesConfig' + +/** Unos valores predichos y la posición en la serie de cada uno */ +export type SeriesLine_t = { label: string, targets: number[], values: number[] } + +type TimeSeriesChartProps = { + /** La fecha de cada valor y, después, las del futuro */ + labels : string[] + values : number[] + valueLabel : string + /** Dónde empieza la prueba: una línea vertical con su nombre */ + split? : { index: number, label: string } + train? : SeriesLine_t + test? : SeriesLine_t + /** Lo que sigue al último valor */ + future? : { label: string, values: number[] } + /** Desde qué posición se enseña (para ver de cerca la prueba y el futuro) */ + from? : number + /** Lo que se ve, para quien no ve la gráfica */ + description : string + /** El nombre de su tabla de datos (distinto en cada gráfica de la página); por defecto, «: real y predicho» */ + dataCaption?: string + testId? : string +} + +/** Una línea vertical discontinua en una posición del eje X, con un texto arriba */ +const splitPlugin = (index: number, label: string, color: string): Plugin<'line'> => ({ + id: 'n4l-series-split', + afterDatasetsDraw(chart) { + const x = chart.scales.x.getPixelForValue(index) + const { top, bottom, left, right } = chart.chartArea + if (x < left || x > right) return + const { ctx } = chart + ctx.save() + ctx.strokeStyle = color + ctx.fillStyle = color + ctx.setLineDash([5, 4]) + ctx.beginPath() + ctx.moveTo(x, top) + ctx.lineTo(x, bottom) + ctx.stroke() + ctx.fillText(label, x + 4, top + 12) + ctx.restore() + }, +}) + +/** La serie real y, si las hay, las predicciones de la red con los datos de entrenamiento, los de prueba y el futuro */ +export default function TimeSeriesChart({ labels, values, valueLabel, split, train, test, future, from = 0, description, dataCaption, testId }: TimeSeriesChartProps) { + const { t } = useTranslation() + const theme = useTheme() + const textColor = theme === 'dark' ? '#dee2e6' : '#495057' + + const data = useMemo(() => { + const total = labels.length + const line = ({ targets, values: predicted }: SeriesLine_t) => { + const points = new Array(total).fill(null) + targets.forEach((target, i) => { points[target] = predicted[i] }) + return points + } + // El futuro empieza en el último valor real, para que la línea siga sin saltos + const futurePoints = new Array(total).fill(null) + if (future !== undefined && future.values.length > 0) { + futurePoints[values.length - 1] = values[values.length - 1] + future.values.forEach((value, i) => { futurePoints[values.length + i] = value }) + } + const common = { pointRadius: 0, pointHoverRadius: 3, borderWidth: 1.5, spanGaps: false } + const colors = seriesColors(theme) + const trainPoints = train !== undefined ? line(train) : null + const testPoints = test !== undefined ? line(test) : null + const hasFuture = future !== undefined && future.values.length > 0 + // Cada línea, también con su trazo (WCAG 1.4.1): la serie y el entrenamiento continuas, la prueba de puntos y el + // futuro de rayas; en la leyenda se ve igual + const chart = { + labels : labels.slice(from), + datasets: [ + { ...common, label: valueLabel, data: values.slice(from), borderColor: textColor, backgroundColor: textColor }, + ...(train !== undefined && trainPoints !== null ? [{ ...common, label: train.label, data: trainPoints.slice(from), borderColor: colors.train, backgroundColor: colors.train }] : []), + ...(test !== undefined && testPoints !== null ? [{ ...common, label: test.label, data: testPoints.slice(from), borderColor: colors.test, backgroundColor: colors.test, borderDash: [2, 3], borderWidth: 2.5 }] : []), + ...(future !== undefined && hasFuture + ? [{ ...common, label: future.label, data: futurePoints.slice(from), borderColor: colors.future, backgroundColor: colors.future, borderDash: [8, 4], borderWidth: 2 }] + : []), + ], + } + // Lo mismo en una tabla: cada fecha con el valor real y lo predicho (el futuro, solo después del último valor) + const table = { + columns: [ + t(prefix + 'windows.date'), valueLabel, + ...(train !== undefined ? [train.label] : []), ...(test !== undefined ? [test.label] : []), ...(future !== undefined && hasFuture ? [future.label] : []), + ], + rows: labels.slice(from).map((date, offset) => { + const i = from + offset + return [ + date, values[i], + ...(trainPoints !== null ? [trainPoints[i]] : []), ...(testPoints !== null ? [testPoints[i]] : []), + ...(hasFuture ? [i >= values.length ? futurePoints[i] : null] : []), + ] + }), + } + return { chart, table } + }, [labels, values, valueLabel, train, test, future, from, textColor, theme, t]) + + const plugins = useMemo(() => (split === undefined ? [] : [splitPlugin(split.index - from, split.label, textColor)]), [split, from, textColor]) + + return ( +
    +
    + +
    + +
    + ) +} diff --git a/src/pages/playground/5_TimeSeries/TimeSeriesEditor.tsx b/src/pages/playground/5_TimeSeries/TimeSeriesEditor.tsx new file mode 100644 index 0000000..85ff5eb --- /dev/null +++ b/src/pages/playground/5_TimeSeries/TimeSeriesEditor.tsx @@ -0,0 +1,115 @@ +import { useMemo } from 'react' +import { Card, Form } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' + +import alertHelper from '@utils/alertHelper' +import N4LEditorLayers from '@components/neural-network/N4LEditorLayers' +import { moveLayer } from '@components/neural-network/moveLayer' +import N4LDenseLayerFields from '@components/neural-network/N4LDenseLayerFields' +import N4LLayerCheck from '@components/neural-network/N4LLayerCheck' +import N4LEmptyState from '@components/loading/N4LEmptyState' +import { flaggedLayers } from '@components/neural-network/layerCheckText' +import { layerSummaryParts } from '@components/neural-network/layerSummary' +import { HyperparameterLearningRate, HyperparameterNumber, HyperparameterSelect, LossOptions, OptimizerOptions } from '@components/neural-network/N4LHyperparameterFields' +import { checkSeriesLayers } from '@core/nn-utils/checkLayers' +import { SERIES_LAYER_CLASSES, SERIES_LAYER_LABELS, type SeriesLayer_t, type SeriesLayerClass_t } from '@core/timeSeries/seriesLayers' +import type { IdLoss_t, IdOptimizer_t } from '@/types/nn-types' + +import { prefix, type SeriesHyper_t } from './timeSeriesConfig' + +const MAX_LAYERS = 10 + +type TimeSeriesEditorLayersProps = { + layers : SeriesLayer_t[] + onChange: (layers: SeriesLayer_t[]) => void + waiting : boolean +} + +/** + * Las capas de la red: Dense o recurrentes (SimpleRNN, LSTM, GRU), que leen la ventana valor a valor y van antes que + * las Dense. La salida, una neurona lineal (el valor que se predice), no se cambia ni se borra + */ +export function TimeSeriesEditorLayers({ layers, onChange, waiting }: TimeSeriesEditorLayersProps) { + const { t } = useTranslation() + const issues = useMemo(() => checkSeriesLayers(layers), [layers]) + + const add = async (layer: SeriesLayer_t, atStart: boolean) => { + if (layers.length > MAX_LAYERS) { + await alertHelper.alertWarning(t('error.layers-length')) + return + } + // Al final, antes de la salida + onChange(atStart ? [layer, ...layers] : [...layers.slice(0, -1), layer, ...layers.slice(-1)]) + } + const change = (index: number, layer: SeriesLayer_t) => onChange(layers.map((item, i) => (i === index ? layer : item))) + + return ( + layerSummaryParts(t, layer).join(', ')} + renderFields={(layer, index) => <> + + + { + const _class = event.target.value as SeriesLayerClass_t + // Las recurrentes suelen usar tanh; al volver a Dense, ReLU + const activation = _class === 'dense' ? 'relu' : 'tanh' + change(index, { ...layer, _class, activation }) + }}> + {SERIES_LAYER_CLASSES.map((value) => )} + + + + change(changed, { ...layers[changed], units, activation })} /> + } + isLocked={(layer) => layer.is_disabled === true} + check={} + flagged={flaggedLayers(issues)} + onAddStart={() => add({ _class: 'dense', units: 16, activation: 'relu' }, true)} + onAddEnd={() => add({ _class: 'dense', units: 16, activation: 'relu' }, false)} + onRemove={(index) => onChange(layers.filter((_layer, i) => i !== index))} + onMove={(from, to) => onChange(moveLayer(layers, from, to))} + onRestore={onChange} + waiting={waiting} + titleAs={'h3'} + /> + ) +} + +type TimeSeriesHyperparametersProps = { + hyper : SeriesHyper_t + onChange: (hyper: SeriesHyper_t) => void + waiting : boolean +} + +/** Cómo se entrena: tasa de aprendizaje, épocas, tamaño del lote, optimizador y función de pérdida */ +export function TimeSeriesHyperparameters({ hyper, onChange, waiting }: TimeSeriesHyperparametersProps) { + const change = (key: K, value: SeriesHyper_t[K]) => onChange({ ...hyper, [key]: value }) + return ( + +

    + + {waiting && } + {!waiting && <> + change('learningRate', value)} /> + change('epochs', value)} /> + change('batchSize', value)} /> +
    + change('optimizer', value as IdOptimizer_t)}> + + + change('loss', value as IdLoss_t)}> + + + } +
    +
    + ) +} diff --git a/src/pages/playground/5_TimeSeries/TimeSeriesForecast.tsx b/src/pages/playground/5_TimeSeries/TimeSeriesForecast.tsx new file mode 100644 index 0000000..08abcfc --- /dev/null +++ b/src/pages/playground/5_TimeSeries/TimeSeriesForecast.tsx @@ -0,0 +1,198 @@ +import { useEffect, useMemo, useState } from 'react' +import { Alert, Card, Col, Form, Row, Spinner, Table, ToggleButton, ToggleButtonGroup } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' + +import { trackEvent } from '@core/analytics' +import { baselineErrors, nextDates, type ForecastErrors_t } from '@core/timeSeries/series' +import { forecastFuture } from '@core/timeSeries/seriesModel' +import N4LEmptyState from '@components/loading/N4LEmptyState' +import N4LNumberField from '@components/form/N4LNumberField' + +import TimeSeriesChart from './TimeSeriesChart' +import { prefix, seriesColors, type ForecastModel_t, type LoadedSeries_t } from './timeSeriesConfig' +import { useTheme } from '@hooks/useTheme' + +type Mode_t = 'one-step' | 'recursive' +type Range_t = 'all' | 'test' + +const MAX_FUTURE = 500 +/** Lo que tiene que mejorar la red a la mejor línea base para decir que predice mejor (5 %) */ +const MARGIN = 0.05 + +type TimeSeriesForecastProps = { + series : LoadedSeries_t + models : ForecastModel_t[] + selected : number + onSelect : (index: number) => void + season? : number + /** Cómo se llama el modelo (sin él, «Modelo N», el de la tabla) */ + modelName?: string +} + +/** Los errores de la red y de las líneas base con los mismos valores */ +type Comparison_t = { model: ForecastErrors_t, naive: ForecastErrors_t, seasonal?: ForecastErrors_t } + +/** La mejor de las líneas base (la que menos se equivoca) y cuánto mejora la red su error */ +function verdict({ model, naive, seasonal }: Comparison_t) { + const baseline = seasonal !== undefined && seasonal.mae < naive.mae ? 'seasonal' : 'naive' + const baselineMae = baseline === 'seasonal' ? seasonal!.mae : naive.mae + const improvement = baselineMae > 0 ? 1 - model.mae / baselineMae : 0 + return { baseline, improvement, level: improvement > MARGIN ? 'better' : improvement < -MARGIN ? 'worse' : 'similar' } as const +} + +/** + * Lo que predice el modelo elegido: la parte de prueba a un paso (cada valor con los reales de antes) o recursivamente + * (toda seguida, con los ya predichos), cuánto se equivoca frente a las predicciones más sencillas y lo que viene después + * del último valor + */ +export default function TimeSeriesForecast({ series, models, selected, onSelect, season, modelName }: TimeSeriesForecastProps) { + const { t, i18n } = useTranslation() + const theme = useTheme() + const number = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumSignificantDigits: 4 }), [i18n.language]) + const percent = useMemo(() => new Intl.NumberFormat(i18n.language, { style: 'percent', maximumFractionDigits: 0 }), [i18n.language]) + const [mode, setMode] = useState('one-step') + const [range, setRange] = useState('all') + const [showTrain, setShowTrain] = useState(false) + const current = models[selected] as ForecastModel_t | undefined + const [steps, setSteps] = useState(() => Math.min(MAX_FUTURE, season ?? 12)) + // El futuro del modelo elegido (con los pasos pedidos); null mientras se calcula. Por su modelo de TF.js: la fila de + // la tabla cambia al terminar de medirlo, el modelo no + const [future, setFuture] = useState<{ model: ForecastModel_t['model'], steps: number, values: number[] } | null>(null) + const model = current?.model + const modelPrepared = current?.prepared + useEffect(() => { + if (model === undefined || modelPrepared === undefined) return + let isCancelled = false + forecastFuture(model, series.values, modelPrepared, steps).then( + (values) => { if (!isCancelled) setFuture({ model, steps, values }) }, + (error: unknown) => console.error(error), + ) + return () => { isCancelled = true } + }, [model, modelPrepared, series.values, steps]) + + const futureValues = future !== null && future.model === model && future.steps === steps ? future.values : null + const futureDates = useMemo(() => nextDates(series.dates[series.dates.length - 1], series.frequency, steps), [series, steps]) + // Las líneas base no dependen del modelo: se recalculan al cambiar la estación, sin volver a usar la red + const baselines = useMemo(() => (modelPrepared === undefined ? null : baselineErrors(series.values, modelPrepared, season)), [series.values, modelPrepared, season]) + + if (current === undefined) return + const { evaluation, prepared } = current + const { testStart, test, train } = prepared + const comparison: Comparison_t | null = evaluation === null || baselines === null + ? null + : { model: mode === 'one-step' ? evaluation.errors.oneStep : evaluation.errors.recursive, ...(mode === 'one-step' ? baselines.oneStep : baselines.recursive) } + const result = comparison === null ? null : verdict(comparison) + const name = modelName ?? t('model.__index__', { index: selected + 1 }) + + const errorsRow = (label: string, errors: ForecastErrors_t | undefined, testId: string, strong = false) => errors !== undefined && ( + + {label} + {number.format(errors.mae)} + {number.format(errors.rmse)} + + ) + + return ( + + +

    {t(prefix + 'forecast.title', { model: name })}

    + {models.length > 1 && + onSelect(Number(event.target.value))}> + {models.map((_model, index) => )} + } +
    + + {evaluation === null &&
    {t(prefix + 'models.evaluating')}
    } + {evaluation !== null && comparison !== null && result !== null && <> +
    + setMode(value)}> + {t(prefix + 'forecast.one-step')} + {t(prefix + 'forecast.recursive')} + + setRange(value)}> + {t(prefix + 'forecast.range-all')} + {t(prefix + 'forecast.range-test')} + + setShowTrain(!showTrain)} /> +
    +

    {t(prefix + (mode === 'one-step' ? 'forecast.one-step-help' : 'forecast.recursive-help'))}

    + +
    + +
    + + + +

    {t(prefix + 'forecast.errors-title')}

    + + + + + + + + + + {errorsRow(t(prefix + 'forecast.network', { model: name }), comparison.model, 'Test-TimeSeries-Errors-Model', true)} + {errorsRow(t(prefix + (mode === 'one-step' ? 'forecast.naive-one-step' : 'forecast.naive-recursive')), comparison.naive, 'Test-TimeSeries-Errors-Naive')} + {errorsRow(t(prefix + (mode === 'one-step' ? 'forecast.seasonal-one-step' : 'forecast.seasonal-recursive'), { season }), comparison.seasonal, 'Test-TimeSeries-Errors-Seasonal')} + +
    {t(prefix + 'forecast.prediction')}MAERMSE
    + + + +

    + {t(prefix + 'forecast.train-vs-test', { train: number.format(evaluation.errors.train.mae), test: number.format(evaluation.errors.oneStep.mae) })} + {evaluation.errors.oneStep.mae > 2 * evaluation.errors.train.mae && <> {t(prefix + 'forecast.overfitting')}} +

    + + +

    {t(prefix + 'forecast.future-title')}

    + { + setSteps(value) + trackEvent('predict', { input: 'forecast' }) + }} /> + {/* Siempre del mismo alto: al llegar los valores (o al pedir otros) no se mueve lo de alrededor */} +
    + {futureValues === null && } + {futureValues !== null && + + + + + + + + + {futureValues.map((value, i) => ( + + + + + ))} + +
    {t(prefix + 'windows.date')} + + {series.valueColumn} +
    {futureDates[i]}{number.format(value)}
    } +
    + +
    + } +
    +
    + ) +} diff --git a/src/pages/playground/5_TimeSeries/TimeSeriesModels.tsx b/src/pages/playground/5_TimeSeries/TimeSeriesModels.tsx new file mode 100644 index 0000000..77e8aa8 --- /dev/null +++ b/src/pages/playground/5_TimeSeries/TimeSeriesModels.tsx @@ -0,0 +1,112 @@ +import { useMemo } from 'react' +import { Button, Card, Spinner, Table } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' +import * as tfvis from '@tensorflow/tfjs-vis' + +import { formatEpochs } from '@core/history/trainingSummary' +import { nnLabel } from '@core/nn-utils/ArchitectureTypesHelper' +import { layersSummary } from '@components/neural-network/layerSummary' +import N4LTrainingCurves from '@components/neural-network/N4LTrainingCurves' +import { N4LBestBadge } from '@components/neural-network/N4LFinalMetrics' +import N4LEmptyState from '@components/loading/N4LEmptyState' + +import { prefix, type TrainedSeriesModel_t } from './timeSeriesConfig' + +type TimeSeriesModelsProps = { + models : TrainedSeriesModel_t[] + selected: number + onSelect: (index: number) => void +} + +/** El que menos se equivoca con los datos de prueba (a un paso), si hay más de uno ya medido */ +function bestSeriesModel(models: TrainedSeriesModel_t[]): number { + let best = -1 + models.forEach(({ evaluation }, index) => { + const mae = evaluation?.errors.oneStep.mae + if (mae !== undefined && Number.isFinite(mae) && (best === -1 || mae < models[best].evaluation!.errors.oneStep.mae)) best = index + }) + return models.length > 1 ? best : -1 +} + +/** + * Los modelos entrenados: con qué se entrenó cada uno y cuánto se equivoca con los datos de prueba (en las unidades de + * la serie), el que se enseña en «Predecir» y sus curvas de entrenamiento (para compararlas) + */ +export default function TimeSeriesModels({ models, selected, onSelect }: TimeSeriesModelsProps) { + const { t, i18n } = useTranslation() + const number = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumSignificantDigits: 4 }), [i18n.language]) + const best = bestSeriesModel(models) + const parameters = models.map(({ hyper, layers, prep }) => ({ + 'window' : String(prep.window), + 'difference' : t(prefix + (prep.difference ? 'models.yes' : 'models.no')), + 'test-size' : prep.testSize + '%', + 'learning-rate': String(hyper.learningRate), + 'n-of-epochs' : String(hyper.epochs), + 'batch-size' : String(hyper.batchSize), + 'layers' : layersSummary(t, layers), + 'id-optimizer' : nnLabel(hyper.optimizer), + 'id-loss' : nnLabel(hyper.loss), + })) + + return ( + + +

    | {models.length}

    +
    + + +
    +
    + + {models.length === 0 && } + {models.length > 0 && <> + + + + + + + + + + + + + + + + {models.map((model, index) => ( + + + + + + + + {model.evaluation === null + ? + : <> + + + } + + + ))} + +
    ID{t('generator.table-models.window')}{t('generator.table-models.difference')}{t('generator.table-models.layers')}{t('generator.table-models.n-of-epochs')}{t('generator.table-models.learning-rate')}{t(prefix + 'models.mae-one-step')}{t(prefix + 'models.mae-recursive')}{t(prefix + 'models.show')}
    {index + 1}{index === best && }{model.prep.window}{parameters[index].difference}{parameters[index].layers}{formatEpochs(model.history.epoch.length, model.hyper.epochs)}{model.hyper.learningRate}{number.format(model.evaluation.errors.oneStep.mae)}{number.format(model.evaluation.errors.recursive.mae)} + +
    +

    {t(prefix + 'models.help')}

    + history.history)} parameters={parameters} /> + } +
    +
    + ) +} diff --git a/src/pages/playground/5_TimeSeries/TimeSeriesPreparation.tsx b/src/pages/playground/5_TimeSeries/TimeSeriesPreparation.tsx new file mode 100644 index 0000000..c4b8751 --- /dev/null +++ b/src/pages/playground/5_TimeSeries/TimeSeriesPreparation.tsx @@ -0,0 +1,87 @@ +import { useEffect } from 'react' +import { Alert, Card, Col, Form, Row } from 'react-bootstrap' +import { Trans, useTranslation } from 'react-i18next' + +import { canPrepare, testStartOf, type SeriesPrep_t } from '@core/timeSeries/series' + +import TimeSeriesChart from './TimeSeriesChart' +import TimeSeriesWindows from './TimeSeriesWindows' +import { prefix, seriesSummary, type LoadedSeries_t } from './timeSeriesConfig' +import { announce } from '@core/a11y/announce' +import N4LNumberField from '@components/form/N4LNumberField' + +type TimeSeriesPreparationProps = { + series : LoadedSeries_t + title : string + prep : SeriesPrep_t + season? : number + onPrep : (prep: SeriesPrep_t) => void + onSeason: (season: number | undefined) => void + disabled: boolean +} + +/** + * La serie y cómo se prepara para la red: con cuántos valores anteriores se predice el siguiente (la ventana), cuántos + * se apartan al final para probar, si se predice el cambio en lugar del valor y la estación (para comparar). Debajo, las + * primeras ventanas, para ver qué recibe la red y qué tiene que predecir + */ +export default function TimeSeriesPreparation({ series, title, prep, season, onPrep, onSeason, disabled }: TimeSeriesPreparationProps) { + const { t } = useTranslation() + const { dates, values } = series + const testStart = testStartOf(values.length, prep.testSize) + const isValid = canPrepare(values.length, prep) + const range = (from: number, to: number) => t(prefix + 'data.range', { first: dates[from], last: dates[to - 1], count: to - from }) + // Al cargar la serie, lo que tiene (también para el lector de pantalla: WCAG 4.1.3) + const summary = seriesSummary(t, series) + useEffect(() => announce(summary), [summary]) + + return ( + +

    {title}

    + +

    + {summary} +

    + {series.dropped > 0 && {t(prefix + 'data.dropped', { count: series.dropped })}} + {series.sorted && {t(prefix + 'data.sorted')}} + + + + + {isValid && +

    + +

    } + + +
    + {t(prefix + 'prep.title')} + {/* Sin máximo: con una ventana demasiado grande para la serie, el aviso de debajo explica por qué no se puede */} + {t(prefix + 'prep.window-help')} {season !== undefined && t(prefix + 'prep.window-season', { season })}} + onChange={(window) => onPrep({ ...prep, window })} /> + onPrep({ ...prep, testSize })} /> + onPrep({ ...prep, difference: !prep.difference })} /> + {t(prefix + 'prep.difference-help')} + onSeason(value > 1 ? value : undefined)} /> +
    + +
    + + {!isValid && {t(prefix + 'prep.too-short')}} + {isValid &&
    } +
    +
    + ) +} diff --git a/src/pages/playground/5_TimeSeries/TimeSeriesTestMetrics.tsx b/src/pages/playground/5_TimeSeries/TimeSeriesTestMetrics.tsx new file mode 100644 index 0000000..c048085 --- /dev/null +++ b/src/pages/playground/5_TimeSeries/TimeSeriesTestMetrics.tsx @@ -0,0 +1,32 @@ +import { Alert } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import { prefix } from './timeSeriesConfig' + +type TimeSeriesTestMetricsProps = { + /** Las del manifiesto del modelo: test_mae y, para compararse, test_naive_mae y (con estación) test_seasonal_mae */ + metrics : Record | undefined + testSize: number +} + +/** + * Cómo predice el modelo de una serie con la parte final, que no vio al entrenarlo: su error medio a un paso frente al + * de repetir el valor anterior y el de hace una estación. Si no mejora la mejor de las dos, se dice + */ +export default function TimeSeriesTestMetrics({ metrics, testSize }: TimeSeriesTestMetricsProps) { + const { t, i18n } = useTranslation() + if (metrics?.test_mae === undefined || metrics.test_naive_mae === undefined) return null + const number = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 2 }) + const baseline = Math.min(metrics.test_naive_mae, metrics.test_seasonal_mae ?? Infinity) + const isBetter = metrics.test_mae < baseline + return ( + +

    {t('n4l.metrics.title')}

    +

    + {t(prefix + 'review.metrics', { testSize, mae: number.format(metrics.test_mae), naive: number.format(metrics.test_naive_mae) })} + {metrics.test_seasonal_mae !== undefined && <> {t(prefix + 'review.metrics-seasonal', { seasonal: number.format(metrics.test_seasonal_mae) })}} +

    + {!isBetter &&

    {t(prefix + 'review.metrics-no-better')}

    } +
    + ) +} diff --git a/src/pages/playground/5_TimeSeries/TimeSeriesUpload.tsx b/src/pages/playground/5_TimeSeries/TimeSeriesUpload.tsx new file mode 100644 index 0000000..fd3c52d --- /dev/null +++ b/src/pages/playground/5_TimeSeries/TimeSeriesUpload.tsx @@ -0,0 +1,107 @@ +import { useEffect, useEffectEvent, useState } from 'react' +import { Alert, Card, Col, Form, Row } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import { TASKS } from '@/TASKS' +import DragAndDrop from '@components/dragAndDrop/DragAndDrop' +import { DATASET_ACCEPT } from '@core/dataframe/datasetFormats' +import { readDatasetInWorker } from '@core/dataframe/datasetReaderClient' +import { inferFrequency, parseDate, readSeries } from '@core/timeSeries/series' +import { useProjectDatasetUpload } from '@hooks/useProjectDatasetUpload' +import { datasetKey, datasetVariables, projectDatasetByKey } from '@pages/analyze/projectDatasets' + +import { prefix, type LoadedSeries_t } from './timeSeriesConfig' + +/** Lo leído del fichero */ +type Table_t = { name: string, columns: string[], rows: unknown[][], numeric: boolean[] } + +const NO_DATE = '' + +/** Si casi todos los valores de una columna de texto son fechas (1949-01, 1981-01-01, 2024-03-01 10:00…) */ +function looksLikeDates(rows: unknown[][], column: number): boolean { + const sample = rows.slice(0, 50).map((row) => String(row[column] ?? '').trim()).filter((value) => value !== '') + return sample.length > 0 && sample.filter((value) => Number.isFinite(parseDate(value))).length >= sample.length * 0.9 +} + +/** + * Subir una serie propia (CSV, ARFF, JSON, JSONL o Parquet) y elegir la columna con sus valores y, si la tiene, la de + * sus fechas. Se proponen las de su ficha (si es un CSV del proyecto) o la última numérica y la primera con fechas + */ +export default function TimeSeriesUpload({ onLoaded }: { onLoaded: (series: LoadedSeries_t | null) => void }) { + const { t } = useTranslation() + const [table, setTable] = useState(null) + const [valueColumn, setValueColumn] = useState('') + const [dateColumn, setDateColumn] = useState(NO_DATE) + const [error, setError] = useState(false) + + const handleUpload = async (files: File[]) => { + if (files.length !== 1) return + try { + const { columns, rows, dtypes } = await readDatasetInWorker(files[0]) + const numeric = dtypes.map((dtype) => dtype === 'float32' || dtype === 'int32') + // Un CSV del proyecto (desde /datasets, o descargado y vuelto a subir): su objetivo y su fecha, según su ficha + const project = projectDatasetByKey(datasetKey(files[0].name)) + const variables = project === undefined ? undefined : datasetVariables(project.file) + const target = variables?.find(({ role, name }) => role === 'Target' && columns.includes(name))?.name + const date = variables?.find(({ type, name }) => type === 'Date' && columns.includes(name))?.name + setTable({ name: files[0].name, columns, rows, numeric }) + setValueColumn(target ?? [...columns].reverse().find((_column, i) => numeric[columns.length - 1 - i]) ?? '') + setDateColumn(date ?? columns.find((_column, i) => !numeric[i] && looksLikeDates(rows, i)) ?? NO_DATE) + setError(false) + } catch (reason) { + console.error(reason) + setTable(null) + setError(true) + } + } + + // Desde «Entrenar» en /datasets (?dataset=…): se carga como si se hubiera subido + useProjectDatasetUpload(TASKS.TIME_SERIES, true, (files) => { void handleUpload(files) }) + + // La serie, cada vez que se elige otra columna + const notify = useEffectEvent(onLoaded) + useEffect(() => { + if (table === null || valueColumn === '') { + notify(null) + return + } + const series = readSeries(table.columns, table.rows, valueColumn, dateColumn === NO_DATE ? null : dateColumn) + notify({ ...series, name: table.name, valueColumn, frequency: dateColumn === NO_DATE ? undefined : inferFrequency(series.dates) }) + }, [table, valueColumn, dateColumn]) + + return ( + +

    {t(prefix + 'upload.title')}

    + +

    {t(prefix + 'upload.text')}

    + { void handleUpload(files) }} /> + {error && {t('error.file-upload')}} + {table !== null && !table.numeric.some(Boolean) && + {t(prefix + 'upload.no-numeric')}} + {table !== null && table.numeric.some(Boolean) && + + + + {t(prefix + 'upload.value-column')} + setValueColumn(event.target.value)}> + {table.columns.map((column, i) => table.numeric[i] && )} + + {t(prefix + 'upload.value-column-help')} + + + + + {t(prefix + 'upload.date-column')} + setDateColumn(event.target.value)}> + + {table.columns.map((column) => column !== valueColumn && )} + + {t(prefix + 'upload.date-column-help')} + + + } +
    +
    + ) +} diff --git a/src/pages/playground/5_TimeSeries/TimeSeriesWindows.tsx b/src/pages/playground/5_TimeSeries/TimeSeriesWindows.tsx new file mode 100644 index 0000000..4f07d43 --- /dev/null +++ b/src/pages/playground/5_TimeSeries/TimeSeriesWindows.tsx @@ -0,0 +1,67 @@ +import { useMemo } from 'react' +import { Table } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' + +import { firstTarget, testStartOf, type SeriesPrep_t } from '@core/timeSeries/series' + +import { prefix } from './timeSeriesConfig' + +/** Cuántos ejemplos se enseñan y, en una ventana larga, cuántos valores de cada extremo */ +const EXAMPLES = 3 +const EDGE = 3 + +type TimeSeriesWindowsProps = { + dates : string[] + values: number[] + prep : SeriesPrep_t +} + +/** + * Lo que aprende la red: las primeras ventanas de entrenamiento, cada una con los valores anteriores (o sus cambios, al + * diferenciar) que recibe y el que tiene que predecir, sin escalar para que se lean bien + */ +export default function TimeSeriesWindows({ dates, values, prep }: TimeSeriesWindowsProps) { + const { t, i18n } = useTranslation() + const number = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 3 }), [i18n.language]) + const signed = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 3, signDisplay: 'exceptZero' }), [i18n.language]) + const testStart = testStartOf(values.length, prep.testSize) + const first = firstTarget(prep) + + const examples = Array.from({ length: Math.max(0, Math.min(EXAMPLES, testStart - first)) }, (_value, i) => { + const target = first + i + const at = (position: number) => (prep.difference ? values[position] - values[position - 1] : values[position]) + const inputs = Array.from({ length: prep.window }, (_item, k) => at(target - prep.window + k)) + const format = (value: number) => (prep.difference ? signed : number).format(value) + const shown = inputs.length > 2 * EDGE + 1 ? [...inputs.slice(0, EDGE).map(format), '…', ...inputs.slice(-EDGE).map(format)] : inputs.map(format) + return { date: dates[target], inputs: shown.join(', '), output: format(at(target)) } + }) + if (examples.length === 0) return null + + return ( +
    +

    {t(prefix + 'windows.title')}

    +

    {t(prefix + (prep.difference ? 'windows.text-difference' : 'windows.text'), { window: prep.window })}

    +
    + + + + + + + + + + {examples.map(({ date, inputs, output }) => ( + + + + + + ))} + +
    {t(prefix + 'windows.date')}{t(prefix + (prep.difference ? 'windows.inputs-difference' : 'windows.inputs'), { window: prep.window })}{t(prefix + (prep.difference ? 'windows.output-difference' : 'windows.output'))}
    {date}{inputs}{output}
    +
    +

    {t(prefix + 'windows.scaled', { count: testStart - first })}

    +
    + ) +} diff --git a/src/pages/playground/5_TimeSeries/modelReviewGuide.ts b/src/pages/playground/5_TimeSeries/modelReviewGuide.ts new file mode 100644 index 0000000..b02aa63 --- /dev/null +++ b/src/pages/playground/5_TimeSeries/modelReviewGuide.ts @@ -0,0 +1,38 @@ +import { TASKS } from '@/TASKS' +import { n4lPackagesOf } from '@core/n4l/catalog' +import type { GuideStep_t } from '@components/guide/N4LGuide' +import { buildGuideSteps, centerStep, guideStep, type GuideTranslate_t } from '@components/guide/buildGuideSteps' + +/** + * Modelos con guía en su página (/playground/time-series/model/): los de los paquetes con serie temporal. Sus + * textos van en guide.5-time-series.common (las tres páginas son iguales) y, si alguno necesita uno propio, en + * guide.5-time-series. + */ +export const TIME_SERIES_REVIEW_GUIDES = n4lPackagesOf(TASKS.TIME_SERIES).filter(({ section }) => section.models.length > 0).map(({ section }) => section.key) + +/** + * Los pasos de la guía de la página de un modelo de una serie temporal (null si no tiene), en el orden de la página, + * como en las de las demás tareas: el modelo, la serie y cómo se preparó, el formulario para predecir un valor y su + * resultado; después, cómo predice toda la prueba (a un paso o seguida) frente a las predicciones sencillas y el futuro + */ +export function timeSeriesReviewGuide(t: GuideTranslate_t, modelKey: string): GuideStep_t[] | null { + if (!TIME_SERIES_REVIEW_GUIDES.includes(modelKey)) return null + return buildGuideSteps(t, 'guide.5-time-series', modelKey, [ + centerStep('intro'), + guideStep('model', 'model'), + guideStep('model-summary', 'model-summary'), + guideStep('dataset', 'dataset'), + guideStep('dataset-chart', 'dataset-chart', 'bottom'), + guideStep('dataset-windows', 'dataset-windows', 'bottom'), + guideStep('instances', 'instances', 'bottom'), + guideStep('form', 'form'), + guideStep('vector', 'vector'), + guideStep('predict', 'predict'), + guideStep('result', 'result'), + guideStep('mode', 'forecast-mode', 'bottom'), + guideStep('chart', 'forecast-chart', 'top'), + guideStep('errors', 'errors'), + guideStep('future', 'future'), + centerStep('end'), + ]) +} diff --git a/src/pages/playground/5_TimeSeries/models/MODEL_N4L.tsx b/src/pages/playground/5_TimeSeries/models/MODEL_N4L.tsx new file mode 100644 index 0000000..31fd001 --- /dev/null +++ b/src/pages/playground/5_TimeSeries/models/MODEL_N4L.tsx @@ -0,0 +1,23 @@ +import { TASKS } from '@/TASKS' +import type { MenuModel_t } from '@/DATA_MODEL' +import { n4lTaskText } from '@core/n4l/format' +import type { N4LPackage_t } from '@core/n4l/source' +import N4LPackageDescription from '@components/n4l/N4LPackageDescription' + +/** + * Lo que los menús saben de una serie de un paquete .n4l (la de su modelo ya entrenado y la de entrenar): su nombre y + * la descripción del paquete, con las métricas de su modelo + */ +export default class MODEL_N4L implements MenuModel_t { + readonly pkg : N4LPackage_t + readonly i18n_TITLE: string + + constructor(pkg: N4LPackage_t) { + this.pkg = pkg + this.i18n_TITLE = n4lTaskText(pkg.namespace, TASKS.TIME_SERIES) + 'name' + } + + DESCRIPTION() { + return + } +} diff --git a/src/pages/playground/5_TimeSeries/models/index.ts b/src/pages/playground/5_TimeSeries/models/index.ts new file mode 100644 index 0000000..f2eb3fb --- /dev/null +++ b/src/pages/playground/5_TimeSeries/models/index.ts @@ -0,0 +1,20 @@ +import { TASKS } from '@/TASKS' +import type { MenuModel_t } from '@/DATA_MODEL' +import type { ModelRegistry } from '@core/models/modelRegistry' +import { builtinN4LPackage, n4lPackagesOf, type N4LCatalogEntry_t } from '@core/n4l/catalog' + +/** La clase de una serie de un paquete: MODEL_N4L con ese paquete (se descarga al usarla, como las demás) */ +const n4lModelClass = (entry: N4LCatalogEntry_t) => async () => { + const { default: MODEL_N4L } = await import('./MODEL_N4L') + return class extends MODEL_N4L { + constructor() { + super(builtinN4LPackage(entry)) + } + } +} + +/** Las series de los paquetes .n4l de la aplicación, por su clave: su nombre y su descripción en los menús */ +const MAP_TS_CLASSES: ModelRegistry = Object.fromEntries(n4lPackagesOf(TASKS.TIME_SERIES).map(({ entry, section }) => + [section.key, n4lModelClass(entry)])) + +export { MAP_TS_CLASSES } diff --git a/src/pages/playground/5_TimeSeries/timeSeriesConfig.ts b/src/pages/playground/5_TimeSeries/timeSeriesConfig.ts new file mode 100644 index 0000000..e88298c --- /dev/null +++ b/src/pages/playground/5_TimeSeries/timeSeriesConfig.ts @@ -0,0 +1,105 @@ +import type * as tfjs from '@tensorflow/tfjs' + +import type { IdLoss_t, IdMetric_t, IdOptimizer_t } from '@/types/nn-types' +import type { N4LForecast_t, N4LLayer_t } from '@core/n4l/format' +import type { TrainingHistory_t } from '@core/training/buildModels' +import { canPrepare, DEFAULT_SEASONS, firstTarget, MIN_TRAIN_WINDOWS, testStartOf, type Frequency_t, type PreparedSeries_t, type Series_t, type SeriesPrep_t } from '@core/timeSeries/series' +import type { SeriesEvaluation_t } from '@core/timeSeries/seriesModel' +import { SERIES_OUTPUT_LAYER, type SeriesLayer_t } from '@core/timeSeries/seriesLayers' +import { chartColor } from '@core/chartColors' +import type { Theme_t } from '@core/theme' +import type { TFunction } from 'i18next' + +export const prefix = 'pages.playground.time-series.' + +// Los mismos colores en toda la página: la red al entrenar en azul y con los datos de prueba en naranja (como las +// curvas de entrenamiento y validación) y el futuro en morado +/** El resumen de la serie en una frase (para anunciarlo al cargarla): cuántos valores, desde cuándo y cada cuánto */ +export const seriesSummary = (t: TFunction, series: LoadedSeries_t) => [ + t(prefix + 'data.summary', { count: series.values.length, first: series.dates[0], last: series.dates[series.dates.length - 1] }), + ...(series.frequency !== undefined ? [t(prefix + 'frequency.' + series.frequency)] : []), + t(prefix + 'data.value-column', { column: series.valueColumn }), +].join(', ') + +export const seriesColors = (theme: Theme_t) => ({ train: chartColor('blue', theme), test: chartColor('orange', theme), future: chartColor('purple', theme) }) + +/** La serie con la que se trabaja: sus valores, de qué columna salen y cada cuánto hay uno */ +export type LoadedSeries_t = Series_t & { + /** El nombre del fichero o la clave del nombre del conjunto */ + name : string + valueColumn: string + frequency? : Frequency_t + /** Filas sin un número, que no entran en la serie */ + dropped : number + /** Si venía desordenada y se ha ordenado por fecha */ + sorted : boolean +} + +/** Cómo se entrena (además de las capas y la preparación de la serie) */ +export type SeriesHyper_t = { + learningRate: number + epochs : number + batchSize : number + optimizer : IdOptimizer_t + loss : IdLoss_t +} + +/** Se mide el error absoluto medio en cada época (con los valores escalados) */ +export const SERIES_METRICS: IdMetric_t[] = ['metrics-meanAbsoluteError'] + +export const DEFAULT_HYPER: SeriesHyper_t = { learningRate: 0.01, epochs: 50, batchSize: 32, optimizer: 'train-adam', loss: 'losses-meanSquaredError' } +export const DEFAULT_LAYERS: SeriesLayer_t[] = [{ _class: 'dense', units: 32, activation: 'relu' }, SERIES_OUTPUT_LAYER] +export const DEFAULT_TEST_SIZE = 20 + +/** Un modelo entrenado en la página: con qué se entrenó, su historial y, cuando se calcula, cómo predice */ +export type TrainedSeriesModel_t = { + model : tfjs.LayersModel + history : TrainingHistory_t + layers : SeriesLayer_t[] + prep : SeriesPrep_t + hyper : SeriesHyper_t + prepared : PreparedSeries_t + evaluation: SeriesEvaluation_t | null +} + +/** Lo que necesita «Predecir» de un modelo: él, su preparación y cómo predice (también los ya entrenados de los paquetes) */ +export type ForecastModel_t = Pick + +/** Lo que se guarda en el navegador de cada modelo (además del modelo) */ +export type StoredSeriesModel_t = Pick + +/** Las capas del manifiesto como las edita la página; la salida, protegida */ +export function seriesLayersOf(layers: N4LLayer_t[]): SeriesLayer_t[] { + return layers.flatMap((layer): SeriesLayer_t[] => { + const locked = layer.locked === true ? { is_disabled: true } : {} + switch (layer.class) { + case 'dense': + return [{ _class: 'dense', units: layer.units, activation: layer.activation, ...locked }] + case 'simpleRNN': + case 'lstm': + case 'gru': + return [{ _class: layer.class, units: layer.units, activation: layer.activation ?? 'tanh', ...locked }] + default: + return [] + } + }) +} + +/** + * La preparación con la que se empieza: la del paquete o, al subir una serie, una ventana de una estación (según su + * frecuencia; sin ella, 12 valores). Si no hay datos suficientes para esa ventana, una más corta + */ +export function initialPrep(length: number, frequency: Frequency_t | undefined, forecast?: N4LForecast_t): { prep: SeriesPrep_t, season?: number } { + const season = forecast !== undefined ? forecast.season : frequency !== undefined ? DEFAULT_SEASONS[frequency] : undefined + const prep: SeriesPrep_t = { + window : forecast?.window ?? Math.min(Math.max(season ?? 12, 4), 60), + testSize : forecast?.testSize ?? DEFAULT_TEST_SIZE, + difference: forecast?.difference ?? false, + } + while (prep.window > 1 && !canPrepare(length, prep)) prep.window = Math.max(1, Math.floor(prep.window / 2)) + return { prep, season } +} + +/** La ventana más grande que deja ejemplos para entrenar */ +export const maxWindow = (length: number, prep: SeriesPrep_t) => + Math.max(1, testStartOf(length, prep.testSize) - firstTarget({ ...prep, window: 0 }) - MIN_TRAIN_WINDOWS) diff --git a/src/pages/playground/5_TimeSeries/trainerGuide.ts b/src/pages/playground/5_TimeSeries/trainerGuide.ts new file mode 100644 index 0000000..aa864de --- /dev/null +++ b/src/pages/playground/5_TimeSeries/trainerGuide.ts @@ -0,0 +1,32 @@ +import type { GuideStep_t } from '@components/guide/N4LGuide' +import { buildGuideSteps, centerStep, guideStep, type GuideTranslate_t } from '@components/guide/buildGuideSteps' + +/** + * La guía de la página de entrenamiento de una serie (/playground/time-series/dataset/), en el orden de la + * página: la serie y su preparación, la red, cada hiperparámetro, el entrenamiento, los modelos y la predicción. Textos + * en guide.train.5-time-series.common (y, si una serie necesita los suyos, en .). Un elemento que todavía no está + * (sin la serie subida) se salta + */ +export function timeSeriesTrainerGuide(t: GuideTranslate_t, dataset: string, upload: boolean): GuideStep_t[] { + return buildGuideSteps(t, 'guide.train.5-time-series', dataset, [ + centerStep('intro'), + guideStep('session', 'session', 'bottom'), + guideStep('manual', 'manual', 'bottom'), + guideStep('dataset-info', 'dataset-info', 'bottom'), + ...(upload ? [guideStep('process', 'process')] : []), + guideStep('dataset', 'dataset'), + guideStep('preparation', 'preparation'), + guideStep('windows', 'windows'), + guideStep('layers', 'layers'), + guideStep('layers-add', 'layers-add', 'bottom'), + guideStep('learning-rate', 'hp-learning-rate'), + guideStep('epochs', 'hp-number-of-epochs'), + guideStep('batch-size', 'hp-batch-size'), + guideStep('optimizer', 'hp-optimizer'), + guideStep('loss', 'hp-loss'), + guideStep('train', 'train'), + guideStep('models', 'models'), + guideStep('predict', 'predict'), + centerStep('end'), + ]) +} diff --git a/src/pages/playground/5_TimeSeries/usePackageSeries.ts b/src/pages/playground/5_TimeSeries/usePackageSeries.ts new file mode 100644 index 0000000..94a1f3b --- /dev/null +++ b/src/pages/playground/5_TimeSeries/usePackageSeries.ts @@ -0,0 +1,47 @@ +import { useEffect, useEffectEvent, useState } from 'react' + +import type { N4LCatalogTask_t } from '@core/n4l/catalog' +import { isTableDataset, n4lTaskText, n4lNamespace } from '@core/n4l/format' +import { readDatasetInWorker } from '@core/dataframe/datasetReaderClient' +import { readSeries } from '@core/timeSeries/series' +import { fileName } from '@pages/analyze/projectDatasets' + +import type { LoadedSeries_t } from './timeSeriesConfig' + +type PackageSeries_t = { series: LoadedSeries_t | null, error: boolean } + +/** + * La serie de un paquete: su CSV, con la columna de la fecha y la del objetivo de su ficha, y su frecuencia. `pkg` + * tiene que ser el mismo objeto mientras no cambie (el catálogo da uno nuevo en cada llamada: con useMemo). `onLoaded`, + * al llegar (para prepararla) + */ +export function usePackageSeries(pkg: N4LCatalogTask_t | undefined, file: string | undefined, onLoaded?: (series: LoadedSeries_t) => void): PackageSeries_t { + const [loaded, setLoaded] = useState({ series: null, error: false }) + const notify = useEffectEvent((series: LoadedSeries_t) => onLoaded?.(series)) + + useEffect(() => { + const table = pkg?.datasets.find(isTableDataset) + const valueColumn = table?.columns.find(({ role }) => role === 'Target')?.name + const dateColumn = table?.columns.find(({ type }) => type === 'Date')?.name ?? null + if (pkg === undefined || file === undefined || table === undefined || valueColumn === undefined) return + let isCancelled = false + fetch(import.meta.env.VITE_PATH + '/' + file) + .then(async (response) => { + if (!response.ok) throw new Error(`${response.status} ${file}`) + const { columns, rows } = await readDatasetInWorker(new File([await response.blob()], fileName(file), { type: 'text/csv' })) + if (isCancelled) return + const name = n4lTaskText(n4lNamespace(pkg.entry.id), pkg.section.task) + 'name' + const series = { ...readSeries(columns, rows, valueColumn, dateColumn), name, valueColumn, frequency: table.frequency } + setLoaded({ file, error: false, series }) + notify(series) + }) + .catch((reason: unknown) => { + console.error(reason) + if (!isCancelled) setLoaded({ file, series: null, error: true }) + }) + return () => { isCancelled = true } + }, [pkg, file]) + + // Lo de otro fichero (al cambiar de conjunto) no vale + return loaded.file === file ? loaded : { series: null, error: false } +} diff --git a/src/pages/playground/Playground.tsx b/src/pages/playground/Playground.tsx index 8980218..017185b 100644 --- a/src/pages/playground/Playground.tsx +++ b/src/pages/playground/Playground.tsx @@ -1,19 +1,21 @@ import { lazy, Suspense } from 'react' import { useParams } from 'react-router' +import { Container } from 'react-bootstrap' import NotFoundPage from '../notFound/NotFoundPage' import Loading from '../Loading' -import { RegressionProvider } from '@context/RegressionContext' -import { TabularClassificationProvider } from '@context/TabularClassificationContext' import { TASKS } from '@/TASKS' +import N4LBreadcrumb from '@components/breadcrumb/N4LBreadcrumb' +import { isTask } from '@components/task/taskInfo' // Cada vista se carga bajo demanda: así una tarea no descarga los modelos y librerías -// de las demás (p. ej. la clasificación tabular no necesita face-api ni mediapipe). +// de las demás (p. ej. la clasificación tabular no necesita face-api ni mediapipe). Las de entrenar de la clasificación +// tabular y la regresión llevan su contexto, que importa danfo.js: tampoco va con el playground // Tabular Classification -const TabularClassification = lazy(() => import('./0_TabularClassification/TabularClassification')) +const TabularClassification = lazy(() => import('./0_TabularClassification/TabularClassificationPage')) const ModelReviewTabularClassification = lazy(() => import('./0_TabularClassification/ModelReviewTabularClassification')) // Regression -const Regression = lazy(() => import('./1_Regression/Regression')) +const Regression = lazy(() => import('./1_Regression/RegressionPage')) const ModelReviewRegression = lazy(() => import('./1_Regression/ModelReviewRegression')) // Object Detection const ModelReviewObjectDetection = lazy(() => import('./2_ObjectDetection/ModelReviewObjectDetection')) @@ -21,6 +23,11 @@ const ModelReviewObjectDetection = lazy(() => import('./2_ObjectDetection/ModelR const ImageClassification = lazy(() => import('./3_ImageClassification/ImageClassification')) const ModelReviewImageClassification = lazy(() => import('./3_ImageClassification/ModelReviewImageClassification')) +const Clustering = lazy(() => import('./4_Clustering/Clustering')) +// Time series +const TimeSeries = lazy(() => import('./5_TimeSeries/TimeSeries')) +const ModelReviewTimeSeries = lazy(() => import('./5_TimeSeries/ModelReviewTimeSeries')) + type MisParams = { id : string @@ -34,12 +41,8 @@ const PrintHTMLPlaygroundView = ({ id, option, example }: MisParams) => { if (option === 'model') { return } else if (option === 'dataset') { - return ( - // key: cada dataset empieza con su propio estado (modelos entrenados, predicción…) - - - - ) + // key: cada dataset empieza con su propio estado (modelos entrenados, predicción…) + return } break } @@ -47,11 +50,7 @@ const PrintHTMLPlaygroundView = ({ id, option, example }: MisParams) => { if (option === 'model') { return } else if (option === 'dataset') { - return <> - - - - + return } break } @@ -70,6 +69,16 @@ const PrintHTMLPlaygroundView = ({ id, option, example }: MisParams) => { } break } + case TASKS.CLUSTERING: { + // Se agrupa al momento: no hay modelos preentrenados + if (option === 'dataset') return + break + } + case TASKS.TIME_SERIES: { + if (option === 'model') return + if (option === 'dataset') return + break + } } // Tarea u opción no reconocida return @@ -78,12 +87,21 @@ const PrintHTMLPlaygroundView = ({ id, option, example }: MisParams) => { export default function Playground() { const { id, option, example } = useParams() if (!id || !option || !example) return null + const kind = option === 'model' || option === 'dataset' ? option : undefined return ( <>
    + {isTask(id) && kind !== undefined && + + + + } }> + {/* Otra tarea, opción o ejemplo (p. ej. desde el desplegable de las migas de pan) es otra página: se monta de + nuevo en vez de reutilizar el estado del anterior (el modelo de Car con los datos del formulario de Iris) */} readReport(), []) + const number = useMemo(() => new Intl.NumberFormat(i18n.language, { maximumSignificantDigits: 4 }), [i18n.language]) + + // Una pestaña abierta con window.open en segundo plano no tiene tamaño ni dibuja (sin requestAnimationFrame): las + // gráficas (Chart.js) se quedarían con el tamaño de ese momento, diminutas. Se dibujan al verse la pestaña + const isShown = () => document.visibilityState === 'visible' && window.innerWidth > 0 + const [hasSize, setHasSize] = useState(isShown) + useEffect(() => { + if (hasSize) return + const check = () => { if (isShown()) setHasSize(true) } + const timer = window.setInterval(check, 200) + document.addEventListener('visibilitychange', check) + window.addEventListener('resize', check) + return () => { + window.clearInterval(timer) + document.removeEventListener('visibilitychange', check) + window.removeEventListener('resize', check) + } + }, [hasSize]) + + // Al imprimir, cada gráfica (Chart.js no se redibuja bien al cambiar al tamaño del papel) sale como la imagen de lo + // que se ve en pantalla; al acabar, vuelven las gráficas. También con Ctrl+P, no solo con el botón + useEffect(() => { + const before = () => { + document.querySelectorAll('.n4l-report canvas:not(.n4l-print-hidden)').forEach((canvas) => { + const image = document.createElement('img') + image.src = canvas.toDataURL('image/png') + image.alt = '' + image.className = 'n4l-print-image' + canvas.after(image) + canvas.classList.add('n4l-print-hidden') + }) + } + const after = () => { + document.querySelectorAll('.n4l-report .n4l-print-image').forEach((image) => image.remove()) + document.querySelectorAll('.n4l-report .n4l-print-hidden').forEach((canvas) => canvas.classList.remove('n4l-print-hidden')) + } + window.addEventListener('beforeprint', before) + window.addEventListener('afterprint', after) + return () => { + window.removeEventListener('beforeprint', before) + window.removeEventListener('afterprint', after) + } + }, []) + + if (report === null) { + return ( +
    + +

    {t(prefix + 'title')}

    + +
    +
    + ) + } + + const datasetTitle = report.dataset === UPLOAD + ? t(prefix + 'uploaded') + : t(taskOptions(report.task, 'dataset').find(({ value }) => value === report.dataset)?.i18n ?? report.dataset) + const date = new Intl.DateTimeFormat(i18n.language, { dateStyle: 'long', timeStyle: 'short' }).format(new Date(report.createdAt)) + const curves = historyCurves(report.history) + const format = (values: number[] | null) => { + const last = values?.at(-1) + return last === undefined ? '—' : Number.isFinite(last) ? number.format(last) : '—' + } + + return ( +
    + +
    +
    +

    {t(prefix + 'title')}

    +

    + {t('pages.index.' + report.task + '.1-title')}, {datasetTitle}, {t('model.__index__', { index: report.model })} +

    +

    {t(prefix + 'created', { date })} (Nets4Learning)

    +
    +
    + + {t(prefix + 'back')} +
    +
    + + + + +

    {t(prefix + 'network')}

    + +
      {report.layers.map((layer, index) =>
    1. {layer}
    2. )}
    +
    +
    + + + +

    {t(prefix + 'hyperparameters')}

    + + + + {Object.entries(report.parameters).filter(([name]) => name !== 'layers').map(([name, value]) => ( + + ))} + +
    {t('generator.table-models.' + name)}{value}
    +
    +
    + +
    + + +

    {t(prefix + 'results')}

    + + + + + + + + {curves.map(({ name, train, validation }) => ( + + ))} + +
    {t(prefix + 'results-caption')}
    {t(prefix + 'metric')}{t('pages.playground.generator.training.train')}{t('pages.playground.generator.training.validation')}
    {name}{format(train)}{format(validation)}
    + + {hasSize && } + {report.evaluation !== undefined && } +
    +
    +
    +
    + ) +} diff --git a/src/pages/settings/Settings.tsx b/src/pages/settings/Settings.tsx new file mode 100644 index 0000000..3ae0d63 --- /dev/null +++ b/src/pages/settings/Settings.tsx @@ -0,0 +1,632 @@ +import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react' +import { Alert, Badge, Button, Card, Col, Container, Form, Nav, Row, Tab } from 'react-bootstrap' +import { Link, useLocation, useNavigate } from 'react-router' +import { ChevronLeft, ChevronRight } from 'react-bootstrap-icons' +import { Trans, useTranslation } from 'react-i18next' + +import { readConsent, saveConsent, type AnalyticsConsent_t } from '@core/analytics' +import { changeUserLanguage, LANGUAGE_OPTIONS, isSupportedLanguage } from '@core/i18n/language' +import { changeUserTheme, clearUserTheme, readSavedTheme, isTheme } from '@core/theme' +import { + changeUserTFBackend, + DEFAULT_TF_BACKEND, + detectWebGPUAdapter, + getActiveTFBackend, + isTFBackendAvailable, + subscribeActiveTFBackend, + TF_BACKEND_LABELS, + TF_BACKENDS, + type TFBackend_t, + type WebGPUAdapter_t, +} from '@core/tfBackend' +import { clearAllGuideProgress } from '@components/guide/guideProgress' +import { MAX_RATE, MIN_RATE, setGuideVoice, updateGuideSettings, useGuideSettings } from '@components/guide/guideSettings' +import { isSpeechSupported, useSpeech, useVoices, voicesForLanguage } from '@components/guide/speech' +import { setStepByStepEnabled, useStepByStepEnabled } from '@components/neural-network/stepByStep/stepByStepSetting' +import { deleteTrainedModels, storedModelsUsage } from '@core/training/modelStore' +import { downloadReason, setDownloadWarning, useDownloadWarning, type DownloadWarning_t } from '@core/models/downloadConsent' +import { clearOfflinePages, clearSavedModel, clearSavedModels, offlineUsage, type SavedModel_t } from '@core/offline/offline' +import { resetAllSettings } from './storedSettings' +import N4LConfirmButton from '@components/form/N4LConfirmButton' +import { useMediaQuery } from '@hooks/useMediaQuery' +import { TEXT_SIZES, updateDisplaySettings, useDisplaySettings, type DisplaySettings_t } from '@core/a11y/displaySettings' + +const prefix = 'pages.settings.' + +/** El contenido de un apartado de la configuración (su pestaña es el ancla: /settings#backend…) */ +function Section({ id, title, help, children }: { id: string, title: string, help?: string, children: ReactNode }) { + return ( + + {/* En el móvil, el ancla del apartado (/settings#privacy) y lo que recibe el foco al abrirlo */} +

    {title}

    + + {help &&

    {help}

    } + {children} +
    +
    + ) +} + +/** + * Configuración general de la aplicación: idioma y tema, accesibilidad, backend de TensorFlow.js, voz de las guías, progreso de las + * guías, herramientas para aprender (Paso a paso), cookies y lo guardado en el navegador. Los mismos ajustes que la barra de navegación y la guía, en un + * solo sitio y explicados. + */ +export default function Settings() { + const { t } = useTranslation() + const { hash } = useLocation() + // El apartado abierto va en la dirección (/settings#privacy): los enlaces llevan directos a él + const requested = decodeURIComponent(hash.slice(1)) + const section = SECTIONS.some(({ id }) => id === requested) ? requested : null + // En pantallas anchas, pestañas verticales; en el móvil, como los ajustes del teléfono: la lista de apartados y, al + // tocar uno, el apartado solo + const isWide = useMediaQuery('(min-width: 768px)') + + return ( +
    + +

    {t(prefix + 'title')}

    + {(isWide || section === null) &&

    {t(prefix + 'intro')}

    } + {isWide ? : } +
    +
    + ) +} + +/** + * Pantallas anchas: pestañas verticales a la izquierda y el apartado a la derecha. Cambiar de pestaña no añade una + * entrada al historial: «atrás» sale de la configuración + */ +function SettingsTabs({ active }: { active: string }) { + const { t } = useTranslation() + const navigate = useNavigate() + + // Si el foco estaba en el apartado que se cierra (p. ej. en un enlace a otro apartado, #speech), pasa a la pestaña + // abierta: si no, se quedaría en algo oculto + useEffect(() => { + const focused = document.activeElement + if (focused === null || focused === document.body || focused.getClientRects().length > 0) return + document.getElementById(childId(active, 'tab'))?.focus() + }, [active]) + + return ( + // Sin fundido al cambiar de apartado: el contenido aparece al momento + key !== null && key !== active && navigate({ hash: key }, { replace: true })}> + + + + + + + {SECTIONS.map(({ id, Content }) => )} + + + + + ) +} + +/** + * Móvil: la lista de apartados, cada uno con lo que tiene, y al tocar uno, ese apartado solo, con «Todos los apartados» + * para volver (también el botón atrás del teléfono: entrar en un apartado añade una entrada al historial). Al cambiar de + * vista, arriba y el foco en lo que se acaba de abrir: el título del apartado o, al volver, el apartado del que se viene + */ +function SettingsList({ active }: { active: string | null }) { + const { t } = useTranslation() + const navigate = useNavigate() + const location = useLocation() + const fromList = (location.state as { fromList?: boolean } | null)?.fromList === true + + const previous = useRef(active) + useEffect(() => { + const from = previous.current + if (from === active) return + previous.current = active + window.scrollTo({ top: 0, left: 0, behavior: 'instant' }) + if (active !== null) document.getElementById(headingId(active))?.focus({ preventScroll: true }) + else if (from !== null) document.querySelector(`[data-settings-item="${from}"]`)?.focus({ preventScroll: true }) + }, [active]) + + if (active === null) { + return ( + + ) + } + + const { Content } = SECTIONS.find(({ id }) => id === active)! + return <> + {/* Volver: si se ha llegado desde la lista, como el botón atrás; si se ha entrado directo (un enlace), a la lista */} + + + +} + +type ThemeChoice_t = 'system' | 'light' | 'dark' + +function AppearanceSettings() { + const { t, i18n } = useTranslation() + // "Como el sistema" mientras no se elija otro (no hay nada guardado) + const [theme, setTheme] = useState(() => { + const saved = readSavedTheme() + return saved !== null && isTheme(saved) ? saved : 'system' + }) + + const handleChange_Theme = (choice: ThemeChoice_t) => { + setTheme(choice) + if (choice === 'system') clearUserTheme() + else changeUserTheme(choice) + } + + return ( +
    + + {t(prefix + 'appearance.language')} + isSupportedLanguage(event.target.value) && changeUserLanguage(i18n, event.target.value)}> + {LANGUAGE_OPTIONS.map(({ language, label }) => )} + + + + {t(prefix + 'appearance.theme')} + handleChange_Theme(event.target.value as ThemeChoice_t)}> + + + + + {t(prefix + 'appearance.theme-help')} + +
    + ) +} + +/** + * Accesibilidad: el tamaño del texto, el espaciado, el contraste, el movimiento, los enlaces, el foco y el visor de + * tfjs-vis. Lo que ya pide el sistema (menos movimiento, más contraste) se aplica también sin activarlo aquí + */ +function AccessibilitySettings() { + const { t, i18n } = useTranslation() + const settings = useDisplaySettings() + const percent = new Intl.NumberFormat(i18n.language, { style: 'percent' }) + const systemReducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false + const systemMoreContrast = window.matchMedia?.('(prefers-contrast: more)').matches ?? false + const flags: Array<{ key: Exclude, note?: string }> = [ + { key: 'spacing' }, + { key: 'highContrast', note: systemMoreContrast ? t(prefix + 'accessibility.system-on') : undefined }, + { key: 'reduceMotion', note: systemReducedMotion ? t(prefix + 'accessibility.system-on') : undefined }, + { key: 'underlineLinks' }, + { key: 'strongFocus' }, + { key: 'openVisor' }, + ] + + return ( +
    + {/* Fuera de las analíticas: ni los clics en estos ajustes (docs/analytics.md) */} +
    +
    + {t(prefix + 'accessibility.text-size')} + {TEXT_SIZES.map((size) => ( + updateDisplaySettings({ textSize: size })} /> + ))} +
    + {flags.map(({ key, note }) => ( +
    + updateDisplaySettings({ [key]: event.target.checked })} /> + + {t(prefix + 'accessibility.' + key + '-help')}{note !== undefined && <> {note}} + +
    + ))} +

    + {t(prefix + 'accessibility.guide')} {t(prefix + 'speech.title')} +

    +
    +
    + ) +} + +function BackendSettings() { + const { t } = useTranslation() + const active = useSyncExternalStore(subscribeActiveTFBackend, getActiveTFBackend) + const [changing, setChanging] = useState(false) + // Que exista navigator.gpu no basta para WebGPU: se pregunta qué adaptador hay (undefined mientras no se sabe) + const [webgpuAdapter, setWebgpuAdapter] = useState(undefined) + const [failed, setFailed] = useState(null) + + useEffect(() => { + if (isTFBackendAvailable('webgpu')) detectWebGPUAdapter().then(setWebgpuAdapter) + }, []) + + const handleChange_Backend = async (backend: TFBackend_t) => { + setChanging(true) + setFailed(null) + const changed = await changeUserTFBackend(backend) + setChanging(false) + if (!changed) setFailed(backend) + } + + return ( +
    +
    + {t(prefix + 'backend.title')} + {TF_BACKENDS.map((backend) => { + const available = isTFBackendAvailable(backend) && (backend !== 'webgpu' || webgpuAdapter !== null) + return ( + + handleChange_Backend(backend)} /> + + {TF_BACKEND_LABELS[backend]} + {active === backend && {t(prefix + 'backend.active')}} + {backend === DEFAULT_TF_BACKEND && {t('header.backend-default')}} + {!available && {t('header.backend-unavailable')}} + {backend === 'webgpu' && webgpuAdapter === 'software' && {t('header.backend-software')}} + {t(prefix + 'backend.' + backend)} + + + ) + })} +
    + {failed !== null && + + {t('header.backend-error', { backend: TF_BACKEND_LABELS[failed] })}. {t('header.backend-error-fallback', { backend: TF_BACKEND_LABELS[active] })} + } +
    + ) +} + +function SpeechSettings() { + const { t, i18n } = useTranslation() + const { voice, auto, rate, voices: chosen } = useGuideSettings() + const language = (i18n.language || 'es').slice(0, 2) + const voices = voicesForLanguage(useVoices(), language) + const voiceURI = voices.some((option) => option.voiceURI === chosen[language]) ? chosen[language] : '' + const { speak, cancel, speaking } = useSpeech(i18n.language, { voiceURI, rate }) + const format = useMemo(() => new Intl.NumberFormat(i18n.language, { minimumFractionDigits: 1, maximumFractionDigits: 2 }), [i18n.language]) + + if (!isSpeechSupported()) { + return ( +
    + {t('guide.no-voice')} +
    + ) + } + + return ( +
    + updateGuideSettings({ voice: event.target.checked })} /> + {/* El lector de pantalla ya dice cada paso: con las dos voces a la vez no se entiende ninguna */} + {t(prefix + 'speech.screen-reader')} + updateGuideSettings({ auto: event.target.checked })} /> + + {t('guide.voice')} + setGuideVoice(language, event.target.value)}> + + {voices.map((option) => ( + + ))} + + {voices.length === 0 ? t(prefix + 'speech.no-voices') : t(prefix + 'speech.voice-help')} + + + {t(prefix + 'speech.rate', { rate: format.format(rate) })} + updateGuideSettings({ rate: Number(event.target.value) })} /> + + +
    + ) +} + +function TutorialSettings() { + const { t } = useTranslation() + const [guidesReset, setGuidesReset] = useState(false) + + return ( +
    +

    {t(prefix + 'tutorials.guides-help')}

    +
    + + {guidesReset && {t(prefix + 'tutorials.done')}} +
    +
    + ) +} + +const DOWNLOAD_WARNINGS: DownloadWarning_t[] = ['auto', 'always', 'never'] + +/** Si se pregunta antes de descargar un modelo preentrenado grande, y qué dice ahora el navegador de la conexión */ +function DownloadSettings() { + const { t } = useTranslation() + const warning = useDownloadWarning() + const connection = (navigator as Navigator & { connection?: { saveData?: boolean, effectiveType?: string } }).connection + const now = downloadReason('auto', connection) ?? 'normal' + return ( +
    +
    + {t(prefix + 'downloads.title')} + {DOWNLOAD_WARNINGS.map((value) => ( + + setDownloadWarning(value)} /> + + {t(prefix + 'downloads.' + value)} + {t(prefix + 'downloads.' + value + '-help')} + + + ))} +
    +

    {t(prefix + 'downloads.now-' + now)}

    +

    + }} /> +

    +
    + ) +} + +/** Lo que se puede enseñar de más en las páginas para aprender: de momento, Paso a paso (oculto por defecto) */ +function LearningSettings() { + const { t } = useTranslation() + const stepByStep = useStepByStepEnabled() + return ( +
    + setStepByStepEnabled(event.target.checked)} /> +

    {t(prefix + 'learning.step-by-step-help')}

    +
    + ) +} + +function PrivacySettings() { + const { t } = useTranslation() + const [consent, setConsent] = useState(readConsent) + + const handleChange_Consent = (accepted: boolean) => { + const decision = accepted ? 'accepted' : 'rejected' + saveConsent(decision, 'settings') + setConsent(decision) + } + + return ( +
    + handleChange_Consent(event.target.checked)} /> +

    + {t(prefix + 'privacy.status-' + (consent ?? 'undecided'))} +

    + {t(prefix + 'privacy.more')} +
    + ) +} + +/** Un tamaño en el idioma de la página, en la unidad que toque: «350 kB», «12,4 MB», «1,2 GB» */ +function formatBytes(bytes: number, language: string): string { + const [value, unit] = bytes >= 1024 ** 3 ? [bytes / 1024 ** 3, 'gigabyte'] : bytes >= 1024 ** 2 ? [bytes / 1024 ** 2, 'megabyte'] : [bytes / 1024, 'kilobyte'] + return new Intl.NumberFormat(language, { style: 'unit', unit, maximumFractionDigits: 1 }).format(value) +} + +type Usage_t = { count: number, bytes: number } +type StoredUsage_t = { + trained : Usage_t + // Lo de las cachés del service worker (null si el navegador no tiene Cache Storage); los modelos, uno a uno + pretrained: (Usage_t & { list: SavedModel_t[] }) | null + offline : Usage_t | null + // Lo que ocupa la web en total y lo que le deja el navegador (null si no lo dice) + total : { usage: number, quota: number } | null +} + +async function readStoredUsage(): Promise { + const [trained, cached, estimate] = await Promise.all([ + storedModelsUsage(), + typeof caches === 'undefined' ? null : offlineUsage(), + navigator.storage?.estimate?.().catch(() => null) ?? null, + ]) + return { + trained, + // Cuántos modelos: los ficheros que no son de ninguno conocido no cuentan como uno + pretrained: cached === null ? null : { + count: cached.models.list.filter(({ model }) => model !== null).length, + bytes: cached.models.bytes, + list : cached.models.list, + }, + offline: cached === null ? null : { count: cached.files - cached.models.files, bytes: cached.bytes - cached.models.bytes }, + total : estimate?.usage === undefined ? null : { usage: estimate.usage, quota: estimate.quota ?? 0 }, + } +} + +/** + * Una cosa guardada: qué es, cuánto hay (cuánto ocupa y cuántos son) y, si hay algo, el botón para borrarlo y el + * detalle (`children`, debajo) + */ +function StoredItem({ id, usage, action, children }: { id: string, usage?: Usage_t, action?: ReactNode, children?: ReactNode }) { + const { t, i18n } = useTranslation() + const hasData = usage !== undefined && (usage.count > 0 || usage.bytes > 0) + return ( +
  • +
    + {t(prefix + 'data.' + id + '.title')} + {t(prefix + 'data.' + id + '.help')} +
    + {usage !== undefined && +
    + + {hasData && {formatBytes(usage.bytes, i18n.language)}} + {t(prefix + 'data.' + id + '.count', { count: usage.count })} + + {hasData && action} +
    } + {children} +
  • + ) +} + +/** Los modelos preentrenados guardados, cada uno con lo que ocupa, un enlace a su página y un botón para borrarlo */ +function SavedModelsList({ list, onDelete }: { list: SavedModel_t[], onDelete: (model: SavedModel_t['model']) => Promise }) { + const { t, i18n } = useTranslation() + return ( +
      + {list.map(({ model, bytes }) => { + const name = model === null ? t(prefix + 'data.pretrained.other') : t(model.title) + return ( +
    • + {model === null + ? {name} + : {name}} + + {formatBytes(bytes, i18n.language)} + onDelete(model)} /> + +
    • + ) + })} +
    + ) +} + +/** + * Lo guardado en el navegador, cada cosa con lo que ocupa y su botón para borrarla: los modelos entrenados, los + * preentrenados descargados, lo guardado para usar sin conexión (en la versión publicada) y los ajustes. Y, aparte, + * restablecerlo todo + */ +function StoredDataSettings() { + const { t, i18n } = useTranslation() + const [usage, setUsage] = useState(null) + const [confirming, setConfirming] = useState(false) + + useEffect(() => { + let isCancelled = false + readStoredUsage().then((result) => { + if (!isCancelled) setUsage(result) + }) + return () => { isCancelled = true } + }, []) + + const deleteAndRefresh = async (remove: () => Promise) => { + await remove() + setUsage(await readStoredUsage()) + } + const handleClick_Reset = async () => { + await resetAllSettings() + // Para que todo vuelva a su valor por defecto (idioma del navegador, tema del sistema…) + window.location.reload() + } + const confirmLabel = t(prefix + 'data.delete-confirm') + + return ( +
    + {usage?.total && +

    + }} /> +

    } +
      + deleteAndRefresh(() => deleteTrainedModels())} />} /> + {usage?.pretrained && + deleteAndRefresh(clearSavedModels)} />}> + {usage.pretrained.list.length > 0 && + deleteAndRefresh(() => clearSavedModel(model))} />} + } + {import.meta.env.PROD && usage?.offline && + deleteAndRefresh(clearOfflinePages)} />} />} + +
    + +
    +

    {t(prefix + 'data.reset')}

    +

    {t(prefix + 'data.reset-help')}

    + {!confirming && } + {confirming && + +

    {t(prefix + 'data.confirm')}

    +
    + + +
    +
    } +
    +
    + ) +} + +// Los apartados, en el orden de las pestañas: cada uno con su ancla (/settings#privacy…) y su contenido +const SECTIONS = [ + { id: 'appearance', Content: AppearanceSettings }, + { id: 'accessibility', Content: AccessibilitySettings }, + { id: 'backend', Content: BackendSettings }, + { id: 'downloads', Content: DownloadSettings }, + { id: 'speech', Content: SpeechSettings }, + { id: 'tutorials', Content: TutorialSettings }, + { id: 'learning', Content: LearningSettings }, + { id: 'privacy', Content: PrivacySettings }, + { id: 'data', Content: StoredDataSettings }, +] as const + +/** + * Los ids de las pestañas y de sus paneles. /settings#privacy lleva a la pestaña (data-hash-target, en + * N4LScrollManager), le da el foco (el lector la anuncia) y deja la página arriba: las pestañas ya se ven al cargarla + */ +const childId = (key: unknown, type: string) => `settings-${type}-${String(key)}` +/** El id del título de cada apartado (al que va el foco al abrirlo en el móvil) */ +const headingId = (section: string) => `settings-heading-${section}` diff --git a/src/pages/settings/storedSettings.ts b/src/pages/settings/storedSettings.ts new file mode 100644 index 0000000..08078a3 --- /dev/null +++ b/src/pages/settings/storedSettings.ts @@ -0,0 +1,49 @@ +import { clearConsent } from '@core/analytics' +import { LANGUAGE_STORAGE_KEY } from '@core/i18n/language' +import { THEME_STORAGE_KEY } from '@core/theme' +import { TF_BACKEND_STORAGE_KEY } from '@core/tfBackend' +import { clearAllGuideProgress } from '@components/guide/guideProgress' +import { resetGuideSettings } from '@components/guide/guideSettings' +import { resetStepByStep } from '@components/neural-network/stepByStep/stepByStepSetting' +import { deleteTrainedModels } from '@core/training/modelStore' +import { resetDownloadConsent } from '@core/models/downloadConsent' +import { resetLearningPath } from '@core/learning/learningPath' +import { clearOfflineData } from '@core/offline/offline' +import { resetDisplaySettings } from '@core/a11y/displaySettings' + +// Lo que la aplicación guarda en el navegador (localStorage y la cookie del consentimiento), para borrarlo desde +// /settings. + +/** + * Las versiones anteriores tenían en las páginas de entrenamiento un tutorial que apuntaba si ya se había visto + * (.joyride-). Ahora son guías como las demás, pero esas claves pueden seguir en el navegador. + */ +function removeLegacyTutorialKeys() { + try { + Object.keys(localStorage).filter((key) => key.includes('.joyride-')).forEach((key) => localStorage.removeItem(key)) + } catch { + // Sin almacenamiento no había nada guardado + } +} + +/** + * Borra todos los ajustes: idioma, tema, accesibilidad, backend, voz y progreso de las guías, Paso a paso, el aviso de descargas, el + * progreso de «Empieza aquí», modelos guardados, lo guardado para usar sin conexión y cookies + */ +export async function resetAllSettings() { + try { + [LANGUAGE_STORAGE_KEY, THEME_STORAGE_KEY, TF_BACKEND_STORAGE_KEY].forEach((key) => localStorage.removeItem(key)) + } catch { + // Sin almacenamiento no había nada guardado + } + resetGuideSettings() + resetDisplaySettings() + clearAllGuideProgress() + resetStepByStep() + resetDownloadConsent() + resetLearningPath() + removeLegacyTutorialKeys() + clearConsent() + await deleteTrainedModels() + await clearOfflineData() +} diff --git a/src/pages/task/Task.tsx b/src/pages/task/Task.tsx new file mode 100644 index 0000000..8410555 --- /dev/null +++ b/src/pages/task/Task.tsx @@ -0,0 +1,87 @@ +import { Card, Col, Container, Row } from 'react-bootstrap' +import { Link, Navigate, useParams } from 'react-router' +import { useTranslation } from 'react-i18next' + +import { TASKS, UPLOAD, type TASKS_TYPE_V } from '@/TASKS' +import { taskOptions, type TaskKind_t } from '@/TASK_OPTIONS' +import { isTask, TASK_INFO } from '@components/task/taskInfo' +import N4LBreadcrumb from '@components/breadcrumb/N4LBreadcrumb' + +const prefix = 'pages.task.' + +type TaskOptionProps = { + task : TASKS_TYPE_V + kind : TaskKind_t + /** Claves i18n del título, el texto y el botón */ + texts: { title: string, text: string, button: string, count: string } +} + +/** Una de las dos maneras de usar la tarea: su explicación, sus modelos o conjuntos (cada uno abre el suyo) y el botón */ +function TaskOption({ task, kind, texts }: TaskOptionProps) { + const { t } = useTranslation() + const options = taskOptions(task, kind) + const items = options.filter(({ value }) => value !== UPLOAD) + const canUpload = options.some(({ value }) => value === UPLOAD) + const href = (value: string) => `/playground/${task}/${kind}/${value}` + return ( + + +

    {t(texts.title)}

    +

    {t(texts.text)}

    +

    {t(texts.count, { count: items.length })}

    +
      + {items.map(({ value, i18n }) => ( +
    • {t(i18n)}
    • + ))} + {canUpload &&
    • {t(prefix + 'upload')}
    • } +
    +
    + {t(texts.button)} +
    +
    +
    + ) +} + +/** + * La página de una tarea (desde «Tareas» en la cabecera): elegir entre probar los modelos ya entrenados o diseñar, + * crear y entrenar una red con un conjunto de datos. Identificación de objetos solo tiene modelos ya entrenados y + * el agrupamiento, solo conjuntos de datos (sin red: k-means) + */ +export default function Task() { + const { id } = useParams<{ id: string }>() + const { t } = useTranslation() + if (!isTask(id)) return + const hasModels = taskOptions(id, 'model').length > 0 + const hasDatasets = taskOptions(id, 'dataset').some(({ value }) => value !== UPLOAD) + const isClustering = id === TASKS.CLUSTERING + + return ( +
    + + +
    +

    {t(TASK_INFO[id].i18nTitle)}

    +

    {t(`pages.index.${id}.1-description-1`)}

    +
    + + {hasModels && + + + } + {hasDatasets && + + + } + + {/* Si falta una de las dos, por qué */} + {!hasDatasets &&

    {t(prefix + 'only-pretrained')}

    } + {isClustering &&

    {t(prefix + 'only-cluster')}

    } +
    +
    + ) +} diff --git a/src/pages/terms/TermsAndConditions.tsx b/src/pages/terms/TermsAndConditions.tsx index 82a5abc..24b0bb1 100644 --- a/src/pages/terms/TermsAndConditions.tsx +++ b/src/pages/terms/TermsAndConditions.tsx @@ -1,41 +1,125 @@ -import { Card, Col, Container, Row } from 'react-bootstrap' -import { Trans } from 'react-i18next' +import { useState, type ReactNode } from 'react' +import { Alert, Button, Card, Container, Nav, Table } from 'react-bootstrap' +import { Link } from 'react-router' +import { useTranslation } from 'react-i18next' + +import { readConsent, saveConsent, type AnalyticsConsent_t } from '@core/analytics' +import AnalyticsDisclosure from '@components/cookiesBanner/AnalyticsDisclosure' import { VERBOSE } from '@/CONSTANTS' -export default function TermsAndConditions () { - - if(VERBOSE) console.debug('render TermsAndConditions') - return <> -
    - - -

    -
    - - - - -

    - - - - - -
    - - -

    - - - - - -
    - - -
    +const prefix = 'pages.terms.' + +// Los apartados, en orden: cada uno con su ancla (el enlace "Preferencias de cookies" del pie apunta a #cookies) +const SECTIONS = ['use', 'privacy', 'storage', 'third-parties', 'cookies', 'contact'] as const + +// Las cookies que se pueden guardar: la de la decisión siempre; las de Google Analytics, solo si se aceptan +const COOKIES = [ + { name: 'n4l-accept-cookies', key: 'consent' }, + { name: '_ga', key: 'ga' }, + { name: '_ga_', key: 'ga-session' }, +] as const + +function Section({ id, children }: { id: string, children: ReactNode }) { + const { t } = useTranslation() + return ( + +

    {t(prefix + id + '.title')}

    + {children} +
    + ) +} + +/** Términos de uso, privacidad (qué se procesa y qué se guarda), servicios externos, cookies y contacto */ +export default function TermsAndConditions() { + const { t } = useTranslation() + const [consent, setConsent] = useState(readConsent) + // Las listas vienen de la traducción (un elemento por línea) + const list = (key: string) => { + const items = t(prefix + key, { returnObjects: true }) + return Array.isArray(items) ? items as string[] : [] + } + const items = (key: string) => ( +
      {list(key).map((item) =>
    • {item}
    • )}
    + ) + + const handleClick_Decide = (decision: AnalyticsConsent_t) => { + saveConsent(decision, 'terms') + setConsent(decision) + } + + if (VERBOSE) console.debug('render TermsAndConditions') + return ( +
    + +

    {t(prefix + 'title')}

    +

    {t(prefix + 'updated')}

    + + +

    {t(prefix + 'summary-title')}

    + {items('summary')} +
    + + + +
    {items('use.items')}
    + +
    +

    {t(prefix + 'privacy.text')}

    + {items('privacy.items')} +
    + +
    +

    {t(prefix + 'storage.text')}

    + {items('storage.items')} +

    + {t(prefix + 'storage.settings')} {t('footer.settings')}. +

    +
    + +
    {items('third-parties.items')}
    + +
    +

    {t(prefix + 'cookies.text')}

    + + + + + + + + + + {COOKIES.map(({ name, key }) => ( + + + + + + ))} + +
    {t(prefix + 'cookies.name')}{t(prefix + 'cookies.purpose')}{t(prefix + 'cookies.duration')}
    {name}{t(prefix + 'cookies.' + key + '.purpose')}{t(prefix + 'cookies.' + key + '.duration')}
    +
    + +
    +
    + {t('pages.settings.privacy.status-' + (consent ?? 'undecided'))} + + +
    +
    + +
    +

    {t(prefix + 'contact.text')}

    + +
    - - -} \ No newline at end of file + ) +} diff --git a/src/pages/version/Version.tsx b/src/pages/version/Version.tsx index 757f995..5bd066d 100644 --- a/src/pages/version/Version.tsx +++ b/src/pages/version/Version.tsx @@ -1,68 +1,118 @@ -import { Card, Col, Container, Row, Table } from 'react-bootstrap' -import { Trans } from 'react-i18next' +import { Fragment, useMemo, useState, useSyncExternalStore, version as reactVersion } from 'react' +import { Badge, Card, Col, Container, Form, Row, Tab, Table, Tabs } from 'react-bootstrap' +import { useTranslation } from 'react-i18next' +import * as tfjs from '@tensorflow/tfjs' + import packageInfo from '../../../package.json' +import { getActiveTFBackend, subscribeActiveTFBackend, TF_BACKEND_LABELS } from '@core/tfBackend' + +const REPOSITORY = 'https://github.com/SIMIDAT/nets4learning' + +type Dependencies_t = Record + +/** Una tabla de dependencias (nombre con enlace a npm y versión declarada), filtrada por lo que se busca */ +function DependencyTable({ dependencies, filter }: { dependencies: Dependencies_t, filter: string }) { + const { t } = useTranslation() + const rows = Object.entries(dependencies).filter(([name]) => name.toLowerCase().includes(filter.trim().toLowerCase())) + if (rows.length === 0) return

    {t('pages.version.no-results')}

    + return ( + + + + + + + + + {rows.map(([name, range]) => ( + + + + + ))} + +
    {t('pages.version.package')}{t('pages.version.declared')}
    {name}{range}
    + ) +} + +/** La versión de la aplicación, con qué se está ejecutando y de qué depende */ +export default function Version() { + const { t } = useTranslation() + const prefix = 'pages.version.' + const backend = useSyncExternalStore(subscribeActiveTFBackend, getActiveTFBackend) + const [filter, setFilter] = useState('') + + // Lo que se ejecuta de verdad (no el rango declarado en package.json) + const runtime = useMemo(() => [ + { label: t(prefix + 'app'), value: packageInfo.version }, + { label: t(prefix + 'environment'), value: `${import.meta.env.VITE_ENVIRONMENT ?? '—'} (${import.meta.env.MODE})` }, + { label: 'TensorFlow.js', value: tfjs.version.tfjs }, + { label: t(prefix + 'backend'), value: TF_BACKEND_LABELS[backend] }, + { label: 'React', value: reactVersion }, + ], [t, backend]) -export default function Version () { + const dependencies = packageInfo.dependencies as Dependencies_t + const devDependencies = packageInfo.devDependencies as Dependencies_t - return <> - - - -

    N4L App {packageInfo.version}

    - -
    - - - - -

    -
    - - - - - - - - - - {Object.entries(packageInfo.dependencies).map(([dependency_name, dependency_version], index) => { - return - - - - })} - -
    {dependency_name}{dependency_version}
    -
    -
    + return ( +
    + +

    {t(prefix + 'title')}

    +

    + Nets4Learning {packageInfo.version} +

    - - -

    -
    - - - - - - - - - - {Object.entries(packageInfo.devDependencies).map(([dependency_name, dependency_version], index) => { - return - - - - })} - -
    {dependency_name}{dependency_version}
    -
    -
    + + + +

    {t(prefix + 'runtime')}

    + +
    + {runtime.map(({ label, value }) => ( + +
    {label}
    +
    {value}
    +
    + ))} +
    +
    +
    + + + +

    {t(prefix + 'changes')}

    + +

    {t(prefix + 'changes-text')}

    + +
    +
    + +
    - - -
    - + + +

    {t(prefix + 'dependencies')}

    + setFilter(event.target.value)} /> +
    + +

    {t(prefix + 'dependencies-help')}

    + + + + + + + + +
    +
    + +
    + ) } diff --git a/src/styles/fonts/Barlow-Regular.woff2 b/src/styles/fonts/Barlow-Regular.woff2 new file mode 100644 index 0000000..f1be346 Binary files /dev/null and b/src/styles/fonts/Barlow-Regular.woff2 differ diff --git a/src/styles/fonts/Barlow-SemiBold.woff2 b/src/styles/fonts/Barlow-SemiBold.woff2 new file mode 100644 index 0000000..74f3f4f Binary files /dev/null and b/src/styles/fonts/Barlow-SemiBold.woff2 differ diff --git a/src/types/jszip-utils.d.ts b/src/types/jszip-utils.d.ts index 903f1c4..c748674 100644 --- a/src/types/jszip-utils.d.ts +++ b/src/types/jszip-utils.d.ts @@ -1,4 +1,4 @@ -declare module "jszip-utils" { +declare module 'jszip-utils' { export function getBinaryContent( path: string, callback: (err: Error | null, data: any) => void diff --git a/src/types/nn-types.ts b/src/types/nn-types.ts index ffaff80..bb5e377 100644 --- a/src/types/nn-types.ts +++ b/src/types/nn-types.ts @@ -2,98 +2,96 @@ import * as tfjs from '@tensorflow/tfjs'; // Train Map -> Optimizers export type TrainMap_t = { - "sgd" : tfjs.SGDOptimizer; - "momentum" : tfjs.MomentumOptimizer; - "adagrad" : tfjs.AdagradOptimizer; - "adadelta" : tfjs.AdadeltaOptimizer; - "adamax" : tfjs.AdamaxOptimizer; - "adam" : tfjs.AdamOptimizer; - "rmsprop" : tfjs.RMSPropOptimizer; - "train-sgd" : tfjs.SGDOptimizer; - "train-momentum": tfjs.MomentumOptimizer; - "train-adagrad" : tfjs.AdagradOptimizer; - "train-adadelta": tfjs.AdadeltaOptimizer; - "train-adamax" : tfjs.AdamaxOptimizer; - "train-adam" : tfjs.AdamOptimizer; - "train-rmsprop" : tfjs.RMSPropOptimizer; + 'sgd' : tfjs.SGDOptimizer; + 'momentum' : tfjs.MomentumOptimizer; + 'adagrad' : tfjs.AdagradOptimizer; + 'adadelta' : tfjs.AdadeltaOptimizer; + 'adamax' : tfjs.AdamaxOptimizer; + 'adam' : tfjs.AdamOptimizer; + 'rmsprop' : tfjs.RMSPropOptimizer; + 'train-sgd' : tfjs.SGDOptimizer; + 'train-momentum': tfjs.MomentumOptimizer; + 'train-adagrad' : tfjs.AdagradOptimizer; + 'train-adadelta': tfjs.AdadeltaOptimizer; + 'train-adamax' : tfjs.AdamaxOptimizer; + 'train-adam' : tfjs.AdamOptimizer; + 'train-rmsprop' : tfjs.RMSPropOptimizer; } export type IdOptimizer_t = keyof TrainMap_t // Losses and Metrics export type LossAndMetricMap_t = { // Losses - "losses-absoluteDifference" : "absoluteDifference" | typeof tfjs.losses.absoluteDifference - "losses-computeWeightedLoss" : "computeWeightedLoss" | typeof tfjs.losses.computeWeightedLoss - "losses-cosineDistance" : "cosineDistance" | typeof tfjs.losses.cosineDistance - "losses-hingeLoss" : "hingeLoss" | typeof tfjs.losses.hingeLoss - "losses-huberLoss" : "huberLoss" | typeof tfjs.losses.huberLoss - "losses-logLoss" : "logLoss" | typeof tfjs.losses.logLoss - "losses-meanSquaredError" : "meanSquaredError" | typeof tfjs.losses.meanSquaredError - "losses-sigmoidCrossEntropy" : "sigmoidCrossEntropy" | typeof tfjs.losses.sigmoidCrossEntropy - "losses-softmaxCrossEntropy" : "softmaxCrossEntropy" | typeof tfjs.losses.softmaxCrossEntropy - "accuracy" : "accuracy" - "metrics-accuracy" : "accuracy" - "metrics-binaryAccuracy" : "binaryAccuracy" | typeof tfjs.metrics.binaryAccuracy - "metrics-binaryCrossentropy" : "binaryCrossentropy" | typeof tfjs.metrics.binaryCrossentropy - "metrics-categoricalAccuracy" : "categoricalAccuracy" | typeof tfjs.metrics.categoricalAccuracy - "metrics-categoricalCrossentropy" : "categoricalCrossentropy" | typeof tfjs.metrics.categoricalCrossentropy - "metrics-cosineProximity" : "cosineProximity" | typeof tfjs.metrics.cosineProximity - "metrics-meanAbsoluteError" : "meanAbsoluteError" | typeof tfjs.metrics.meanAbsoluteError - "metrics-meanAbsolutePercentageError": "meanAbsolutePercentageError" | typeof tfjs.metrics.meanAbsolutePercentageError - "metrics-meanSquaredError" : "meanSquaredError" | typeof tfjs.metrics.meanSquaredError - "metrics-precision" : "precision" | typeof tfjs.metrics.precision - "metrics-recall" : "recall" | typeof tfjs.metrics.recall - "metrics-sparseCategoricalAccuracy" : "sparseCategoricalAccuracy" | typeof tfjs.metrics.sparseCategoricalAccuracy + 'losses-absoluteDifference' : 'absoluteDifference' | typeof tfjs.losses.absoluteDifference + 'losses-computeWeightedLoss' : 'computeWeightedLoss' | typeof tfjs.losses.computeWeightedLoss + 'losses-cosineDistance' : 'cosineDistance' | typeof tfjs.losses.cosineDistance + 'losses-hingeLoss' : 'hingeLoss' | typeof tfjs.losses.hingeLoss + 'losses-huberLoss' : 'huberLoss' | typeof tfjs.losses.huberLoss + 'losses-logLoss' : 'logLoss' | typeof tfjs.losses.logLoss + 'losses-meanSquaredError' : 'meanSquaredError' | typeof tfjs.losses.meanSquaredError + 'losses-sigmoidCrossEntropy' : 'sigmoidCrossEntropy' | typeof tfjs.losses.sigmoidCrossEntropy + 'losses-softmaxCrossEntropy' : 'softmaxCrossEntropy' | typeof tfjs.losses.softmaxCrossEntropy + 'accuracy' : 'accuracy' + 'metrics-accuracy' : 'accuracy' + 'metrics-binaryAccuracy' : 'binaryAccuracy' | typeof tfjs.metrics.binaryAccuracy + 'metrics-binaryCrossentropy' : 'binaryCrossentropy' | typeof tfjs.metrics.binaryCrossentropy + 'metrics-categoricalAccuracy' : 'categoricalAccuracy' | typeof tfjs.metrics.categoricalAccuracy + 'metrics-categoricalCrossentropy' : 'categoricalCrossentropy' | typeof tfjs.metrics.categoricalCrossentropy + 'metrics-cosineProximity' : 'cosineProximity' | typeof tfjs.metrics.cosineProximity + 'metrics-meanAbsoluteError' : 'meanAbsoluteError' | typeof tfjs.metrics.meanAbsoluteError + 'metrics-meanAbsolutePercentageError': 'meanAbsolutePercentageError' | typeof tfjs.metrics.meanAbsolutePercentageError + 'metrics-meanSquaredError' : 'meanSquaredError' | typeof tfjs.metrics.meanSquaredError + 'metrics-precision' : 'precision' | typeof tfjs.metrics.precision + 'metrics-recall' : 'recall' | typeof tfjs.metrics.recall + 'metrics-sparseCategoricalAccuracy' : 'sparseCategoricalAccuracy' | typeof tfjs.metrics.sparseCategoricalAccuracy } export type IdLossAndMetric_t = keyof LossAndMetricMap_t -export type LossMap_t = { - "absoluteDifference" : "absoluteDifference" // | typeof tfjs.losses.absoluteDifference - "computeWeightedLoss" : "computeWeightedLoss" // | typeof tfjs.losses.computeWeightedLoss - "cosineDistance" : "cosineDistance" // | typeof tfjs.losses.cosineDistance - "hingeLoss" : "hingeLoss" // | typeof tfjs.losses.hingeLoss - "huberLoss" : "huberLoss" // | typeof tfjs.losses.huberLoss - "logLoss" : "logLoss" // | typeof tfjs.losses.logLoss - "meanSquaredError" : "meanSquaredError" // | typeof tfjs.losses.meanSquaredError - "sigmoidCrossEntropy" : "sigmoidCrossEntropy" // | typeof tfjs.losses.sigmoidCrossEntropy - "softmaxCrossEntropy" : "softmaxCrossEntropy" // | typeof tfjs.losses.softmaxCrossEntropy - "losses-absoluteDifference" : "absoluteDifference" // | typeof tfjs.losses.absoluteDifference - "losses-computeWeightedLoss": "computeWeightedLoss" // | typeof tfjs.losses.computeWeightedLoss - "losses-cosineDistance" : "cosineDistance" // | typeof tfjs.losses.cosineDistance - "losses-hingeLoss" : "hingeLoss" // | typeof tfjs.losses.hingeLoss - "losses-huberLoss" : "huberLoss" // | typeof tfjs.losses.huberLoss - "losses-logLoss" : "logLoss" // | typeof tfjs.losses.logLoss - "losses-meanSquaredError" : "meanSquaredError" // | typeof tfjs.losses.meanSquaredError - "losses-sigmoidCrossEntropy": "sigmoidCrossEntropy" // | typeof tfjs.losses.sigmoidCrossEntropy - "losses-softmaxCrossEntropy": "softmaxCrossEntropy" // | typeof tfjs.losses.softmaxCrossEntropy -} +// Pérdidas que model.compile() acepta por nombre (lossesMap de @tensorflow/tfjs-layers). +// Las de tf.losses.* (absoluteDifference, huberLoss, softmaxCrossEntropy…) no valen: lanzan "Unknown loss". +export type LossName_t = + | 'meanSquaredError' + | 'meanAbsoluteError' + | 'meanAbsolutePercentageError' + | 'meanSquaredLogarithmicError' + | 'logcosh' + | 'poisson' + | 'cosineProximity' + | 'categoricalCrossentropy' + | 'binaryCrossentropy' + | 'kullbackLeiblerDivergence' + | 'hinge' + | 'squaredHinge' + | 'categoricalHinge' +// La clave puede llevar el prefijo "losses-", como los valores de los selectores +export type LossMap_t = { [K in LossName_t]: K } & { [K in LossName_t as `losses-${K}`]: K } export type IdLoss_t = keyof LossMap_t // Metrics export type MetricMap_t = { - "binaryAccuracy" : "binaryAccuracy" | typeof tfjs.metrics.binaryAccuracy - "binaryCrossentropy" : "binaryCrossentropy" | typeof tfjs.metrics.binaryCrossentropy - "categoricalAccuracy" : "categoricalAccuracy" | typeof tfjs.metrics.categoricalAccuracy - "categoricalCrossentropy" : "categoricalCrossentropy" | typeof tfjs.metrics.categoricalCrossentropy - "cosineProximity" : "cosineProximity" | typeof tfjs.metrics.cosineProximity - "meanAbsoluteError" : "meanAbsoluteError" | typeof tfjs.metrics.meanAbsoluteError - "meanAbsolutePercentageError" : "meanAbsolutePercentageError" | typeof tfjs.metrics.meanAbsolutePercentageError - "meanSquaredError" : "meanSquaredError" | typeof tfjs.metrics.meanSquaredError - "precision" : "precision" | typeof tfjs.metrics.precision - "recall" : "recall" | typeof tfjs.metrics.recall - "sparseCategoricalAccuracy" : "sparseCategoricalAccuracy" | typeof tfjs.metrics.sparseCategoricalAccuracy + 'binaryAccuracy' : 'binaryAccuracy' | typeof tfjs.metrics.binaryAccuracy + 'binaryCrossentropy' : 'binaryCrossentropy' | typeof tfjs.metrics.binaryCrossentropy + 'categoricalAccuracy' : 'categoricalAccuracy' | typeof tfjs.metrics.categoricalAccuracy + 'categoricalCrossentropy' : 'categoricalCrossentropy' | typeof tfjs.metrics.categoricalCrossentropy + 'cosineProximity' : 'cosineProximity' | typeof tfjs.metrics.cosineProximity + 'meanAbsoluteError' : 'meanAbsoluteError' | typeof tfjs.metrics.meanAbsoluteError + 'meanAbsolutePercentageError' : 'meanAbsolutePercentageError' | typeof tfjs.metrics.meanAbsolutePercentageError + 'meanSquaredError' : 'meanSquaredError' | typeof tfjs.metrics.meanSquaredError + 'precision' : 'precision' | typeof tfjs.metrics.precision + 'recall' : 'recall' | typeof tfjs.metrics.recall + 'sparseCategoricalAccuracy' : 'sparseCategoricalAccuracy' | typeof tfjs.metrics.sparseCategoricalAccuracy // TODO - "accuracy" : "accuracy" - "metrics-accuracy" : "accuracy" - "metrics-binaryAccuracy" : "binaryAccuracy" | typeof tfjs.metrics.binaryAccuracy - "metrics-binaryCrossentropy" : "binaryCrossentropy" | typeof tfjs.metrics.binaryCrossentropy - "metrics-categoricalAccuracy" : "categoricalAccuracy" | typeof tfjs.metrics.categoricalAccuracy - "metrics-categoricalCrossentropy" : "categoricalCrossentropy" | typeof tfjs.metrics.categoricalCrossentropy - "metrics-cosineProximity" : "cosineProximity" | typeof tfjs.metrics.cosineProximity - "metrics-meanAbsoluteError" : "mae" | "meanAbsoluteError" | typeof tfjs.metrics.meanAbsoluteError - "metrics-meanAbsolutePercentageError": "meanAbsolutePercentageError" | typeof tfjs.metrics.meanAbsolutePercentageError - "metrics-meanSquaredError" : "mse" | "meanSquaredError" | typeof tfjs.metrics.meanSquaredError - "metrics-precision" : "precision" | typeof tfjs.metrics.precision - "metrics-recall" : "recall" | typeof tfjs.metrics.recall - "metrics-sparseCategoricalAccuracy" : "sparseCategoricalAccuracy" | typeof tfjs.metrics.sparseCategoricalAccuracy + 'accuracy' : 'accuracy' + 'metrics-accuracy' : 'accuracy' + 'metrics-binaryAccuracy' : 'binaryAccuracy' | typeof tfjs.metrics.binaryAccuracy + 'metrics-binaryCrossentropy' : 'binaryCrossentropy' | typeof tfjs.metrics.binaryCrossentropy + 'metrics-categoricalAccuracy' : 'categoricalAccuracy' | typeof tfjs.metrics.categoricalAccuracy + 'metrics-categoricalCrossentropy' : 'categoricalCrossentropy' | typeof tfjs.metrics.categoricalCrossentropy + 'metrics-cosineProximity' : 'cosineProximity' | typeof tfjs.metrics.cosineProximity + 'metrics-meanAbsoluteError' : 'mae' | 'meanAbsoluteError' | typeof tfjs.metrics.meanAbsoluteError + 'metrics-meanAbsolutePercentageError': 'meanAbsolutePercentageError' | typeof tfjs.metrics.meanAbsolutePercentageError + 'metrics-meanSquaredError' : 'mse' | 'meanSquaredError' | typeof tfjs.metrics.meanSquaredError + 'metrics-precision' : 'precision' | typeof tfjs.metrics.precision + 'metrics-recall' : 'recall' | typeof tfjs.metrics.recall + 'metrics-sparseCategoricalAccuracy' : 'sparseCategoricalAccuracy' | typeof tfjs.metrics.sparseCategoricalAccuracy } export type IdMetric_t = keyof MetricMap_t diff --git a/src/types/plotly.js-dist-min.d.ts b/src/types/plotly.js-dist-min.d.ts index ea903c3..e0feb09 100644 --- a/src/types/plotly.js-dist-min.d.ts +++ b/src/types/plotly.js-dist-min.d.ts @@ -1,4 +1,4 @@ -declare module "plotly.js-dist-min" { - import Plotly from "plotly.js" +declare module 'plotly.js-dist-min' { + import Plotly from 'plotly.js' export default Plotly } diff --git a/src/types/types.ts b/src/types/types.ts index 429dc87..1e862e8 100644 --- a/src/types/types.ts +++ b/src/types/types.ts @@ -1,20 +1,8 @@ import type { ClassLayer_t } from '@core/types'; import type { ChartOptions } from 'chart.js' -/** - * @typedef {Object} Layer_t - * @property {string} _class // MaxPooling2D or Conv2D - * // if _class === Conv2D - * @property {number} kernelSize - * @property {number} filters - * @property {number} strides - * @property {string} activation - * - * @property {string} kernelInitializer - * @property {number} poolSize - * @property {number} strides - */ -export type Layer_t = { +/** Una capa de la red de imágenes (conv2d, maxPooling2d, flatten o dense), como la edita su editor de capas */ +export type ImageLayer_t = { _class : ClassLayer_t; _protected? : boolean; // Solo en las capas que las usan (dense y conv2d) diff --git a/src/types/virtual-n4l-catalog.d.ts b/src/types/virtual-n4l-catalog.d.ts new file mode 100644 index 0000000..edcaf30 --- /dev/null +++ b/src/types/virtual-n4l-catalog.d.ts @@ -0,0 +1,7 @@ +// Los paquetes .n4l de public/n4l/, reunidos por el plugin vite/n4lPackages.ts +declare module 'virtual:n4l-catalog' { + import type { N4LManifest_t } from '@core/n4l/format' + + const catalog: Array + export default catalog +} diff --git a/src/utils/alertHelper.tsx b/src/utils/alertHelper.tsx index d06b110..8d9d4e7 100644 --- a/src/utils/alertHelper.tsx +++ b/src/utils/alertHelper.tsx @@ -1,8 +1,18 @@ +import i18next from 'i18next' import Swal from 'sweetalert2' import withReactContent from 'sweetalert2-react-content' const MySwal = withReactContent(Swal) +// Azul primario de Bootstrap, el mismo en todas las alertas +const CONFIRM_BUTTON_COLOR = '#0d6efd' + +// Lo que dura a la vista el aviso de que algo ha ido bien (se para con el ratón encima) +const SUCCESS_TIMER_MS = 6000 + +// Las alertas siguen el tema elegido en la aplicación (no el del sistema) +const currentTheme = () => (document.documentElement.getAttribute('data-bs-theme') === 'dark' ? 'dark' : 'light') + type AlertParams = { text? : string @@ -23,12 +33,13 @@ export default class AlertHelper { */ static async alertError(title: string, params = { text: 'Error', footer: '', html: <> }, { ...props } = {}) { return await MySwal.fire({ + theme : currentTheme(), icon : 'error', title : title, text : params.text, footer : params.footer, html : params.html, - confirmButtonColor: '#0081D5', + confirmButtonColor: CONFIRM_BUTTON_COLOR, ...props }) } @@ -42,13 +53,14 @@ export default class AlertHelper { */ static async alertWarning(title: string, params = { text: 'Warning', footer: '', html: <> }, { ...props } = {}) { return await MySwal.fire({ + theme : currentTheme(), ...props, icon : 'warning', title : title, text : params.text, html : params.html, footer : params.footer, - confirmButtonColor: '#0081D5', + confirmButtonColor: CONFIRM_BUTTON_COLOR, }) } @@ -61,33 +73,47 @@ export default class AlertHelper { */ static async alertInfo(title: string, params = { text: 'Info', footer: '', html: <> }, { ...props } = {}) { return await MySwal.fire({ + theme : currentTheme(), ...props, icon : 'question', title : title, text : params.text, html : params.html, footer : params.footer, - confirmButtonColor: '#0D6EFD', + confirmButtonColor: CONFIRM_BUTTON_COLOR, }) } /** + * Un aviso de que algo ha ido bien, en una esquina y sin interrumpir (WCAG 4.1.3): no se lleva el foco ni tapa la + * página, el lector de pantalla lo lee cuando termina lo que estaba diciendo y se cierra solo, pero se puede parar + * dejando el ratón encima o cerrar con su botón (2.2.1) + * * @param {string} title * @param {{text: string, footer?: string, html?: JSX.Element}} params * @param {object} props * @return {Promise>} */ - static async alertSuccess(title: string, params: AlertParams = DEFAULT_SUCCESS_PARAMS, { ...props } = {}) { const { text, footer = '' } = params return await MySwal.fire({ + theme : currentTheme(), ...props, - icon : 'success', - showConfirmButton: false, - timer : 1500, - title : title, - text : text, - footer : footer, + toast : true, + position : 'bottom-end', + icon : 'success', + showConfirmButton : false, + showCloseButton : true, + closeButtonAriaLabel: i18next.t('alert.close'), + timer : SUCCESS_TIMER_MS, + timerProgressBar : true, + title : title, + text : text, + footer : footer, + didOpen : (popup) => { + popup.addEventListener('mouseenter', Swal.stopTimer) + popup.addEventListener('mouseleave', Swal.resumeTimer) + }, }) } } diff --git a/src/utils/statistics.ts b/src/utils/statistics.ts index 3a30d46..10b9619 100644 --- a/src/utils/statistics.ts +++ b/src/utils/statistics.ts @@ -1,4 +1,4 @@ -import * as dfd from "danfojs" +import * as dfd from 'danfojs' /** * diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 0fe036e..3c6f407 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -26,7 +26,7 @@ export function isWebView() { return false } } else { - if (userAgent.includes("wv")) { + if (userAgent.includes('wv')) { // Android webview return true } else { @@ -50,6 +50,6 @@ export function generateColor() { borderColor : `rgba(${r}, ${g}, ${b})`, backgroundColor : `rgba(${Math.ceil(r * 0.95)}, ${Math.ceil(g * 0.95)}, ${Math.ceil(b * 0.95)})`, pointBorderColor : `rgba(${r}, ${g}, ${b})`, - pointBackgroundColor: "rgba(0, 0, 0, 0)", + pointBackgroundColor: 'rgba(0, 0, 0, 0)', } } diff --git a/tests/App.test.tsx b/tests/App.test.tsx index 89b719a..cb0d453 100644 --- a/tests/App.test.tsx +++ b/tests/App.test.tsx @@ -1,15 +1,14 @@ -import { waitFor, waitForElementToBeRemoved, screen } from '@testing-library/react' +import { screen } from '@testing-library/react' import { renderApp, renderWithRouter } from './setup/utils' import TestPageEasy from '@pages/TestPageEasy' describe('App', () => { test('renders App', async () => { - const { getByText } = renderApp() - await waitFor(() => {}) - await waitForElementToBeRemoved(() => screen.getByText(/Loading\.\.\./i)) - // expect(getByText(/Loading\.\.\./i)).toBeInTheDocument() - expect(getByText(/pages\.index\.regression\.1-title/i)).toBeInTheDocument() + renderApp() + // Mientras llega el código de la página se ve el indicador de carga; después, la portada + expect(await screen.findByText(/pages\.index\.regression\.1-title/i)).toBeInTheDocument() + expect(screen.queryByTestId('Test-PageLoading')).not.toBeInTheDocument() }) test('renders TestPage', () => { diff --git a/tests/components/DataFramePlot.test.tsx b/tests/components/DataFramePlot.test.tsx index 64610cf..3247101 100644 --- a/tests/components/DataFramePlot.test.tsx +++ b/tests/components/DataFramePlot.test.tsx @@ -1,12 +1,12 @@ -import { describe, test, expect } from "vitest" -import { render } from "@testing-library/react" -import * as dfd from "danfojs" +import { describe, test, expect } from 'vitest' +import { render } from '@testing-library/react' +import * as dfd from 'danfojs' -import DataFramePlot from "@components/dataframe/DataFramePlot" -import { DataFramePlotProvider } from "@components/_context/DataFramePlotContext" +import DataFramePlot from '@components/dataframe/DataFramePlot' +import { DataFramePlotProvider } from '@components/_context/DataFramePlotContext' -describe("DataFramePlot", () => { - test("renders DataFramePlot", () => { +describe('DataFramePlot', () => { + test('renders DataFramePlot', () => { const dataframe = new dfd.DataFrame() const { getByText } = render( diff --git a/tests/components/N4LAnnouncer.test.tsx b/tests/components/N4LAnnouncer.test.tsx new file mode 100644 index 0000000..a383c60 --- /dev/null +++ b/tests/components/N4LAnnouncer.test.tsx @@ -0,0 +1,33 @@ +import { describe, test, expect, vi, afterEach } from 'vitest' +import { act, render, screen } from '@testing-library/react' + +import N4LAnnouncer from '@components/a11y/N4LAnnouncer' +import { announce } from '@core/a11y/announce' + +describe('N4LAnnouncer: lo que se anuncia al lector de pantalla', () => { + afterEach(() => { + vi.useRealTimers() + }) + + test('una región aria-live que está desde el principio y dice cada mensaje', () => { + vi.useFakeTimers() + render() + const region = screen.getByTestId('Test-Announcer') + expect(region).toHaveAttribute('aria-live', 'polite') + act(() => announce('Modelo cargado.')) + act(() => vi.advanceTimersByTime(200)) + expect(region).toHaveTextContent('Modelo cargado.') + }) + + test('lo que llega casi a la vez se dice junto (el último no tapa a los demás) y sin repetir', () => { + vi.useFakeTimers() + render() + act(() => { + announce('Capa 3 eliminada.') + announce('Las capas ya no tienen nada que revisar.') + announce('Las capas ya no tienen nada que revisar.') + }) + act(() => vi.advanceTimersByTime(200)) + expect(screen.getByTestId('Test-Announcer')).toHaveTextContent('Capa 3 eliminada. Las capas ya no tienen nada que revisar.') + }) +}) diff --git a/tests/components/N4LClassificationChart.test.tsx b/tests/components/N4LClassificationChart.test.tsx new file mode 100644 index 0000000..c51757a --- /dev/null +++ b/tests/components/N4LClassificationChart.test.tsx @@ -0,0 +1,105 @@ +import { describe, test, expect, vi } from 'vitest' +import { render } from '@testing-library/react' +import N4LClassificationChart from '@components/neural-network/N4LClassificationChart' +import { argMax, isProbabilityDistribution } from '@core/nn-utils/classificationOutput' +import { makeImagePrediction } from '@pages/playground/3_ImageClassification/utils/imagePrediction' +import { subscribeAnnouncements } from '@core/a11y/announce' + +// jsdom no tiene canvas: la gráfica se sustituye por un elemento con lo que recibiría Chart.js +vi.mock('react-chartjs-2', () => ({ + Bar: ({ data, options, ...props }: any) => ( +
    + ), +})) + +describe('argMax, makeImagePrediction e isProbabilityDistribution', () => { + + test('la clase elegida es la de mayor valor', () => { + expect(argMax([0.1, 0.7, 0.2])).toBe(1) + expect(argMax([])).toBe(-1) + expect(makeImagePrediction([0.1, 0.7, 0.2], 2)).toEqual({ values: [0.1, 0.7, 0.2], index: 1, modelIndex: 2 }) + }) + + test('solo es una distribución de probabilidad si los valores están entre 0 y 1 y suman 1', () => { + expect(isProbabilityDistribution([0.1, 0.7, 0.2])).toBe(true) + expect(isProbabilityDistribution([0.5, 0.5, 0.5])).toBe(false) + expect(isProbabilityDistribution([2.3, -1, 0.1])).toBe(false) + expect(isProbabilityDistribution([])).toBe(false) + }) +}) + +describe('N4LClassificationChart', () => { + + const classLabels = ['お', 'き', 'す'] + + test('con softmax: clase predicha, su probabilidad y las barras en porcentaje con la elegida resaltada', () => { + const { getByTestId, getByText } = render( + , + ) + expect(getByTestId('Test-ClassificationChart-class').textContent).toBe('き') + expect(getByText('pages.playground.generator.classify.chart-title')).toBeInTheDocument() + const bar = getByTestId('bar') + expect(JSON.parse(bar.dataset.values!).map(Math.round)).toEqual([5, 90, 5]) + expect(bar.dataset.yMax).toBe('100') + const colors = JSON.parse(bar.dataset.colors!) + expect(colors[1]).not.toBe(colors[0]) + expect(colors[0]).toBe(colors[2]) + // Sin espacios: el porcentaje se formatea en el idioma del sistema ("5%" o "5 %") + expect(bar.getAttribute('aria-label')?.replace(/\s/g, '')).toBe('お:5%,き:90%,す:5%') + }) + + test('sin softmax: valores tal cual, sin probabilidad ni eje hasta 100', () => { + const { getByTestId, getByText, queryByText } = render( + , + ) + expect(getByTestId('Test-ClassificationChart-class').textContent).toBe('す') + expect(getByText('pages.playground.generator.classify.chart-title-output')).toBeInTheDocument() + expect(queryByText('pages.playground.generator.classify.confidence')).toBeNull() + expect(JSON.parse(getByTestId('bar').dataset.values!)).toEqual([-1.5, 0.2, 3.1]) + expect(getByTestId('bar').dataset.yMax).toBeUndefined() + }) + + test('nombres de clase largos (tabular) y clase elegida indicada desde fuera', () => { + const { getByTestId } = render( + , + ) + expect(getByTestId('Test-ClassificationChart-class').textContent).toBe('Iris-versicolor') + }) + + test('con la clase real dice si el modelo acierta', () => { + const { getByTestId, rerender } = render() + expect(getByTestId('Test-ClassificationChart-actual')).toHaveClass('bg-success') + expect(getByTestId('Test-ClassificationChart-actual').textContent).toContain('pages.playground.generator.classify.actual-class') + // Si acierta, también sin el color: con una marca y con palabras + expect(getByTestId('Test-ClassificationChart-actual').textContent).toContain('pages.playground.generator.classify.hit') + rerender() + expect(getByTestId('Test-ClassificationChart-actual')).toHaveClass('bg-danger') + }) + + test('el resultado se anuncia al lector de pantalla, con la clase real si se sabe', () => { + const messages: string[] = [] + const unsubscribe = subscribeAnnouncements((message) => messages.push(message)) + render() + unsubscribe() + expect(messages).toHaveLength(1) + expect(messages[0]).toContain('pages.playground.generator.classify.predicted-class: 2') + expect(messages[0]).toContain('pages.playground.generator.classify.miss') + }) + + test('una clase real sin salida en el modelo (CAR «good») se nombra y cuenta como fallo', () => { + const { getByTestId } = render( + , + ) + expect(getByTestId('Test-ClassificationChart-actual')).toHaveClass('bg-danger') + expect(JSON.parse(getByTestId('bar').dataset.values!)).toHaveLength(3) + }) + + test('sin clase real no se indica nada', () => { + const { queryByTestId } = render() + expect(queryByTestId('Test-ClassificationChart-actual')).toBeNull() + }) +}) diff --git a/tests/components/N4LConfirmButton.test.tsx b/tests/components/N4LConfirmButton.test.tsx new file mode 100644 index 0000000..d1cdf87 --- /dev/null +++ b/tests/components/N4LConfirmButton.test.tsx @@ -0,0 +1,28 @@ +import { describe, test, expect, vi } from 'vitest' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' + +import N4LConfirmButton from '@components/form/N4LConfirmButton' + +const renderButton = (onConfirm = vi.fn()) => { + render() + return onConfirm +} + +describe('N4LConfirmButton: pregunta antes de lo que no se puede deshacer (WCAG 3.3.4)', () => { + test('primero pregunta, con el foco en «Cancelar»; cancelar no hace nada y devuelve el foco al botón', async () => { + const onConfirm = renderButton() + fireEvent.click(screen.getByRole('button', { name: 'Borrar los modelos' })) + expect(screen.getByRole('group', { name: 'Se borrarán 3 modelos.' })).toBeInTheDocument() + await waitFor(() => expect(screen.getByRole('button', { name: 'form.cancel' })).toHaveFocus()) + fireEvent.click(screen.getByRole('button', { name: 'form.cancel' })) + await waitFor(() => expect(screen.getByRole('button', { name: 'Borrar los modelos' })).toHaveFocus()) + expect(onConfirm).not.toHaveBeenCalled() + }) + + test('al confirmar lo hace', async () => { + const onConfirm = renderButton() + fireEvent.click(screen.getByRole('button', { name: 'Borrar los modelos' })) + fireEvent.click(screen.getByRole('button', { name: 'Borrarlos' })) + await waitFor(() => expect(onConfirm).toHaveBeenCalledTimes(1)) + }) +}) diff --git a/tests/components/N4LConfusionMatrix.test.tsx b/tests/components/N4LConfusionMatrix.test.tsx new file mode 100644 index 0000000..fcd453f --- /dev/null +++ b/tests/components/N4LConfusionMatrix.test.tsx @@ -0,0 +1,36 @@ +import { describe, test, expect } from 'vitest' +import { render, within } from '@testing-library/react' +import N4LConfusionMatrix from '@components/neural-network/N4LConfusionMatrix' + +// Sin espacios: el porcentaje se formatea en el idioma del sistema ("50%" o "50 %") +const text = (element: Element) => (element.textContent ?? '').replace(/\s/g, '') + +describe('N4LConfusionMatrix', () => { + + // Reales: A, A, B, C, C — predichas: A, B, B, C, A + const props = { classes: ['A', 'B', 'C'], labels: [0, 0, 1, 2, 2], predictions: [0, 1, 1, 2, 0] } + + test('cada celda tiene el recuento y su parte de la fila', () => { + const { getByTestId } = render() + expect(text(getByTestId('Test-ConfusionMatrix-0-0'))).toBe('150%') + expect(text(getByTestId('Test-ConfusionMatrix-2-0'))).toBe('150%') + expect(text(getByTestId('Test-ConfusionMatrix-1-1'))).toBe('1100%') + expect(text(getByTestId('Test-ConfusionMatrix-1-0'))).toBe('00%') + }) + + test('aciertos en verde, errores en rojo y las celdas vacías sin color', () => { + const { getByTestId } = render() + expect(getByTestId('Test-ConfusionMatrix-0-0').style.backgroundColor).toContain('--bs-success-rgb') + expect(getByTestId('Test-ConfusionMatrix-0-1').style.backgroundColor).toContain('--bs-danger-rgb') + expect(getByTestId('Test-ConfusionMatrix-1-0').style.backgroundColor).toBe('') + }) + + test('sensibilidad por clase real, precisión por clase predicha y exactitud', () => { + const { container } = render() + const rows = container.querySelectorAll('tbody tr') + // Fila A: 2 ejemplos, 1 acierto + expect(within(rows[0] as HTMLElement).getAllByRole('cell').slice(-2).map(text)).toStrictEqual(['2', '50%']) + const footer = within(container.querySelector('tfoot tr') as HTMLElement).getAllByRole('cell').map(text) + expect(footer).toStrictEqual(['50%', '50%', '100%', '5', '60%']) + }) +}) diff --git a/tests/components/N4LDataFrameTable.test.tsx b/tests/components/N4LDataFrameTable.test.tsx new file mode 100644 index 0000000..67c4832 --- /dev/null +++ b/tests/components/N4LDataFrameTable.test.tsx @@ -0,0 +1,57 @@ +import { describe, test, expect, vi, beforeEach } from 'vitest' +import { render, screen } from '@testing-library/react' +import * as dfd from 'danfojs' + +import N4LDataFrameTable from '@components/dataframe/N4LDataFrameTable' +import N4LDataFrameDescribe from '@components/dataframe/N4LDataFrameDescribe' +import { DataFrameTablePlot } from '@core/dataframe/DataFrameTable' + +// jsdom no puede dibujar con Plotly: se comprueba con qué se llama +vi.mock('@core/dataframe/DataFrameTable', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, DataFrameTablePlot: vi.fn(), DataFrameTablePurge: vi.fn(), DataFrameTableResize: vi.fn() } +}) + +const dataframe = () => new dfd.DataFrame({ x: [1, 2, 3], y: [0.5, 1.5, 2.5], class: ['a', 'b', 'a'] }) + +describe('N4LDataFrameTable', () => { + + beforeEach(() => vi.mocked(DataFrameTablePlot).mockClear()) + + test('dibuja la tabla (cuando el navegador está libre) con la última columna como objetivo y explica su color y el tamaño', async () => { + render() + expect(DataFrameTablePlot).not.toHaveBeenCalled() + await vi.waitFor(() => expect(DataFrameTablePlot).toHaveBeenCalledWith(expect.any(HTMLElement), expect.any(dfd.DataFrame), + expect.objectContaining({ target: undefined, subtitles: 'dtype', theme: 'light' }))) + expect(screen.getByTestId('Test-DataFrameTable-target')).toHaveTextContent('dataframe.table.target') + expect(screen.getByText('dataframe.table.shape')).toBeInTheDocument() + }) + + test('sin objetivo no hay leyenda de color', () => { + render() + expect(screen.queryByTestId('Test-DataFrameTable-target')).toBeNull() + }) + + test('avisa de que hay más filas que las que se ven', () => { + render() + expect(screen.getByText(/dataframe.table.scroll-rows/)).toBeInTheDocument() + }) +}) + +describe('N4LDataFrameDescribe', () => { + + beforeEach(() => vi.mocked(DataFrameTablePlot).mockClear()) + + test('una fila por columna numérica, con la del objetivo resaltada', async () => { + render() + await vi.waitFor(() => expect(DataFrameTablePlot).toHaveBeenCalled()) + const [, describe, options] = vi.mocked(DataFrameTablePlot).mock.lastCall! + expect(describe.index).toEqual(['x', 'y']) + expect(options).toEqual(expect.objectContaining({ target: 'y', targetAxis: 'row' })) + }) + + test('sin columnas numéricas lo dice', () => { + render() + expect(screen.getByText('dataframe.describe.no-numeric')).toBeInTheDocument() + }) +}) diff --git a/tests/components/N4LDatasetProcessForm.test.tsx b/tests/components/N4LDatasetProcessForm.test.tsx new file mode 100644 index 0000000..9472a51 --- /dev/null +++ b/tests/components/N4LDatasetProcessForm.test.tsx @@ -0,0 +1,67 @@ +import { describe, test, expect, vi } from 'vitest' +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import * as dfd from 'danfojs' +import N4LDatasetProcessForm from '@components/dataframe/N4LDatasetProcessForm' + +const prefix = 'dataset-process.' +const dataframe = () => new dfd.DataFrame({ + color : ['red', 'blue', 'red', 'green'], + size : [1, 2, 3, 4], + weight: [1.5, 2.5, 3.5, 4.5], + label : ['a', 'b', 'a', 'b'], +}) + +describe('N4LDatasetProcessForm: preparar un conjunto de datos subido', () => { + test('clasificación: la última columna es la clase, el texto va como categoría y lo que no se usa se descarta', async () => { + const onProcess = vi.fn() + render() + // Cuántas clases tiene la columna elegida + expect(screen.getByTestId('Test-DatasetProcess-TargetInfo')).toHaveTextContent(prefix + 'target-classes') + // "size" no se usa y "weight" se usa como categoría + fireEvent.click(within(screen.getByTestId('Test-DatasetProcess-Column-size')).getByRole('checkbox')) + fireEvent.change(within(screen.getByTestId('Test-DatasetProcess-Column-weight')).getByRole('combobox'), { target: { value: 'label-encoder' } }) + fireEvent.click(screen.getByLabelText(new RegExp(prefix + 'scalers.standard-scaler.name'))) + fireEvent.click(screen.getByTestId('Test-DatasetProcess-Submit')) + await waitFor(() => expect(onProcess).toHaveBeenCalledTimes(1)) + expect(onProcess).toHaveBeenCalledWith({ + target : 'label', + scaler : 'standard-scaler', + transforms: [ + { column_name: 'color', column_transform: 'label-encoder' }, + { column_name: 'size', column_transform: 'drop' }, + { column_name: 'weight', column_transform: 'label-encoder' }, + { column_name: 'label', column_transform: 'label-encoder' }, + ], + }) + }) + + test('una columna de texto solo se puede usar como categoría', () => { + render() + const color = screen.getByTestId('Test-DatasetProcess-Column-color') + expect(within(color).queryByRole('combobox')).toBeNull() + expect(color).toHaveTextContent(prefix + 'transforms.label-encoder') + }) + + test('regresión: un objetivo de texto no se puede predecir; uno numérico sí, y se queda como está', async () => { + const onProcess = vi.fn() + render() + expect(screen.getByTestId('Test-DatasetProcess-TargetInfo')).toHaveTextContent(prefix + 'target-not-numeric') + expect(screen.getByTestId('Test-DatasetProcess-Submit')).toBeDisabled() + fireEvent.change(screen.getByLabelText(prefix + 'regression.target-title'), { target: { value: 'weight' } }) + expect(screen.getByTestId('Test-DatasetProcess-TargetInfo')).toHaveTextContent(prefix + 'target-range') + fireEvent.click(screen.getByTestId('Test-DatasetProcess-Submit')) + await waitFor(() => expect(onProcess).toHaveBeenCalledTimes(1)) + expect(onProcess.mock.calls[0][0].transforms).toContainEqual({ column_name: 'weight', column_transform: 'float32' }) + // La columna que antes era el objetivo vuelve a ser una entrada + expect(onProcess.mock.calls[0][0].transforms).toContainEqual({ column_name: 'label', column_transform: 'label-encoder' }) + }) + + test('sin ninguna columna de entrada no se puede procesar', () => { + render() + for (const column of ['color', 'size', 'weight']) { + fireEvent.click(within(screen.getByTestId('Test-DatasetProcess-Column-' + column)).getByRole('checkbox')) + } + expect(screen.getByTestId('Test-DatasetProcess-Summary')).toHaveTextContent(prefix + 'no-inputs') + expect(screen.getByTestId('Test-DatasetProcess-Submit')).toBeDisabled() + }) +}) diff --git a/tests/components/N4LDatasetViews.test.tsx b/tests/components/N4LDatasetViews.test.tsx new file mode 100644 index 0000000..563bdd1 --- /dev/null +++ b/tests/components/N4LDatasetViews.test.tsx @@ -0,0 +1,32 @@ +import { describe, test, expect } from 'vitest' +import { fireEvent, render, screen } from '@testing-library/react' +import * as dfd from 'danfojs' +import N4LDatasetViews from '@components/dataframe/N4LDatasetViews' +import type * as _Types from '@core/types' + +const original = new dfd.DataFrame({ color: ['red', 'blue', 'red'], size: [10, 20, 30], price: [1.5, 2.5, 3.5] }) +const encoded = new dfd.DataFrame({ color: [1, 0, 1], size: [10, 20, 30], price: [1.5, 2.5, 3.5] }) +const X = new dfd.DataFrame({ color: [1, 0, 1], size: [0, 0.5, 1] }) +const dataset = { + is_dataset_processed: true, + dataframe_original : original, + dataframe_processed : encoded, + data_processed : { X, y: new dfd.Series([1.5, 2.5, 3.5]), column_name_target: 'price', scaler: {} }, +} as unknown as _Types.DatasetProcessed_t + +describe('N4LDatasetViews: original, codificado y escalado', () => { + test('lo escalado son las entradas de la red y, al final, lo que se predice sin escalar', () => { + const { container } = render() + expect(screen.getByRole('columnheader', { name: 'color' })).toBeInTheDocument() + expect(screen.getAllByText('red', { selector: 'td' })).toHaveLength(2) + + fireEvent.click(screen.getByText('dataset-view.encoded')) + expect(screen.queryAllByText('red', { selector: 'td' })).toHaveLength(0) + + fireEvent.click(screen.getByText('dataset-view.scaled')) + const headers = [...container.querySelectorAll('thead th')].map((cell) => cell.textContent) + expect(headers.slice(-3)).toEqual(['color', 'size', 'price']) + expect(screen.getByText('0.5', { selector: 'td' })).toBeInTheDocument() + expect(screen.getByText('2.5', { selector: 'td' })).toBeInTheDocument() + }) +}) diff --git a/tests/components/N4LEditorLayers.test.tsx b/tests/components/N4LEditorLayers.test.tsx new file mode 100644 index 0000000..0cbaf9c --- /dev/null +++ b/tests/components/N4LEditorLayers.test.tsx @@ -0,0 +1,137 @@ +import { afterEach, beforeAll, describe, expect, test, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { useState } from 'react' + +import N4LEditorLayers from '@components/neural-network/N4LEditorLayers' +import { moveLayer } from '@components/neural-network/moveLayer' + +type Layer_t = { name: string, locked?: boolean } + +/** El editor con sus capas en un estado, como en los entrenadores; la última, fija (como la salida de regresión) */ +function Editor({ initial }: { initial: Layer_t[] }) { + const [layers, setLayers] = useState(initial) + return <> + layer.name} renderFields={(layer) =>

    {'campos de ' + layer.name}

    } + isLocked={(layer) => layer.locked === true} + onAddEnd={() => undefined} onRemove={() => undefined} + onMove={(from, to) => setLayers((current) => moveLayer(current, from, to))} /> + {layers.map(({ name }) => name).join(',')} + +} + +const LAYERS: Layer_t[] = [{ name: 'a' }, { name: 'b' }, { name: 'c' }, { name: 'salida', locked: true }] +const move = (direction: 'up' | 'down', index: number) => document.querySelector(`[data-move="${direction}-${index}"]`)! +const header = (index: number) => screen.getAllByRole('button').find((element) => element.classList.contains('accordion-button') && element.textContent?.startsWith('pages.playground.generator.editor-layers.layer-id') && element.closest('[data-guide="layer-' + index + '"]'))! + +describe('N4LEditorLayers: ordenar las capas', () => { + afterEach(() => cleanup()) + + test('moveLayer: la capa a su nuevo puesto y las demás en su orden', () => { + expect(moveLayer(['a', 'b', 'c', 'd'], 0, 2)).toEqual(['b', 'c', 'a', 'd']) + expect(moveLayer(['a', 'b', 'c'], 2, 1)).toEqual(['a', 'c', 'b']) + const same = ['a', 'b'] + expect(moveLayer(same, 1, 5)).toBe(same) + }) + + test('se sube y se baja con botones; la capa sigue abierta y el foco, en ella', () => { + render() + fireEvent.click(header(0)) + expect(screen.getByText('campos de a')).toBeVisible() + // La primera no sube + expect(move('up', 0)).toBeDisabled() + + fireEvent.click(move('down', 0)) + expect(screen.getByTestId('order')).toHaveTextContent('b,a,c,salida') + // Abierta en su nuevo puesto (el 2) y con el foco en «Bajar» + expect(screen.getByText('campos de a')).toBeVisible() + expect(document.activeElement).toHaveAttribute('data-move', 'down-1') + + fireEvent.click(move('down', 1)) + expect(screen.getByTestId('order')).toHaveTextContent('b,c,a,salida') + // Ya no puede bajar más (la salida es fija): el foco pasa a «Subir» + expect(document.querySelector('[data-move="down-2"]')).toBeDisabled() + expect(document.activeElement).toHaveAttribute('data-move', 'up-2') + }) + + test('una capa fija no se mueve', () => { + render() + fireEvent.click(header(3)) + expect(document.querySelector('[data-move="up-3"]')).toBeDisabled() + expect(document.querySelector('[data-move="down-3"]')).toBeDisabled() + }) + + describe('arrastrando', () => { + beforeAll(() => { + // jsdom no tiene PointerEvent + if (window.PointerEvent === undefined) { + class PointerEventPolyfill extends MouseEvent { + pointerId: number + constructor(type: string, init: PointerEventInit = {}) { + super(type, init) + this.pointerId = init.pointerId ?? 0 + } + } + window.PointerEvent = PointerEventPolyfill as unknown as typeof PointerEvent + } + }) + afterEach(() => vi.restoreAllMocks()) + + /** Cada capa, de 40 px de alto, una debajo de otra (jsdom no coloca nada) */ + const stack = () => vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) { + const index = Number(this.getAttribute('data-layer-item')) + return { top: index * 40, height: 40, bottom: index * 40 + 40, left: 0, right: 300, width: 300, x: 0, y: index * 40, toJSON: () => ({}) } as DOMRect + }) + const handle = (index: number) => document.querySelector(`[data-drag="${index}"]`)! + const item = (index: number) => document.querySelector(`[data-layer-item="${index}"]`)! + const drag = (from: number, y: number) => { + fireEvent.pointerDown(handle(from), { button: 0, pointerId: 1, clientY: from * 40 + 20 }) + fireEvent.pointerMove(handle(from), { pointerId: 1, clientY: y }) + } + + test('la capa cae donde se suelta, con una raya que lo marca mientras se arrastra', () => { + stack() + render() + // La primera, por debajo del centro de la tercera (100 px) + drag(0, 110) + expect(item(0)).toHaveClass('n4l-layer-dragging') + expect(item(2)).toHaveClass('n4l-layer-drop-after') + fireEvent.pointerUp(handle(0), { pointerId: 1, clientY: 110 }) + expect(screen.getByTestId('order')).toHaveTextContent('b,c,a,salida') + expect(item(0)).not.toHaveClass('n4l-layer-dragging') + }) + + test('no pasa por encima de una capa fija: al soltarla al final, se queda justo antes de la salida', () => { + stack() + render() + drag(0, 1000) + fireEvent.pointerUp(handle(0), { pointerId: 1, clientY: 1000 }) + expect(screen.getByTestId('order')).toHaveTextContent('b,c,a,salida') + }) + + test('una capa fija no se arrastra, y soltar en el mismo sitio no cambia nada', () => { + stack() + render() + drag(3, 0) + expect(item(3)).not.toHaveClass('n4l-layer-dragging') + drag(1, 60) + fireEvent.pointerUp(handle(1), { pointerId: 1, clientY: 60 }) + expect(screen.getByTestId('order')).toHaveTextContent('a,b,c,salida') + }) + + test('el panel abierto sigue con su capa', () => { + stack() + render() + fireEvent.click(header(1)) + drag(0, 1000) + fireEvent.pointerUp(handle(0), { pointerId: 1, clientY: 1000 }) + // b estaba abierta en el puesto 2 y ahora está en el 1: sigue abierta + expect(screen.getByText('campos de b')).toBeVisible() + }) + }) + + test('sin onMove, no hay botones para mover', () => { + render( layer.name} renderFields={() => null} onAddEnd={() => undefined} onRemove={() => undefined} />) + fireEvent.click(header(0)) + expect(document.querySelector('[data-move]')).toBeNull() + }) +}) diff --git a/tests/components/N4LGuide.test.tsx b/tests/components/N4LGuide.test.tsx new file mode 100644 index 0000000..1e5a1a8 --- /dev/null +++ b/tests/components/N4LGuide.test.tsx @@ -0,0 +1,233 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import N4LGuide, { type GuideStep_t } from '@components/guide/N4LGuide' +import { pickVoice, speechLang, splitSentences } from '@components/guide/speech' +import { readGuideProgress, RESTORE_MS, shouldRestore } from '@components/guide/guideProgress' +import { getGuideSettings, resetGuideSettings } from '@components/guide/guideSettings' + +// En medio de la pantalla: jsdom no maqueta y así no depende de dónde estén los elementos +const STEPS: GuideStep_t[] = [ + { target: 'body', placement: 'center', title: 'Uno', content: 'El primer paso.' }, + { target: 'body', placement: 'center', title: 'Dos', content: 'El segundo paso.' }, + { target: 'body', placement: 'center', title: '¿Tres?', content: 'El último paso.' }, +] + +// La voz del navegador, de mentira: jsdom no tiene speechSynthesis +class FakeUtterance { + text : string + lang = '' + voice : unknown = null + onstart: (() => void) | null = null + onend : (() => void) | null = null + onerror: (() => void) | null = null + constructor(text: string) { + this.text = text + } +} +const spoken: FakeUtterance[] = [] +const synth = { + speak : vi.fn((utterance: FakeUtterance) => { spoken.push(utterance) }), + cancel : vi.fn(), + getVoices: (): SpeechSynthesisVoice[] => [], +} + +const tooltip = () => screen.queryByTestId('Test-GuideTooltip') +const spokenText = () => spoken.map(({ text }) => text).join(' ') +const click = async (element: Element) => { + await act(async () => { + fireEvent.click(element) + }) +} + +describe('speech', () => { + test('parte el texto en frases (sin partir los decimales) y las muy largas por sus comas', () => { + expect(splitSentences('Hola. El valor es 1.5 aquí. ¿Ya?')).toEqual(['Hola.', 'El valor es 1.5 aquí.', '¿Ya?']) + expect(splitSentences('これは例です。次へ進みます。')).toEqual(['これは例です。', '次へ進みます。']) + const long = Array.from({ length: 12 }, (_, index) => `una parte bastante larga número ${index}`).join(', ') + '.' + const chunks = splitSentences(long) + expect(chunks.length).toBeGreaterThan(1) + expect(chunks.every((chunk) => chunk.length <= 180)).toBe(true) + expect(chunks.join(' ')).toBe(long) + }) + + test('elige la voz de la variante preferida del idioma y, si no, otra del idioma', () => { + const voice = (lang: string, isDefault = false) => ({ lang, default: isDefault, name: lang }) as SpeechSynthesisVoice + expect(pickVoice([voice('en-US'), voice('es-MX'), voice('es-ES')], 'es')?.lang).toBe('es-ES') + expect(pickVoice([voice('en-US'), voice('es-MX')], 'es')?.lang).toBe('es-MX') + expect(pickVoice([voice('es_ES', true)], 'es')?.lang).toBe('es_ES') + expect(pickVoice([voice('en-US')], 'ja')).toBeNull() + expect(speechLang('ja')).toBe('ja-JP') + }) +}) + +describe('N4LGuide', () => { + beforeEach(() => { + spoken.length = 0 + synth.speak.mockClear() + synth.cancel.mockClear() + localStorage.clear() + resetGuideSettings() + vi.stubGlobal('speechSynthesis', synth) + vi.stubGlobal('SpeechSynthesisUtterance', FakeUtterance) + }) + afterEach(() => { + // Se desmonta (y corta la voz) antes de quitar la voz de mentira + cleanup() + vi.useRealTimers() + vi.unstubAllGlobals() + }) + + test('solo empieza con el botón, lee cada paso en voz alta y se cierra', async () => { + render() + expect(tooltip()).toBeNull() + expect(synth.speak).not.toHaveBeenCalled() + + await click(screen.getByTestId('Test-GuideButton')) + expect(await screen.findByText('El primer paso.')).toBeInTheDocument() + expect(spokenText()).toBe('Uno. El primer paso.') + + // Al pasar de paso se corta lo que se leía y se lee el nuevo + spoken.length = 0 + await click(screen.getByText('guide.next')) + expect(await screen.findByText('El segundo paso.')).toBeInTheDocument() + expect(synth.cancel).toHaveBeenCalled() + expect(spokenText()).toBe('Dos. El segundo paso.') + + // Sin voz no se lee nada (y la preferencia se recuerda) + spoken.length = 0 + await click(screen.getByTestId('Test-GuideVoice')) + await click(screen.getByText('guide.next')) + expect(await screen.findByText('El último paso.')).toBeInTheDocument() + expect(spoken).toEqual([]) + expect(getGuideSettings().voice).toBe(false) + + // Con la voz otra vez: un título que acaba en "?" no lleva además un punto + await click(screen.getByTestId('Test-GuideVoice')) + expect(spokenText()).toBe('¿Tres? El último paso.') + + await click(screen.getByRole('button', { name: 'guide.close' })) + expect(tooltip()).toBeNull() + }) + + test('avanzando solo, pasa al siguiente paso al terminar de leer el actual', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }) + render() + await click(screen.getByTestId('Test-GuideButton')) + expect(await screen.findByText('El primer paso.')).toBeInTheDocument() + await click(screen.getByTestId('Test-GuideAuto')) + + // Hasta que no termina de leer, sigue en el mismo paso + await act(async () => { + await vi.advanceTimersByTimeAsync(1000) + }) + expect(screen.getByText('El primer paso.')).toBeInTheDocument() + + await act(async () => { + spoken.at(-1)!.onend!() + await vi.advanceTimersByTimeAsync(1000) + }) + expect(await screen.findByText('El segundo paso.')).toBeInTheDocument() + }) + + test('guarda por qué paso va: cerrada, el botón sigue desde ahí; terminada, vuelve a empezar', async () => { + render() + await click(screen.getByTestId('Test-GuideButton')) + await click(await screen.findByText('guide.next')) + expect(await screen.findByText('El segundo paso.')).toBeInTheDocument() + expect(readGuideProgress('prueba')).toMatchObject({ step: 1, open: true }) + + await click(screen.getByRole('button', { name: 'guide.close' })) + expect(tooltip()).toBeNull() + expect(readGuideProgress('prueba')).toMatchObject({ step: 1, open: false }) + expect(screen.getByTestId('Test-GuideButton')).toHaveTextContent('guide.resume') + + await click(screen.getByTestId('Test-GuideButton')) + expect(await screen.findByText('El segundo paso.')).toBeInTheDocument() + // "Volver al principio" + await click(screen.getByTestId('Test-GuideRestart')) + expect(await screen.findByText('El primer paso.')).toBeInTheDocument() + expect(readGuideProgress('prueba')).toMatchObject({ step: 0, open: true }) + + await click(screen.getByText('guide.next')) + await click(await screen.findByText('guide.next')) + await click(await screen.findByText('guide.finish')) + expect(tooltip()).toBeNull() + expect(readGuideProgress('prueba')).toBeNull() + expect(screen.getByTestId('Test-GuideButton')).toHaveTextContent('guide.button') + }) + + test('abierta al recargar la página, se vuelve a abrir sola en su paso y lo lee al tocar la página', async () => { + localStorage.setItem('n4l-guide-progress.prueba', JSON.stringify({ step: 1, open: true, savedAt: Date.now() })) + // Recién cargada, el navegador no deja hablar hasta que se toca algo + Object.defineProperty(navigator, 'userActivation', { value: { hasBeenActive: false }, configurable: true }) + try { + render() + expect(await screen.findByText('El segundo paso.')).toBeInTheDocument() + expect(synth.speak).not.toHaveBeenCalled() + + await click(document.body) + expect(spokenText()).toBe('Dos. El segundo paso.') + } finally { + Reflect.deleteProperty(navigator, 'userActivation') + } + }) + + test('el desplegable de pasos va directamente a cualquiera', async () => { + render() + await click(screen.getByTestId('Test-GuideButton')) + expect(await screen.findByText('El primer paso.')).toBeInTheDocument() + await act(async () => { + fireEvent.change(screen.getByTestId('Test-GuideStepSelect'), { target: { value: '2' } }) + }) + expect(await screen.findByText('El último paso.')).toBeInTheDocument() + expect(readGuideProgress('prueba')).toMatchObject({ step: 2, open: true }) + }) + + test('el desplegable de voces tiene las del idioma de la aplicación y, al cambiarla, vuelve a leer el paso con ella', async () => { + const voice = (name: string, lang: string, localService = true) => ({ name, lang, voiceURI: name, localService, default: false }) as SpeechSynthesisVoice + const voices = [voice('Laura', 'es-ES'), voice('Jorge', 'es-MX', false), voice('Samantha', 'en-US')] + vi.spyOn(synth, 'getVoices').mockReturnValue(voices) + // El t de los tests no tiene idioma: el del navegador de jsdom es inglés + Object.defineProperty(navigator, 'language', { value: 'es-ES', configurable: true }) + try { + render() + await click(screen.getByTestId('Test-GuideButton')) + expect(await screen.findByText('El primer paso.')).toBeInTheDocument() + const select = screen.getByTestId('Test-GuideVoiceSelect') as HTMLSelectElement + // Automática, las dos de español (la de España primero) y la que funciona en un servidor, marcada + expect(Array.from(select.options).map(({ text }) => text)).toEqual(['guide.voice-auto', 'Laura', 'Jorge (guide.voice-online)']) + + spoken.length = 0 + await act(async () => { + fireEvent.change(select, { target: { value: 'Jorge' } }) + }) + expect(getGuideSettings().voices).toEqual({ es: 'Jorge' }) + expect(spoken.at(-1)?.voice).toBe(voices[1]) + expect(spokenText()).toBe('Uno. El primer paso.') + } finally { + Reflect.deleteProperty(navigator, 'language') + } + }) + + test('abierta hace más de una hora, no se abre sola: se sigue con el botón', async () => { + localStorage.setItem('n4l-guide-progress.prueba', JSON.stringify({ step: 2, open: true, savedAt: Date.now() - RESTORE_MS - 1000 })) + render() + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 500)) + }) + expect(tooltip()).toBeNull() + expect(screen.getByTestId('Test-GuideButton')).toHaveTextContent('guide.resume') + }) +}) + +describe('guideProgress', () => { + test('lo guardado mal o a medias no cuenta', () => { + localStorage.setItem('n4l-guide-progress.mal', '{no es json') + expect(readGuideProgress('mal')).toBeNull() + localStorage.setItem('n4l-guide-progress.mal', JSON.stringify({ step: -1, savedAt: 1 })) + expect(readGuideProgress('mal')).toBeNull() + expect(shouldRestore({ step: 3, open: false, savedAt: Date.now() })).toBe(false) + expect(shouldRestore({ step: 3, open: true, savedAt: Date.now() })).toBe(true) + expect(shouldRestore(null)).toBe(false) + }) +}) diff --git a/tests/components/N4LHelpTerm.test.tsx b/tests/components/N4LHelpTerm.test.tsx new file mode 100644 index 0000000..a622641 --- /dev/null +++ b/tests/components/N4LHelpTerm.test.tsx @@ -0,0 +1,49 @@ +import { describe, test, expect, vi, afterEach } from 'vitest' +import { act, fireEvent, render, screen } from '@testing-library/react' + +import N4LHelpTerm from '@components/helpLink/N4LHelpTerm' + +describe('N4LHelpTerm: la ayuda al pasar el ratón o con el foco (WCAG 1.4.13)', () => { + afterEach(() => { + vi.useRealTimers() + }) + + test('aparece con el ratón, no se cierra al llevarlo hasta ella y se cierra al salir de las dos', () => { + vi.useFakeTimers() + render() + const term = screen.getByRole('button', { name: 'Época' }) + fireEvent.mouseEnter(term) + const popover = screen.getByTestId('Test-HelpTerm-Popover') + expect(term).toHaveAccessibleDescription('Una pasada por todos los datos') + // Del término a la ayuda: hay tiempo para llegar + fireEvent.mouseLeave(term) + fireEvent.mouseEnter(popover) + act(() => vi.advanceTimersByTime(1000)) + expect(screen.getByTestId('Test-HelpTerm-Popover')).toBeInTheDocument() + fireEvent.mouseLeave(popover) + act(() => vi.advanceTimersByTime(1000)) + // Cerrada: ya no describe el término (en jsdom el fundido de salida no termina, así que no se quita del todo) + expect(term).toHaveAccessibleDescription('') + }) + + test('con el foco aparece y Escape la cierra sin quitar el foco', () => { + render() + const term = screen.getByRole('button', { name: 'Época' }) + act(() => term.focus()) + expect(screen.getByTestId('Test-HelpTerm-Popover')).toBeInTheDocument() + fireEvent.keyDown(term, { key: 'Escape' }) + expect(term).toHaveAccessibleDescription('') + expect(term).toHaveFocus() + }) + + test('también se abre al pulsarlo (en pantallas táctiles no hay «pasar el ratón») y se cierra al ir a otra parte', () => { + vi.useFakeTimers() + render() + const term = screen.getByRole('button', { name: 'Época' }) + fireEvent.click(term) + expect(term).toHaveAccessibleDescription('Una pasada por todos los datos') + fireEvent.blur(term) + act(() => vi.advanceTimersByTime(1000)) + expect(term).toHaveAccessibleDescription('') + }) +}) diff --git a/tests/components/N4LMaximize.test.tsx b/tests/components/N4LMaximize.test.tsx new file mode 100644 index 0000000..2bdc29d --- /dev/null +++ b/tests/components/N4LMaximize.test.tsx @@ -0,0 +1,57 @@ +import { describe, test, expect, afterEach } from 'vitest' +import { fireEvent, render, screen } from '@testing-library/react' +import { Card } from 'react-bootstrap' +import N4LMaximizeButton from '@components/maximize/N4LMaximizeButton' +import { useMaximize } from '@components/maximize/useMaximize' + +// Como en N4LLayerDesign: la clase va en la tarjeta y el botón en su cabecera +function MaximizableCard() { + const maximize = useMaximize() + return ( + + + + + + ) +} + +describe('useMaximize y N4LMaximizeButton', () => { + afterEach(() => { + document.body.classList.remove('modal-open') + }) + + test('el botón maximiza la tarjeta, bloquea el desplazamiento de la página y la vuelve a su sitio', () => { + render() + expect(screen.getByTestId('card')).not.toHaveClass('n4l-maximized') + + fireEvent.click(screen.getByRole('button', { name: 'ui.maximize' })) + expect(screen.getByTestId('card')).toHaveClass('n4l-maximized') + expect(document.body).toHaveClass('n4l-maximized-open') + + fireEvent.click(screen.getByRole('button', { name: 'ui.minimize' })) + expect(screen.getByTestId('card')).not.toHaveClass('n4l-maximized') + expect(document.body).not.toHaveClass('n4l-maximized-open') + }) + + test('Escape la devuelve a su sitio, salvo con un modal abierto encima', () => { + render() + fireEvent.click(screen.getByRole('button', { name: 'ui.maximize' })) + + document.body.classList.add('modal-open') + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.getByTestId('card')).toHaveClass('n4l-maximized') + + document.body.classList.remove('modal-open') + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.getByTestId('card')).not.toHaveClass('n4l-maximized') + expect(document.body).not.toHaveClass('n4l-maximized-open') + }) + + test('al desmontar la tarjeta maximizada, la página se puede volver a desplazar', () => { + const { unmount } = render() + fireEvent.click(screen.getByRole('button', { name: 'ui.maximize' })) + unmount() + expect(document.body).not.toHaveClass('n4l-maximized-open') + }) +}) diff --git a/tests/components/N4LModelCode.test.tsx b/tests/components/N4LModelCode.test.tsx new file mode 100644 index 0000000..45e0ded --- /dev/null +++ b/tests/components/N4LModelCode.test.tsx @@ -0,0 +1,45 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' + +import N4LModelCode from '@components/neural-network/N4LModelCode' +import type { ModelCode_t } from '@core/nn-utils/modelCode' + +const SPEC: ModelCode_t = { + inputShape : [4], + layers : [{ kind: 'dense', units: 10, activation: 'relu' }, { kind: 'dense', units: 3, activation: 'softmax' }], + optimizer : 'train-adam', + learningRate: 0.01, + loss : 'categoricalCrossentropy', + metrics : ['accuracy'], + epochs : 20, + batchSize : 32, + dataComment : 'X e y', +} + +describe('N4LModelCode: Ver el código', () => { + afterEach(() => { + cleanup() + vi.unstubAllGlobals() + }) + + test('sin datos (no se sabe cuántas entradas tiene la red), no se enseña', () => { + render() + expect(screen.queryByTestId('Test-ModelCode')).toBeNull() + }) + + test('el código en TensorFlow.js y, al cambiar, en Keras; y se copia', async () => { + const writeText = vi.fn(async () => undefined) + vi.stubGlobal('navigator', { ...navigator, clipboard: { writeText } }) + render() + const code = () => screen.getByTestId('Test-ModelCode-Code').textContent ?? '' + expect(code()).toContain("model.add(tf.layers.dense({ units: 10, activation: 'relu', inputShape: [4] }))") + + fireEvent.click(screen.getByRole('button', { name: 'Keras (Python)' })) + expect(screen.getByRole('button', { name: 'Keras (Python)' })).toHaveAttribute('aria-pressed', 'true') + expect(code()).toContain('layers.Dense(10, activation="relu")') + + await act(async () => { fireEvent.click(screen.getByTestId('Test-ModelCode-Copy')) }) + expect(writeText).toHaveBeenCalledWith(code()) + expect(screen.getByRole('status')).toHaveTextContent('model-code.copied') + }) +}) diff --git a/tests/components/N4LModelSummaryButton.test.tsx b/tests/components/N4LModelSummaryButton.test.tsx new file mode 100644 index 0000000..df97a27 --- /dev/null +++ b/tests/components/N4LModelSummaryButton.test.tsx @@ -0,0 +1,43 @@ +import { describe, test, expect, beforeAll } from 'vitest' +import { fireEvent, render, screen, within } from '@testing-library/react' +import * as tfjs from '@tensorflow/tfjs' + +import N4LModelSummaryButton from '@components/neural-network/N4LModelSummaryButton' + +const model = () => tfjs.sequential({ + layers: [ + tfjs.layers.dense({ inputShape: [4], units: 3, activation: 'relu', name: 'oculta' }), + tfjs.layers.dense({ units: 2, activation: 'softmax', name: 'salida' }), + ], +}) + +describe('N4LModelSummaryButton', () => { + // En jsdom no hay WebGL + beforeAll(async () => { + await tfjs.setBackend('cpu') + }) + + test('el botón despliega una tabla con cada capa, su forma de salida y sus parámetros', () => { + render() + const toggle = screen.getByTestId('Test-ModelSummary-Toggle') + expect(toggle).toHaveAttribute('aria-expanded', 'false') + fireEvent.click(toggle) + expect(toggle).toHaveAttribute('aria-expanded', 'true') + const table = within(screen.getByTestId('Test-ModelSummary')).getByRole('table') + const rows = within(table).getAllByRole('row').map((row) => row.textContent) + // Cabecera, dos capas y el total: 4 × 3 + 3 = 15 y 3 × 2 + 2 = 8 + expect(rows).toHaveLength(4) + expect(rows[1]).toContain('oculta') + expect(rows[1]).toContain('(—, 3)') + expect(rows[1]).toContain('15') + expect(rows[2]).toContain('(—, 2)') + expect(rows[3]).toContain('23') + fireEvent.click(toggle) + expect(screen.queryByTestId('Test-ModelSummary')).toBeNull() + }) + + test('sin un LayersModel (MobileNet, los detectores) no aparece', () => { + const { container } = render() + expect(container).toBeEmptyDOMElement() + }) +}) diff --git a/tests/components/N4LNavbar.test.tsx b/tests/components/N4LNavbar.test.tsx new file mode 100644 index 0000000..e55f2d9 --- /dev/null +++ b/tests/components/N4LNavbar.test.tsx @@ -0,0 +1,107 @@ +import { describe, test, expect, afterEach } from 'vitest' +import { fireEvent, render, screen } from '@testing-library/react' +import { MemoryRouter, useLocation } from 'react-router' +import N4LNavbar from '@components/header/N4LNavbar' +import { IndexedDBPackageStore, MemoryPackageStore, setN4LPackageStore, type LocalPackage_t } from '@core/n4l/localPackages' + +function LocationDisplay() { + return

    {useLocation().pathname}

    +} + +const renderAt = (path: string) => render( + + + + , +) + +const link = (name: string) => screen.getByRole('link', { name }) +const toggler = () => screen.getByRole('button', { name: 'header.menu' }) + +describe('N4LNavbar', () => { + afterEach(() => setN4LPackageStore(new IndexedDBPackageStore())) + + test('marca la página actual (y Inicio solo en la home)', () => { + renderAt('/manual') + expect(link('header.manual')).toHaveAttribute('aria-current', 'page') + expect(link('header.manual')).toHaveClass('active') + expect(link('header.home')).not.toHaveAttribute('aria-current') + + renderAt('/') + expect(screen.getAllByRole('link', { name: 'header.home' }).at(-1)).toHaveAttribute('aria-current', 'page') + }) + + test('en el móvil el menú se cierra al ir a otra página', () => { + renderAt('/') + expect(toggler()).toHaveAttribute('aria-expanded', 'false') + fireEvent.click(toggler()) + expect(toggler()).toHaveAttribute('aria-expanded', 'true') + + fireEvent.click(link('header.glossary')) + expect(screen.getByTestId('location')).toHaveTextContent('/glossary') + expect(toggler()).toHaveAttribute('aria-expanded', 'false') + }) + + test('también se cierra al pulsar la página en la que ya se está', () => { + renderAt('/datasets') + fireEvent.click(toggler()) + fireEvent.click(link('header.datasets')) + expect(toggler()).toHaveAttribute('aria-expanded', 'false') + }) + + test('«Tareas» enlaza a la página de cada una y se marca en la tarea en la que se está', () => { + renderAt('/playground/regression/dataset/AUTO_MPG') + const tasks = document.getElementById('tasks-nav-dropdown')! + expect(tasks).toHaveTextContent('header.tasks') + expect(tasks).toHaveClass('active') + fireEvent.click(tasks) + expect(link('pages.index.tabular-classification.1-title')).toHaveAttribute('href', '/task/tabular-classification') + expect(link('pages.index.clustering.1-title')).toHaveAttribute('href', '/task/clustering') + expect(link('pages.index.regression.1-title')).toHaveClass('active') + expect(link('pages.index.time-series.1-title')).toHaveAttribute('href', '/task/time-series') + expect(screen.getAllByRole('link').filter((element) => element.getAttribute('href')?.startsWith('/task/'))).toHaveLength(6) + + fireEvent.click(link('pages.index.object-detection.1-title')) + expect(screen.getByTestId('location')).toHaveTextContent('/task/object-detection') + }) + + test('«Tareas» también lleva al laboratorio 2D, aparte de las seis tareas, y se marca en él', () => { + renderAt('/lab') + const tasks = document.getElementById('tasks-nav-dropdown')! + expect(tasks).toHaveClass('active') + fireEvent.click(tasks) + const lab = screen.getByTestId('Test-Navbar-Lab') + expect(lab).toHaveAttribute('href', '/lab') + expect(lab).toHaveTextContent('header.lab') + expect(lab).toHaveAttribute('aria-current', 'page') + }) + + test('fuera de las tareas, «Tareas» no se marca', () => { + renderAt('/glossary') + expect(document.getElementById('tasks-nav-dropdown')).not.toHaveClass('active') + }) + + test('«Paquetes .n4l», aparte: lleva a su página y dice cuántos hay guardados', async () => { + const store = new MemoryPackageStore() + const info = (id: string): LocalPackage_t => ({ id, version: '1.0.0', importedAt: 0, bytes: 1, tasks: [{ task: 'regression', names: {}, models: 1 }] }) + await store.save(info('a'), new ArrayBuffer(1)) + await store.save(info('b'), new ArrayBuffer(1)) + setN4LPackageStore(store) + renderAt('/packages') + const packages = screen.getByTestId('Test-Navbar-Packages') + expect(packages).toHaveAttribute('href', '/packages') + expect(packages).toHaveAttribute('aria-current', 'page') + expect(await screen.findByTitle('header.packages-saved')).toHaveTextContent('2') + }) + + test('cada ajuste enseña su valor actual', () => { + renderAt('/') + expect(document.getElementById('change-theme-nav-dropdown')).toHaveTextContent(/header\.theme\s*header\.theme-(light|dark)/) + expect(document.getElementById('change-tf-backend-nav-dropdown')).toHaveTextContent(/header\.backend\s*(WebGL|WebGPU|WebAssembly|CPU)/) + // GitHub con su nombre (en el menú del móvil el icono solo no se entiende) y diciendo que abre otra pestaña + const github = screen.getByRole('link', { name: 'header.github' }) + expect(github).toHaveAttribute('href', 'https://github.com/SIMIDAT/nets4learning') + expect(github).toHaveAttribute('target', '_blank') + expect(github).toHaveTextContent('GitHub') + }) +}) diff --git a/tests/components/N4LNumberField.test.tsx b/tests/components/N4LNumberField.test.tsx new file mode 100644 index 0000000..6117dd5 --- /dev/null +++ b/tests/components/N4LNumberField.test.tsx @@ -0,0 +1,54 @@ +import { describe, test, expect, vi } from 'vitest' +import { fireEvent, render, screen } from '@testing-library/react' + +import N4LNumberField from '@components/form/N4LNumberField' + +// t devuelve la clave (tests/setupTests.ts) +const field = (props: Partial[0]> = {}) => { + const onChange = vi.fn() + const view = render() + return { onChange, input: screen.getByRole('spinbutton', { name: 'Épocas' }), ...view } +} + +describe('N4LNumberField', () => { + test('un valor válido se usa y el campo no tiene error', () => { + const { onChange, input } = field() + fireEvent.change(input, { target: { value: '30' } }) + expect(onChange).toHaveBeenCalledWith(30) + expect(input).toHaveAttribute('aria-invalid', 'false') + expect(input).toHaveAccessibleDescription('Cuántas veces') + }) + + test('lo que no vale no se recorta en silencio: se dice junto al campo y se sigue usando el último valor bueno', () => { + const { onChange, input } = field() + fireEvent.change(input, { target: { value: '500' } }) + expect(onChange).not.toHaveBeenCalled() + expect(input).toHaveValue(500) + expect(input).toHaveAttribute('aria-invalid', 'true') + expect(input).toHaveAccessibleDescription('Cuántas veces form.number.range form.number.in-use') + expect(screen.getByTestId('Test-NumberField-Error')).toHaveAttribute('aria-live', 'polite') + }) + + test('se puede borrar el número para escribir otro', () => { + const { onChange, input } = field() + fireEvent.change(input, { target: { value: '' } }) + expect(input).toHaveValue(null) + expect(onChange).not.toHaveBeenCalled() + fireEvent.change(input, { target: { value: '7' } }) + expect(onChange).toHaveBeenLastCalledWith(7) + expect(input).toHaveAttribute('aria-invalid', 'false') + }) + + test('sin máximo, el mensaje dice el mínimo; los decimales no valen', () => { + const { onChange, input } = field({ max: undefined }) + fireEvent.change(input, { target: { value: '2.5' } }) + expect(onChange).not.toHaveBeenCalled() + expect(screen.getByTestId('Test-NumberField-Error')).toHaveTextContent('form.number.at-least') + }) + + test('si el valor cambia desde fuera, el campo lo enseña', () => { + const { input, rerender, onChange } = field() + rerender() + expect(input).toHaveValue(42) + }) +}) diff --git a/tests/components/N4LPagination.test.tsx b/tests/components/N4LPagination.test.tsx index 51760a4..bb47b93 100644 --- a/tests/components/N4LPagination.test.tsx +++ b/tests/components/N4LPagination.test.tsx @@ -2,14 +2,22 @@ import { describe, test, expect, vi } from 'vitest' import { render, fireEvent } from '@testing-library/react' import N4LPagination from '@components/table/N4LPagination' +// Lo que se ve de los números de página (sin las flechas ni el nombre oculto para el lector de pantalla) +const pageNumbers = (container: HTMLElement) => Array.from(container.querySelectorAll('.page-item')) + .slice(2, -2) + .map((li) => li.querySelector('[aria-hidden="true"]')?.textContent?.trim()) + describe('N4LPagination', () => { - test('muestra la página actual, sus vecinas existentes y "-" para las que no existen', () => { + test('enseña las páginas desde 1 y solo las que existen', () => { const { container } = render( {}} />) - const items = Array.from(container.querySelectorAll('.page-item')).map((li) => li.textContent?.replace(/[«‹›»]|First|Previous|Next|Last|\(current\)/g, '').trim()) - // First, Prev, -3, -2, -1, actual, +1, +2, +3, Next, Last - expect(items.slice(2, 9)).toStrictEqual(['-', '-', '0', '1', '2', '-', '-']) - expect(container.querySelector('.page-item.active')?.textContent).toContain('1') + expect(pageNumbers(container)).toStrictEqual(['1', '2', '3']) + expect(container.querySelector('.page-item.active')?.textContent).toContain('2') + }) + + test('hasta tres páginas a cada lado de la actual', () => { + const { container } = render( {}} />) + expect(pageNumbers(container)).toStrictEqual(['3', '4', '5', '6', '7', '8', '9']) }) test('desactiva la navegación en los extremos y avisa de la página elegida', () => { @@ -18,7 +26,23 @@ describe('N4LPagination', () => { const items = container.querySelectorAll('.page-item') expect(items[0].classList.contains('disabled')).toBe(true) // First expect(items[items.length - 1].classList.contains('disabled')).toBe(false) // Last - fireEvent.click(getByText('1')) + fireEvent.click(getByText('2')) expect(onChange).toHaveBeenCalledWith(1) }) + + test('cada botón tiene su nombre (oculto) y la página actual se marca', () => { + // t devuelve la clave (tests/setupTests.ts) + const { container, getByRole } = render( {}} />) + expect(getByRole('navigation')).toHaveAttribute('aria-label', 'pagination.label') + const items = container.querySelectorAll('.page-item') + expect(items[0].querySelector('.visually-hidden')?.textContent).toBe('pagination.first') + expect(container.querySelector('[aria-current="page"]')?.textContent).toContain('2') + // Sin aria-label: en la página actual y en las flechas desactivadas es un , que no puede llevarlo + expect(container.querySelector('[aria-label]:not(nav)')).toBeNull() + }) + + test('con una sola página no se muestra', () => { + const { container } = render( {}} />) + expect(container.querySelector('.pagination')).toBeNull() + }) }) diff --git a/tests/components/N4LSectionNav.test.tsx b/tests/components/N4LSectionNav.test.tsx new file mode 100644 index 0000000..afc99bd --- /dev/null +++ b/tests/components/N4LSectionNav.test.tsx @@ -0,0 +1,103 @@ +import { describe, test, expect, vi, beforeEach } from 'vitest' +import { act, fireEvent, render, screen } from '@testing-library/react' +import N4LSectionNav, { N4LSectionBar } from '@components/divider/N4LSectionNav' +import N4LDivider from '@components/divider/N4LDivider' +import { useActiveSection } from '@components/divider/useActiveSection' + +const STEPS = ['hr.information', 'hr.model', 'hr.classify'] + +// jsdom no maqueta: cada separador dice a qué altura de la ventana está +function placeDividers(tops: number[]) { + STEPS.forEach((step, index) => { + const element = document.getElementById(`n4l-section-${step.replace(/[^a-z0-9]+/gi, '-')}`)! + element.getBoundingClientRect = () => ({ top: tops[index] } as DOMRect) + }) +} + +async function scroll() { + await act(async () => { + fireEvent.scroll(window) + await new Promise((resolve) => requestAnimationFrame(resolve)) + }) +} + +// Como en N4LSectionLayout: la sección actual se calcula una vez y la enseña el índice (lateral o barra) +function Page({ bar = false }: { bar?: boolean }) { + const { activeId, started } = useActiveSection(STEPS) + return <> + {String(started)} + {bar ? : } + {STEPS.map((step) => )} + +} + +function renderPage(bar = false) { + return render() +} + +const activeLink = () => screen.getAllByRole('link').find((link) => link.getAttribute('aria-current') === 'location')?.textContent + +describe('N4LSectionNav', () => { + + beforeEach(() => { + Object.defineProperty(window, 'innerHeight', { configurable: true, value: 800 }) + Object.defineProperty(document.documentElement, 'scrollHeight', { configurable: true, value: 5000 }) + }) + + test('un enlace numerado por sección, al separador de cada una', () => { + renderPage() + const links = screen.getAllByRole('link') + expect(links.map((link) => link.textContent)).toEqual(['1. hr.information', '2. hr.model', '3. hr.classify']) + expect(links[1]).toHaveAttribute('href', '#n4l-section-hr-model') + expect(document.getElementById('n4l-section-hr-model')).toHaveTextContent('2. hr.model') + }) + + test('marca la última sección cuyo título ya ha subido por encima de la cuarta parte de la ventana', async () => { + renderPage() + placeDividers([-900, 150, 700]) + await scroll() + expect(activeLink()).toBe('2. hr.model') + placeDividers([-1500, -400, 100]) + await scroll() + expect(activeLink()).toBe('3. hr.classify') + }) + + test('arriba del todo, la primera', async () => { + renderPage() + placeDividers([50, 900, 1800]) + await scroll() + expect(activeLink()).toBe('1. hr.information') + }) + + test('al hacer clic lleva a la sección y le da el foco', () => { + renderPage() + const divider = document.getElementById('n4l-section-hr-classify')! + divider.scrollIntoView = vi.fn() + fireEvent.click(screen.getByRole('link', { name: '3. hr.classify' })) + expect(divider.scrollIntoView).toHaveBeenCalledWith(expect.objectContaining({ block: 'start' })) + expect(divider).toHaveFocus() + }) + + test('sabe cuándo la primera sección ha subido por encima de la ventana (la barra del móvil aparece entonces)', async () => { + renderPage() + placeDividers([120, 900, 1800]) + await scroll() + expect(screen.getByTestId('started')).toHaveTextContent('false') + placeDividers([-10, 700, 1600]) + await scroll() + expect(screen.getByTestId('started')).toHaveTextContent('true') + }) + + test('la barra del móvil: los mismos enlaces, marca la sección actual y lleva a ella', async () => { + renderPage(true) + placeDividers([-900, 150, 700]) + await scroll() + expect(screen.getAllByRole('link').map((link) => link.textContent)).toEqual(['1. hr.information', '2. hr.model', '3. hr.classify']) + expect(activeLink()).toBe('2. hr.model') + const divider = document.getElementById('n4l-section-hr-classify')! + divider.scrollIntoView = vi.fn() + fireEvent.click(screen.getByRole('link', { name: '3. hr.classify' })) + expect(divider.scrollIntoView).toHaveBeenCalled() + expect(divider).toHaveFocus() + }) +}) diff --git a/tests/components/N4LStepByStep.test.tsx b/tests/components/N4LStepByStep.test.tsx new file mode 100644 index 0000000..be77a67 --- /dev/null +++ b/tests/components/N4LStepByStep.test.tsx @@ -0,0 +1,65 @@ +import { describe, test, expect } from 'vitest' +import { fireEvent, render, screen, within } from '@testing-library/react' +import N4LStepByStep from '@components/neural-network/stepByStep/N4LStepByStep' + +const prefix = 'pages.playground.step-by-step.' +// Cuatro características y tres clases, como IRIS +const X = [[0.1, 0.5, 0.2, 0.9], [0.8, 0.3, 0.7, 0.1], [0.4, 0.4, 0.5, 0.5], [0.9, 0.9, 0.1, 0.2]] +const y = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]] +const props = { + kind : 'classification' as const, + X, y, + featureNames: ['a', 'b', 'c', 'd'], + outputNames : ['uno', 'dos', 'tres'], + learningRate: 0.1, +} +const small = [{ units: 5, activation: 'relu' }, { units: 3, activation: 'softmax' }] + +describe('N4LStepByStep: el entrenamiento paso a paso', () => { + test('recorre la entrada, cada capa hacia delante, el error, cada capa hacia atrás y la actualización', () => { + render() + const phase = () => screen.getByTestId('Test-StepByStep-Phase').textContent + const seen = [phase()] + for (let i = 0; i < 6; i++) { + fireEvent.click(screen.getByTestId('Test-StepByStep-Next')) + seen.push(phase()) + } + expect(seen).toEqual(['input', 'forward', 'forward', 'loss', 'backward', 'backward', 'update'].map((kind) => prefix + 'phase-title.' + kind)) + // Con la actualización termina el ejemplo: aparece la pérdida y se vuelve a la entrada con el siguiente + expect(screen.queryByTestId('Test-StepByStep-History')).toBeNull() + fireEvent.click(screen.getByTestId('Test-StepByStep-Next')) + expect(phase()).toBe(prefix + 'phase-title.input') + expect(screen.getByTestId('Test-StepByStep-History')).toBeInTheDocument() + }) + + test('al pulsar una neurona se explican sus cuentas, y la de antes se puede volver a ver con Atrás', () => { + render() + fireEvent.click(screen.getByTestId('Test-StepByStep-Next')) + fireEvent.click(document.querySelectorAll('.n4l-sbs-node')[6]) + // La 3.ª neurona de la capa 1 (las 4 primeras son las de entrada): su suma ponderada y su activación + expect(screen.getByTestId('Test-StepByStep-Formula').textContent).toMatch(/^z = .* → relu\(z\) = /) + fireEvent.click(screen.getByTestId('Test-StepByStep-Back')) + expect(screen.getByTestId('Test-StepByStep-Phase').textContent).toBe(prefix + 'phase-title.input') + expect(screen.getByTestId('Test-StepByStep-Back')).toBeDisabled() + }) + + test('10 ejemplos de golpe: la pérdida media queda apuntada y se sigue desde la entrada', () => { + render() + fireEvent.click(screen.getByTestId('Test-StepByStep-Ten')) + expect(screen.getByTestId('Test-StepByStep-History')).toBeInTheDocument() + expect(screen.getByTestId('Test-StepByStep-Phase').textContent).toBe(prefix + 'phase-title.input') + }) + + test('con 64 neuronas o más (contando las de entrada) no se dibuja: dice cuántas tiene y cómo reducirla', () => { + render() + const card = screen.getByTestId('Test-StepByStep') + expect(within(card).getByTestId('Test-StepByStep-TooBig')).toHaveTextContent(prefix + 'too-big') + expect(within(card).queryByTestId('Test-StepByStep-Next')).toBeNull() + }) + + test('si la salida no tiene una neurona por clase, avisa en lugar de dibujar', () => { + render() + expect(screen.getByTestId('Test-StepByStep')).toHaveTextContent(prefix + 'mismatch') + expect(screen.queryByTestId('Test-StepByStep-Next')).toBeNull() + }) +}) diff --git a/tests/components/N4LTrainingPrediction.test.tsx b/tests/components/N4LTrainingPrediction.test.tsx new file mode 100644 index 0000000..ccabb78 --- /dev/null +++ b/tests/components/N4LTrainingPrediction.test.tsx @@ -0,0 +1,62 @@ +import { afterEach, describe, expect, test } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { MemoryRouter } from 'react-router' + +import N4LTrainingPrediction from '@components/neural-network/N4LTrainingPrediction' +import N4LTrainingDiagnosis from '@components/neural-network/N4LTrainingDiagnosis' +import { diagnoseTraining } from '@core/training/diagnoseTraining' +import { isRightPrediction, setPrediction } from '@core/training/trainingPrediction' + +// La pérdida de entrenamiento baja siempre; la de prueba baja hasta la época 8 y luego sube: sobreajuste +const epochs = Array.from({ length: 20 }, (_, i) => i) +const OVERFITTING = { loss: epochs.map((i) => 1 / (1 + i)), val_loss: epochs.map((i) => (i < 8 ? 1 - i * 0.08 : 0.36 + (i - 8) * 0.06)) } +// Las dos bajan y se estabilizan: aprende bien +const GOOD = { loss: epochs.map((i) => 0.2 + 0.8 * Math.exp(-i / 2)), val_loss: epochs.map((i) => 0.25 + 0.8 * Math.exp(-i / 2)) } + +function renderAt(path: string, ui: React.ReactNode) { + return render({ui}) +} + +describe('Predice antes de entrenar', () => { + afterEach(() => cleanup()) + + test('los historiales de prueba dan el diagnóstico que se espera', () => { + expect(diagnoseTraining(OVERFITTING).map(({ kind }) => kind)).toContain('overfitting') + expect(diagnoseTraining(GOOD).map(({ kind }) => kind)).toContain('good') + }) + + test('«apenas aprenderá» también se acierta si la pérdida empeoró', () => { + expect(isRightPrediction('not-learning', ['worse'])).toBe(true) + expect(isRightPrediction('good', ['overfitting'])).toBe(false) + }) + + test('se elige antes de entrenar y el diagnóstico de ese modelo dice si se acertó', () => { + const page = '/playground/tabular-classification/dataset/IRIS' + renderAt(page, ) + fireEvent.click(screen.getByLabelText('training-prediction.options.overfitting')) + expect(screen.getByText('training-prediction.chosen')).toBeInTheDocument() + cleanup() + + renderAt(page, ) + expect(screen.getByTestId('Test-TrainingPrediction-Result')).toHaveTextContent('training-prediction.right') + }) + + test('si pasó otra cosa, lo dice; y la predicción es de ese modelo y de esa página', () => { + const page = '/playground/regression/dataset/SALARY' + setPrediction(page, 2, 'diverged') + renderAt(page, ) + expect(screen.getByTestId('Test-TrainingPrediction-Result')).toHaveTextContent('training-prediction.wrong') + cleanup() + // Otro modelo u otra página: sin predicción + renderAt(page, ) + expect(screen.queryByTestId('Test-TrainingPrediction-Result')).toBeNull() + cleanup() + renderAt('/playground/regression/dataset/AUTO_MPG', ) + expect(screen.queryByTestId('Test-TrainingPrediction-Result')).toBeNull() + }) + + test('mientras se entrena no se puede cambiar', () => { + renderAt('/x', ) + expect(screen.getByLabelText('training-prediction.options.good')).toBeDisabled() + }) +}) diff --git a/tests/components/N4LVirtualSelect.test.tsx b/tests/components/N4LVirtualSelect.test.tsx new file mode 100644 index 0000000..88f54e0 --- /dev/null +++ b/tests/components/N4LVirtualSelect.test.tsx @@ -0,0 +1,107 @@ +import { describe, test, expect, vi } from 'vitest' +import { fireEvent, render, screen } from '@testing-library/react' +import N4LVirtualSelect from '@components/select/N4LVirtualSelect' +import { filterVirtualSelectOptions } from '@components/select/filterVirtualSelectOptions' + +const CLASSES = ['unacc', 'acc', 'good', 'vgood'] +// Como las filas de un conjunto de datos grande: "#número: clase" +const OPTIONS = Array.from({ length: 5000 }, (_, index) => ({ value: index, label: `#${index}: ${CLASSES[index % 4]}` })) + +function renderSelect(onChange = vi.fn(), value: number | null = null) { + render( `${shown} de ${total}`} />) + return onChange +} + +const open = () => fireEvent.click(screen.getByRole('button', { name: /Selecciona la entidad|#/ })) + +describe('filterVirtualSelectOptions', () => { + + test('sin búsqueda, todas; con búsqueda, primero las que empiezan por ella (sin contar el "#")', () => { + expect(filterVirtualSelectOptions(OPTIONS, ' ')).toBe(OPTIONS) + const found = filterVirtualSelectOptions(OPTIONS, '12') + expect(found.slice(0, 3).map((o) => o.label)).toEqual(['#12: unacc', '#120: unacc', '#121: acc']) + expect(found.some((o) => o.label === '#112: unacc')).toBe(true) + expect(found.findIndex((o) => o.label === '#112: unacc')).toBeGreaterThan(found.findIndex((o) => o.label === '#1299: vgood')) + }) + + test('también busca por la clase, sin distinguir mayúsculas', () => { + expect(filterVirtualSelectOptions(OPTIONS, 'VGOOD')).toHaveLength(1250) + }) +}) + +describe('N4LVirtualSelect', () => { + + test('con miles de opciones solo pinta las que se ven', () => { + renderSelect() + expect(screen.getByRole('button')).toHaveTextContent('Selecciona la entidad') + open() + expect(screen.getByRole('combobox')).toHaveFocus() + expect(screen.getByText('5000 de 5000')).toBeInTheDocument() + const options = screen.getAllByRole('option') + expect(options.length).toBeLessThan(30) + expect(options[0]).toHaveAttribute('aria-setsize', '5000') + expect(options[0]).toHaveAttribute('aria-posinset', '1') + }) + + test('al hacer scroll aparecen las filas de esa altura', () => { + renderSelect() + open() + const list = screen.getByRole('listbox') + list.scrollTop = 32 * 4000 + fireEvent.scroll(list) + expect(screen.getByText('#4000: unacc')).toBeInTheDocument() + expect(screen.queryByText('#0: unacc')).toBeNull() + }) + + test('se busca y se elige con el teclado', () => { + const onChange = renderSelect() + open() + const search = screen.getByRole('combobox') + fireEvent.change(search, { target: { value: '4999' } }) + expect(screen.getByText('1 de 5000')).toBeInTheDocument() + expect(search).toHaveAttribute('aria-activedescendant', screen.getByRole('option').id) + fireEvent.keyDown(search, { key: 'Enter' }) + expect(onChange).toHaveBeenCalledWith(4999) + expect(screen.queryByRole('listbox')).toBeNull() + }) + + test('las flechas mueven la opción activa y Esc cierra sin elegir', () => { + const onChange = renderSelect() + open() + const search = screen.getByRole('combobox') + fireEvent.keyDown(search, { key: 'ArrowDown' }) + fireEvent.keyDown(search, { key: 'ArrowDown' }) + expect(search.getAttribute('aria-activedescendant')).toBe(screen.getByText('#2: good').id) + fireEvent.keyDown(search, { key: 'Escape' }) + expect(screen.queryByRole('listbox')).toBeNull() + expect(onChange).not.toHaveBeenCalled() + expect(screen.getByRole('button')).toHaveFocus() + }) + + test('se elige con el ratón, y abre en la opción elegida', () => { + const onChange = renderSelect(vi.fn(), 2500) + expect(screen.getByRole('button')).toHaveTextContent('#2500: unacc') + open() + expect(screen.getByRole('option', { name: '#2500: unacc' })).toHaveAttribute('aria-selected', 'true') + fireEvent.click(screen.getByRole('option', { name: '#2501: acc' })) + expect(onChange).toHaveBeenCalledWith(2501) + }) + + test('sin coincidencias lo dice', () => { + renderSelect() + open() + fireEvent.change(screen.getByRole('combobox'), { target: { value: 'xyz' } }) + expect(screen.getByText('Nada')).toBeInTheDocument() + expect(screen.queryAllByRole('option')).toHaveLength(0) + }) + + test('deshabilitado no se abre', () => { + render() + expect(screen.getByRole('button')).toBeDisabled() + fireEvent.click(screen.getByRole('button')) + expect(screen.queryByRole('listbox')).toBeNull() + }) +}) diff --git a/tests/components/scrollAction.test.ts b/tests/components/scrollAction.test.ts new file mode 100644 index 0000000..670a753 --- /dev/null +++ b/tests/components/scrollAction.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, test } from 'vitest' +import { NavigationType } from 'react-router' + +import { scrollAction } from '@components/navigation/scrollAction' + +const page = (pathname: string, hash = '') => ({ pathname, hash }) + +describe('scrollAction: el scroll al cambiar de página', () => { + test('una página nueva empieza arriba (también entre conjuntos de datos del mismo entrenador)', () => { + expect(scrollAction(page('/glossary'), page('/manual'), NavigationType.Push, undefined)).toEqual({ type: 'top' }) + expect(scrollAction(page('/playground/tabular-classification/dataset/IRIS'), page('/playground/tabular-classification/dataset/CAR'), NavigationType.Push, 1200)) + .toEqual({ type: 'top' }) + }) + + test('con #sección, a la sección; atrás y adelante, a donde se estaba', () => { + expect(scrollAction(page('/settings'), page('/terms-and-conditions', '#cookies'), NavigationType.Push, undefined)).toEqual({ type: 'hash', id: 'cookies' }) + expect(scrollAction(page('/manual'), page('/glossary'), NavigationType.Pop, 2400)).toEqual({ type: 'restore', y: 2400 }) + // Sin posición guardada (p. ej. historial de antes de cargar la aplicación): como una página nueva + expect(scrollAction(page('/manual'), page('/glossary'), NavigationType.Pop, undefined)).toEqual({ type: 'top' }) + }) + + test('en la misma página (secciones, ?task=…) no se toca; al entrar, solo la sección si la hay', () => { + expect(scrollAction(page('/glossary'), page('/glossary', '#glossary-loss'), NavigationType.Push, undefined)).toEqual({ type: 'none' }) + expect(scrollAction(null, page('/learn'), NavigationType.Pop, undefined)).toEqual({ type: 'none' }) + expect(scrollAction(null, page('/learn', '#challenges'), NavigationType.Pop, undefined)).toEqual({ type: 'hash', id: 'challenges' }) + }) + + test('lo que va tras # y no es una sección (un enlace compartido) no se busca', () => { + expect(scrollAction(null, page('/playground/tabular-classification/dataset/IRIS', '#n4z=q1YqKs4vSgk'), NavigationType.Pop, undefined)).toEqual({ type: 'none' }) + expect(scrollAction(page('/'), page('/playground/regression/dataset/SALARY', '#n4z=abc'), NavigationType.Push, undefined)).toEqual({ type: 'top' }) + }) +}) diff --git a/tests/components/stepByStepSetting.test.ts b/tests/components/stepByStepSetting.test.ts new file mode 100644 index 0000000..9bb07dd --- /dev/null +++ b/tests/components/stepByStepSetting.test.ts @@ -0,0 +1,23 @@ +import { describe, test, expect, beforeEach } from 'vitest' +import { act, renderHook } from '@testing-library/react' +import { + isStepByStepEnabled, resetStepByStep, setStepByStepEnabled, STEP_BY_STEP_STORAGE_KEY, useStepByStepEnabled, +} from '@components/neural-network/stepByStep/stepByStepSetting' + +describe('ajuste de Paso a paso', () => { + beforeEach(() => resetStepByStep()) + + test('está oculto por defecto; al activarlo se guarda y las páginas se enteran al momento', () => { + const { result } = renderHook(() => useStepByStepEnabled()) + expect(result.current).toBe(false) + expect(localStorage.getItem(STEP_BY_STEP_STORAGE_KEY)).toBeNull() + act(() => setStepByStepEnabled(true)) + expect(result.current).toBe(true) + expect(isStepByStepEnabled()).toBe(true) + expect(localStorage.getItem(STEP_BY_STEP_STORAGE_KEY)).toBe('true') + // Desactivado no se guarda nada: vuelve a ser lo de por defecto + act(() => setStepByStepEnabled(false)) + expect(result.current).toBe(false) + expect(localStorage.getItem(STEP_BY_STEP_STORAGE_KEY)).toBeNull() + }) +}) diff --git a/tests/components/useTrainingProgress.test.ts b/tests/components/useTrainingProgress.test.ts new file mode 100644 index 0000000..3ff4124 --- /dev/null +++ b/tests/components/useTrainingProgress.test.ts @@ -0,0 +1,85 @@ +import { describe, test, expect, vi, beforeEach } from 'vitest' +import { act, renderHook } from '@testing-library/react' + +const trackEvent = vi.hoisted(() => vi.fn()) +vi.mock('@core/analytics', () => ({ trackEvent })) +const announce = vi.hoisted(() => vi.fn()) +vi.mock('@core/a11y/announce', () => ({ announce })) +vi.mock('i18next', () => ({ default: { t: (key: string) => key } })) + +import { useTrainingProgress } from '@hooks/useTrainingProgress' + +const SUMMARY = { epochs: 10, learningRate: 0.01, optimizer: 'adam', loss: 'categoricalCrossentropy', layers: 3 } +const trainEnd = () => trackEvent.mock.calls.find(([name]) => name === 'train_end')?.[1] + +describe('useTrainingProgress: analíticas del entrenamiento', () => { + beforeEach(() => { + trackEvent.mockClear() + announce.mockClear() + }) + + test('al empezar, los hiperparámetros; al terminar bien, completed con las épocas hechas', () => { + const { result } = renderHook(() => useTrainingProgress()) + act(() => result.current.start(SUMMARY)) + expect(trackEvent).toHaveBeenCalledWith('train_start', { epochs: 10, learning_rate: 0.01, optimizer: 'adam', loss: 'categoricalCrossentropy', layers: 3 }) + act(() => { + for (let epoch = 1; epoch <= 10; epoch++) result.current.callbacks.onEpochEnd(epoch, 10) + result.current.complete() + result.current.finish() + }) + expect(trainEnd()).toEqual(expect.objectContaining({ outcome: 'completed', epochs: 10, epochs_done: 10 })) + }) + + test('parado a mitad: stopped; sin complete (falló): error', () => { + const { result } = renderHook(() => useTrainingProgress()) + act(() => { + result.current.start(SUMMARY) + result.current.callbacks.onEpochEnd(4, 10) + result.current.stop() + result.current.finish() + }) + expect(trainEnd()).toEqual(expect.objectContaining({ outcome: 'stopped', epochs_done: 4 })) + + trackEvent.mockClear() + act(() => { + result.current.start(SUMMARY) + result.current.finish() + }) + expect(trainEnd()).toEqual(expect.objectContaining({ outcome: 'error', epochs_done: 0 })) + }) + + test('el lector de pantalla oye que empieza, cómo va cada 10 s (no en cada época) y si se para', () => { + const now = vi.spyOn(performance, 'now').mockReturnValue(0) + const { result } = renderHook(() => useTrainingProgress()) + act(() => result.current.start(SUMMARY)) + expect(announce).toHaveBeenLastCalledWith('pages.playground.generator.training.announce-start') + act(() => { + for (let epoch = 1; epoch <= 4; epoch++) { + now.mockReturnValue(epoch * 3_000) + result.current.callbacks.onEpochEnd(epoch, 10) + } + }) + // A los 12 s (época 4): una sola vez + expect(announce).toHaveBeenCalledTimes(2) + // La época y lo que queda + expect(announce).toHaveBeenLastCalledWith(expect.stringMatching(/training\.epoch.*training\.remaining/)) + act(() => { + result.current.stop() + result.current.finish() + }) + expect(announce).toHaveBeenLastCalledWith('pages.playground.generator.training.announce-stopped') + now.mockRestore() + }) + + test('al terminar bien no se anuncia nada más: ya lo dice el aviso de «modelo entrenado»', () => { + const { result } = renderHook(() => useTrainingProgress()) + act(() => result.current.start(SUMMARY)) + announce.mockClear() + act(() => { + result.current.callbacks.onEpochEnd(10, 10) + result.current.complete() + result.current.finish() + }) + expect(announce).not.toHaveBeenCalled() + }) +}) diff --git a/tests/core/DataFrameTable.test.ts b/tests/core/DataFrameTable.test.ts new file mode 100644 index 0000000..a9837d0 --- /dev/null +++ b/tests/core/DataFrameTable.test.ts @@ -0,0 +1,115 @@ +import { describe, test, expect } from 'vitest' +import * as dfd from 'danfojs' + +import { + CELL_HEIGHT, + DataFrameDescribeTable, + TABLE_PALETTE, + TARGET_COLOR, + buildDataFrameTable, + resolveTableTarget, +} from '@core/dataframe/DataFrameTable' + +const iris = () => new dfd.DataFrame({ + 'sepal length': [5.1, 4.9, 7.0, 6.3], + 'petal width' : [0.2, 0.2, 1.4, 2.5], + 'class' : ['Iris-setosa', 'Iris-setosa', 'Iris-versicolor', 'Iris-virginica'], +}) + +type Trace_t = { + header: { values: string[][], fill: { color: string[] }, font: { color: string[] }, align: string[] } + cells : { values: unknown[][], fill: { color: string[][] }, font: { color: Array }, format: string[], align: string[] } +} +const traceOf = (table: ReturnType) => table.data as unknown as Trace_t + +describe('resolveTableTarget', () => { + + test('por defecto la última columna; null o una que no existe, ninguna', () => { + expect(resolveTableTarget(iris(), {})).toBe('class') + expect(resolveTableTarget(iris(), { target: 'petal width' })).toBe('petal width') + expect(resolveTableTarget(iris(), { target: null })).toBeNull() + expect(resolveTableTarget(iris(), { target: 'species' })).toBeNull() + }) +}) + +describe('buildDataFrameTable', () => { + + test('la columna objetivo con su color en la cabecera y las celdas teñidas', () => { + const table = buildDataFrameTable(iris(), { target: 'class' }) + const trace = traceOf(table) + // [#, sepal length, petal width, class] + expect(trace.header.fill.color).toEqual([TABLE_PALETTE.light.header, TABLE_PALETTE.light.header, TABLE_PALETTE.light.header, TARGET_COLOR]) + expect(trace.header.font.color[3]).toBe('#ffffff') + expect(trace.cells.fill.color[3]).toEqual([ + TABLE_PALETTE.light.target, TABLE_PALETTE.light.targetStripe, TABLE_PALETTE.light.target, TABLE_PALETTE.light.targetStripe, + ]) + // El resto, filas alternas + expect(trace.cells.fill.color[1]).toEqual([ + TABLE_PALETTE.light.cell, TABLE_PALETTE.light.stripe, TABLE_PALETTE.light.cell, TABLE_PALETTE.light.stripe, + ]) + expect(trace.cells.font.color[3]).toBe(TABLE_PALETTE.light.targetText) + }) + + test('sin objetivo no se resalta nada', () => { + const trace = traceOf(buildDataFrameTable(iris(), { target: null })) + expect(trace.header.fill.color).not.toContain(TARGET_COLOR) + }) + + test('índice de filas, tipo bajo cada nombre, números a la derecha con 4 decimales como mucho y textos a la izquierda', () => { + const trace = traceOf(buildDataFrameTable(iris(), { subtitles: 'dtype' })) + expect(trace.cells.values[0]).toEqual(['0', '1', '2', '3']) + expect(trace.header.values[1][0]).toContain('sepal length
    ') + expect(trace.header.values[1][0]).toContain('float32') + expect(trace.header.values[3][0]).toContain('string') + expect(trace.cells.format).toEqual(['', '.4~f', '.4~f', '']) + expect(trace.cells.align).toEqual(['left', 'right', 'right', 'left']) + }) + + test('los textos se escapan: Plotly interpreta algo de HTML', () => { + const dataframe = new dfd.DataFrame({ 'x': ['a
    b', 'c'], y: [1, 2] }) + const trace = traceOf(buildDataFrameTable(dataframe, { index: false })) + expect(trace.header.values[0][0]).toBe('<b>x</b>') + expect(trace.cells.values[0]).toEqual(['a<br>b', 'c']) + }) + + test('altura justa para las filas visibles: sin hueco debajo y con desplazamiento a partir de maxRows', () => { + const small = buildDataFrameTable(iris(), {}) + expect(small.layout.height).toBe(34 + 4 * CELL_HEIGHT + 4) + const many = new dfd.DataFrame({ a: Array.from({ length: 100 }, (_, i) => i) }) + expect(buildDataFrameTable(many, { maxRows: 10 }).layout.height).toBe(34 + 10 * CELL_HEIGHT + 4) + }) + + test('colores del tema oscuro y ancho mínimo para que las columnas no se aplasten', () => { + const table = buildDataFrameTable(iris(), { theme: 'dark', target: null }) + expect(traceOf(table).header.fill.color[1]).toBe(TABLE_PALETTE.dark.header) + expect(table.layout.font.color).toBe(TABLE_PALETTE.dark.text) + expect(table.minWidth).toBeGreaterThanOrEqual(3 * 96) + }) + + test('con el objetivo en una fila (describe), se tiñe esa fila entera', () => { + const describe = DataFrameDescribeTable(new dfd.DataFrame({ a: [1, 2, 3], target: [10, 20, 30] }))! + const trace = traceOf(buildDataFrameTable(describe, { target: 'target', targetAxis: 'row' })) + const targetRow = 1 + for (const column of trace.cells.fill.color) { + expect([TABLE_PALETTE.light.target, TABLE_PALETTE.light.targetStripe]).toContain(column[targetRow]) + expect([TABLE_PALETTE.light.target, TABLE_PALETTE.light.targetStripe]).not.toContain(column[0]) + } + expect((trace.cells.font.color[1] as string[])[targetRow]).toBe(TABLE_PALETTE.light.targetText) + }) +}) + +describe('DataFrameDescribeTable', () => { + + test('una fila por columna numérica, con los estadísticos redondeados', () => { + const describe = DataFrameDescribeTable(iris())! + expect(describe.index).toEqual(['sepal length', 'petal width']) + expect(describe.columns).toContain('mean') + const mean = describe.column('mean').values as number[] + expect(mean[0]).toBe(5.825) + expect(mean[1]).toBe(1.075) + }) + + test('sin columnas numéricas, null', () => { + expect(DataFrameDescribeTable(new dfd.DataFrame({ a: ['x', 'y'] }))).toBeNull() + }) +}) diff --git a/tests/core/DataFrameUtils.test.ts b/tests/core/DataFrameUtils.test.ts index 1b1e652..982138f 100644 --- a/tests/core/DataFrameUtils.test.ts +++ b/tests/core/DataFrameUtils.test.ts @@ -6,9 +6,10 @@ import { DataFrameEncoder, DataFrameFixMixedColumns, DataFrameReadCSV, + LabelEncoderClasses, } from '../../src/core/dataframe/DataFrameUtils' -const CAR_CSV = 'public/models/00-tabular-classification/car/car.csv' +const CAR_CSV = 'public/n4l/car.n4l/data/car.csv' const csvFile = (path: string) => new File([fs.readFileSync(path, 'utf8')], 'data.csv', { type: 'text/csv' }) const dtypeOf = (df: dfd.DataFrame, column: string) => df.dtypes[df.columns.indexOf(column)] @@ -61,3 +62,16 @@ describe('DataFrameUtils — columnas con tipos mezclados', () => { expect(DataFrameDescribeNumeric(numeric)?.columns).toStrictEqual(['A']) }) }) + +describe('DataFrameUtils — clases del LabelEncoder', () => { + + test('siguen el orden de los índices y de las columnas del OneHotEncoder, también con clases numéricas', () => { + const target = new dfd.Series([3, 2, 4, 1, 3, 2]) + const classes = LabelEncoderClasses(new dfd.LabelEncoder().fit(target.values)) + // Object.keys(encoder.classes) daría ['1', '2', '3', '4'] + expect(classes).toStrictEqual(['3', '2', '4', '1']) + const oneHot = new dfd.OneHotEncoder().fit(target).transform(target) as dfd.DataFrame + const decoded = (oneHot.values as number[][]).map((row) => classes[row.indexOf(1)]) + expect(decoded).toStrictEqual(['3', '2', '4', '1', '3', '2']) + }) +}) diff --git a/tests/core/analytics.test.ts b/tests/core/analytics.test.ts new file mode 100644 index 0000000..dcc2955 --- /dev/null +++ b/tests/core/analytics.test.ts @@ -0,0 +1,95 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest' +import ReactGA from 'react-ga4' + +// analytics.ts decide al cargarse si envía a Google Analytics (solo en producción): cada prueba lo carga de nuevo +async function loadAnalytics(environment: 'production' | 'development') { + vi.stubEnv('VITE_ENVIRONMENT', environment) + vi.resetModules() + const { default: GA } = await import('react-ga4') + const initialize = vi.spyOn(GA, 'initialize').mockImplementation(() => {}) + const gtag = vi.spyOn(GA, 'gtag').mockImplementation(() => {}) + return { ...await import('@core/analytics'), initialize, gtag } +} + +const eventsOf = (gtag: { mock: { calls: unknown[][] } }) => gtag.mock.calls.filter((call) => call[0] === 'event').map((call) => [call[1], call[2]]) + +describe('analytics', () => { + beforeEach(() => { + document.cookie = 'n4l-accept-cookies=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/' + }) + afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllEnvs() + }) + + test('sin decisión guardada no hay consentimiento ni se envía nada', async () => { + const { readConsent, trackEvent, trackPageView, initialize, gtag } = await loadAnalytics('production') + expect(readConsent()).toBeNull() + trackPageView('https://n4l/playground/regression/model/AUTO_MPG', { page_type: 'playground', task: 'regression' }) + trackEvent('predict', { input: 'form' }) + expect(initialize).not.toHaveBeenCalled() + expect(gtag).not.toHaveBeenCalled() + }) + + test('al rechazar se recuerda, no se envía nada y se borran las cookies de Google Analytics', async () => { + const { readConsent, saveConsent, trackEvent, gtag } = await loadAnalytics('production') + document.cookie = '_ga=GA1.1.123; path=/' + document.cookie = '_ga_3644EFBXMG=GS1.1.456; path=/' + saveConsent('rejected') + expect(readConsent()).toBe('rejected') + trackEvent('predict', { input: 'form' }) + expect(gtag).not.toHaveBeenCalled() + expect(document.cookie).not.toMatch(/_ga/) + }) + + test('al aceptar se carga sin publicidad y se registra la página en la que se está', async () => { + const { saveConsent, trackPageView, initialize, gtag } = await loadAnalytics('production') + // Antes de aceptar: no se envía, pero la página queda como la actual + trackPageView('https://n4l/playground/tabular-classification/model/CAR', { page_type: 'playground', task: 'tabular-classification', mode: 'pretrained', item: 'CAR' }) + saveConsent('accepted') + + expect(gtag).toHaveBeenCalledWith('consent', 'default', expect.objectContaining({ analytics_storage: 'granted', ad_storage: 'denied', ad_user_data: 'denied', ad_personalization: 'denied' })) + expect(initialize).toHaveBeenCalledWith(expect.any(String), { + gtagOptions: expect.objectContaining({ send_page_view: false, allow_google_signals: false, allow_ad_personalization_signals: false }), + }) + expect(eventsOf(gtag)).toContainEqual(['page_view', { + page_location: 'https://n4l/playground/tabular-classification/model/CAR', + page_title : 'playground / tabular-classification / pretrained / CAR', + page_type : 'playground', + task : 'tabular-classification', + mode : 'pretrained', + item : 'CAR', + }]) + expect(eventsOf(gtag)).toContainEqual(['consent_granted', expect.objectContaining({ source: 'banner', item: 'CAR' })]) + }) + + test('cada evento lleva el contexto de la página; al retirar el consentimiento se deja de enviar', async () => { + const { saveConsent, trackPageView, trackEvent, setUserProperties, gtag } = await loadAnalytics('production') + saveConsent('accepted', 'settings') + trackPageView('https://n4l/playground/regression/dataset/AUTO_MPG', { page_type: 'playground', task: 'regression', mode: 'train', item: 'AUTO_MPG' }) + trackEvent('train_start', { epochs: 20 }) + expect(eventsOf(gtag)).toContainEqual(['train_start', { page_type: 'playground', task: 'regression', mode: 'train', item: 'AUTO_MPG', epochs: 20 }]) + setUserProperties({ app_language: 'es', tf_backend: 'webgl' }) + expect(gtag).toHaveBeenCalledWith('set', 'user_properties', { app_language: 'es', tf_backend: 'webgl' }) + + gtag.mockClear() + saveConsent('rejected', 'settings') + expect(gtag).toHaveBeenCalledWith('consent', 'update', { analytics_storage: 'denied' }) + trackEvent('predict', { input: 'form' }) + expect(eventsOf(gtag)).toEqual([]) + }) + + test('en desarrollo no se carga Google Analytics: los eventos van a la consola', async () => { + const debug = vi.spyOn(console, 'debug').mockImplementation(() => {}) + const { saveConsent, trackEvent, initialize, gtag } = await loadAnalytics('development') + saveConsent('accepted') + trackEvent('predict', { input: 'drawing' }) + expect(initialize).not.toHaveBeenCalled() + expect(gtag).not.toHaveBeenCalled() + expect(debug).toHaveBeenCalledWith('[analytics]', 'predict', { input: 'drawing' }) + }) + + test('react-ga4 sigue siendo el mismo módulo (la prueba no deja el real inicializado)', () => { + expect(ReactGA.isInitialized).toBe(false) + }) +}) diff --git a/tests/core/analyticsPage.test.ts b/tests/core/analyticsPage.test.ts new file mode 100644 index 0000000..cc1dcb3 --- /dev/null +++ b/tests/core/analyticsPage.test.ts @@ -0,0 +1,68 @@ +import { describe, test, expect } from 'vitest' +import { clickTargetName, pageContextFromPath, pageTitle } from '@core/analyticsPage' + +describe('analyticsPage: el contexto de cada ruta', () => { + test.each([ + ['/', '', { page_type: 'home' }], + ['/home', '', { page_type: 'home' }], + ['/select-model/regression', '', { page_type: 'select_model', task: 'regression' }], + ['/task/regression', '', { page_type: 'task', task: 'regression' }], + ['/select-dataset/tabular-classification', '', { page_type: 'select_dataset', task: 'tabular-classification' }], + ['/playground/tabular-classification/model/CAR', '', { page_type: 'playground', task: 'tabular-classification', mode: 'pretrained', item: 'CAR' }], + ['/playground/regression/dataset/UPLOAD', '', { page_type: 'playground', task: 'regression', mode: 'train', item: 'UPLOAD' }], + ['/playground/description-regression', '', { page_type: 'regression_description', task: 'regression' }], + ['/analyze', '?dataset=car', { page_type: 'analyze', item: 'car' }], + ['/analyze', '', { page_type: 'analyze' }], + ['/terms-and-conditions', '', { page_type: 'terms' }], + ['/404', '', { page_type: 'not_found' }], + ['/test-page-easy-lazy', '', { page_type: 'dev' }], + ['/otra-cosa', '', { page_type: 'other' }], + ])('%s%s', (pathname, search, context) => { + expect(pageContextFromPath(pathname, search)).toEqual(context) + }) + + test('el título de la página no depende del idioma', () => { + expect(pageTitle({ page_type: 'playground', task: 'regression', mode: 'train', item: 'AUTO_MPG' })).toBe('playground / regression / train / AUTO_MPG') + expect(pageTitle({ page_type: 'glossary' })).toBe('glossary') + }) +}) + +describe('analyticsPage: el nombre de lo que se pulsa', () => { + const render = (html: string) => { + document.body.innerHTML = html + return document.body + } + + test('data-analytics, data-testid o id estable; también si se pulsa algo de dentro (un icono)', () => { + const body = render(` + + + + + `) + expect(clickTargetName(body.querySelector('path'))).toBe('Test-TrainButton') + expect(clickTargetName(body.querySelector('[data-analytics]'))).toBe('guide-voice') + expect(clickTargetName(body.querySelector('input'))).toBe('settings-privacy-analytics') + expect(clickTargetName(body.querySelector('[id=":r1:"]'))).toBeNull() + expect(clickTargetName(body.querySelectorAll('button')[3])).toBeNull() + }) + + test('un enlace interno, por su ruta sin el basename; uno a otra web (ya lo mide GA) o a "#" no', () => { + const body = render(` + Manual + GitHub + Oscuro +

    Texto

    `) + expect(clickTargetName(body.querySelector('a'), '/n4l')).toBe('link:/manual') + expect(clickTargetName(body.querySelectorAll('a')[1], '/n4l')).toBeNull() + expect(clickTargetName(body.querySelectorAll('a')[2], '/n4l')).toBeNull() + expect(clickTargetName(body.querySelector('p'))).toBeNull() + }) +}) + +describe('analyticsPage: lo privado no se registra', () => { + test('un clic dentro de [data-analytics-private] (los ajustes de accesibilidad) no tiene nombre', () => { + document.body.innerHTML = '
    ' + expect(clickTargetName(document.getElementById('settings-display-highContrast'))).toBeNull() + }) +}) diff --git a/tests/core/chartColors.test.ts b/tests/core/chartColors.test.ts new file mode 100644 index 0000000..8475061 --- /dev/null +++ b/tests/core/chartColors.test.ts @@ -0,0 +1,40 @@ +import { describe, test, expect } from 'vitest' + +import { CHART_PALETTE, categoryColor, CLASS_ORDER, withAlpha } from '@core/chartColors' + +// Contraste de WCAG entre dos colores #rrggbb +const luminance = (hex: string) => { + const [r, g, b] = [1, 3, 5].map((start) => Number.parseInt(hex.slice(start, start + 2), 16) / 255) + .map((channel) => (channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4)) + return 0.2126 * r + 0.7152 * g + 0.0722 * b +} +const contrast = (a: string, b: string) => { + const [light, dark] = [luminance(a), luminance(b)].sort((x, y) => y - x) + return (light + 0.05) / (dark + 0.05) +} + +// Donde van las gráficas: la tarjeta, el fondo terciario y el de la página +const BACKGROUNDS = { + light: ['#ffffff', '#f8f9fa', '#e8eaed'], + dark : ['#212529', '#2b3035', '#343a40'], +} + +describe('chartColors', () => { + test.each(Object.entries(CHART_PALETTE))('%s tiene al menos 3:1 sobre los fondos de los dos temas (WCAG 1.4.11)', (_name, tones) => { + for (const theme of ['light', 'dark'] as const) { + for (const background of BACKGROUNDS[theme]) { + expect(contrast(tones[theme], background), `${tones[theme]} sobre ${background}`).toBeGreaterThanOrEqual(3) + } + } + }) + + test('cada categoría tiene siempre el mismo color y se repiten al acabarse', () => { + expect(categoryColor(CLASS_ORDER, 0, 'light')).toBe(CHART_PALETTE.blue.light) + expect(categoryColor(CLASS_ORDER, 1, 'dark')).toBe(CHART_PALETTE.orange.dark) + expect(categoryColor(CLASS_ORDER, CLASS_ORDER.length, 'light')).toBe(categoryColor(CLASS_ORDER, 0, 'light')) + }) + + test('withAlpha da el mismo color con transparencia', () => { + expect(withAlpha('#0d6efd', 0.5)).toBe('rgba(13, 110, 253, 0.5)') + }) +}) diff --git a/tests/core/checkLayers.test.ts b/tests/core/checkLayers.test.ts new file mode 100644 index 0000000..6751619 --- /dev/null +++ b/tests/core/checkLayers.test.ts @@ -0,0 +1,130 @@ +import { describe, test, expect } from 'vitest' +import { checkDenseLayers, checkImageLayers, imageLayerShapes } from '@core/nn-utils/checkLayers' +import { buildImageModel } from '@core/training/buildModels' +import type { ImageLayer_t } from '@/types/types' + +type Dense_t = { units: number, activation: string | null } +const kinds = (issues: { kind: string }[]) => issues.map(({ kind }) => kind) + +describe('checkDenseLayers: capas de clasificación tabular y regresión', () => { + const output = { units: 3, activation: 'softmax' } + const good: Dense_t[] = [{ units: 10, activation: 'relu' }, { units: 3, activation: 'softmax' }] + + test('una red bien montada no tiene nada que decir', () => { + expect(checkDenseLayers(good, output)).toEqual([]) + }) + + test('la salida necesita una neurona por clase (error) y softmax (aviso); el arreglo deja la red bien', () => { + const issues = checkDenseLayers([{ units: 10, activation: 'relu' }, { units: 5, activation: 'sigmoid' }], output) + expect(kinds(issues)).toEqual(['output-units', 'output-activation']) + expect(issues[0]).toMatchObject({ severity: 'error', layer: 1, values: { units: 5, classes: 3 } }) + expect(issues[1]).toMatchObject({ severity: 'warning', values: { activation: 'sigmoid', expected: 'softmax' } }) + expect(checkDenseLayers(issues[1].fixed, output)).toHaveLength(1) + expect(checkDenseLayers(checkDenseLayers(issues[0].fixed, output)[0].fixed, output)).toEqual([]) + }) + + test('unidades vacías, a cero o de más: error, y el arreglo pone un valor válido', () => { + const issues = checkDenseLayers([{ units: NaN, activation: 'relu' }, { units: 500, activation: 'relu' }, { units: 0, activation: 'softmax' }], output) + expect(issues.map(({ kind, layer, values }) => [kind, layer, values.value])).toEqual([['param', 0, 10], ['param', 1, 200], ['param', 2, 3]]) + }) + + test('softmax en una capa oculta: aviso, y se cambia por ReLU', () => { + const [issue] = checkDenseLayers([{ units: 10, activation: 'softmax' }, { units: 3, activation: 'softmax' }], output) + expect(issue).toMatchObject({ kind: 'hidden-softmax', severity: 'warning', layer: 0 }) + expect(issue.fixed[0]).toEqual({ units: 10, activation: 'relu' }) + }) + + test('sin salida fijada (regresión), la última capa no se mira', () => { + expect(checkDenseLayers([{ units: 8, activation: 'relu' }, { units: 1, activation: 'linear' }])).toEqual([]) + }) + + test('no cambia las capas que recibe', () => { + const layers = [{ units: 10, activation: 'relu' }, { units: 5, activation: 'relu' }] + checkDenseLayers(layers, output) + expect(layers).toEqual([{ units: 10, activation: 'relu' }, { units: 5, activation: 'relu' }]) + }) +}) + +describe('checkImageLayers: la red de imágenes, siguiendo el tamaño de los datos capa a capa', () => { + const conv = (kernelSize = 3, filters = 8): ImageLayer_t => ({ _class: 'conv2d', kernelSize, filters, activation: 'relu' }) + const pool = (poolSize = 2, strides = 2): ImageLayer_t => ({ _class: 'maxPooling2d', poolSize, strides }) + const flatten: ImageLayer_t = { _class: 'flatten' } + const dense = (units: number, activation = 'relu'): ImageLayer_t => ({ _class: 'dense', units, activation }) + const first: ImageLayer_t = { ...conv(), _protected: true, inputShape: [28, 28, 1] } + const good = [first, pool(), conv(), pool(), flatten, dense(32), dense(10, 'softmax')] + + // El arreglo vale de verdad: tfjs construye la red y da una salida por clase + const builds = (layers: ImageLayer_t[]) => expect(buildImageModel(layers).outputs[0].shape).toEqual([null, 10]) + + test('la red por defecto está bien y se construye', () => { + expect(checkImageLayers(good, 10)).toEqual([]) + builds(good) + }) + + test('Dense sin aplanar antes: error, y el arreglo añade Flatten delante', () => { + const issues = checkImageLayers([first, pool(), dense(10, 'softmax')], 10) + expect(kinds(issues)).toEqual(['dense-before-flatten']) + expect(issues[0].fixed.map(({ _class }) => _class)).toEqual(['conv2d', 'maxPooling2d', 'flatten', 'dense']) + expect(checkImageLayers(issues[0].fixed, 10)).toEqual([]) + builds(issues[0].fixed) + }) + + test('convolución o pooling después de Flatten, o un segundo Flatten: error, y se quitan', () => { + const issues = checkImageLayers([first, flatten, conv(), flatten, dense(10, 'softmax')], 10) + expect(issues.map(({ kind, layer }) => [kind, layer])).toEqual([['after-flatten', 2], ['flatten-again', 3]]) + const fixed = checkImageLayers(issues[0].fixed, 10)[0].fixed + expect(checkImageLayers(fixed, 10)).toEqual([]) + builds(fixed) + }) + + test('la imagen se queda más pequeña que la ventana: error con su tamaño en ese punto', () => { + // 28 → 26 → 13 → 11 → 5 → 3 → 1: un pooling de 2 ya no cabe + const layers = [first, pool(), conv(), pool(), conv(), pool(), pool(), flatten, dense(10, 'softmax')] + const [issue, ...rest] = checkImageLayers(layers, 10) + expect(rest).toEqual([]) + expect(issue).toMatchObject({ kind: 'too-small', layer: 6, values: { type: 'Max Pooling 2D', height: 1, width: 1, window: 2 } }) + builds(issue.fixed) + }) + + test('la salida: falta la Dense final (se añade) o no tiene una neurona por clase o softmax', () => { + const missing = checkImageLayers([first, pool()], 10) + expect(kinds(missing)).toEqual(['output-missing']) + builds(missing[0].fixed) + + const issues = checkImageLayers([first, flatten, dense(4, 'sigmoid')], 10) + expect(kinds(issues)).toEqual(['output-units', 'output-activation']) + builds(issues[0].fixed) + }) + + test('una capa añadida después de la salida: solo se dice que sobra (la salida sigue siendo la Dense de antes)', () => { + const issues = checkImageLayers([...good, pool()], 10) + expect(issues.map(({ kind, layer }) => [kind, layer])).toEqual([['after-flatten', 7]]) + expect(issues[0].fixed).toEqual(good) + }) + + test('parámetros vacíos o a cero: error con el valor que se pondría', () => { + const issues = checkImageLayers([first, { ...pool(), poolSize: NaN }, flatten, dense(0, 'softmax')], 10) + expect(issues.map(({ kind, values }) => [kind, values.param, values.value])).toEqual([['param', 'poolSize', 2], ['param', 'units', 10]]) + }) +}) + +describe('imageLayerShapes: el tamaño de los datos y los pesos de cada capa', () => { + test('la red por defecto de MNIST: 28×28×1 → … → 10, con los mismos pesos que cuenta tfjs', () => { + const layers: ImageLayer_t[] = [ + { _class: 'conv2d', _protected: true, inputShape: [28, 28, 1], kernelSize: 3, filters: 16, activation: 'relu' }, + { _class: 'maxPooling2d', poolSize: 2, strides: 2 }, + { _class: 'conv2d', kernelSize: 3, filters: 32, activation: 'relu' }, + { _class: 'flatten' }, + { _class: 'dense', units: 10, activation: 'softmax' }, + ] + const shapes = imageLayerShapes(layers) + expect(shapes.map((shape) => shape?.output)).toEqual([[26, 26, 16], [13, 13, 16], [11, 11, 32], [3872], [10]]) + expect(shapes.map((shape) => shape?.params)).toEqual([160, 0, 4640, 0, 38730]) + expect(buildImageModel(layers).layers.map((layer) => layer.countParams())).toEqual([160, 0, 4640, 0, 38730]) + }) + + test('desde la primera capa que no encaja, null', () => { + const shapes = imageLayerShapes([{ _class: 'conv2d', inputShape: [28, 28, 1], kernelSize: 3, filters: 8, activation: 'relu' }, { _class: 'dense', units: 10, activation: 'softmax' }, { _class: 'flatten' }]) + expect(shapes.map((shape) => shape?.output ?? null)).toEqual([[26, 26, 8], null, null]) + }) +}) diff --git a/tests/core/columnProfile.test.ts b/tests/core/columnProfile.test.ts new file mode 100644 index 0000000..f54329a --- /dev/null +++ b/tests/core/columnProfile.test.ts @@ -0,0 +1,26 @@ +import { describe, test, expect } from 'vitest' +import * as dfd from 'danfojs' +import { profileColumns } from '@core/dataframe/columnProfile' + +describe('profileColumns: cómo es cada columna para el formulario de procesamiento', () => { + test('tipo, valores distintos, ejemplos y, en las numéricas, rango y media', () => { + const dataframe = new dfd.DataFrame({ + buying: ['low', 'med', 'low', 'high', 'vhigh', 'med'], + doors : [2, 4, 4, 3, 2, 5], + price : [1.5, 2.5, 3, 4, 5.5, 1.5], + }) + const [buying, doors, price] = profileColumns(dataframe) + expect(buying).toEqual({ name: 'buying', type: 'string', numeric: false, distinct: 4, sample: ['low', 'med', 'high', 'vhigh'] }) + expect(doors).toMatchObject({ type: 'int32', numeric: true, distinct: 4, min: 2, max: 5, mean: 20 / 6 }) + expect(price).toMatchObject({ type: 'float32', numeric: true, distinct: 5, min: 1.5, max: 5.5 }) + // Como mucho 4 ejemplos, en el orden en que aparecen + expect(price.sample).toEqual(['1.5', '2.5', '3', '4']) + }) + + test('los valores vacíos no cuentan', () => { + const dataframe = new dfd.DataFrame({ a: ['x', null, 'y', ''], b: [1, NaN, 3, 5] }) + const [a, b] = profileColumns(dataframe) + expect(a.distinct).toBe(2) + expect(b).toMatchObject({ distinct: 3, min: 1, max: 5, mean: 3 }) + }) +}) diff --git a/tests/core/createLoss.test.ts b/tests/core/createLoss.test.ts new file mode 100644 index 0000000..cace91d --- /dev/null +++ b/tests/core/createLoss.test.ts @@ -0,0 +1,18 @@ +import { describe, test, expect } from 'vitest' +import * as tfjs from '@tensorflow/tfjs' +import { createLoss } from '../../src/core/nn-utils/ArchitectureHelper' +import { TYPE_LOSSES } from '../../src/core/nn-utils/ArchitectureTypesHelper' + +describe('createLoss', () => { + + // model.compile() lanza "Unknown loss" si el nombre no está en el lossesMap de tfjs-layers + test.each(TYPE_LOSSES.map(({ key }) => key))('tfjs-layers compila la pérdida %s del selector', (key) => { + const model = tfjs.sequential({ layers: [tfjs.layers.dense({ units: 2, inputShape: [3], activation: 'softmax' })] }) + expect(() => model.compile({ optimizer: 'adam', loss: createLoss(`losses-${key}`, {}) })).not.toThrow() + }) + + test('acepta el identificador con o sin prefijo', () => { + expect(createLoss('losses-meanSquaredError', {})).toBe('meanSquaredError') + expect(createLoss('categoricalCrossentropy', {})).toBe('categoricalCrossentropy') + }) +}) diff --git a/tests/core/createMetrics.test.ts b/tests/core/createMetrics.test.ts new file mode 100644 index 0000000..dbc6974 --- /dev/null +++ b/tests/core/createMetrics.test.ts @@ -0,0 +1,23 @@ +import { describe, test, expect } from 'vitest' +import * as tfjs from '@tensorflow/tfjs' +import { createMetrics, createMetricsList } from '../../src/core/nn-utils/ArchitectureHelper' +import { TYPE_METRICS } from '../../src/core/nn-utils/ArchitectureTypesHelper' +import type { IdMetric_t } from '../../src/types/nn-types' + +const compile = (metrics: string | string[]) => { + const model = tfjs.sequential({ layers: [tfjs.layers.dense({ units: 2, inputShape: [3], activation: 'softmax' })] }) + model.compile({ optimizer: 'adam', loss: 'categoricalCrossentropy', metrics }) +} + +describe('createMetrics', () => { + // model.compile() lanza "Unknown metric" si el nombre no es uno de los que reconoce tfjs-layers + test.each(TYPE_METRICS.map(({ key }) => key))('tfjs-layers compila la métrica %s, con y sin prefijo', (key) => { + expect(() => compile(createMetrics(key as IdMetric_t, {}))).not.toThrow() + expect(() => compile(createMetrics(`metrics-${key}` as IdMetric_t, {}))).not.toThrow() + expect(() => compile(createMetricsList([key as IdMetric_t], {}))).not.toThrow() + }) + + test('traduce los nombres largos a los de tfjs-layers', () => { + expect(createMetrics(['metrics-meanAbsoluteError', 'meanSquaredError'], {})).toStrictEqual(['mae', 'mse']) + }) +}) diff --git a/tests/core/csvFormat.test.ts b/tests/core/csvFormat.test.ts new file mode 100644 index 0000000..4cb57fe --- /dev/null +++ b/tests/core/csvFormat.test.ts @@ -0,0 +1,121 @@ +import { describe, test, expect } from 'vitest' + +import { detectCSVFormat, isDecimalCommaColumn, parseDecimalComma } from '@core/dataframe/csvFormat' +import fs from 'node:fs' +import { columnDtypes, convertDecimalComma, dropEmptyColumns, readDatasetRows, textMixedColumns } from '@core/dataframe/datasetReader' + +// Las primeras filas de AirQualityUCI.csv (UCI) en sus dos formas: la original (";" y coma decimal) y la "alineada" +// por un editor (comas con espacios como separador y la coma decimal pegada a los números) +const SEMICOLON = [ + 'Date;Time;CO(GT);PT08.S1(CO);C6H6(GT);T;RH;AH;;', + '10/03/2004;18.00.00;2,6;1360;11,9;13,6;48,9;0,7578;;', + '10/03/2004;19.00.00;2;1292;9,4;13,3;47,7;0,7255;;', + ';;;;;;;;;', +].join('\r\n') + +const ALIGNED = [ + 'Date , Time , CO(GT), PT08.S1(CO), T , AH , , ', + '10/03/2004, 18.00.00, 2,6 , 1360 , 13,6, 0,7578, , ', + '10/03/2004, 19.00.00, 2 , 1292 , 13,3, 0,7255, , ', +].join('\r\n') + +describe('formato de un CSV subido', () => { + + test('con comas, como siempre', () => { + const text = 'sepal_length,sepal_width,class\n5.1,3.5,Iris-setosa\n4.9,3,Iris-setosa\n' + expect(detectCSVFormat(text)).toEqual({ delimiter: ',', decimalComma: false, text }) + }) + + test('las comas entre comillas no cuentan', () => { + const text = 'name,price\n"Laptop, 15 inch",999\n"Mouse",19\n' + expect(detectCSVFormat(text).delimiter).toBe(',') + }) + + test('con ";" (Excel en español): coma decimal', () => { + expect(detectCSVFormat(SEMICOLON)).toEqual({ delimiter: ';', decimalComma: true, text: SEMICOLON }) + }) + + test('con tabuladores', () => { + expect(detectCSVFormat('a\tb\tc\n1\t2\t3\n4\t5\t6').delimiter).toBe('\t') + }) + + test('alineado: las comas con espacios son el separador y las pegadas a cifras, decimales', () => { + const format = detectCSVFormat(ALIGNED) + expect(format.decimalComma).toBe(true) + const rows = format.text.split('\r\n').map((line) => line.split(format.delimiter).map((field) => field.trim())) + expect(rows[0]).toEqual(['Date', 'Time', 'CO(GT)', 'PT08.S1(CO)', 'T', 'AH', '', '']) + expect(rows[1]).toEqual(['10/03/2004', '18.00.00', '2,6', '1360', '13,6', '0,7578', '', '']) + }) + + test('si ningún separador cuadra, la coma (papaparse dirá qué fila falla)', () => { + expect(detectCSVFormat('a,b\n1,2,3\n4\n5,6,7,8').delimiter).toBe(',') + expect(detectCSVFormat('').delimiter).toBe(',') + }) + + test('números con coma decimal', () => { + expect(parseDecimalComma('2,6')).toBe(2.6) + expect(parseDecimalComma(' -0,7578 ')).toBe(-0.7578) + expect(parseDecimalComma(1360)).toBe(1360) + expect(parseDecimalComma('')).toBeNull() + expect(isDecimalCommaColumn(['2,6', 2, null, '11,9'])).toBe(true) + // Sin ninguna coma decimal no hace falta tocarla; con texto no es numérica + expect(isDecimalCommaColumn([2, 3])).toBe(false) + expect(isDecimalCommaColumn(['2,6', '18.00.00'])).toBe(false) + expect(isDecimalCommaColumn(['10/03/2004'])).toBe(false) + }) +}) + +describe('columnas de un CSV subido', () => { + + test('las de coma decimal pasan a ser numéricas, sin cambiar el orden de las columnas', () => { + const table = convertDecimalComma({ + columns: ['Date', 'CO(GT)', '2004', 'AH'], + rows : [['10/03/2004', '2,6', 1360, '0,7578'], ['10/03/2004', 2, 1292, '0,7255']], + }) + expect(table.columns).toEqual(['Date', 'CO(GT)', '2004', 'AH']) + expect(table.rows).toEqual([['10/03/2004', 2.6, 1360, 0.7578], ['10/03/2004', 2, 1292, 0.7255]]) + }) + + test('se quitan las columnas vacías sin nombre (los ";;" del final de cada fila), no las que tienen nombre', () => { + const table = dropEmptyColumns({ columns: ['T', '', '_1', 'notas'], rows: [[1, null, null, null], [2, null, '', null]] }) + expect(table).toEqual({ columns: ['T', 'notas'], rows: [[1, null], [2, null]] }) + }) + + test('una columna con números y textos pasa a ser de texto (los ausentes se quedan)', () => { + const table = textMixedColumns({ columns: ['Doors', 'n'], rows: [[2, 1], [3, 2], [null, 3], ['5more', 4]] }) + expect(table.rows).toEqual([['2', 1], ['3', 2], [null, 3], ['5more', 4]]) + }) +}) + +describe('leer un fichero subido (lo que hace el worker)', () => { + + test.each([ + ['";" y coma decimal', SEMICOLON], + ['alineado con comas', ALIGNED], + ])('%s: columnas, números y sin las columnas vacías del final', async (_name, text) => { + const { columns, rows } = await readDatasetRows(new File([text], 'aire.csv')) + expect(columns.slice(0, 4)).toEqual(['Date', 'Time', 'CO(GT)', 'PT08.S1(CO)']) + expect(columns).not.toContain('') + expect(rows).toHaveLength(2) + expect(rows[0].slice(0, 4)).toEqual(['10/03/2004', '18.00.00', 2.6, 1360]) + expect(rows[1].at(-1)).toBe(0.7255) + }) + + test('el tipo de cada columna sigue las reglas de danfo, mirando todas las filas', async () => { + const dtypesOf = async (file: string) => (await readDatasetRows(new File([fs.readFileSync(file, 'utf8')], 'datos.csv'))).dtypes + expect(await dtypesOf('public/n4l/iris.n4l/data/iris.csv')).toEqual(['float32', 'float32', 'float32', 'float32', 'string']) + // "displacement" tiene un solo decimal (97.5, en la fila 58) y "mpg" el primero en la fila 186: decimales + expect(await dtypesOf('public/n4l/auto-mpg.n4l/data/auto-mpg.csv')) + .toEqual(['int32', 'float32', 'int32', 'int32', 'float32', 'int32', 'float32']) + // Con texto más allá de las 500 primeras filas danfo diría int32; aquí es texto (lo que arreglaba FixMixedColumns) + const rows = Array.from({ length: 600 }, (_, i) => (i === 599 ? '5more' : String(2 + (i % 3)))) + const late = await readDatasetRows(new File(['doors\n' + rows.join('\n')], 'puertas.csv')) + expect(late.dtypes).toEqual(['string']) + expect(columnDtypes({ columns: ['a', 'b', 'c'], rows: [[1, 1.5, true], [null, 2, false]] })).toEqual(['float32', 'float32', 'boolean']) + }) + + test('los errores de papaparse llegan como los daba danfo', async () => { + await expect(readDatasetRows(new File(['a,b\n1,2,3\n'], 'mal.csv'))).rejects.toThrow('CSV parsing errors: Too many fields') + await expect(readDatasetRows(new File(['a,b\n'], 'vacio.csv'))).rejects.toThrow('No data found') + }) +}) diff --git a/tests/core/datasetFormats.test.ts b/tests/core/datasetFormats.test.ts new file mode 100644 index 0000000..25b9b52 --- /dev/null +++ b/tests/core/datasetFormats.test.ts @@ -0,0 +1,125 @@ +import { describe, test, expect } from 'vitest' +import fs from 'node:fs' +import path from 'node:path' + +import { datasetFileToCSV, datasetFormat, parseARFF, parseJSON, parseJSONL, parseParquet, readFileText, tableToCSV } from '@core/dataframe/datasetFormats' + +const FIXTURES = path.resolve(__dirname, '../../e2e/files') +const fixture = (name: string) => fs.readFileSync(path.join(FIXTURES, name)) +const IRIS_COLUMNS = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class'] +const IRIS_FIRST = [5.1, 3.5, 1.4, 0.2, 'Setosa'] + +/** Iris en otro formato pasado a CSV: la misma cabecera, 150 filas y la primera igual que en iris.csv */ +async function expectIrisCSV(name: string) { + const csv = await datasetFileToCSV(new File([fixture(name)], name)) + expect(csv.name).toBe(name.replace(/\.[^.]+$/, '') + '.csv') + const lines = (await readFileText(csv)).trim().split('\n') + expect(lines[0]).toBe(IRIS_COLUMNS.join(',')) + expect(lines).toHaveLength(151) + expect(lines[1]).toBe(IRIS_FIRST.join(',')) +} + +describe('formatos de conjuntos de datos', () => { + + test('el formato sale de la extensión', () => { + expect(datasetFormat('datos.CSV')).toBe('csv') + expect(datasetFormat('iris.arff')).toBe('arff') + expect(datasetFormat('a.json')).toBe('json') + expect(datasetFormat('a.jsonl')).toBe('jsonl') + expect(datasetFormat('a.ndjson')).toBe('jsonl') + expect(datasetFormat('a.parquet')).toBe('parquet') + expect(datasetFormat('a.xlsx')).toBeNull() + }) + + test.each(['iris.arff', 'iris.json', 'iris-pandas.json', 'iris.jsonl', 'iris.parquet', 'iris-zstd.parquet'])('%s se convierte en el mismo CSV que iris.csv', async (name) => { + await expectIrisCSV(name) + }) + + test('un CSV se queda tal cual', async () => { + const file = new File(['a;b\n1;2\n'], 'datos.csv') + expect(await datasetFileToCSV(file)).toBe(file) + }) +}) + +describe('ARFF', () => { + + test('nombres con comillas, nominales, ausentes ("?"), comentarios y el peso de la instancia', () => { + const table = parseARFF([ + '% comentario', + '@RELATION tiempo', + "@ATTRIBUTE 'outlook type' {sunny, overcast, 'light rain'}", + '@attribute temperature REAL', + '@attribute note string', + '@attribute day date "yyyy-MM-dd"', + '@data', + "sunny, 85, 'hot, dry', 2024-01-01", + "'light rain', ?, \"it's wet\", 2024-01-02, {2}", + ].join('\n')) + expect(table.columns).toEqual(['outlook type', 'temperature', 'note', 'day']) + expect(table.rows).toEqual([ + ['sunny', 85, 'hot, dry', '2024-01-01'], + ['light rain', null, "it's wet", '2024-01-02'], + ]) + }) + + test('filas dispersas: lo que falta es 0 (o el primer valor nominal)', () => { + const table = parseARFF([ + '@relation dispersa', + '@attribute a numeric', + '@attribute b numeric', + '@attribute c {no, yes}', + '@attribute d string', + '@data', + "{1 3.5, 3 'x y'}", + '{2 yes}', + ].join('\n')) + expect(table.rows).toEqual([[0, 3.5, 'no', 'x y'], [0, 0, 'yes', '']]) + }) + + test('una fila con más o menos valores que atributos es un error claro', () => { + expect(() => parseARFF('@attribute a numeric\n@attribute b numeric\n@data\n1,2,3')).toThrow('expected 2 values but found 3') + expect(() => parseARFF('@relation vacio\n@data\n1')).toThrow('no @attribute') + }) +}) + +describe('JSON y JSONL', () => { + + test('registros con claves que faltan o sobran: todas las columnas, en el orden en que aparecen', () => { + expect(parseJSON('[{"a": 1, "b": "x"}, {"b": "y", "c": true}]')).toEqual({ columns: ['a', 'b', 'c'], rows: [[1, 'x', undefined], [undefined, 'y', true]] }) + }) + + test('las formas de pandas: split, index y list', () => { + expect(parseJSON('{"columns": ["a", "b"], "index": [0, 1], "data": [[1, 2], [3, 4]]}')).toEqual({ columns: ['a', 'b'], rows: [[1, 2], [3, 4]] }) + expect(parseJSON('{"0": {"a": 1, "b": 2}, "1": {"a": 3, "b": 4}}')).toEqual({ columns: ['a', 'b'], rows: [[1, 2], [3, 4]] }) + expect(parseJSON('{"a": [1, 3], "b": [2, 4]}')).toEqual({ columns: ['a', 'b'], rows: [[1, 2], [3, 4]] }) + expect(parseJSON('{"data": [{"a": 1}]}')).toEqual({ columns: ['a'], rows: [[1]] }) + }) + + test('una lista de listas con cabecera', () => { + expect(parseJSON('[["a", "b"], [1, 2]]')).toEqual({ columns: ['a', 'b'], rows: [[1, 2]] }) + }) + + test('JSONL: una línea mal escrita dice cuál es', () => { + expect(parseJSONL('{"a": 1}\n\n{"a": 2}\n')).toEqual({ columns: ['a'], rows: [[1], [2]] }) + expect(() => parseJSONL('{"a": 1}\n{a: 2}')).toThrow('line 2') + }) +}) + +describe('Parquet y CSV', () => { + + test('Parquet: columnas del esquema y valores', async () => { + // Con el ArrayBuffer del entorno de la prueba (el del Buffer de Node es de otro "realm" y no pasa el instanceof) + const bytes = fixture('iris.parquet') + const buffer = new ArrayBuffer(bytes.byteLength) + new Uint8Array(buffer).set(bytes) + const table = await parseParquet(buffer) + expect(table.columns).toEqual(IRIS_COLUMNS) + expect(table.rows).toHaveLength(150) + expect(table.rows[0]).toEqual(IRIS_FIRST) + }) + + test('la tabla como CSV: comillas cuando hacen falta, vacío para lo que falta y los objetos como JSON', () => { + const csv = tableToCSV({ columns: ['texto', 'n', 'otro'], rows: [['a, "b"', 1.5, null], [' x', Number.NaN, { k: 1 }]] }) + expect(csv).toBe('texto,n,otro\n"a, ""b""",1.5,\n" x",,"{""k"":1}"\n') + }) +}) diff --git a/tests/core/datasetInfo.test.ts b/tests/core/datasetInfo.test.ts new file mode 100644 index 0000000..94327d4 --- /dev/null +++ b/tests/core/datasetInfo.test.ts @@ -0,0 +1,32 @@ +import { describe, test, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import { TASK_DATASET_OPTIONS, type TaskOption_t } from '../../src/TASK_OPTIONS' + +// Los CSV de los datasets no llevan comillas: basta con partir por comas +const readCsv = (path: string) => { + const [head, ...body] = readFileSync(`public/${path}`, 'utf-8').split(/\r?\n/).filter((line) => line.trim() !== '') + return { columns: head.split(','), rows: body.map((line) => line.split(',')) } +} + +const csvOptions = Object.values(TASK_DATASET_OPTIONS as Record) + .flat() + .filter((option) => option.info?.files !== undefined) + .map((option) => [option.value, option.info!] as const) + +describe('Datos de los datasets en la galería', () => { + test.each(csvOptions)('%s coincide con sus CSV', (_value, info) => { + const files = info.files!.map(readCsv) + expect(files.map(({ rows }) => rows.length)).toStrictEqual(info.rows) + if (info.features !== undefined) { + for (const { columns } of files) expect(columns.length - 1).toBe(info.features) + } + const targetColumn = info.target ?? (info.classes !== undefined ? files[0].columns[files[0].columns.length - 1] : undefined) + if (info.target !== undefined) { + for (const { columns } of files) expect(columns).toContain(info.target) + } + if (info.classes !== undefined && targetColumn !== undefined) { + const index = files[0].columns.indexOf(targetColumn) + expect(new Set(files[0].rows.map((row) => row[index])).size).toBe(info.classes) + } + }) +}) diff --git a/tests/core/diagnoseTraining.test.ts b/tests/core/diagnoseTraining.test.ts new file mode 100644 index 0000000..de9f70e --- /dev/null +++ b/tests/core/diagnoseTraining.test.ts @@ -0,0 +1,62 @@ +import { describe, test, expect } from 'vitest' +import { diagnoseTraining } from '@core/training/diagnoseTraining' + +const kinds = (history: Record) => diagnoseTraining(history).map(({ kind }) => kind) + +describe('diagnoseTraining: qué ha pasado en un entrenamiento', () => { + test('la pérdida se dispara (NaN o infinito): lo primero y lo único que se dice', () => { + expect(diagnoseTraining({ loss: [1.2, 0.9, NaN, NaN], val_loss: [1.2, 1, NaN, NaN] })).toEqual([ + { kind: 'diverged', severity: 'danger', values: { epoch: 3 } }, + ]) + expect(kinds({ loss: [1, Infinity] })).toEqual(['diverged']) + }) + + test('apenas aprende: la pérdida baja menos de un 5 %', () => { + expect(kinds({ loss: [1.1, 1.09, 1.08, 1.07, 1.06], val_loss: [1.1, 1.1, 1.09, 1.09, 1.08] })).toEqual(['not-learning']) + }) + + test('la pérdida ha subido: la tasa de aprendizaje es demasiado alta', () => { + expect(diagnoseTraining({ loss: [5.1, 7.2, 4.9, 6.8, 6.2] })).toEqual([{ kind: 'worse', severity: 'warning', values: { first: 5.1, last: 6.2 } }]) + }) + + test('sobreajuste: la de prueba vuelve a subir desde su mínimo mientras la de entrenamiento sigue bajando', () => { + const [diagnosis] = diagnoseTraining({ + loss : [1, 0.6, 0.4, 0.3, 0.2, 0.12, 0.08], + val_loss: [1, 0.65, 0.5, 0.48, 0.55, 0.62, 0.7], + }) + expect(diagnosis).toEqual({ kind: 'overfitting', severity: 'warning', values: { epoch: 4, min: 0.48, last: 0.7 } }) + }) + + // Entrenamientos de verdad: Auto MPG con tasa de aprendizaje 0,01 (a saltos) y 0,001 (baja sin parar) + const autoMpgFast = { + loss : [267, 43.2, 26.4, 20.8, 21.3, 19.8, 22.1, 17.2, 13.1, 18.2, 10.7, 14.8, 12.5, 13.3, 14.0, 13.0, 13.9, 12.9, 12.2, 8.78], + val_loss: [81.8, 55.9, 23.7, 27.4, 17.5, 53.9, 16.0, 32.2, 37.0, 13.3, 24.8, 22.9, 13.0, 24.9, 23.4, 41.4, 11.9, 14.8, 10.8, 70.0], + } + const autoMpgSlow = { + loss : [588, 547, 495, 429, 355, 280, 217, 174, 147, 124, 105, 89.3, 75.7, 64.1, 54.4, 45.5, 38.0, 32.1, 27.4, 23.8, 21.8, 20.3, 19.0, 18.2, 17.8, 16.6, 16.1, 15.5, 14.9, 14.6, 13.9, 13.6, 13.2, 12.8, 12.4, 12.1, 11.8, 11.6, 11.1, 11.0], + val_loss: [616, 566, 500, 422, 336, 256, 197, 160, 131, 110, 94.0, 78.5, 64.6, 55.6, 47.9, 39.2, 34.7, 28.4, 24.7, 23.4, 21.3, 20.0, 19.3, 19.1, 18.5, 17.1, 18.4, 17.3, 15.5, 18.4, 15.0, 18.4, 14.7, 14.1, 13.5, 15.8, 13.7, 14.6, 12.6, 12.8], + } + + test('inestable: la de prueba va a saltos (no es sobreajuste aunque acabe más alta que su mínimo)', () => { + expect(kinds(autoMpgFast)).toEqual(['unstable']) + }) + + test('con algo de ruido, pero bajando: seguía mejorando (ni inestable ni sobreajuste)', () => { + expect(kinds(autoMpgSlow)).toEqual(['still-improving']) + }) + + test('seguía mejorando al terminar: con más épocas aprendería más', () => { + expect(kinds({ loss: [1, 0.8, 0.65, 0.5, 0.4], val_loss: [1, 0.82, 0.68, 0.55, 0.45] })).toEqual(['still-improving']) + }) + + test('ha aprendido bien: baja y se estabiliza sin separarse la de prueba', () => { + expect(kinds({ loss: [1, 0.4, 0.2, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15], val_loss: [1, 0.45, 0.25, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2] })) + .toEqual(['good']) + }) + + test('sin datos de prueba se mira solo la de entrenamiento; con muy pocas épocas, seguía mejorando', () => { + expect(kinds({ loss: [1, 0.5, 0.3, 0.2, 0.12] })).toEqual(['still-improving']) + expect(kinds({ loss: [1, 0.5] })).toEqual(['still-improving']) + expect(kinds({})).toEqual([]) + }) +}) diff --git a/tests/core/displaySettings.test.ts b/tests/core/displaySettings.test.ts new file mode 100644 index 0000000..e878989 --- /dev/null +++ b/tests/core/displaySettings.test.ts @@ -0,0 +1,44 @@ +import { describe, test, expect, beforeEach } from 'vitest' + +import { + DEFAULT_DISPLAY_SETTINGS, + DISPLAY_SETTINGS_STORAGE_KEY, + getDisplaySettings, + parseDisplaySettings, + prefersReducedMotion, + resetDisplaySettings, + shouldOpenVisor, + updateDisplaySettings, +} from '@core/a11y/displaySettings' + +describe('displaySettings: los ajustes de accesibilidad', () => { + beforeEach(() => resetDisplaySettings()) + + test('lo guardado que no vale (o nada) se queda en los valores por defecto', () => { + expect(parseDisplaySettings(null)).toEqual(DEFAULT_DISPLAY_SETTINGS) + expect(parseDisplaySettings('no es JSON')).toEqual(DEFAULT_DISPLAY_SETTINGS) + expect(parseDisplaySettings(JSON.stringify({ textSize: 175, spacing: 'sí', underlineLinks: true }))) + .toEqual({ ...DEFAULT_DISPLAY_SETTINGS, underlineLinks: true }) + }) + + test('al cambiarlos se aplican en y se recuerdan', () => { + const root = document.documentElement + updateDisplaySettings({ textSize: 150, spacing: true, highContrast: true, reduceMotion: true, underlineLinks: true, strongFocus: true, openVisor: false }) + expect(root).toHaveAttribute('data-n4l-text-size', '150') + for (const name of ['n4l-text-spacing', 'n4l-high-contrast', 'n4l-reduce-motion', 'n4l-underline-links', 'n4l-strong-focus']) { + expect(root.classList.contains(name), name).toBe(true) + } + expect(prefersReducedMotion()).toBe(true) + expect(shouldOpenVisor()).toBe(false) + expect(JSON.parse(localStorage.getItem(DISPLAY_SETTINGS_STORAGE_KEY)!)).toEqual(getDisplaySettings()) + }) + + test('restablecerlos los quita y los olvida', () => { + updateDisplaySettings({ textSize: 200, underlineLinks: true }) + resetDisplaySettings() + expect(document.documentElement).not.toHaveAttribute('data-n4l-text-size') + expect(document.documentElement.classList.contains('n4l-underline-links')).toBe(false) + expect(localStorage.getItem(DISPLAY_SETTINGS_STORAGE_KEY)).toBeNull() + expect(getDisplaySettings()).toEqual(DEFAULT_DISPLAY_SETTINGS) + }) +}) diff --git a/tests/core/downloadConsent.test.ts b/tests/core/downloadConsent.test.ts new file mode 100644 index 0000000..0b92d2e --- /dev/null +++ b/tests/core/downloadConsent.test.ts @@ -0,0 +1,54 @@ +import { afterEach, describe, expect, test } from 'vitest' +import { renderHook, act } from '@testing-library/react' + +import { askBeforeDownload, cancelPendingDownload, downloadReason, getDownloadWarning, resetDownloadConsent, setDownloadWarning, usePendingDownload } from '@core/models/downloadConsent' + +describe('downloadConsent: preguntar antes de descargar un modelo grande', () => { + afterEach(() => { + cancelPendingDownload() + resetDownloadConsent() + }) + + test('el motivo: ahorro de datos o conexión lenta en automático; siempre o nunca, según se pida', () => { + expect(downloadReason('auto', { saveData: true, effectiveType: '4g' })).toBe('save-data') + expect(downloadReason('auto', { effectiveType: '3g' })).toBe('slow') + expect(downloadReason('auto', { effectiveType: '4g' })).toBeNull() + expect(downloadReason('auto', undefined)).toBeNull() + expect(downloadReason('always', undefined)).toBe('always') + expect(downloadReason('never', { saveData: true })).toBeNull() + }) + + test('sin motivo, o con un modelo pequeño o sin tamaño conocido, la descarga sigue sin preguntar', async () => { + await expect(askBeforeDownload('object-detection', 'COCO-SSD')).resolves.toBeUndefined() + setDownloadWarning('always') + await expect(askBeforeDownload('tabular-classification', 'IRIS')).resolves.toBeUndefined() + }) + + test('con «preguntar siempre», espera a que se acepte; lo aceptado ya no se vuelve a preguntar', async () => { + setDownloadWarning('always') + const { result } = renderHook(() => usePendingDownload()) + let finished = false + let download: Promise = Promise.resolve() + act(() => { + download = askBeforeDownload('object-detection', 'COCO-SSD').then(() => { finished = true }) + }) + expect(result.current).toMatchObject({ model: 'object-detection/COCO-SSD', mb: 17.7, reason: 'always' }) + await Promise.resolve() + expect(finished).toBe(false) + + act(() => result.current!.accept()) + await download + expect(finished).toBe(true) + expect(result.current).toBeNull() + await expect(askBeforeDownload('object-detection', 'COCO-SSD')).resolves.toBeUndefined() + expect(result.current).toBeNull() + }) + + test('la preferencia se guarda en el navegador y "Restablecer todo" la devuelve a automático', () => { + setDownloadWarning('never') + expect(localStorage.getItem('n4l-download-warning')).toBe('never') + resetDownloadConsent() + expect(getDownloadWarning()).toBe('auto') + expect(localStorage.getItem('n4l-download-warning')).toBeNull() + }) +}) diff --git a/tests/core/downloadProgress.test.ts b/tests/core/downloadProgress.test.ts new file mode 100644 index 0000000..4f1ab0a --- /dev/null +++ b/tests/core/downloadProgress.test.ts @@ -0,0 +1,70 @@ +import { describe, test, expect, vi, afterEach } from 'vitest' +import { act, renderHook } from '@testing-library/react' +import { trackDownloads, useDownloadProgress } from '@core/downloadProgress' + +/** Una respuesta que llega en trozos, con o sin content-length */ +function chunkedResponse(chunks: number[], contentLength?: number) { + const body = new ReadableStream({ + start(controller) { + for (const size of chunks) controller.enqueue(new Uint8Array(size)) + controller.close() + }, + }) + const headers = contentLength === undefined ? undefined : { 'content-length': String(contentLength) } + return new Response(body, { headers }) +} + +const wait = (ms: number) => act(() => new Promise((resolve) => setTimeout(resolve, ms))) + +describe('downloadProgress', () => { + afterEach(() => { + vi.unstubAllGlobals() + }) + + test('cuenta los bytes que llegan mientras dura la carga y después fetch vuelve a ser el de siempre', async () => { + const original = vi.fn(async () => chunkedResponse([300, 300, 400], 1000)) + vi.stubGlobal('fetch', original) + const { result } = renderHook(() => useDownloadProgress()) + expect(result.current).toBeNull() + + await trackDownloads(async () => { + expect(window.fetch).not.toBe(original) + const response = await window.fetch('/modelo/pesos.bin') + // La respuesta sigue siendo la misma: estado, cabeceras y todo el contenido + expect(response.ok).toBe(true) + expect(response.headers.get('content-length')).toBe('1000') + expect((await response.arrayBuffer()).byteLength).toBe(1000) + await wait(150) + expect(result.current).toEqual({ loaded: 1000, total: 1000 }) + }) + + expect(window.fetch).toBe(original) + expect(result.current).toBeNull() + }) + + test('sin content-length el total no se sabe; comprimido, llega más de lo anunciado y el total crece', async () => { + const responses = [chunkedResponse([500]), chunkedResponse([800, 700], 1000)] + vi.stubGlobal('fetch', vi.fn(async () => responses.shift()!)) + const { result } = renderHook(() => useDownloadProgress()) + + await trackDownloads(async () => { + await (await window.fetch('/model.json')).arrayBuffer() + await wait(150) + expect(result.current).toEqual({ loaded: 500, total: null }) + }) + await trackDownloads(async () => { + await (await window.fetch('/pesos.bin')).arrayBuffer() + await wait(150) + expect(result.current).toEqual({ loaded: 1500, total: 1500 }) + }) + }) + + test('si la carga falla, fetch también vuelve a ser el de siempre', async () => { + const original = vi.fn(async () => chunkedResponse([10], 10)) + vi.stubGlobal('fetch', original) + await expect(trackDownloads(async () => { + throw new Error('sin red') + })).rejects.toThrow('sin red') + expect(window.fetch).toBe(original) + }) +}) diff --git a/tests/core/duration.test.ts b/tests/core/duration.test.ts new file mode 100644 index 0000000..6e01b57 --- /dev/null +++ b/tests/core/duration.test.ts @@ -0,0 +1,21 @@ +import { describe, test, expect } from 'vitest' + +import { formatDuration } from '@core/format/duration' + +// Intl separa el número y la unidad con un espacio normal o uno que no se parte, según el idioma +const plain = (text: string) => text.replace(/\s/g, ' ') + +describe('formatDuration: cuánto tarda, en palabras', () => { + test.each([ + [400, '0,4 segundos'], + [45_000, '45 segundos'], + [180_000, '3 minutos'], + [5_400_000, '1,5 horas'], + ])('%i ms → %s', (ms, text) => { + expect(plain(formatDuration(ms, 'es'))).toBe(text) + }) + + test('en inglés', () => { + expect(plain(formatDuration(45_000, 'en'))).toBe('45 seconds') + }) +}) diff --git a/tests/core/eda.test.ts b/tests/core/eda.test.ts new file mode 100644 index 0000000..ffa7ed5 --- /dev/null +++ b/tests/core/eda.test.ts @@ -0,0 +1,203 @@ +import { describe, test, expect } from 'vitest' +import * as dfd from 'danfojs' + +import { + binCenters, + binCounts, + boxStats, + columnKind, + correlationMatrix, + extent, + dataWarnings, + histogram, + isMissing, + pearson, + problemType, + profileColumn, + profileDataFrame, + quantile, + toNumbers, + topValues, + countValues, + valueCounts, +} from '@core/dataframe/eda' +import { dataframeToCSV, preprocessDataFrame } from '@core/dataframe/preprocess' + +describe('valores ausentes y tipo de columna', () => { + + test('vacío, "?", NaN, null y undefined son ausentes; 0 y "0" no', () => { + expect(['', ' ? ', NaN, null, undefined, 'NA'].every(isMissing)).toBe(true) + expect([0, '0', 'a', false].some(isMissing)).toBe(false) + }) + + test('una columna de texto con números y "?" es numérica (Bare_Nuclei de breast-cancer-wisconsin)', () => { + expect(columnKind(['1', '10', '?', '2'], 'string')).toBe('numeric') + expect(columnKind(['a', '10'], 'string')).toBe('categorical') + expect(columnKind([1.5, 2], 'float32')).toBe('numeric') + expect(toNumbers(['1', '?', 2.5, 'x'])).toEqual([1, NaN, 2.5, NaN]) + }) +}) + +describe('estadísticos', () => { + + test('cuantiles con interpolación lineal, como pandas', () => { + expect(quantile([1, 2, 3, 4], 0.5)).toBe(2.5) + expect(quantile([1, 2, 3, 4], 0.25)).toBe(1.75) + expect(quantile([], 0.5)).toBeNaN() + }) + + test('mínimo y máximo de un millón de valores sin desbordar la pila (Math.min(...valores) falla)', () => { + const values = Array.from({ length: 1_000_000 }, (_, i) => (i * 7919) % 1_000_003 - 500) + const expected = values.reduce(([min, max], value) => [Math.min(min, value), Math.max(max, value)], [Infinity, -Infinity]) + expect(extent(values)).toEqual(expected) + expect(histogram(values).counts.reduce((a, b) => a + b, 0)).toBe(1_000_000) + }) + + test('recuentos por intervalo con los bordes de otro histograma (los de cada clase se comparan)', () => { + const { edges } = histogram([0, 10], 5) + expect(binCounts([0, 1.9, 2, 9.99, 10, 11, NaN], edges)).toEqual([2, 1, 0, 0, 2]) + expect(binCenters(edges)).toEqual({ centers: [1, 3, 5, 7, 9], width: 2 }) + }) + + test('diagrama de caja calculado: cuartiles, bigotes, media y atípicos (como mucho los pedidos)', () => { + const stats = boxStats([1, 2, 3, 4, 5, 6, 7, 8, 100, NaN])! + expect(stats).toMatchObject({ q1: 3, median: 5, q3: 7, lowerfence: 1, upperfence: 8, count: 9, outliers: [100] }) + expect(stats.mean).toBeCloseTo(136 / 9) + // 10 000 valores entre 0 y 1 y 200 muy alejados: 200 atípicos, de los que se dibujan 50 (de todo su rango) + const many = boxStats([...Array.from({ length: 10000 }, (_, i) => i / 10000), ...Array.from({ length: 200 }, (_, i) => 1000 + i)], 50)! + expect(many.outliers).toHaveLength(50) + expect(many.outliers[0]).toBe(1000) + expect(many.outliers[49]).toBeGreaterThan(1190) + expect(boxStats([NaN])).toBeNull() + }) + + test('histograma: un intervalo por entero si hay pocos; si no, Sturges', () => { + expect(histogram([1, 2, 2, 3])).toEqual({ edges: [0.5, 1.5, 2.5, 3.5], counts: [1, 2, 1] }) + const continuous = histogram(Array.from({ length: 100 }, (_, i) => i / 10)) + expect(continuous.counts.length).toBe(8) + expect(continuous.counts.reduce((a, b) => a + b, 0)).toBe(100) + expect(histogram([5, 5, 5], 10)).toEqual({ edges: [4.5, 5.5], counts: [3] }) + }) + + test('frecuencias de más a menos, sin contar ausentes', () => { + expect(valueCounts(['b', 'a', 'b', '?', 'c', 'a', 'b'])).toEqual([ + { value: 'b', count: 3 }, { value: 'a', count: 2 }, { value: 'c', count: 1 }, + ]) + }) + + test('los más frecuentes sin ordenar todo dan lo mismo que ordenar todo (empates en orden natural)', () => { + // Valores con muchos empates de frecuencia y números que se ordenan mal como texto ("10" antes que "2") + const values = Array.from({ length: 5000 }, (_, i) => String((i * 7919) % 613 % 97)) + const all = valueCounts(values) + expect(topValues(countValues(values), 10)).toEqual(all.slice(0, 10)) + expect(valueCounts(values, 30)).toEqual(all.slice(0, 30)) + expect(valueCounts(['10', '2', '2', '10', '1'], 2)).toEqual([{ value: '2', count: 2 }, { value: '10', count: 2 }]) + }) + + test('perfil de una columna numérica: ausentes, distintos, media, desviación típica muestral y atípicos', () => { + const profile = profileColumn('x', [1, 2, 3, 4, 100, NaN], 'float32') + expect(profile).toMatchObject({ kind: 'numeric', count: 5, missing: 1, distinct: 5 }) + expect(profile.numeric!.mean).toBe(22) + expect(profile.numeric!.median).toBe(3) + expect(profile.numeric!.std).toBeCloseTo(43.6, 1) + expect(profile.numeric!.outliers).toBe(1) + }) + + test('perfil de una columna categórica: valores más frecuentes', () => { + const profile = profileColumn('color', ['rojo', 'azul', 'rojo', ''], 'string') + expect(profile).toMatchObject({ kind: 'categorical', count: 3, missing: 1, distinct: 2 }) + expect(profile.numeric).toBeUndefined() + expect(profile.top[0]).toEqual({ value: 'rojo', count: 2 }) + }) + + test('Pearson con las filas completas de las dos columnas', () => { + expect(pearson([1, 2, 3, NaN], [2, 4, 6, 100])).toBeCloseTo(1) + expect(pearson([1, 2, 3], [3, 2, 1])).toBeCloseTo(-1) + expect(pearson([1, 1, 1], [1, 2, 3])).toBeNaN() + const { names, matrix } = correlationMatrix([{ name: 'a', values: [1, 2, 3] }, { name: 'b', values: [1, 2, 4] }]) + expect(names).toEqual(['a', 'b']) + expect(matrix[0][0]).toBe(1) + expect(matrix[0][1]).toBeCloseTo(0.98, 2) + }) +}) + +describe('conjunto de datos', () => { + + const iris = () => new dfd.DataFrame({ + sepal_length: [5.1, 4.9, 7.0, 6.4, 6.3, 5.8, 5.1], + petal_length: [1.4, 1.4, 4.7, 4.5, 6.0, 5.1, 1.4], + class : ['Iris-setosa', 'Iris-setosa', 'Iris-versicolor', 'Iris-versicolor', 'Iris-virginica', 'Iris-virginica', 'Iris-setosa'], + }) + + test('filas, columnas, celdas vacías y filas repetidas', () => { + const profile = profileDataFrame(iris()) + expect(profile).toMatchObject({ rows: 7, columns: 3, missingCells: 0, duplicateRows: 1 }) + expect(profile.profiles.map(({ kind }) => kind)).toEqual(['numeric', 'numeric', 'categorical']) + }) + + test('tipo de problema: texto o pocos enteros, clasificación; números continuos, regresión', () => { + expect(problemType(profileColumn('class', ['a', 'b'], 'string'))).toBe('classification') + expect(problemType(profileColumn('lymph', [1, 2, 3, 4, 2], 'int32'))).toBe('classification') + expect(problemType(profileColumn('mpg', [18, 15.5, 24, 30.2], 'float32'))).toBe('regression') + }) + + test('avisos: repetidas, ausentes, constantes, identificadores, desequilibrio y atributos casi iguales', () => { + const rows = 40 + const dataframe = new dfd.DataFrame({ + id : Array.from({ length: rows }, (_, i) => i + 1000), + a : Array.from({ length: rows }, (_, i) => i), + b : Array.from({ length: rows }, (_, i) => 2 * i + 1), + constant: Array.from({ length: rows }, () => 7), + class : Array.from({ length: rows }, (_, i) => (i < 38 ? 'yes' : 'no')), + }) + const profile = profileDataFrame(dataframe) + const correlations = correlationMatrix(['id', 'a', 'b'].map((name) => ({ name, values: toNumbers(dataframe[name].values as unknown[]) }))) + const types = dataWarnings(profile, 'class', correlations).map((warning) => ('column' in warning ? `${warning.type}:${warning.column}` : warning.type)) + expect(types).toContain('constant:constant') + expect(types).toContain('identifier:id') + expect(types).toContain('imbalance:class') + expect(types).toContain('correlation:a') + expect(types).not.toContain('identifier:class') + }) +}) + +describe('preprocesado', () => { + + const raw = () => new dfd.DataFrame({ + size : [1, 2, NaN, 4, 1], + color: ['red', 'blue', 'red', '?', 'red'], + id : [10, 11, 12, 13, 10], + class: ['a', 'b', 'a', 'b', 'a'], + }) + + test('codifica el texto, descarta columnas y deja el objetivo sin escalar', () => { + const result = preprocessDataFrame(raw(), { + columns : { size: 'keep', color: 'label-encoder', id: 'drop', class: 'label-encoder' }, + missing : 'keep', + duplicates: false, + scaler : 'min-max', + target : 'class', + }) + expect(result.dataframe.columns).toEqual(['size', 'color', 'class']) + expect(result.encodings.color).toEqual(['red', 'blue']) + expect(result.dataframe.column('color').values).toEqual([0, 1, 0, NaN, 0]) + expect(result.dataframe.column('class').values).toEqual([0, 1, 0, 1, 0]) + expect(result.dataframe.column('size').values).toEqual([0, 1 / 3, NaN, 1, 0]) + expect(result.applied.size).toBe('float32, min-max') + }) + + test('quita filas repetidas o incompletas, o rellena los ausentes con la media y el valor más frecuente', () => { + const base = { columns: {}, scaler: 'none' as const, target: 'class' } + const dropped = preprocessDataFrame(raw(), { ...base, missing: 'drop-rows', duplicates: true }) + expect(dropped.removedRows).toEqual({ duplicates: 1, missing: 2 }) + expect(dropped.dataframe.shape[0]).toBe(2) + const imputed = preprocessDataFrame(raw(), { ...base, missing: 'impute', duplicates: false }) + expect(imputed.imputed).toEqual({ size: 2, color: 'red' }) + expect(imputed.dataframe.column('size').values).toEqual([1, 2, 2, 4, 1]) + }) + + test('el CSV descargado se puede volver a leer: comillas donde hay comas', () => { + const csv = dataframeToCSV(new dfd.DataFrame({ name: ['a,b', 'c'], value: [1, NaN] })) + expect(csv).toBe('name,value\n"a,b",1\nc,\n') + }) +}) diff --git a/tests/core/idleQueue.test.tsx b/tests/core/idleQueue.test.tsx new file mode 100644 index 0000000..17c533c --- /dev/null +++ b/tests/core/idleQueue.test.tsx @@ -0,0 +1,35 @@ +import { describe, test, expect, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import { pendingIdleJobs, scheduleIdle } from '@core/scheduler/idleQueue' +import N4LDeferredMount from '@components/loading/N4LDeferredMount' + +describe('cola de tiempo libre', () => { + + test('un trabajo por hueco, en orden, y se pueden cancelar', async () => { + const done: string[] = [] + scheduleIdle(() => done.push('a')) + const cancel = scheduleIdle(() => done.push('b')) + scheduleIdle(() => done.push('c')) + cancel() + expect(done).toEqual([]) + await vi.waitFor(() => expect(done).toEqual(['a', 'c'])) + expect(pendingIdleJobs()).toBe(0) + }) + + test('un trabajo que falla se registra y no para la cola', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const done: string[] = [] + scheduleIdle(() => { throw new Error('mal') }) + scheduleIdle(() => done.push('después')) + await vi.waitFor(() => expect(done).toEqual(['después'])) + expect(error).toHaveBeenCalledWith('Idle job failed', expect.objectContaining({ message: 'mal' })) + error.mockRestore() + }) + + test('N4LDeferredMount reserva el sitio y monta el contenido cuando le toca', async () => { + render(

    contenido

    ) + expect(screen.queryByText('contenido')).toBeNull() + expect(screen.getByTestId('Test-DeferredMount')).toHaveStyle({ minHeight: '123px' }) + expect(await screen.findByText('contenido')).toBeInTheDocument() + }) +}) diff --git a/tests/core/imageUtils.test.ts b/tests/core/imageUtils.test.ts index fb285fb..04b1018 100644 --- a/tests/core/imageUtils.test.ts +++ b/tests/core/imageUtils.test.ts @@ -1,9 +1,11 @@ import { describe, test, expect } from 'vitest' import { + grayscaleToImageData, imageDataToMnistTensor4d, resampleImageData, thresholdImageData, } from '../../src/pages/playground/3_ImageClassification/utils/utils' +import { SpriteImageDataset } from '../../src/pages/playground/3_ImageClassification/models/SpriteImageDataset' /** ImageData de width × height con todos los píxeles a [r, g, b, a]. */ function solid(width: number, height: number, rgba: [number, number, number, number]): ImageData { @@ -48,3 +50,35 @@ describe('utilidades de imagen (clasificación de imágenes)', () => { expect(imageDataToMnistTensor4d(solid(28, 28, [0, 0, 0, 255])).shape).toStrictEqual([1, 28, 28, 1]) }) }) + +describe('grayscaleToImageData', () => { + + test('una imagen del dataset llega al modelo con los mismos valores (trazo oscuro sobre fondo claro, opaca)', async () => { + const pixels = Float32Array.from({ length: 28 * 28 }, (_, i) => (i % 7) / 6) + const imageData = grayscaleToImageData(pixels, 28, 28) + expect(Array.from(imageData.data.slice(0, 8))).toEqual([255, 255, 255, 255, 212, 212, 212, 255]) + const tensor = imageDataToMnistTensor4d(imageData) + const values = await tensor.data() + tensor.dispose() + values.forEach((value, i) => expect(value).toBeCloseTo(pixels[i], 2)) + }) +}) + +describe('SpriteImageDataset: imágenes de test', () => { + + test('cuenta las imágenes de test y da la clase y los píxeles de cada una', () => { + const dataset = new SpriteImageDataset({ name: 'TEST', imagesUrl: '', labelsUrl: '', numElements: 3, numTrain: 1, numClasses: 10, image: { width: 28, height: 28, channels: 1 } }) + const oneHot = (label: number) => Array.from({ length: 10 }, (_, i) => (i === label ? 1 : 0)) + // Lo que deja load(): las dos imágenes de test y sus etiquetas en one-hot + Object.assign(dataset, { + testImages: Float32Array.from({ length: 2 * 784 }, (_, i) => (i < 784 ? 0 : 1)), + testLabels: Uint8Array.from([...oneHot(7), ...oneHot(2)]), + }) + expect(dataset.numTest).toBe(2) + expect(dataset.testClasses()).toEqual([7, 2]) + const { pixels, label } = dataset.testExample(1) + expect(label).toBe(2) + expect(pixels).toHaveLength(784) + expect(pixels.every((value) => value === 1)).toBe(true) + }) +}) diff --git a/tests/core/kmeans.test.ts b/tests/core/kmeans.test.ts new file mode 100644 index 0000000..99185a8 --- /dev/null +++ b/tests/core/kmeans.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, test } from 'vitest' +import { readFileSync } from 'node:fs' + +import { compareWithLabels, elbow, kmeans, pca2, silhouette, standardize } from '@core/clustering/kmeans' + +// Iris del proyecto: 4 medidas y la especie +const [, ...rows] = readFileSync('public/n4l/iris.n4l/data/iris.csv', 'utf-8').trim().split(/\r?\n/).map((line) => line.split(',')) +const irisPoints = rows.map((row) => row.slice(0, 4).map(Number)) +const irisLabels = rows.map((row) => row[4]) + +describe('kmeans: agrupar sin etiquetas', () => { + test('dos nubes bien separadas: dos grupos perfectos, silueta alta y converge', () => { + const points = [[0, 0], [0.2, 0.1], [0.1, 0.3], [10, 10], [10.2, 9.9], [9.9, 10.1]] + const result = kmeans(points, { k: 2, seed: 3 }) + expect(result.converged).toBe(true) + expect(new Set(result.assignments.slice(0, 3)).size).toBe(1) + expect(result.assignments[0]).not.toBe(result.assignments[3]) + expect(silhouette(points, result.assignments)).toBeGreaterThan(0.9) + expect(compareWithLabels(result.assignments, ['a', 'a', 'a', 'b', 'b', 'b'], 2)).toMatchObject({ purity: 1, ari: 1 }) + }) + + test('la comparación con las clases: totales, la clase mayoritaria de cada grupo y los grupos mezclados', () => { + // Grupo 0: 3 «a» y 1 «b» (75 %); grupo 1: 2 «b» y 2 «c» (50 %, mezcla); grupo 2: vacío + const comparison = compareWithLabels([0, 0, 0, 0, 1, 1, 1, 1], ['a', 'a', 'b', 'a', 'b', 'c', 'c', 'b'], 3) + expect(comparison.classes).toStrictEqual(['a', 'b', 'c']) + expect(comparison.table).toStrictEqual([[3, 1, 0], [0, 2, 2], [0, 0, 0]]) + expect(comparison.classTotals).toStrictEqual([3, 3, 2]) + expect(comparison.groups).toStrictEqual([ + { size: 4, majority: 0, share: 0.75, isMixed: false }, + { size: 4, majority: 1, share: 0.5, isMixed: true }, + { size: 0, majority: 0, share: 0, isMixed: false }, + ]) + expect(comparison.purity).toBeCloseTo(5 / 8) + }) + + test('la misma semilla da los mismos grupos; cada paso se guarda y la inercia no sube', () => { + const a = kmeans(standardize(irisPoints), { k: 3, seed: 7 }) + const b = kmeans(standardize(irisPoints), { k: 3, seed: 7 }) + expect(a.assignments).toStrictEqual(b.assignments) + expect(a.steps.length).toBeGreaterThan(1) + a.steps.slice(1).forEach((step, index) => expect(step.inertia).toBeLessThanOrEqual(a.steps[index].inertia + 1e-9)) + }) + + test('Iris escalado con k = 3: se parece bastante a las especies (sin haberlas visto)', () => { + const points = standardize(irisPoints) + const result = kmeans(points, { k: 3, seed: 1 }) + const { purity, ari, table } = compareWithLabels(result.assignments, irisLabels, 3) + expect(table.flat().reduce((sum, value) => sum + value, 0)).toBe(150) + expect(purity).toBeGreaterThan(0.75) + expect(ari).toBeGreaterThan(0.5) + const score = silhouette(points, result.assignments) + expect(score).toBeGreaterThan(0.35) + expect(score).toBeLessThan(0.6) + }) + + test('el codo: la inercia baja al subir k', () => { + const values = elbow(standardize(irisPoints), [1, 2, 3, 4, 5]).map(({ inertia }) => inertia) + values.slice(1).forEach((value, index) => expect(value).toBeLessThan(values[index])) + }) + + test('PCA de Iris escalado: las dos primeras componentes recogen casi toda la varianza', () => { + const { explained, project } = pca2(standardize(irisPoints)) + expect(explained[0]).toBeGreaterThan(0.7) + expect(explained[0]).toBeLessThan(0.76) + expect(explained[0] + explained[1]).toBeGreaterThan(0.94) + expect(project([0, 0, 0, 0])).toHaveLength(2) + }) +}) diff --git a/tests/core/lab.test.ts b/tests/core/lab.test.ts new file mode 100644 index 0000000..1dcdd66 --- /dev/null +++ b/tests/core/lab.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, test } from 'vitest' + +import { + boundaryGrid, createLabNetwork, evaluate, makeDataset, seededRandom, splitDataset, trainEpoch, + type LabConfig_t, type LabDataset_t, +} from '@core/learning/lab' + +const BASE: LabConfig_t = { features: ['x', 'y'], hidden: [], activation: 'tanh', learningRate: 0.1, batchSize: 10 } + +/** Entrena `epochs` épocas y devuelve cómo va con los de entrenamiento y los de prueba en cada una */ +function train(kind: LabDataset_t, config: LabConfig_t, { epochs = 300, noise = 0.1, count = 200 } = {}) { + const { train: points, test } = splitDataset(makeDataset(kind, { count, noise, seed: 1 })) + let network = createLabNetwork(config, 1) + const random = seededRandom(101) + const history: Array<{ train: ReturnType, test: ReturnType }> = [] + for (let epoch = 0; epoch < epochs; epoch++) { + network = trainEpoch(network, points, config, random) + history.push({ train: evaluate(network, points, config.features), test: evaluate(network, test, config.features) }) + } + return { network, history, last: history.at(-1)! } +} + +describe('el laboratorio 2D', () => { + test('los conjuntos: la mitad de cada clase, dentro del plano y siempre iguales con la misma semilla', () => { + for (const kind of ['blobs', 'circles', 'xor', 'spiral'] as const) { + const points = makeDataset(kind, { count: 200, noise: 0.3, seed: 7 }) + expect(points).toHaveLength(200) + expect(points.filter(({ label }) => label === 1)).toHaveLength(100) + expect(points.every(({ x, y }) => Math.abs(x) <= 1 && Math.abs(y) <= 1)).toBe(true) + expect(makeDataset(kind, { count: 200, noise: 0.3, seed: 7 })).toEqual(points) + } + }) + + test('la rejilla de la frontera: una probabilidad por celda, de 0 a 1', () => { + const grid = boundaryGrid(createLabNetwork({ ...BASE, hidden: [3] }), ['x', 'y'], 10) + expect(grid).toHaveLength(100) + expect([...grid].every((value) => value >= 0 && value <= 1)).toBe(true) + }) + + // Lo que enseña cada «Prueba esto» de la página + test('XOR sin capas ocultas: una recta no lo separa; con una capa de 4 neuronas, sí', () => { + expect(train('xor', BASE).last.test.accuracy).toBeLessThan(0.7) + expect(train('xor', { ...BASE, hidden: [4] }).last.test.accuracy).toBeGreaterThan(0.9) + }) + + test('círculos: sin capas no se separan con x e y, pero sí con x² e y²', () => { + expect(train('circles', BASE, { epochs: 200 }).last.test.accuracy).toBeLessThan(0.7) + expect(train('circles', { ...BASE, features: ['x2', 'y2'] }, { epochs: 200 }).last.test.accuracy).toBeGreaterThan(0.95) + }) + + test('la espiral: con más características, dos capas de 8 y paciencia', () => { + const { last } = train('spiral', { ...BASE, features: ['x', 'y', 'x2', 'y2', 'xy'], hidden: [8, 8] }, { count: 400, epochs: 700 }) + expect(last.test.accuracy).toBeGreaterThan(0.9) + }) + + test('una tasa de aprendizaje enorme hace que la pérdida vaya a saltos', () => { + const rises = (history: ReturnType['history']) => + history.slice(1).filter(({ train: now }, index) => now.loss > history[index].train.loss * 1.2).length + expect(rises(train('xor', { ...BASE, hidden: [4], learningRate: 3 }).history)).toBeGreaterThan(10) + expect(rises(train('xor', { ...BASE, hidden: [4] }).history)).toBeLessThan(3) + }) + + test('pocos puntos, mucho ruido y una red grande: se los aprende de memoria (sobreajuste)', () => { + const { history, last } = train('circles', { ...BASE, hidden: [8, 8, 8], activation: 'relu' }, { noise: 0.45, count: 60, epochs: 800 }) + const bestTest = Math.min(...history.map(({ test }) => test.loss)) + expect(last.train.accuracy).toBeGreaterThan(0.95) + expect(last.test.loss).toBeGreaterThan(2 * bestTest) + }) +}) diff --git a/tests/core/learningPath.test.ts b/tests/core/learningPath.test.ts new file mode 100644 index 0000000..d7c9d98 --- /dev/null +++ b/tests/core/learningPath.test.ts @@ -0,0 +1,103 @@ +import { afterEach, beforeEach, describe, expect, test } from 'vitest' +import { act, renderHook } from '@testing-library/react' + +import { trackEvent, trackPageView } from '@core/analytics' +import { + LEARNING_STORAGE_KEY, + nextStep, + resetLearningPath, + setStepDone, + startLearningPath, + trackLearningPath, + useJustCompleted, + useLearningPath, +} from '@core/learning/learningPath' + +describe('learningPath: el recorrido «Empieza aquí»', () => { + let stop: () => void + beforeEach(() => { + resetLearningPath() + stop = trackLearningPath() + }) + afterEach(() => stop()) + + test('los pasos se marcan solos con los eventos de la aplicación (sin consentimiento de analíticas)', () => { + const { result } = renderHook(() => useLearningPath()) + act(() => trackPageView('/glossary', { page_type: 'glossary' })) + expect(result.current.done).toEqual(['glossary']) + + // Entrenar en otra tarea no completa el de Iris; un entrenamiento con error, tampoco + act(() => trackPageView('/playground/regression/dataset/AUTO_MPG', { page_type: 'playground', task: 'regression', mode: 'train', item: 'AUTO_MPG' })) + act(() => trackEvent('train_end', { outcome: 'error' })) + act(() => trackEvent('train_end', { outcome: 'completed' })) + expect(result.current.done).toEqual(['glossary', 'regression']) + + act(() => trackEvent('layer_fix', { kind: 'output-units' })) + expect(result.current.done).toContain('fix-layers') + // El primero que falta es el laboratorio + expect(nextStep(result.current.done)?.id).toBe('lab') + expect(JSON.parse(localStorage.getItem(LEARNING_STORAGE_KEY)!).done).toEqual(['glossary', 'regression', 'fix-layers']) + }) + + test('el laboratorio y Paso a paso: se marcan al entrenar en el laboratorio y al avanzar en Paso a paso', () => { + const { result } = renderHook(() => useLearningPath()) + act(() => trackEvent('lab_train', { dataset: 'xor', layers: 1, features: 2 })) + act(() => trackEvent('step_by_step', { action: 'step' })) + expect(result.current.done).toEqual(expect.arrayContaining(['lab', 'step-by-step'])) + expect(nextStep(result.current.done)?.id).toBe('glossary') + }) + + test('solo se avisa del paso completado si ya se ha entrado en /learn', () => { + const { result } = renderHook(() => useJustCompleted()) + act(() => trackEvent('models_compare', { models: 2 })) + expect(result.current).toBeNull() + + act(() => startLearningPath()) + act(() => trackEvent('explain', { method: 'shap' })) + expect(result.current).toEqual({ type: 'step', id: 'explain' }) + }) + + test('se puede marcar y desmarcar a mano, y empezar de cero', () => { + const { result } = renderHook(() => useLearningPath()) + act(() => setStepDone('cnn', true)) + act(() => setStepDone('cnn', true)) + expect(result.current.done).toEqual(['cnn']) + act(() => setStepDone('cnn', false)) + expect(result.current.done).toEqual([]) + act(() => { + setStepDone('train', true) + resetLearningPath() + }) + expect(result.current).toEqual({ started: false, done: [], challenges: {} }) + }) + + test('los retos se superan con el resultado de un entrenamiento en su página, y se guarda el mejor', () => { + const { result } = renderHook(() => useLearningPath()) + const { result: completed } = renderHook(() => useJustCompleted()) + act(() => startLearningPath()) + act(() => trackPageView('/playground/tabular-classification/dataset/IRIS', { page_type: 'playground', task: 'tabular-classification', mode: 'train', item: 'IRIS' })) + + // 90 %, con 4 neuronas ocultas y en 5 épocas: «pocas neuronas» y «pocas épocas», pero no el de todas las flores + act(() => trackEvent('train_result', { accuracy: 0.9, hidden_units: 4, layers: 2, epochs: 5, diagnosis: 'still-improving' })) + expect(result.current.challenges).toEqual({ 'iris-tiny': 0.9, 'iris-fast': 0.9 }) + expect(completed.current).toEqual({ type: 'challenge', id: 'iris-tiny' }) + + act(() => trackEvent('train_result', { accuracy: 0.933, hidden_units: 20, layers: 3, epochs: 30 })) + expect(result.current.challenges).toEqual({ 'iris-tiny': 0.9, 'iris-fast': 0.9 }) + act(() => trackEvent('train_result', { accuracy: 1, hidden_units: 20, layers: 3, epochs: 30 })) + expect(result.current.challenges).toEqual({ 'iris-tiny': 0.9, 'iris-fast': 0.9, 'iris-accuracy': 1 }) + // Otro conjunto de datos no cuenta + act(() => trackPageView('/playground/tabular-classification/dataset/CAR', { page_type: 'playground', task: 'tabular-classification', mode: 'train', item: 'CAR' })) + act(() => trackEvent('train_result', { accuracy: 1, hidden_units: 2, layers: 2, epochs: 2 })) + expect(result.current.challenges['iris-tiny']).toBe(0.9) + }) + + test('el reto de regresión pide un entrenamiento que el diagnóstico da por bueno', () => { + const { result } = renderHook(() => useLearningPath()) + act(() => trackPageView('/playground/regression/dataset/SALARY', { page_type: 'playground', task: 'regression', mode: 'train', item: 'SALARY' })) + act(() => trackEvent('train_result', { hidden_units: 10, layers: 2, epochs: 20, diagnosis: 'overfitting' })) + expect(result.current.challenges).toEqual({}) + act(() => trackEvent('train_result', { hidden_units: 10, layers: 2, epochs: 20, diagnosis: 'good' })) + expect(result.current.challenges).toEqual({ 'regression-good': 1 }) + }) +}) diff --git a/tests/core/lossGlossary.test.ts b/tests/core/lossGlossary.test.ts new file mode 100644 index 0000000..19bcb6f --- /dev/null +++ b/tests/core/lossGlossary.test.ts @@ -0,0 +1,16 @@ +import { describe, test, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import { TYPE_LOSSES } from '../../src/core/nn-utils/ArchitectureTypesHelper' + +const readLocale = (language: string) => JSON.parse(readFileSync(`public/locales/${language}/translation.json`, 'utf-8')) + +describe('Glosario de pérdidas', () => { + test.each(['es', 'en', 'ja'])('cada pérdida del selector tiene descripción en %s', (language) => { + const table = readLocale(language).pages.glossary['loss-functions'].table + for (const { key } of TYPE_LOSSES) { + expect(table[key]?.description, key).toBeTruthy() + } + // Y el glosario no describe pérdidas que ya no se pueden elegir + expect(Object.keys(table).sort()).toStrictEqual(TYPE_LOSSES.map(({ key }) => key).sort()) + }) +}) diff --git a/tests/core/modelCode.test.ts b/tests/core/modelCode.test.ts new file mode 100644 index 0000000..a479ffa --- /dev/null +++ b/tests/core/modelCode.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, test } from 'vitest' +import * as tf from '@tensorflow/tfjs' + +import { buildDenseModel, buildImageModel, buildSeriesModel } from '@core/training/buildModels' +import { denseCodeLayers, imageCodeLayers, kerasCode, seriesCodeLayers, tfjsCode, type ModelCode_t } from '@core/nn-utils/modelCode' + +const IRIS: ModelCode_t = { + inputShape : [4], + layers : denseCodeLayers([{ units: 10, activation: 'relu' }, { units: 3, activation: 'softmax' }]), + optimizer : 'train-adam', + learningRate: 0.01, + loss : 'categoricalCrossentropy', + metrics : ['accuracy'], + epochs : 20, + batchSize : 32, + dataComment : 'X: las filas; y: su clase en one-hot', +} + +/** Ejecuta el código de TF.js generado (sin el import) y devuelve el modelo, compilado y entrenado una época */ +async function run(code: string, inputShape: number[], outputs: number) { + const body = code.replace(/^import .*$/m, '').replace(/epochs: \d+/, 'epochs: 1') + '\nreturn model' + const rows = 8 + const XTrain = tf.randomNormal([rows, ...inputShape]) + // Clases en one-hot o, con una sola salida (regresión), un número + const yTrain = outputs === 1 + ? tf.randomNormal([rows, 1]) + : tf.oneHot(tf.tensor1d(Array.from({ length: rows }, (_, i) => i % outputs), 'int32'), outputs).toFloat() + const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor + const model: tf.Sequential = await new AsyncFunction('tf', 'XTrain', 'yTrain', 'XTest', 'yTest', body)(tf, XTrain, yTrain, XTrain, yTrain) + return model +} + +const shapes = (model: tf.LayersModel) => model.layers.map((layer) => `${layer.getClassName()}:${JSON.stringify(layer.outputShape)}`) + +describe('modelCode: el código equivalente de la red', () => { + test('TF.js: se ejecuta, entrena y da la misma red que la aplicación (clasificación tabular)', async () => { + const model = await run(tfjsCode(IRIS), [4], 3) + expect(shapes(model)).toEqual(shapes(buildDenseModel([{ units: 10, activation: 'relu' }, { units: 3, activation: 'softmax' }], 4))) + expect(model.optimizer.getClassName()).toBe('Adam') + }) + + test('Keras: las mismas capas, el optimizador, la pérdida y las métricas con sus nombres de Python', () => { + const code = kerasCode({ ...IRIS, metrics: ['accuracy', 'precision'] }) + expect(code).toContain('keras.Input(shape=(4,))') + expect(code).toContain('layers.Dense(10, activation="relu")') + expect(code).toContain('layers.Dense(3, activation="softmax")') + expect(code).toContain('optimizer=keras.optimizers.Adam(learning_rate=0.01)') + expect(code).toContain('loss="categorical_crossentropy"') + expect(code).toContain('metrics=["accuracy", keras.metrics.Precision()]') + expect(code).toContain('model.fit(X_train, y_train, epochs=20, batch_size=32, shuffle=True, validation_data=(X_test, y_test))') + expect(code).toContain('# X: las filas; y: su clase en one-hot') + }) + + test('el optimizador con inercia (momentum) lleva su valor; los nombres de las activaciones se traducen', () => { + const spec: ModelCode_t = { ...IRIS, optimizer: 'momentum', momentum: 0.9, layers: denseCodeLayers([{ units: 4, activation: 'hardSigmoid' }, { units: 3, activation: 'softmax' }]) } + expect(tfjsCode(spec)).toContain('optimizer: tf.train.momentum(0.01, 0.9),') + expect(kerasCode(spec)).toContain('optimizer=keras.optimizers.SGD(learning_rate=0.01, momentum=0.9)') + expect(kerasCode(spec)).toContain('layers.Dense(4, activation="hard_sigmoid")') + }) + + test('imágenes: la red convolucional, igual que la de la aplicación', async () => { + const layers = [ + { _class: 'conv2d' as const, _protected: true, inputShape: [28, 28, 1], kernelSize: 5, filters: 8, activation: 'relu' }, + { _class: 'maxPooling2d' as const, poolSize: 2, strides: 2 }, + { _class: 'flatten' as const }, + { _class: 'dense' as const, units: 10, activation: 'softmax' }, + ] + const { inputShape, layers: code } = imageCodeLayers(layers) + const spec = { ...IRIS, inputShape, layers: code } + const model = await run(tfjsCode(spec), inputShape, 10) + expect(shapes(model)).toEqual(shapes(buildImageModel(layers))) + const keras = kerasCode(spec) + expect(keras).toContain('keras.Input(shape=(28, 28, 1))') + expect(keras).toContain('layers.Conv2D(8, kernel_size=5, activation="relu")') + expect(keras).toContain('layers.MaxPooling2D(pool_size=2, strides=2)') + expect(keras).toContain('layers.Flatten()') + }) + + test('series: la ventana como secuencia para las recurrentes, igual que la aplicación', async () => { + const layers = [ + { _class: 'lstm' as const, units: 8, activation: 'tanh' }, + { _class: 'gru' as const, units: 4, activation: 'tanh' }, + { _class: 'dense' as const, units: 1, activation: 'linear' }, + ] + const spec = { ...IRIS, inputShape: [12], layers: seriesCodeLayers(layers, 12), loss: 'meanSquaredError', metrics: ['mse'] } + const model = await run(tfjsCode(spec), [12], 1) + expect(shapes(model)).toEqual(shapes(buildSeriesModel(layers, 12))) + const keras = kerasCode(spec) + expect(keras).toContain('layers.Reshape((12, 1))') + expect(keras).toContain('layers.LSTM(8, activation="tanh", return_sequences=True)') + expect(keras).toContain('layers.GRU(4, activation="tanh")') + expect(keras).toContain('loss="mean_squared_error"') + }) +}) diff --git a/tests/core/n4lFormat.test.ts b/tests/core/n4lFormat.test.ts new file mode 100644 index 0000000..3e8db4b --- /dev/null +++ b/tests/core/n4lFormat.test.ts @@ -0,0 +1,241 @@ +import { describe, test, expect, beforeAll } from 'vitest' +import * as fs from 'fs' +import * as path from 'path' +import * as tfjs from '@tensorflow/tfjs' + +import { N4L_CATALOG, n4lDatasetByFile, n4lPackageByKey, n4lPublicFile } from '@core/n4l/catalog' +import { isTableDataset, n4lLabelKey, n4lLayersModels, n4lTableView, N4L_FORMAT_VERSION, type N4LDataset_t } from '@core/n4l/format' +import { upgradeManifest } from '@core/n4l/migrate' +import { manifestProblems, N4LError, validateManifest } from '@core/n4l/validate' +import { N4LZipSource, openN4LPackage, packN4L } from '@core/n4l/source' +import { loadN4LLayersModel } from '@core/n4l/tfjsModel' +import { taskOptions } from '@/TASK_OPTIONS' +import { readN4LCatalog } from '../../vite/n4lPackages' + +const IRIS_DIR = 'public/n4l/iris.n4l' +const iris = () => JSON.parse(fs.readFileSync(`${IRIS_DIR}/manifest.json`, 'utf-8')) + +/** Los ficheros de una carpeta, con su ruta dentro de ella */ +const filesOf = (dir: string, base = dir): Record => Object.assign({}, ...fs.readdirSync(dir, { withFileTypes: true }) + .map((entry) => (entry.isDirectory() + ? filesOf(path.join(dir, entry.name), base) + : { [path.relative(base, path.join(dir, entry.name))]: new Uint8Array(fs.readFileSync(path.join(dir, entry.name))) }))) + +describe('Formato .n4l: el manifiesto', () => { + test('los paquetes de public/n4l/ son válidos y su carpeta se llama como su id', () => { + expect(N4L_CATALOG.map(({ id }) => id)).toEqual(expect.arrayContaining(['car', 'iris', 'lymphography'])) + for (const entry of N4L_CATALOG) { + expect(manifestProblems(entry), entry.id).toStrictEqual([]) + expect(entry.path).toBe(`n4l/${entry.id}.n4l`) + } + }) + + test('cada problema dice dónde está, y se dicen todos a la vez', () => { + const manifest = iris() + manifest.version = '1.0' + manifest.datasets[0].columns[0].role = 'Input' + manifest.tasks[0].models[0].dataset = 'otro' + manifest.tasks[0].preprocessing.push({ op: 'min-max', columns: 'todas' }, { op: 'label-encoder', columns: ['class', 'color'] }) + expect(manifestProblems(manifest)).toStrictEqual([ + 'version: semver (1.0.0)', + 'datasets[0].columns[0].role: uno de Feature, Target, ID, Other', + 'tasks[0].preprocessing[2].columns: "categorical", "features" o una lista de columnas', + 'tasks[0].preprocessing[3].columns: no están en el conjunto: color', + 'tasks[0].models[0].dataset: uno de los conjuntos del paquete', + ]) + expect(() => validateManifest(manifest)).toThrow(N4LError) + }) + + test('las rutas no pueden salir del paquete', () => { + const manifest = iris() + manifest.datasets[0].file = '../../models/x.csv' + manifest.tasks[0].models[0].path = '/models/x.json' + expect(manifestProblems(manifest)).toStrictEqual(['datasets[0].file: ruta dentro del paquete', 'tasks[0].models[0].path: ruta dentro del paquete']) + }) + + test('los ejemplos tienen que ser de una de las clases (por su id o uno de sus nombres)', () => { + const manifest = iris() + manifest.tasks[0].prediction.examples[0].expected = 'Rosa' + manifest.tasks[0].prediction.examples[1].expected = 'Iris-versicolor' + expect(manifestProblems(manifest)).toStrictEqual(['tasks[0].prediction.examples[0].expected: una de las clases']) + }) + + test('una sección por tarea, con un conjunto del paquete', () => { + const manifest = iris() + manifest.tasks.push({ ...manifest.tasks[1], datasets: ['flores'], listed: 'no' }) + expect(manifestProblems(manifest)).toStrictEqual([ + 'tasks[2].task: clustering ya tiene su sección', + 'tasks[2].datasets: al menos uno, de los conjuntos del paquete', + 'tasks[2].listed: true o false', + ]) + expect(manifestProblems({ ...iris(), tasks: [] })).toStrictEqual(['tasks: al menos una tarea']) + }) + + test('una serie temporal tiene su frecuencia, su fecha (type Date) y lo que se predice; la tarea solo usa series', () => { + const airline = () => JSON.parse(fs.readFileSync('public/n4l/airline-passengers.n4l/manifest.json', 'utf-8')) + expect(manifestProblems(airline())).toStrictEqual([]) + const manifest = airline() + manifest.datasets[0].frequency = 'monthly' + manifest.datasets[0].columns[0].type = 'Categorical' + manifest.datasets[0].columns[1].role = 'Feature' + expect(manifestProblems(manifest)).toStrictEqual([ + 'datasets[0].frequency: una de hour, day, week, month, quarter, year', + 'datasets[0].columns: una serie temporal tiene una columna con su fecha (type Date)', + 'datasets[0].columns: una serie temporal tiene un objetivo (role Target), lo que se predice', + ]) + const table = airline() + delete table.datasets[0].frequency + expect(manifestProblems(table)).toStrictEqual(['tasks[0].datasets: series temporales (con frequency)']) + }) + + test('una serie temporal propone su preparación (forecast) y su red, que puede empezar con capas recurrentes', () => { + const manifest = JSON.parse(fs.readFileSync('public/n4l/airline-passengers.n4l/manifest.json', 'utf-8')) + manifest.tasks[0].training.layers.unshift({ class: 'lstm', units: 8 }, { class: 'gru', units: 0 }) + manifest.tasks[0].forecast = { window: 0, season: 1, difference: 'no', testSize: 100 } + expect(manifestProblems(manifest)).toStrictEqual([ + 'tasks[0].training.layers[1]: dense { units, activation }, conv2d { filters, kernelSize, activation }, maxPooling2d { poolSize, strides }, flatten o simpleRNN, lstm, gru { units }', + 'tasks[0].forecast.window: los valores anteriores con los que se predice (un entero mayor que 0)', + 'tasks[0].forecast.season: los valores que tarda en repetirse el patrón (un entero mayor que 1)', + 'tasks[0].forecast.difference: true o false', + 'tasks[0].forecast.testSize: un porcentaje mayor que 0 y menor que 100', + ]) + }) + + test('las filas de una serie temporal van en orden, una por fecha', () => { + const series = N4L_CATALOG.flatMap((entry) => entry.datasets.filter(isTableDataset) + .filter(({ frequency }) => frequency !== undefined).map((dataset) => ({ entry, dataset }))) + expect(series.map(({ dataset }) => dataset.frequency)).toEqual(['month', 'day', 'month']) + for (const { entry, dataset } of series) { + const [header, ...rows] = fs.readFileSync(`public/${n4lPublicFile(entry, dataset.file)}`, 'utf-8').trim().split('\n').map((line) => line.split(',')) + const dates = rows.map((row) => row[header.indexOf(dataset.columns.find(({ type }) => type === 'Date')!.name)]) + // Fechas ISO (1949-01, 1981-01-01): en orden de texto es en orden de fecha + expect(dates.every((date) => !Number.isNaN(Date.parse(date))), entry.id).toBe(true) + expect(dates.every((date, i) => i === 0 || dates[i - 1] < date), entry.id).toBe(true) + } + }) + + test('las claves de columnas y clases en los textos: sin «.» ni «:» (separadores de i18next)', () => { + expect(n4lLabelKey('bl. of lymph. c')).toBe('bl_ of lymph_ c') + expect(n4lLabelKey('a:b')).toBe('a_b') + for (const entry of N4L_CATALOG) { + for (const language of entry.locales) { + const texts = JSON.parse(fs.readFileSync(`public/${entry.path}/locales/${language}.json`, 'utf-8')) + // Los de cada tarea: su nombre en los menús y su frase en /datasets + for (const { task } of entry.tasks) { + for (const key of ['name', 'summary']) expect(typeof texts.tasks[task]?.[key], `${entry.id} ${language} ${task}.${key}`).toBe('string') + } + // Las columnas de todas sus tablas y, si alguna de sus tareas con tablas las tiene, sus clases. Las de las + // imágenes pueden tener nombre («avión») o enseñarse tal cual («7», «お»), pero no a medias + const columns = new Set(entry.datasets.filter(isTableDataset).flatMap(({ columns: list }) => list.map(({ name }) => n4lLabelKey(name)))) + expect(Object.keys(texts.columns ?? {}).sort(), `${entry.id} ${language}`).toStrictEqual([...columns].sort()) + const classesOf = (sections: typeof entry.tasks) => sections.flatMap((section) => section.classes ?? []).map(({ id }) => n4lLabelKey(id)) + const tableClasses = classesOf(entry.tasks.filter((section) => n4lTableView(entry, section.task) !== undefined)) + const imageClasses = classesOf(entry.tasks.filter((section) => n4lTableView(entry, section.task) === undefined)) + const named = Object.keys(texts.classes ?? {}) + const expected = named.some((key) => imageClasses.includes(key)) ? [...tableClasses, ...imageClasses] : tableClasses + expect(named.sort(), `${entry.id} ${language}`).toStrictEqual([...new Set(expected)].sort()) + } + } + }) +}) + +describe('Formato .n4l: versiones', () => { + test('uno de una versión más nueva del formato se rechaza: hay que actualizar la aplicación', () => { + expect(() => upgradeManifest({ ...iris(), formatVersion: N4L_FORMAT_VERSION + 1 })).toThrow(/actualízala/) + }) + + test('uno de una versión anterior se sube de versión en versión hasta la actual', () => { + // Un formato 3 imaginario: la 2 renombró «key» a «slug» y la 3 pasó «locales» a un objeto + const migrations = { + 1: (manifest: Record) => { + const { key, ...rest } = manifest + return { ...rest, slug: key } + }, + 2: (manifest: Record) => ({ ...manifest, locales: { languages: manifest.locales } }), + } + const upgraded = upgradeManifest({ ...iris(), key: 'IRIS' }, migrations, 3) + expect(upgraded).toMatchObject({ formatVersion: 3, slug: 'IRIS', locales: { languages: ['es', 'en', 'ja'] } }) + expect(upgraded).not.toHaveProperty('key') + expect(() => upgradeManifest(iris(), { 1: migrations[1] }, 3)).toThrow(/no hay migración de la versión 2/) + }) + + test('sin el formato n4l no es un paquete', () => { + expect(() => upgradeManifest({ id: 'x' })).toThrow(/format/) + }) +}) + +describe('Formato .n4l: el plugin que reúne los paquetes', () => { + test('lee las carpetas .n4l de public/n4l y comprueba que estén sus ficheros', () => { + const tmp = fs.mkdtempSync(path.join(fs.realpathSync('/tmp'), 'n4l-')) + const dir = path.join(tmp, 'n4l', 'iris.n4l') + fs.cpSync(IRIS_DIR, dir, { recursive: true }) + expect(readN4LCatalog(tmp).map(({ id, path: where }) => [id, where])).toStrictEqual([['iris', 'n4l/iris.n4l']]) + + fs.rmSync(path.join(dir, 'locales', 'ja.json')) + expect(() => readN4LCatalog(tmp)).toThrow(/falta el fichero locales\/ja\.json/) + fs.cpSync(IRIS_DIR, dir, { recursive: true }) + fs.renameSync(dir, path.join(tmp, 'n4l', 'flores.n4l')) + expect(() => readN4LCatalog(tmp)).toThrow(/la carpeta se tiene que llamar iris\.n4l/) + fs.rmSync(tmp, { recursive: true }) + }) +}) + +describe('Formato .n4l: un fichero .n4l (ZIP)', () => { + beforeAll(async () => { await tfjs.setBackend('cpu') }) + + test('la carpeta comprimida se abre igual: su manifiesto, sus textos y su modelo', async () => { + const pkg = await openN4LPackage(await N4LZipSource.open(await packN4L(filesOf(IRIS_DIR), 'uint8array'))) + expect(pkg.manifest.id).toBe('iris') + expect(pkg.source.url('manifest.json')).toBeNull() + expect(JSON.parse(await pkg.source.readText('locales/es.json')).tasks['tabular-classification'].title).toContain('IRIS') + const model = await loadN4LLayersModel(pkg.source, n4lLayersModels(pkg.manifest.tasks[0])[0].path) + expect(model.inputs[0].shape).toStrictEqual([null, 4]) + }) + + test('también si todo va dentro de su carpeta (al comprimir la carpeta entera)', async () => { + const files = Object.fromEntries(Object.entries(filesOf(IRIS_DIR)).map(([file, data]) => [`iris.n4l/${file}`, data])) + const pkg = await openN4LPackage(await N4LZipSource.open(await packN4L(files, 'uint8array'))) + expect(pkg.manifest.tasks.map(({ task, key }) => `${task}/${key}`)).toStrictEqual(['tabular-classification/IRIS', 'clustering/IRIS']) + await expect(pkg.source.readText('no-existe.json')).rejects.toThrow(/no tiene no-existe\.json/) + }) +}) + +describe('Formato .n4l: en la aplicación', () => { + test('los menús y /datasets toman sus modelos y conjuntos del catálogo', () => { + expect(taskOptions('tabular-classification', 'model').map(({ value }) => value)).toStrictEqual(['CAR', 'IRIS', 'LYMPHOGRAPHY']) + const iris = taskOptions('tabular-classification', 'dataset').find(({ value }) => value === 'IRIS')! + expect(iris).toMatchObject({ + i18n : 'n4l-iris:tasks.tabular-classification.name', + summary: 'n4l-iris:tasks.tabular-classification.summary', + info : { files: ['n4l/iris.n4l/data/iris.csv'], rows: [150], features: 4, classes: 3 }, + }) + }) + + test('las series temporales, en /datasets con su frecuencia y lo que se predicen (sin columnas de entrada)', () => { + const options = taskOptions('time-series', 'dataset').filter(({ value }) => value !== 'UPLOAD') + expect(options.map(({ value }) => value)).toEqual(['AIRLINE-PASSENGERS', 'MELBOURNE-TEMPERATURES', 'SUNSPOTS']) + expect(options[0].info).toStrictEqual({ + source : 'https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/AirPassengers.html', + files : ['n4l/airline-passengers.n4l/data/airline-passengers.csv'], + rows : [144], + frequency: 'month', + target : 'Passengers', + }) + // Cada una, con su modelo ya entrenado + expect(taskOptions('time-series', 'model').map(({ value }) => value)).toEqual(['AIRLINE-PASSENGERS', 'MELBOURNE-TEMPERATURES', 'SUNSPOTS']) + }) + + test('el iris se comparte: un solo CSV para clasificar y para agrupar', () => { + const classification = taskOptions('tabular-classification', 'dataset').find(({ value }) => value === 'IRIS')! + const clustering = taskOptions('clustering', 'dataset').find(({ value }) => value === 'IRIS')! + expect(clustering).toMatchObject({ i18n: 'n4l-iris:tasks.clustering.name', info: { classes: 3 } }) + expect(clustering.info!.files).toStrictEqual(classification.info!.files) + }) + + test('un fichero de un paquete lleva a su paquete y su conjunto', () => { + const { entry, dataset } = n4lPackageByKey('tabular-classification', 'CAR')! + const file = n4lPublicFile(entry, (dataset as N4LDataset_t).file) + expect(n4lDatasetByFile(file)).toMatchObject({ entry: { id: 'car' }, dataset: { rows: 1728 } }) + expect(n4lDatasetByFile('datasets/ecoli.csv')).toBeUndefined() + }) +}) diff --git a/tests/core/n4lLocalPackages.test.ts b/tests/core/n4lLocalPackages.test.ts new file mode 100644 index 0000000..19a2544 --- /dev/null +++ b/tests/core/n4lLocalPackages.test.ts @@ -0,0 +1,176 @@ +import { describe, test, expect, beforeAll, beforeEach, vi } from 'vitest' +import * as tfjs from '@tensorflow/tfjs' + +import { builtinN4LPackage, n4lPackageByKey } from '@core/n4l/catalog' +import { exportN4LPackage, n4lFileName, n4lPackageFiles } from '@core/n4l/export' +import { + importN4LPackage, listLocalPackages, localKey, localPackageName, MAX_IMPORT_BYTES, MemoryPackageStore, openLocalPackage, + removeLocalPackage, setN4LPackageStore, setN4LTextsRegistry, +} from '@core/n4l/localPackages' +import { N4LZipSource, openN4LPackage, packN4L } from '@core/n4l/source' +import { loadN4LLayersModel } from '@core/n4l/tfjsModel' +import { n4lLayersModels } from '@core/n4l/format' +import { hasModel, loadModelClass } from '@core/models/modelRegistry' +import { createReviewModelInstance } from '@core/models/createReviewModelInstance' +import { MAP_TC_CLASSES } from '@pages/playground/0_TabularClassification/models' +import { trainedModelPackage } from '@core/n4l/exportTrained' +import { DataFrameApplyEncoders } from '@core/dataframe/DataFrameUtils' +import * as fs from 'fs' +import { keyT, n4lTabularModel, stubPublicFetch, toPublicPath } from '../helpers/n4l' + +// En jsdom danfo descarga los CSV por XHR: se leen del disco (o del fichero, si viene de un .n4l) +vi.mock('danfojs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readCSV: (source: string | File, options?: object) => actual.readCSV( + typeof source === 'string' ? new File([fs.readFileSync(toPublicPath(source))], 'data.csv', { type: 'text/csv' }) : source, + options, + ), + } +}) + +const iris = () => builtinN4LPackage(n4lPackageByKey('tabular-classification', 'IRIS')!.entry) + +/** El iris de la aplicación en un .n4l, como lo descargaría el usuario */ +async function irisFile(): Promise { + return (await exportN4LPackage(iris(), 'uint8array')).buffer as ArrayBuffer +} + +beforeAll(async () => { + stubPublicFetch() + await tfjs.setBackend('cpu') +}) + +// Los textos de los paquetes abiertos (en la aplicación, i18next) +const texts = new Map>() + +beforeEach(() => { + setN4LPackageStore(new MemoryPackageStore()) + texts.clear() + setN4LTextsRegistry((language, namespace, bundle) => texts.set(`${language}|${namespace}`, bundle)) +}) + +describe('Paquetes .n4l: descargar', () => { + test('el .n4l lleva todo: manifiesto, textos, datos y el modelo con sus pesos', async () => { + expect((await n4lPackageFiles(iris())).sort()).toStrictEqual([ + 'data/iris.csv', 'data/iris.names', 'locales/en.json', 'locales/es.json', 'locales/ja.json', + 'manifest.json', 'models/mlp/model.json', 'models/mlp/model.weights.bin', + ]) + expect(n4lFileName(iris().manifest)).toBe('iris-1.0.0.n4l') + }) +}) + +describe('Paquetes .n4l: abrir los del usuario', () => { + test('lo descargado se abre, se guarda y sale en el menú de su tarea con su nombre en cada idioma', async () => { + const info = await importN4LPackage(await irisFile()) + expect(info).toMatchObject({ id: 'iris', version: '1.0.0', tasks: [{ task: 'tabular-classification' }] }) + // El agrupamiento todavía no se puede usar con un paquete: no sale + expect(info.tasks.map(({ task }) => task)).not.toContain('clustering') + expect(localPackageName(info, 'tabular-classification', 'es')).toBe('Clasificación de flor iris') + // En un idioma que no tiene, el inglés + expect(localPackageName(info, 'tabular-classification', 'fr')).toBe('Iris classification') + expect((await listLocalPackages('tabular-classification')).map(({ id }) => id)).toStrictEqual(['iris']) + expect(await listLocalPackages('regression')).toStrictEqual([]) + }) + + test('abierto, sus textos van a i18next aparte de los de la aplicación, y su modelo se carga', async () => { + await importN4LPackage(await irisFile()) + const pkg = await openLocalPackage('iris') + expect(pkg.namespace).toBe('n4l-local-iris') + expect(pkg.source.url('manifest.json')).toBeNull() + expect(texts.get('es|n4l-local-iris')!.tasks['tabular-classification'].name).toBe('Clasificación de flor iris') + expect([...texts.keys()].sort()).toStrictEqual(['en|n4l-local-iris', 'es|n4l-local-iris', 'ja|n4l-local-iris']) + const model = await loadN4LLayersModel(pkg.source, n4lLayersModels(pkg.manifest.tasks[0])[0].path) + expect(model.outputs[0].shape).toStrictEqual([null, 3]) + }) + + test('el registro de modelos resuelve local-: la página del modelo lo abre como uno de la aplicación', async () => { + await importN4LPackage(await irisFile()) + expect(hasModel(MAP_TC_CLASSES, localKey('iris'))).toBe(true) + const ModelClass = await loadModelClass(MAP_TC_CLASSES, localKey('iris')) + const instance = new ModelClass(keyT, () => {}) + expect(instance.TITLE).toBe('n4l-local-iris:tasks.tabular-classification.title') + expect(instance.N4L_PACKAGE()?.manifest.id).toBe('iris') + + // Uno que ya no está guardado: como una clave que no existe + await removeLocalPackage('iris') + const navigate = vi.fn() + expect(await createReviewModelInstance(MAP_TC_CLASSES, localKey('iris'), (Model) => new Model(keyT, () => {}), navigate)).toBeNull() + expect(navigate).toHaveBeenCalledWith('/404') + }) + + test('se rechaza lo que no se puede usar, diciendo por qué', async () => { + // Uno no válido + const broken = await packN4L({ 'manifest.json': JSON.stringify({ ...iris().manifest, version: 'uno' }) }, 'uint8array') + await expect(importN4LPackage(broken.buffer as ArrayBuffer)).rejects.toMatchObject({ problems: ['version: semver (1.0.0)'] }) + // Uno solo de agrupamiento (todavía sin motor para paquetes) + const files = Object.fromEntries(await Promise.all((await n4lPackageFiles(iris())).map(async (file) => [file, await iris().source.readBytes(file)] as const))) + const manifest = { ...iris().manifest, tasks: iris().manifest.tasks.filter(({ task }) => task === 'clustering') } + const clustering = await packN4L({ ...files, 'manifest.json': JSON.stringify(manifest) }, 'uint8array') + await expect(importN4LPackage(clustering.buffer as ArrayBuffer)).rejects.toMatchObject({ problems: [expect.stringMatching(/ninguna de sus tareas \(clustering\)/)] }) + // Uno que no es un ZIP, o sin manifiesto + await expect(importN4LPackage(new TextEncoder().encode('hola').buffer as ArrayBuffer)).rejects.toMatchObject({ problems: ['no es un fichero .n4l (un ZIP)'] }) + const empty = await packN4L({ 'leeme.txt': 'hola' }, 'uint8array') + await expect(importN4LPackage(empty.buffer as ArrayBuffer)).rejects.toMatchObject({ problems: ['falta manifest.json'] }) + // Uno demasiado grande + await expect(importN4LPackage(new ArrayBuffer(MAX_IMPORT_BYTES + 1))).rejects.toMatchObject({ problems: ['ocupa más de 100 MB'] }) + expect(await listLocalPackages()).toStrictEqual([]) + }) + + test('volver a abrir uno con el mismo id lo sustituye', async () => { + await importN4LPackage(await irisFile()) + const pkg = await openN4LPackage(await N4LZipSource.open(await irisFile())) + const files = Object.fromEntries(await Promise.all((await n4lPackageFiles(pkg)).map(async (file) => [file, await pkg.source.readBytes(file)] as const))) + const newer = await packN4L({ ...files, 'manifest.json': JSON.stringify({ ...pkg.manifest, version: '1.1.0' }) }, 'uint8array') + await importN4LPackage(newer.buffer as ArrayBuffer) + expect((await listLocalPackages()).map(({ id, version }) => `${id}@${version}`)).toStrictEqual(['iris@1.1.0']) + }) +}) + +describe('Paquetes .n4l: un modelo entrenado en la aplicación', () => { + test('se descarga con su conjunto y se abre después: recibe la entrada escalada, como al entrenarlo', async () => { + // Entrenar como el entrenador: con la entrada preparada (codificada y escalada) y el objetivo en one-hot + const trainer = n4lTabularModel('IRIS') + const [dataset] = await trainer.DATASETS() + const { X, y, classes } = dataset.data_processed! + const model = tfjs.sequential({ layers: [ + tfjs.layers.dense({ inputShape: [4], units: 10, activation: 'relu' }), + tfjs.layers.dense({ units: 3, activation: 'softmax' }), + ] }) + model.compile({ optimizer: tfjs.train.adam(0.05), loss: 'categoricalCrossentropy', metrics: ['accuracy'] }) + await model.fit(tfjs.tensor2d(X.values as number[][]), tfjs.tensor2d(y.values as number[][]), { epochs: 60, verbose: 0 }) + + const { manifest, files } = await trainedModelPackage(iris(), 'tabular-classification', { + model, classes: classes!, number : 2, metrics: { acc: 0.9 }, input : 'scaled', + layers : [{ class: 'dense', units: 10, activation: 'relu' }, { class: 'dense', units: 3, activation: 'softmax' }], + }, (_language, name) => `${name} (#2)`) + expect(manifest).toMatchObject({ id: 'iris-model-2', version: '1.0.0' }) + const section = manifest.tasks.find(({ task }) => task === 'tabular-classification')! + expect(section.models).toStrictEqual([{ id: 'trained', format: 'tfjs-layers', path: 'models/trained/model.json', dataset: 'iris', input: 'scaled', metrics: { acc: 0.9 } }]) + expect(section.training!.layers).toHaveLength(2) + expect(section.classes!.map(({ id }) => id)).toStrictEqual(classes) + // Sin el modelo que traía el paquete + expect(Object.keys(files).filter((file) => file.startsWith('models/')).sort()).toStrictEqual(['models/trained/model.json', 'models/trained/model.weights.bin']) + + const bytes = await packN4L(files, 'uint8array') + await importN4LPackage(bytes.buffer as ArrayBuffer) + const [info] = await listLocalPackages('tabular-classification') + expect(localPackageName(info, 'tabular-classification', 'es')).toBe('Clasificación de flor iris (#2)') + + const ModelClass = await loadModelClass(MAP_TC_CLASSES, localKey('iris-model-2')) + const opened = new ModelClass(keyT, () => {}) + expect(opened.MODEL_INPUT()).toBe('scaled') + const loaded = (await opened.LOAD_LAYERS_MODEL({}))! + const [prepared] = await opened.DATASETS() + // Como la página del modelo: codificar y, por ser «scaled», escalar + const predict = (values: Record) => { + const encoded = DataFrameApplyEncoders(prepared.data_processed!.encoders, values, opened.DATA_DEFAULT_KEYS).map((value) => parseFloat(value.toString())) + const scaled = prepared.data_processed!.scaler.transform(encoded) as number[] + const output = (loaded.predict(tfjs.tensor2d([scaled])) as tfjs.Tensor).dataSync() + return output.indexOf(Math.max(...output)) + } + const hits = opened.LIST_EXAMPLES.filter((values, index) => predict(values) === opened.CLASS_INDEX(opened.LIST_EXAMPLES_RESULTS[index])).length + expect(hits).toBe(opened.LIST_EXAMPLES.length) + }, 60_000) +}) diff --git a/tests/core/nnLabel.test.ts b/tests/core/nnLabel.test.ts index ea3291f..2667dba 100644 --- a/tests/core/nnLabel.test.ts +++ b/tests/core/nnLabel.test.ts @@ -17,7 +17,7 @@ describe('nnLabel', () => { test('las opciones de los selectores usan las mismas etiquetas', () => { expect(TYPE_OPTIMIZER.map((o) => o.label)).toStrictEqual(['SGD', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'RMSProp']) - expect(TYPE_LOSSES.find((o) => o.key === 'softmaxCrossEntropy')?.label).toBe('SoftmaxCrossEntropy') + expect(TYPE_LOSSES.find((o) => o.key === 'categoricalCrossentropy')?.label).toBe('CategoricalCrossentropy') expect(TYPE_METRICS.find((o) => o.key === 'accuracy')?.label).toBe('Accuracy') }) }) diff --git a/tests/core/offline.test.ts b/tests/core/offline.test.ts new file mode 100644 index 0000000..be2a376 --- /dev/null +++ b/tests/core/offline.test.ts @@ -0,0 +1,59 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { pretrainedModelOf } from '@core/models/pretrainedModels' +import { offlineUsage } from '@core/offline/offline' + +describe('pretrainedModelOf: de qué modelo es cada fichero descargado', () => { + test.each([ + ['https://cdn.jsdelivr.net/npm/@mediapipe/face_detection/face_detection_short.binarypb', 'FACE-DETECTOR'], + ['https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/face_mesh_solution_packed_assets.data', 'FACE-MESH'], + ['https://cdn.jsdelivr.net/npm/@mediapipe/hands/hands_solution_simd_wasm_bin.wasm', 'HAND-SIGN'], + ['https://tfhub.dev/google/tfjs-model/movenet/multipose/lightning/1/model.json?tfjs-format=file', 'MOVE-NET--POSE-NET'], + ['https://www.kaggle.com/models/google/movenet/tfJs/multipose-lightning/1/model.json?tfjs-format=file', 'MOVE-NET--POSE-NET'], + ['https://storage.googleapis.com/tfjs-models/savedmodel/ssdlite_mobilenet_v2/model.json', 'COCO-SSD'], + ['https://n4l.test/n4l/models/02-object-detection/face-api-js/v1.7.14/ssd_mobilenetv1_model-shard1', 'FACE-API'], + ['https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/classification/2/model.json?tfjs-format=file', 'IMAGE-MOBILENET'], + ])('%s → %s', (url, key) => { + expect(pretrainedModelOf(url)?.key).toBe(key) + }) + + test('uno que no es de ningún modelo conocido: null', () => { + expect(pretrainedModelOf('https://unpkg.com/otra-cosa/fichero.bin')).toBeNull() + }) +}) + +describe('offlineUsage: lo guardado, con los modelos uno a uno', () => { + afterEach(() => vi.unstubAllGlobals()) + + test('los ficheros de cada modelo, juntos, del que más ocupa al que menos y los desconocidos al final', async () => { + const response = (bytes: number, withLength = true) => + new Response(new Uint8Array(bytes), { headers: withLength ? { 'content-length': String(bytes) } : {} }) + const stores: Record> = { + 'n4l-models-v1': new Map([ + ['https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/a.data', response(300)], + // Sin content-length (comprimido): se mide su contenido + ['https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/b.wasm', response(200, false)], + ['https://storage.googleapis.com/tfjs-models/savedmodel/ssdlite_mobilenet_v2/group1-shard1of5', response(1000)], + ['https://unpkg.com/otra-cosa/fichero.bin', response(5000)], + ]), + 'n4l-runtime-v1': new Map([['https://n4l.test/n4l/assets/index-AbCdEf123456.js', response(50)]]), + 'otra-web' : new Map([['https://otra.test/x', response(7)]]), + } + vi.stubGlobal('caches', { + keys: async () => Object.keys(stores), + open: async (name: string) => ({ + keys : async () => [...stores[name].keys()].map((url) => new Request(url)), + match: async (request: Request) => stores[name].get(request.url)?.clone(), + }), + }) + const usage = await offlineUsage() + expect(usage.files).toBe(5) + expect(usage.bytes).toBe(6550) + expect(usage.models.bytes).toBe(6500) + expect(usage.models.list.map(({ model, files, bytes }) => [model?.key ?? null, files, bytes])).toEqual([ + ['COCO-SSD', 1, 1000], + ['FACE-MESH', 2, 500], + [null, 1, 5000], + ]) + }) +}) diff --git a/tests/core/pageTitle.test.ts b/tests/core/pageTitle.test.ts new file mode 100644 index 0000000..60582b7 --- /dev/null +++ b/tests/core/pageTitle.test.ts @@ -0,0 +1,78 @@ +import fs from 'node:fs' +import path from 'node:path' +import { describe, test, expect } from 'vitest' +import type { TFunction } from 'i18next' + +import { APP_NAME, pageTitle, pageTitleParts } from '@core/pageTitle' + +// Con las traducciones de verdad (en español): así la prueba también falla si una clave del título no existe +const PUBLIC = path.join(__dirname, '..', '..', 'public') +const read = (file: string) => JSON.parse(fs.readFileSync(path.join(PUBLIC, file), 'utf-8')) +const LANGUAGES = ['es', 'en', 'ja'] +const TRANSLATIONS = Object.fromEntries(LANGUAGES.map((language) => [language, read(`locales/${language}/translation.json`)])) + +const lookup = (language: string, fullKey: string): string | undefined => { + // «n4l-:clave»: las traducciones de un paquete .n4l (public/n4l/.n4l/locales) + const [namespace, key] = fullKey.includes(':') ? fullKey.split(':') : [undefined, fullKey] + const root = namespace === undefined ? TRANSLATIONS[language] : read(`n4l/${namespace.slice('n4l-'.length)}.n4l/locales/${language}.json`) + const value = key.split('.').reduce((node, part) => node?.[part], root) + return typeof value === 'string' ? value : undefined +} + +const tIn = (language: string) => ((key: string) => { + const value = lookup(language, key) + if (value === undefined) throw new Error(`falta la traducción «${key}» (${language})`) + return value +}) as unknown as TFunction + +const title = (pathname: string, search = '', language = 'es') => pageTitle(pageTitleParts(pathname, search, tIn(language))) + +describe('pageTitle: el título de cada página (WCAG 2.4.2)', () => { + test.each([ + ['/', '', `Inicio - ${APP_NAME}`], + ['/home', '', `Inicio - ${APP_NAME}`], + ['/manual/', '', `Manual - ${APP_NAME}`], + ['/glossary', '', `Glosario - ${APP_NAME}`], + ['/datasets', '', `Conjuntos de datos - ${APP_NAME}`], + ['/datasets', '?task=time-series', `Conjuntos de datos - Series temporales - ${APP_NAME}`], + ['/packages', '', `Paquetes .n4l - ${APP_NAME}`], + ['/analyze', '', `Analizar conjunto de datos - ${APP_NAME}`], + ['/contribute/', '', `Contribuye - ${APP_NAME}`], + ['/terms-and-conditions', '', `Términos y condiciones - ${APP_NAME}`], + ['/version', '', `Versión - ${APP_NAME}`], + ['/settings', '', `Configuración - ${APP_NAME}`], + ['/accessibility', '', `Accesibilidad - ${APP_NAME}`], + ['/learn', '', `Empieza aquí - ${APP_NAME}`], + ['/report', '', `Informe de entrenamiento - ${APP_NAME}`], + ['/404', '', `Página no encontrada - ${APP_NAME}`], + ['/playground/description-regression', '', `Regresión lineal - ${APP_NAME}`], + ['/task/regression', '', `Regresión - ${APP_NAME}`], + ['/select-model/tabular-classification', '', `Modelos pre-entrenados - Clasificación tabular - ${APP_NAME}`], + ['/select-dataset/clustering', '', `Entrenar un modelo - Agrupamiento - ${APP_NAME}`], + ['/playground/time-series/dataset/UPLOAD', '', `Subir el tuyo - Entrenar un modelo - Series temporales - ${APP_NAME}`], + ['/playground/object-detection/model/COCO-SSD', '', `COCO SSD - Detector de objetos - Modelos pre-entrenados - Identificación de objetos - ${APP_NAME}`], + ])('%s%s', (pathname, search, expected) => { + expect(title(pathname, search)).toBe(expected) + }) + + test('los modelos y conjuntos de los paquetes .n4l llevan su nombre', () => { + expect(title('/playground/time-series/dataset/AIRLINE-PASSENGERS')).toBe(`Pasajeros de avión - Entrenar un modelo - Series temporales - ${APP_NAME}`) + }) + + test('el AED con un conjunto del proyecto lleva su nombre delante', () => { + const parts = pageTitleParts('/analyze', '?dataset=auto-mpg', tIn('es')) + expect(parts).toHaveLength(2) + expect(parts[1]).toBe('Analizar conjunto de datos') + }) + + test('una ruta que no es de ninguna página solo lleva el nombre de la aplicación', () => { + expect(title('/otra-cosa')).toBe(APP_NAME) + }) + + test.each(LANGUAGES)('todas las claves de los títulos están traducidas (%s)', (language) => { + const routes = ['/', '/manual', '/glossary', '/datasets', '/packages', '/analyze', '/contribute', '/terms-and-conditions', + '/version', '/settings', '/learn', '/report', '/404', '/playground/description-regression', '/task/time-series', + '/select-model/image-classification', '/select-dataset/regression', '/playground/regression/dataset/UPLOAD'] + for (const route of routes) expect(() => title(route, '', language), route).not.toThrow() + }) +}) diff --git a/tests/core/seriesModel.test.ts b/tests/core/seriesModel.test.ts new file mode 100644 index 0000000..96aad15 --- /dev/null +++ b/tests/core/seriesModel.test.ts @@ -0,0 +1,83 @@ +import { describe, test, expect, beforeAll } from 'vitest' +import * as tfjs from '@tensorflow/tfjs' + +import { buildSeriesModel, modelFromArtifacts, ModelDefinitionError } from '@core/training/buildModels' +import { trainingWorkerApi } from '@core/training/training.worker' +import type { TrainingProgress_t } from '@core/training/trainingTypes' +import { prepareSeries } from '@core/timeSeries/series' +import { evaluateSeriesModel, forecastFuture } from '@core/timeSeries/seriesModel' +import { checkSeriesLayers } from '@core/nn-utils/checkLayers' +import { SERIES_OUTPUT_LAYER, type SeriesLayer_t } from '@core/timeSeries/seriesLayers' + +// Una onda que se repite cada 12 valores, con algo de tendencia +const SERIES = Array.from({ length: 120 }, (_value, i) => 100 + i / 2 + 20 * Math.sin((2 * Math.PI * i) / 12)) +const PREP = { window: 12, testSize: 20, difference: false } + +describe('Series temporales: la red', () => { + beforeAll(async () => { + await tfjs.setBackend('cpu') + }) + + test('Dense recibe la ventana entera; las recurrentes, como secuencia, y solo la última da un valor por ventana', () => { + const dense = buildSeriesModel([{ _class: 'dense', units: 4, activation: 'relu' }, SERIES_OUTPUT_LAYER], 12) + expect(dense.inputs[0].shape).toEqual([null, 12]) + expect(dense.outputs[0].shape).toEqual([null, 1]) + dense.dispose() + + const recurrent = buildSeriesModel([ + { _class: 'lstm', units: 4, activation: 'tanh' }, + { _class: 'gru', units: 3, activation: 'tanh' }, + SERIES_OUTPUT_LAYER, + ], 12) + expect(recurrent.inputs[0].shape).toEqual([null, 12]) + expect(recurrent.layers.map((layer) => layer.getClassName())).toEqual(['Reshape', 'LSTM', 'GRU', 'Dense']) + expect(recurrent.layers[1].outputShape).toEqual([null, 12, 4]) + expect(recurrent.layers[2].outputShape).toEqual([null, 3]) + recurrent.dispose() + }) + + test('una recurrente después de una Dense no se puede montar, y la comprobación lo arregla poniéndolas delante', () => { + const layers: SeriesLayer_t[] = [{ _class: 'dense', units: 4, activation: 'relu' }, { _class: 'simpleRNN', units: 4, activation: 'tanh' }, SERIES_OUTPUT_LAYER] + expect(() => buildSeriesModel(layers, 12)).toThrow(ModelDefinitionError) + const [issue] = checkSeriesLayers(layers) + expect(issue).toMatchObject({ kind: 'recurrent-after-dense', severity: 'error', layer: 1, values: { type: 'SimpleRNN' } }) + expect(issue.fixed.map(({ _class }) => _class)).toEqual(['simpleRNN', 'dense', 'dense']) + expect(checkSeriesLayers(issue.fixed)).toEqual([]) + expect(checkSeriesLayers([{ _class: 'lstm', units: 0, activation: 'tanh' }, SERIES_OUTPUT_LAYER])[0]).toMatchObject({ kind: 'param', values: { value: 10 } }) + }) + + test('el worker entrena con las ventanas de entrenamiento y valida con las de prueba (sin barajar la serie)', async () => { + const prepared = prepareSeries(SERIES, PREP) + const progress: TrainingProgress_t[] = [] + const result = await trainingWorkerApi.trainSeries({ + backend : 'cpu', + window : PREP.window, + X : new Float32Array(prepared.train.X.flat()), + y : new Float32Array(prepared.train.y), + XTest : new Float32Array(prepared.test.X.flat()), + yTest : new Float32Array(prepared.test.y), + layerList : [{ _class: 'dense', units: 16, activation: 'relu' }, SERIES_OUTPUT_LAYER], + compile : { idOptimizer: 'train-adam', idLoss: 'losses-meanSquaredError', idMetrics: ['metrics-meanAbsoluteError'], learningRate: 0.01 }, + numberOfEpoch: 40, + batchSize : 16, + }, { progress: (data) => progress.push(data as TrainingProgress_t), cancelled: () => false }) + + expect(progress.filter(({ kind }) => kind === 'epoch')).toHaveLength(40) + expect(result.history.history.val_loss).toHaveLength(40) + expect(result.history.history.loss.at(-1)!).toBeLessThan(result.history.history.loss[0]) + + const model = await modelFromArtifacts(result.artifacts) + const evaluation = await evaluateSeriesModel(model, SERIES, prepared) + expect(evaluation.trainOneStep).toHaveLength(prepared.train.targets.length) + expect(evaluation.testOneStep).toHaveLength(24) + expect(evaluation.testRecursive).toHaveLength(24) + // Aprende la onda: a un paso se equivoca menos que repetir el valor anterior (que falla por toda la subida o bajada) + const naive = prepared.test.targets.reduce((sum, t) => sum + Math.abs(SERIES[t] - SERIES[t - 1]), 0) / 24 + expect(evaluation.errors.oneStep.mae).toBeLessThan(naive) + + const future = await forecastFuture(model, SERIES, prepared, 6) + expect(future).toHaveLength(6) + expect(future.every(Number.isFinite)).toBe(true) + model.dispose() + }, 30_000) +}) diff --git a/tests/core/serviceWorker.test.ts b/tests/core/serviceWorker.test.ts new file mode 100644 index 0000000..6197415 --- /dev/null +++ b/tests/core/serviceWorker.test.ts @@ -0,0 +1,133 @@ +import { readFileSync } from 'node:fs' +import { runInNewContext } from 'node:vm' +import { describe, expect, test, vi } from 'vitest' + +// public/sw.js, ejecutado en un contexto aparte con lo que le da el navegador a un service worker: cachés y fetch +// falsos. Así se comprueba a qué caché va cada cosa y qué se vuelve a descargar + +const SCOPE = 'https://n4l.test/n4l/' +const SOURCE = readFileSync('public/sw.js', 'utf8') + +class FakeCache { + entries = new Map() + async match(request: Request | string) { + return this.entries.get(typeof request === 'string' ? request : request.url)?.clone() + } + async put(request: Request | string, response: Response) { + this.entries.set(typeof request === 'string' ? request : request.url, response) + } + async keys() { + return [...this.entries.keys()].map((url) => new Request(url)) + } + async delete(request: Request | string) { + return this.entries.delete(typeof request === 'string' ? request : request.url) + } +} + +function serviceWorker({ modelsOnly = false, caches: initial = {} as Record> } = {}) { + const stores = new Map() + for (const [name, entries] of Object.entries(initial)) { + const cache = new FakeCache() + for (const [url, body] of Object.entries(entries)) cache.entries.set(url, new Response(body)) + stores.set(name, cache) + } + const caches = { + open: async (name: string) => { + if (!stores.has(name)) stores.set(name, new FakeCache()) + return stores.get(name)! + }, + has : async (name: string) => stores.has(name), + keys : async () => [...stores.keys()], + delete: async (name: string) => stores.delete(name), + match : async (request: Request) => { + for (const cache of stores.values()) { + const response = await cache.match(request) + if (response) return response + } + return undefined + }, + } + const network = vi.fn(async (request: Request) => new Response(`red: ${request.url}`)) + const listeners: Record void> = {} + const self = { + location : new URL(`${SCOPE}sw.js${modelsOnly ? '?models' : ''}`), + registration : { scope: SCOPE }, + clients : { claim: async () => undefined }, + skipWaiting : async () => undefined, + addEventListener: (type: string, listener: (event: unknown) => void) => { listeners[type] = listener }, + } + runInNewContext(SOURCE, { self, caches, fetch: network, URL, Request, Response, console }) + + /** Una petición: lo que responde el service worker (null si la deja pasar a la red) */ + async function request(url: string, init: RequestInit = {}) { + let response: Promise | null = null + const waits: Array> = [] + listeners.fetch({ + request : new Request(url, init), + respondWith: (promise: Promise) => { response = promise }, + waitUntil : (promise: Promise) => { waits.push(promise) }, + }) + const result = response === null ? null : await (response as Promise).then((r) => r.text()) + await Promise.all(waits) + return result + } + async function lifecycle(type: 'install' | 'activate') { + let done: Promise = Promise.resolve() + listeners[type]({ waitUntil: (promise: Promise) => { done = promise } }) + await done + } + const urls = (name: string) => [...(stores.get(name)?.entries.keys() ?? [])] + return { request, lifecycle, network, stores, urls } +} + +const MEDIAPIPE = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/face_mesh_solution_packed_assets.data' +const COCO = 'https://storage.googleapis.com/tfjs-models/savedmodel/ssdlite_mobilenet_v2/model.json' +const FACE_API = `${SCOPE}models/02-object-detection/face-api-js/v1.7.14/ssd_mobilenetv1_model-weights_manifest.json` + +describe('public/sw.js: los modelos preentrenados se guardan en el navegador (Cache Storage)', () => { + test('un modelo de otra web se guarda en n4l-models-v1 la primera vez y después no se vuelve a descargar', async () => { + const worker = serviceWorker() + expect(await worker.request(COCO)).toBe(`red: ${COCO}`) + expect(await worker.request(COCO)).toBe(`red: ${COCO}`) + expect(worker.network).toHaveBeenCalledTimes(1) + expect(worker.urls('n4l-models-v1')).toEqual([COCO]) + expect(worker.urls('n4l-runtime-v1')).toEqual([]) + }) + + test('los de la aplicación (face-api) también van a la caché de modelos', async () => { + const worker = serviceWorker() + await worker.request(FACE_API) + expect(worker.urls('n4l-models-v1')).toEqual([FACE_API]) + }) + + test('en desarrollo (sw.js?models): se guardan los modelos y el código se deja pasar a Vite', async () => { + const worker = serviceWorker({ modelsOnly: true }) + await worker.lifecycle('install') + expect(await worker.request(MEDIAPIPE)).toBe(`red: ${MEDIAPIPE}`) + expect(await worker.request(MEDIAPIPE)).toBe(`red: ${MEDIAPIPE}`) + expect(worker.network).toHaveBeenCalledTimes(1) + expect(await worker.request(`${SCOPE}src/main.tsx`)).toBeNull() + expect(await worker.request(SCOPE, { mode: 'same-origin' })).toBeNull() + expect([...worker.stores.keys()]).toEqual(['n4l-models-v1']) + }) + + test('el código de la aplicación sigue en su caché, sin mezclarse con los modelos', async () => { + const worker = serviceWorker() + const asset = `${SCOPE}assets/index-AbCdEf123456.js` + await worker.request(asset) + expect(worker.urls('n4l-runtime-v1')).toEqual([asset]) + expect(worker.urls('n4l-models-v1')).toEqual([]) + }) + + test('al activarse, los modelos que la versión anterior guardaba con todo lo demás pasan a su caché', async () => { + const asset = `${SCOPE}assets/index-AbCdEf123456.js` + const worker = serviceWorker({ caches: { 'n4l-runtime-v1': { [COCO]: 'coco', [asset]: 'código' }, 'n4l-runtime-v0': { [asset]: 'viejo' } } }) + await worker.lifecycle('activate') + expect(worker.urls('n4l-models-v1')).toEqual([COCO]) + expect(worker.urls('n4l-runtime-v1')).toEqual([asset]) + expect(worker.stores.has('n4l-runtime-v0')).toBe(false) + // Y se sirve de ahí, sin descargarlo + expect(await worker.request(COCO)).toBe('coco') + expect(worker.network).not.toHaveBeenCalled() + }) +}) diff --git a/tests/core/stepByStep.test.ts b/tests/core/stepByStep.test.ts new file mode 100644 index 0000000..1a5bb7f --- /dev/null +++ b/tests/core/stepByStep.test.ts @@ -0,0 +1,114 @@ +import { describe, test, expect } from 'vitest' +import { TYPE_ACTIVATION } from '@core/nn-utils/ArchitectureTypesHelper' +import { + backward, countNodes, forward, initNetwork, lossOf, MAX_STEP_NODES, stepPhases, update, + type StepLayer_t, type StepLoss_t, type StepNetwork_t, +} from '@core/nn-utils/stepByStep' + +/** El gradiente de un peso medido a mano: cuánto cambia la pérdida al mover el peso un poquito */ +function numericGradient(network: StepNetwork_t, input: number[], target: number[], kind: StepLoss_t, l: number, j: number, i: number) { + const h = 1e-6 + const shifted = (delta: number) => { + const weights = network.weights.map((layer) => layer.map((row) => [...row])) + weights[l][j][i] += delta + const trace = forward({ ...network, weights }, input) + return lossOf(kind, trace.a.at(-1)!, target) + } + return (shifted(h) - shifted(-h)) / (2 * h) +} + +const INPUT = [0.3, -0.7, 0.9] + +describe('stepByStep: una red pequeña calculada a mano', () => { + // Las activaciones del editor de capas, todas + test.each(TYPE_ACTIVATION.map(({ key }) => key))('la retropropagación con %s da los mismos gradientes que medirlos a mano', (activation) => { + const kind: StepLoss_t = activation === 'softmax' ? 'cross-entropy' : 'mse' + const layers: StepLayer_t[] = [{ units: 4, activation }, { units: 2, activation: kind === 'cross-entropy' ? 'softmax' : 'linear' }] + const network = initNetwork(3, layers, 7) + const target = kind === 'cross-entropy' ? [0, 1] : [0.4, -0.2] + const gradients = backward(network, forward(network, INPUT), target, kind) + for (const [l, j, i] of [[0, 0, 0], [0, 3, 2], [1, 1, 3], [1, 0, 1]]) { + expect(gradients.gradWeights[l][j][i]).toBeCloseTo(numericGradient(network, INPUT, target, kind, l, j, i), 5) + } + }) + + test('con softmax y entropía cruzada, el delta de la salida es probabilidad menos objetivo', () => { + const network = initNetwork(3, [{ units: 5, activation: 'relu' }, { units: 3, activation: 'softmax' }]) + const trace = forward(network, INPUT) + const target = [0, 0, 1] + const { deltas } = backward(network, trace, target, 'cross-entropy') + trace.a[1].forEach((p, k) => expect(deltas[1][k]).toBeCloseTo(p - target[k], 10)) + // Las probabilidades suman 1 + expect(trace.a[1].reduce((sum, p) => sum + p, 0)).toBeCloseTo(1, 10) + }) + + test('un paso de descenso del gradiente baja la pérdida de ese ejemplo', () => { + for (const kind of ['cross-entropy', 'mse'] as const) { + const layers: StepLayer_t[] = [{ units: 6, activation: 'tanh' }, { units: kind === 'mse' ? 1 : 3, activation: kind === 'mse' ? 'linear' : 'softmax' }] + const network = initNetwork(3, layers) + const target = kind === 'mse' ? [0.8] : [1, 0, 0] + const trace = forward(network, INPUT) + const before = lossOf(kind, trace.a.at(-1)!, target) + const after = update(network, backward(network, trace, target, kind), 0.1) + expect(lossOf(kind, forward(after, INPUT).a.at(-1)!, target)).toBeLessThan(before) + // La red de antes no cambia: cada paso se puede volver a enseñar + expect(forward(network, INPUT).a).toEqual(trace.a) + } + }) + + test('los pesos iniciales son los mismos con la misma semilla, y del tamaño de cada capa', () => { + const layers: StepLayer_t[] = [{ units: 10, activation: 'relu' }, { units: 3, activation: 'softmax' }] + expect(initNetwork(4, layers, 1)).toEqual(initNetwork(4, layers, 1)) + expect(initNetwork(4, layers, 1).weights).not.toEqual(initNetwork(4, layers, 2).weights) + const { weights, biases } = initNetwork(4, layers) + expect(weights.map((layer) => [layer.length, layer[0].length])).toEqual([[10, 4], [3, 10]]) + expect(biases).toEqual([new Array(10).fill(0), new Array(3).fill(0)]) + // Glorot uniforme: |w| ≤ √(6 / (entradas + salidas)) + expect(Math.max(...weights[0].flat().map(Math.abs))).toBeLessThanOrEqual(Math.sqrt(6 / 14)) + }) + + test('cuenta los nodos de la red (entradas y neuronas) y el límite es 64', () => { + // IRIS por defecto: 4 entradas, 10 + 10 + 3 neuronas + expect(countNodes(4, [{ units: 10, activation: 'relu' }, { units: 10, activation: 'relu' }, { units: 3, activation: 'softmax' }])).toBe(27) + expect(MAX_STEP_NODES).toBe(64) + }) + + test('las fases: entrada, cada capa hacia delante, error, cada capa hacia atrás desde la salida y actualización', () => { + expect(stepPhases(2)).toEqual([ + { kind: 'input' }, + { kind: 'forward', layer: 0 }, + { kind: 'forward', layer: 1 }, + { kind: 'loss' }, + { kind: 'backward', layer: 1 }, + { kind: 'backward', layer: 0 }, + { kind: 'update' }, + ]) + }) +}) + +describe('networkFromModel: los pesos de un modelo de TF.js ya entrenado', () => { + test('con sus pesos, el paso hacia delante da lo mismo que model.predict', async () => { + const tf = await import('@tensorflow/tfjs') + const { networkFromModel } = await import('@core/nn-utils/stepByStepModel') + await tf.setBackend('cpu') + const model = tf.sequential({ + layers: [ + tf.layers.dense({ inputShape: [3], units: 4, activation: 'tanh' }), + tf.layers.dense({ units: 2, activation: 'softmax' }), + ], + }) + const network = await networkFromModel(model) + expect(network).not.toBeNull() + expect(network!.inputs).toBe(3) + expect(network!.layers).toEqual([{ units: 4, activation: 'tanh' }, { units: 2, activation: 'softmax' }]) + const expected = Array.from(await (model.predict(tf.tensor2d([INPUT])) as import('@tensorflow/tfjs').Tensor).data()) + forward(network!, INPUT).a.at(-1)!.forEach((value, k) => expect(value).toBeCloseTo(expected[k], 5)) + }) + + test('una red que no es solo de capas densas no se puede enseñar así', async () => { + const tf = await import('@tensorflow/tfjs') + const { networkFromModel } = await import('@core/nn-utils/stepByStepModel') + const model = tf.sequential({ layers: [tf.layers.flatten({ inputShape: [2, 2] }), tf.layers.dense({ units: 2 })] }) + expect(await networkFromModel(model)).toBeNull() + }) +}) diff --git a/tests/core/tfBackend.test.ts b/tests/core/tfBackend.test.ts new file mode 100644 index 0000000..aed968d --- /dev/null +++ b/tests/core/tfBackend.test.ts @@ -0,0 +1,173 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest' + +// TF.js de mentira: setBackend falla con los backends de `failing` +const { failing, setBackend } = vi.hoisted(() => { + const failing = new Set() + return { failing, setBackend: vi.fn(async (backend: string) => !failing.has(backend)) } +}) +vi.mock('@tensorflow/tfjs', () => ({ setBackend })) +vi.mock('@tensorflow/tfjs-backend-webgpu', () => ({})) +vi.mock('@tensorflow/tfjs-backend-wasm', () => ({ setWasmPaths: vi.fn() })) + +const { changeUserTFBackend, detectTFBackend, getActiveTFBackend } = await import('../../src/core/tfBackend') + +describe('detectTFBackend', () => { + + test('manda el backend que eligió el usuario', () => { + expect(detectTFBackend('wasm')).toBe('wasm') + expect(detectTFBackend('cpu')).toBe('cpu') + }) + + test('sin elección guardada, el de TF.js', () => { + expect(detectTFBackend(null)).toBe('webgl') + }) + + test('una elección guardada que no es un backend se ignora', () => { + expect(detectTFBackend('tensorflow')).toBe('webgl') + expect(detectTFBackend('')).toBe('webgl') + }) +}) + +describe('changeUserTFBackend', () => { + + beforeEach(() => { + failing.clear() + setBackend.mockClear() + localStorage.clear() + }) + + test('activa el backend y lo recuerda', async () => { + expect(await changeUserTFBackend('cpu')).toBe(true) + expect(setBackend).toHaveBeenLastCalledWith('cpu') + expect(getActiveTFBackend()).toBe('cpu') + expect(localStorage.getItem('tf-backend')).toBe('cpu') + }) + + test('si el navegador no puede usarlo, vuelve al anterior y no lo recuerda', async () => { + await changeUserTFBackend('cpu') + failing.add('wasm') + + expect(await changeUserTFBackend('wasm')).toBe(false) + expect(setBackend).toHaveBeenLastCalledWith('cpu') + expect(getActiveTFBackend()).toBe('cpu') + expect(localStorage.getItem('tf-backend')).toBe('cpu') + }) + + test('runWithTFBackend usa otro backend solo mientras dura y no lo recuerda', async () => { + const { runWithTFBackend } = await import('../../src/core/tfBackend') + await changeUserTFBackend('webgl') + setBackend.mockClear() + expect(await runWithTFBackend('cpu', async () => 'medido')).toBe('medido') + expect(setBackend.mock.calls).toEqual([['cpu'], ['webgl']]) + expect(getActiveTFBackend()).toBe('webgl') + expect(localStorage.getItem('tf-backend')).toBe('webgl') + }) + + test('runWithTFBackend devuelve null si no se puede usar el backend, y vuelve aunque fn falle', async () => { + const { runWithTFBackend } = await import('../../src/core/tfBackend') + await changeUserTFBackend('webgl') + failing.add('wasm') + expect(await runWithTFBackend('wasm', async () => 'nunca')).toBeNull() + setBackend.mockClear() + await expect(runWithTFBackend('cpu', async () => { throw new Error('falla') })).rejects.toThrow('falla') + expect(setBackend).toHaveBeenLastCalledWith('webgl') + // Los cambios siguientes se siguen haciendo + expect(await changeUserTFBackend('cpu')).toBe(true) + }) + + test('dos cambios seguidos se aplican en orden', async () => { + await Promise.all([changeUserTFBackend('webgl'), changeUserTFBackend('cpu')]) + expect(setBackend.mock.calls.map(([backend]) => backend)).toEqual(['webgl', 'cpu']) + expect(getActiveTFBackend()).toBe('cpu') + }) +}) + +describe('startupTFBackend', () => { + + beforeEach(() => { + // Cada prueba arranca la aplicación de cero + vi.resetModules() + failing.clear() + setBackend.mockClear() + localStorage.clear() + }) + + test('sin elección guardada no hay nada que esperar ni se carga TF.js', async () => { + const { startupTFBackend } = await import('../../src/core/tfBackend') + expect(startupTFBackend()).toBeNull() + expect(setBackend).not.toHaveBeenCalled() + }) + + test('activa el backend guardado una sola vez', async () => { + localStorage.setItem('tf-backend', 'wasm') + const { startupTFBackend, getActiveTFBackend } = await import('../../src/core/tfBackend') + const startup = startupTFBackend() + expect(getActiveTFBackend()).toBe('wasm') + expect(startupTFBackend()).toBe(startup) + await startup + expect(setBackend.mock.calls).toEqual([['wasm']]) + }) + + test('si el guardado ya no se puede usar, sigue con el de por defecto sin olvidar la elección', async () => { + localStorage.setItem('tf-backend', 'webgpu') + failing.add('webgpu') + const { startupTFBackend, getActiveTFBackend } = await import('../../src/core/tfBackend') + await startupTFBackend() + expect(setBackend).toHaveBeenLastCalledWith('webgl') + expect(getActiveTFBackend()).toBe('webgl') + expect(localStorage.getItem('tf-backend')).toBe('webgpu') + }) +}) + +describe('WebGPU', () => { + + // requestAdapter() devuelve, por orden, cada valor de `adapters` (el último se repite) + const setGPU = (...adapters: unknown[]) => { + const requestAdapter = vi.fn(async () => adapters.length > 1 ? adapters.shift() : adapters[0]) + Object.defineProperty(navigator, 'gpu', { configurable: true, value: { requestAdapter } }) + return requestAdapter + } + + beforeEach(() => { + // La comprobación del adaptador se hace una vez por visita: cada prueba carga el módulo de cero + vi.resetModules() + failing.clear() + setBackend.mockClear() + localStorage.clear() + }) + + afterEach(() => { + delete (navigator as { gpu?: unknown }).gpu + }) + + test('sin adaptador no se le pasa a TF.js', async () => { + setGPU(null) + const { changeUserTFBackend, detectWebGPUAdapter } = await import('../../src/core/tfBackend') + expect(await detectWebGPUAdapter()).toBeNull() + expect(await changeUserTFBackend('webgpu')).toBe(false) + expect(setBackend.mock.calls).toEqual([['webgl']]) + }) + + test('con adaptador se activa', async () => { + setGPU({ info: { isFallbackAdapter: false } }) + const { changeUserTFBackend, detectWebGPUAdapter, getActiveTFBackend } = await import('../../src/core/tfBackend') + expect(await detectWebGPUAdapter()).toBe('hardware') + expect(await changeUserTFBackend('webgpu')).toBe(true) + expect(setBackend).toHaveBeenLastCalledWith('webgpu') + expect(getActiveTFBackend()).toBe('webgpu') + }) + + test('pide la GPU de alto rendimiento, como TF.js, y repite si la primera petición no da adaptador', async () => { + const requestAdapter = setGPU(null, {}) + const { detectWebGPUAdapter } = await import('../../src/core/tfBackend') + expect(await detectWebGPUAdapter()).toBe('hardware') + expect(requestAdapter.mock.calls).toEqual([[{ powerPreference: 'high-performance' }], [{ powerPreference: 'high-performance' }]]) + }) + + test('el adaptador de SwiftShader (la GPU emulada en la CPU) se distingue, pero se puede usar', async () => { + setGPU({ info: { isFallbackAdapter: true } }) + const { changeUserTFBackend, detectWebGPUAdapter } = await import('../../src/core/tfBackend') + expect(await detectWebGPUAdapter()).toBe('software') + expect(await changeUserTFBackend('webgpu')).toBe(true) + }) +}) diff --git a/tests/core/theme.test.ts b/tests/core/theme.test.ts new file mode 100644 index 0000000..e9c2a76 --- /dev/null +++ b/tests/core/theme.test.ts @@ -0,0 +1,20 @@ +import { describe, test, expect } from 'vitest' +import { detectTheme } from '../../src/core/theme' + +describe('detectTheme', () => { + + test('manda el tema que eligió el usuario', () => { + expect(detectTheme('light', true)).toBe('light') + expect(detectTheme('dark', false)).toBe('dark') + }) + + test('sin elección guardada, el tema del sistema', () => { + expect(detectTheme(null, true)).toBe('dark') + expect(detectTheme(null, false)).toBe('light') + }) + + test('una elección guardada que no es un tema se ignora', () => { + expect(detectTheme('sepia', true)).toBe('dark') + expect(detectTheme('', false)).toBe('light') + }) +}) diff --git a/tests/core/timeSeries.test.ts b/tests/core/timeSeries.test.ts new file mode 100644 index 0000000..977ee66 --- /dev/null +++ b/tests/core/timeSeries.test.ts @@ -0,0 +1,150 @@ +import { describe, test, expect } from 'vitest' + +import { + baselineErrors, + canPrepare, + fitScale, + forecastErrors, + inferFrequency, + naiveMultiStep, + naiveOneStep, + nextDates, + oneStepValues, + prepareSeries, + readSeries, + recursiveForecast, + seasonalMultiStep, + seasonalOneStep, + testStartOf, + unscaleValue, +} from '@core/timeSeries/series' +import { initialPrep, seriesLayersOf } from '@pages/playground/5_TimeSeries/timeSeriesConfig' + +const range = (length: number, f: (i: number) => number = (i) => i) => Array.from({ length }, (_value, i) => f(i)) + +describe('Series temporales: de la serie a las ventanas', () => { + test('cada ejemplo son los valores anteriores y el siguiente; la prueba es lo último, sin barajar', () => { + const values = range(20, (i) => 10 + i) + const prepared = prepareSeries(values, { window: 3, testSize: 20, difference: false }) + expect(prepared.testStart).toBe(16) + expect(prepared.train.targets).toEqual(range(13, (i) => 3 + i)) + expect(prepared.test.targets).toEqual([16, 17, 18, 19]) + // Escalado con el entrenamiento (10…25): la prueba (26…29) se sale de 0–1 + expect(prepared.scale).toEqual({ min: 10, max: 25 }) + expect(prepared.train.X[0]).toEqual([0, 1 / 15, 2 / 15]) + expect(prepared.train.y[0]).toBeCloseTo(3 / 15) + expect(prepared.test.y.at(-1)).toBeCloseTo(19 / 15) + }) + + test('al diferenciar, la red ve y predice cambios; con lo que predice se vuelve a los valores', () => { + const values = [1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120] + const prep = { window: 2, testSize: 20, difference: true } + const prepared = prepareSeries(values, prep) + // El primero que se puede predecir es el 3: necesita dos cambios antes (el 1.º valor no tiene anterior) + expect(prepared.train.targets[0]).toBe(3) + expect(prepared.scale).toEqual(fitScale(values, prepared.testStart, true)) + // Si la red acertara (lo que predice es su objetivo), se recuperan los valores reales + const recovered = oneStepValues(values, prepared.test.targets, prepared.test.y, prep, prepared.scale) + prepared.test.targets.forEach((t, i) => expect(recovered[i]).toBeCloseTo(values[t])) + expect(unscaleValue(prepared.train.y[0], prepared.scale)).toBeCloseTo(values[3] - values[2]) + }) + + test('la predicción recursiva usa lo ya predicho: una red que siempre predice «+1» sigue la recta', async () => { + const values = range(30) + const prep = { window: 4, testSize: 20, difference: true } + const { scale } = prepareSeries(values, prep) + // Todos los cambios del entrenamiento valen 1: el escalado lo deja en 0 (min = 1, max = 2) + const seen: number[][] = [] + const forecast = await recursiveForecast(values, 30, 5, prep, scale, (window) => { + seen.push(window) + return 0 + }) + expect(forecast).toEqual([30, 31, 32, 33, 34]) + expect(seen).toHaveLength(5) + }) + + test('si no quedan ventanas para entrenar o valores para probar, no se puede preparar', () => { + expect(canPrepare(144, { window: 24, testSize: 20, difference: false })).toBe(true) + expect(canPrepare(30, { window: 24, testSize: 20, difference: false })).toBe(false) + expect(testStartOf(10, 1)).toBe(9) + }) +}) + +describe('Series temporales: errores y líneas base', () => { + const values = [10, 12, 14, 11, 13, 15, 12, 14, 16] + + test('MAE y RMSE en las unidades de la serie', () => { + expect(forecastErrors([1, 2, 3], [2, 2, 1])).toEqual({ mae: 1, rmse: Math.sqrt(5 / 3) }) + expect(forecastErrors([], []).mae).toBeNaN() + }) + + test('la ingenua repite el anterior y la estacional el de hace una estación', () => { + expect(naiveOneStep(values, [6, 7, 8])).toEqual([15, 12, 14]) + expect(seasonalOneStep(values, [6, 7, 8], 3)).toEqual([11, 13, 15]) + expect(naiveMultiStep(values, 6, 3)).toEqual([15, 15, 15]) + expect(seasonalMultiStep(values, 6, 4, 3)).toEqual([11, 13, 15, 11]) + // Sin una estación entera antes, la ingenua + expect(seasonalMultiStep(values, 2, 2, 3)).toEqual([12, 12]) + }) + + test('con la prueba de la preparación: a un paso y seguidas; sin estación, solo la ingenua', () => { + const prepared = prepareSeries(range(40, (i) => i % 4), { window: 4, testSize: 20, difference: false }) + const errors = baselineErrors(range(40, (i) => i % 4), prepared, 4) + expect(errors.oneStep.seasonal?.mae).toBe(0) + expect(errors.recursive.seasonal?.mae).toBe(0) + expect(errors.oneStep.naive.mae).toBeGreaterThan(0) + expect(baselineErrors(range(40), prepared).oneStep.seasonal).toBeUndefined() + }) +}) + +describe('Series temporales: leer la serie, su frecuencia y las fechas siguientes', () => { + test('sin las filas sin número, ordenada por fecha y, sin fecha, numerada', () => { + const rows = [['1949-03', '132'], ['1949-01', '112'], ['1949-02', ''], ['1949-04', 'x'], ['1949-05', 121]] + expect(readSeries(['Month', 'Passengers'], rows, 'Passengers', 'Month')).toEqual({ + dates: ['1949-01', '1949-03', '1949-05'], values: [112, 132, 121], dropped: 2, sorted: true, + }) + expect(readSeries(['a', 'b'], [[1, 5], [2, 6]], 'b', null)).toEqual({ dates: ['1', '2'], values: [5, 6], dropped: 0, sorted: false }) + }) + + test('la frecuencia sale de lo que hay entre dos fechas', () => { + expect(inferFrequency(['1949-01', '1949-02', '1949-03', '1949-04'])).toBe('month') + expect(inferFrequency(['1981-01-01', '1981-01-02', '1981-01-03'])).toBe('day') + expect(inferFrequency(['2024-01-01 10:00', '2024-01-01 11:00', '2024-01-01 12:00'])).toBe('hour') + expect(inferFrequency(['1749', '1750', '1751'])).toBe('year') + // Números de fila, no fechas + expect(inferFrequency(['1', '2', '3'])).toBeUndefined() + expect(inferFrequency(['a', 'b', 'c'])).toBeUndefined() + }) + + test('las fechas que siguen, con el mismo formato; si no se sabe, +1, +2…', () => { + expect(nextDates('1960-11', 'month', 3)).toEqual(['1960-12', '1961-01', '1961-02']) + expect(nextDates('1990-12-30', 'day', 3)).toEqual(['1990-12-31', '1991-01-01', '1991-01-02']) + expect(nextDates('2024-02-28', 'week', 1)).toEqual(['2024-03-06']) + expect(nextDates('2023-12', 'quarter', 2)).toEqual(['2024-03', '2024-06']) + expect(nextDates('2024-01-01T23:00', 'hour', 2)).toEqual(['2024-01-02T00:00', '2024-01-02T01:00']) + expect(nextDates('1983', 'year', 2)).toEqual(['1984', '1985']) + expect(nextDates('144', undefined, 2)).toEqual(['+1', '+2']) + }) +}) + +describe('Series temporales: con qué se empieza', () => { + test('la preparación del paquete o, al subir una serie, una ventana de una estación según su frecuencia', () => { + expect(initialPrep(144, 'month', { window: 24, season: 12 })).toEqual({ prep: { window: 24, testSize: 20, difference: false }, season: 12 }) + expect(initialPrep(500, 'day')).toEqual({ prep: { window: 7, testSize: 20, difference: false }, season: 7 }) + expect(initialPrep(500, undefined)).toEqual({ prep: { window: 12, testSize: 20, difference: false }, season: undefined }) + // Con pocos datos, una ventana más corta + expect(initialPrep(25, 'month').prep.window).toBe(6) + }) + + test('las capas del manifiesto: la salida, protegida; las recurrentes, con tanh si no dicen otra', () => { + expect(seriesLayersOf([ + { class: 'lstm', units: 16 }, + { class: 'dense', units: 8, activation: 'relu' }, + { class: 'dense', units: 1, activation: 'linear', locked: true }, + ])).toEqual([ + { _class: 'lstm', units: 16, activation: 'tanh' }, + { _class: 'dense', units: 8, activation: 'relu' }, + { _class: 'dense', units: 1, activation: 'linear', is_disabled: true }, + ]) + }) +}) diff --git a/tests/core/trainDenseModel.test.ts b/tests/core/trainDenseModel.test.ts index 959cbb4..90b6f71 100644 --- a/tests/core/trainDenseModel.test.ts +++ b/tests/core/trainDenseModel.test.ts @@ -36,17 +36,35 @@ describe('trainDenseModel', () => { test('entrena con y en one-hot (clasificación) y devuelve modelo e historial', async () => { const y = new dfd.DataFrame({ c0: [1, 1, 1, 0, 0, 0, 1, 0, 1, 0], c1: [0, 0, 0, 1, 1, 1, 0, 1, 0, 1] }) - const { model, history } = await trainDenseModel(params(dataset(y))) + const { model, history, evaluation } = await trainDenseModel(params(dataset(y))) expect(model.layers).toHaveLength(2) expect(history.epoch).toStrictEqual([0, 1]) + // Clase real y predicha de cada ejemplo de validación (el 20 % de 10 filas) + expect(evaluation?.labels).toHaveLength(2) + expect(evaluation?.predictions).toHaveLength(2) }) test('entrena con y numérica (regresión)', async () => { const y = new dfd.Series([1, 2, 3, 4, 5, 6, 1.5, 5.5, 2.5, 4.5]) const p = params(dataset(y)) p.layerList = [{ units: 4, activation: 'relu' }, { units: 1, activation: 'linear' }] - const { history } = await trainDenseModel(p) + const { history, evaluation } = await trainDenseModel(p) expect(history.history.loss).toHaveLength(2) + expect(evaluation).toBeUndefined() + }) + + test('avisa al acabar cada época y se detiene cuando se le pide', async () => { + const y = new dfd.Series([1, 2, 3, 4, 5, 6, 1.5, 5.5, 2.5, 4.5]) + const p = params(dataset(y)) + p.layerList = [{ units: 4, activation: 'relu' }, { units: 1, activation: 'linear' }] + p.numberOfEpoch = 10 + const onEpochEnd = vi.fn() + // Se pide parar al acabar la tercera época + p.onEpochEnd = onEpochEnd + p.shouldStop = () => onEpochEnd.mock.calls.length >= 3 + const { history } = await trainDenseModel(p) + expect(onEpochEnd.mock.calls.slice(0, 3)).toStrictEqual([[1, 10], [2, 10], [3, 10]]) + expect(history.epoch).toHaveLength(3) }) test('rechaza una capa sin activación válida', async () => { diff --git a/tests/core/trainResult.test.ts b/tests/core/trainResult.test.ts new file mode 100644 index 0000000..8149600 --- /dev/null +++ b/tests/core/trainResult.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, test } from 'vitest' + +import { evaluationAccuracy, trainResult } from '@core/training/trainResult' + +describe('trainResult: cómo terminó un entrenamiento, en números', () => { + test('aciertos con los datos de prueba', () => { + expect(evaluationAccuracy({ labels: [0, 1, 2, 2], predictions: [0, 1, 1, 2] })).toBe(0.75) + expect(evaluationAccuracy({ labels: [], predictions: [] })).toBeUndefined() + }) + + test('neuronas ocultas (sin la salida), capas, épocas y diagnóstico', () => { + const result = trainResult({ + history : { loss: [1, 0.8, 0.6, 0.45, 0.35], val_loss: [1, 0.82, 0.66, 0.5, 0.4] }, + layers : [{ _class: 'dense', units: 8 }, { _class: 'dense', units: 4 }, { _class: 'dense', units: 3 }], + evaluation: { labels: [0, 1], predictions: [0, 1] }, + }) + expect(result).toEqual({ accuracy: 1, hidden_units: 12, layers: 3, epochs: 5, diagnosis: 'still-improving' }) + }) + + test('red de imágenes: solo cuentan las dense ocultas; regresión, sin aciertos', () => { + const image = trainResult({ + history: { loss: [1, 0.5] }, + layers : [{ _class: 'conv2d' }, { _class: 'flatten' }, { _class: 'dense', units: 32 }, { _class: 'dense', units: 10 }], + }) + expect(image.hidden_units).toBe(32) + expect(image).not.toHaveProperty('accuracy') + // Sin _class (regresión): dense + expect(trainResult({ history: { loss: [1] }, layers: [{ units: 5 }, { units: 1 }] }).hidden_units).toBe(5) + }) +}) diff --git a/tests/core/trainingReport.test.ts b/tests/core/trainingReport.test.ts new file mode 100644 index 0000000..b89ec84 --- /dev/null +++ b/tests/core/trainingReport.test.ts @@ -0,0 +1,36 @@ +import { afterEach, describe, expect, test } from 'vitest' + +import { historyNumbers, readReport, REPORT_STORAGE_KEY, saveReport, type TrainingReport_t } from '@core/report/trainingReport' + +const report: TrainingReport_t = { + version : 1, + task : 'tabular-classification', + dataset : 'IRIS', + model : 2, + createdAt : '2026-10-03T10:00:00.000Z', + layers : ['Dense, 10 neuronas, ReLU', 'Dense, 3 neuronas, Softmax'], + parameters: { 'learning-rate': '0.01', 'n-of-epochs': '20' }, + history : { loss: [1, 0.5], val_loss: [1.1, 0.6] }, + evaluation: { classes: ['a', 'b'], labels: [0, 1], predictions: [0, 0] }, +} + +describe('trainingReport: el informe de un modelo, de la tabla a /report', () => { + afterEach(() => localStorage.clear()) + + test('se guarda y se lee igual', () => { + expect(saveReport(report)).toBe(true) + expect(readReport()).toStrictEqual(report) + }) + + test('sin informe, o con uno de otra versión o roto, no hay nada que enseñar', () => { + expect(readReport()).toBeNull() + localStorage.setItem(REPORT_STORAGE_KEY, JSON.stringify({ ...report, version: 2 })) + expect(readReport()).toBeNull() + localStorage.setItem(REPORT_STORAGE_KEY, '{roto') + expect(readReport()).toBeNull() + }) + + test('el historial de TF.js, en números', () => { + expect(historyNumbers({ loss: [1, 0.5], acc: [0.5, 0.9] })).toStrictEqual({ loss: [1, 0.5], acc: [0.5, 0.9] }) + }) +}) diff --git a/tests/core/trainingSession.test.ts b/tests/core/trainingSession.test.ts new file mode 100644 index 0000000..c40783f --- /dev/null +++ b/tests/core/trainingSession.test.ts @@ -0,0 +1,52 @@ +import { describe, test, expect } from 'vitest' +import { parseSession, sessionFileName, sessionFromHash, sessionHash, type TrainingSession_t } from '../../src/core/session/trainingSession' + +const session: TrainingSession_t = { + app : 'nets4learning', + version : 1, + task : 'tabular-classification', + dataset : 'IRIS', + layers : [{ _class: 'dense', units: 10, activation: 'relu' }, { _class: 'dense', units: 3, activation: 'softmax' }], + hyperparameters: { learningRate: 0.01, epochs: 30, testSize: 10, optimizer: 'adam', loss: 'losses-categoricalCrossentropy', metrics: ['categoricalAccuracy'] }, +} + +describe('trainingSession', () => { + test('una sesión exportada se vuelve a importar igual', () => { + expect(parseSession(JSON.stringify(session), 'tabular-classification')).toStrictEqual(session) + }) + + test('el nombre del fichero lleva la tarea y el dataset', () => { + expect(sessionFileName(session)).toBe('nets4learning-tabular-classification-iris.json') + }) + + test('rechaza ficheros que no son una sesión de esta tarea', () => { + expect(() => parseSession('no es json', 'tabular-classification')).toThrow('session.error-not-json') + expect(() => parseSession('{"a": 1}', 'tabular-classification')).toThrow('session.error-not-session') + expect(() => parseSession(JSON.stringify(session), 'regression')).toThrow('session.error-other-task') + expect(() => parseSession(JSON.stringify({ ...session, layers: [] }), 'tabular-classification')).toThrow('session.error-not-session') + const badEpochs = { ...session, hyperparameters: { ...session.hyperparameters, epochs: '30' } } + expect(() => parseSession(JSON.stringify(badEpochs), 'tabular-classification')).toThrow('session.error-not-session') + }) + + test('enlace para compartir: la sesión va comprimida tras #n4z= y se recupera igual (también con caracteres no ASCII)', async () => { + const hash = await sessionHash(session) + expect(hash).toMatch(/^#n4z=[A-Za-z0-9_-]+$/) + expect(hash.length).toBeLessThan(JSON.stringify(session).length) + expect(parseSession((await sessionFromHash(hash))!, 'tabular-classification')).toStrictEqual(session) + + const japanese = { ...session, dataset: 'お試し' } + expect(JSON.parse((await sessionFromHash(await sessionHash(japanese)))!)).toStrictEqual(japanese) + }) + + test('sin compresión en el navegador: el JSON tal cual tras #n4l=, que también se lee', async () => { + const plain = '#n4l=' + btoa(JSON.stringify(session)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') + expect(parseSession((await sessionFromHash(plain))!, 'tabular-classification')).toStrictEqual(session) + }) + + test('enlace sin sesión (otro #) o cortado', async () => { + expect(await sessionFromHash('')).toBeNull() + expect(await sessionFromHash('#modelos')).toBeNull() + await expect(sessionFromHash('#n4l=%%%')).rejects.toThrow('session.error-link') + await expect(sessionFromHash((await sessionHash(session)).slice(0, 40))).rejects.toThrow('session.error-link') + }) +}) diff --git a/tests/core/trainingSummary.test.ts b/tests/core/trainingSummary.test.ts new file mode 100644 index 0000000..e21fc10 --- /dev/null +++ b/tests/core/trainingSummary.test.ts @@ -0,0 +1,65 @@ +import { describe, test, expect } from 'vitest' +import { bestModelIndex, changedParameters, confusionMatrix, confusionStats, finalLoss, formatEpochs, historyCurves } from '../../src/core/history/trainingSummary' + +describe('trainingSummary', () => { + test('una curva por métrica, con la pérdida primero y su validación', () => { + const curves = historyCurves({ acc: [0.5, 0.8], loss: [1, 0.5], val_loss: [1.2, 0.7], val_acc: [0.4, 0.7], mse: [3, 2] }) + expect(curves.map(({ name }) => name)).toStrictEqual(['loss', 'acc', 'mse']) + expect(curves[0]).toStrictEqual({ name: 'loss', train: [1, 0.5], validation: [1.2, 0.7] }) + expect(curves[2].validation).toBeNull() + }) + + test('la pérdida final es la de validación de la última época, o la de entrenamiento si no hay', () => { + expect(finalLoss({ loss: [1, 0.5], val_loss: [1.2, 0.7] })).toBe(0.7) + expect(finalLoss({ loss: [1, 0.5] })).toBe(0.5) + expect(finalLoss({ acc: [0.5] })).toBeNull() + }) + + test('el mejor modelo es el de menor pérdida final', () => { + expect(bestModelIndex([{ val_loss: [0.9] }, { val_loss: [0.3] }, { val_loss: [0.5] }])).toBe(1) + expect(bestModelIndex([{ acc: [0.5] }])).toBe(-1) + }) + + test('las épocas de un entrenamiento detenido se enseñan como entrenadas/configuradas', () => { + expect(formatEpochs(10, 10)).toBe('10') + expect(formatEpochs(2, 5)).toBe('2/5') + }) + + test('matriz de confusión: filas reales, columnas predichas', () => { + expect(confusionMatrix([0, 0, 1, 2, 2], [0, 1, 1, 2, 0], 3)).toStrictEqual([ + [1, 1, 0], + [0, 1, 0], + [1, 0, 1], + ]) + }) + + test('totales de la matriz: sensibilidad por fila, precisión por columna y exactitud', () => { + const stats = confusionStats([ + [1, 1, 0], + [0, 1, 0], + [1, 0, 1], + ]) + expect(stats.support).toStrictEqual([2, 1, 2]) + expect(stats.recall).toStrictEqual([0.5, 1, 0.5]) + expect(stats.precision).toStrictEqual([0.5, 0.5, 1]) + expect(stats).toMatchObject({ correct: 3, total: 5, accuracy: 0.6 }) + }) + + test('una clase sin ejemplos o que nunca se predice no tiene sensibilidad o precisión', () => { + const stats = confusionStats([ + [2, 0], + [0, 0], + ]) + expect(stats.recall).toStrictEqual([1, null]) + expect(stats.precision).toStrictEqual([1, null]) + expect(confusionStats([]).accuracy).toBe(0) + }) + + test('changedParameters: lo que no vale lo mismo en todos los modelos que se comparan', () => { + const a = { 'learning-rate': '0.01', 'n-of-epochs': '10', 'id-optimizer': 'Adam' } + expect(changedParameters([a, { ...a, 'learning-rate': '0.1' }])).toEqual(['learning-rate']) + expect(changedParameters([a, { ...a, 'learning-rate': '0.1' }, { ...a, 'id-optimizer': 'SGD' }])).toEqual(['learning-rate', 'id-optimizer']) + expect(changedParameters([a, { ...a }])).toEqual([]) + expect(changedParameters([a])).toEqual([]) + }) +}) diff --git a/tests/core/trainingVisor.test.ts b/tests/core/trainingVisor.test.ts new file mode 100644 index 0000000..b8bc522 --- /dev/null +++ b/tests/core/trainingVisor.test.ts @@ -0,0 +1,52 @@ +import { describe, test, expect, vi, beforeEach } from 'vitest' + +// El visor de tfjs-vis: al crearlo (primera llamada a visor()) mete su contenedor en la página, ya abierto +const visor = { open: vi.fn(), close: vi.fn() } +vi.mock('@tensorflow/tfjs-vis', () => ({ + visor: () => { + if (document.getElementById('tfjs-visor-container') === null) { + const container = document.createElement('div') + container.id = 'tfjs-visor-container' + document.body.appendChild(container) + } + return visor + }, +})) + +const { showTrainingVisor } = await import('@core/nn-utils/trainingVisor') + +function screen(small: boolean) { + window.matchMedia = vi.fn().mockReturnValue({ matches: small }) as unknown as typeof window.matchMedia +} + +describe('visor al entrenar', () => { + + beforeEach(() => { + document.getElementById('tfjs-visor-container')?.remove() + visor.open.mockClear() + visor.close.mockClear() + }) + + test('en escritorio se abre', () => { + screen(false) + showTrainingVisor() + expect(visor.open).toHaveBeenCalled() + expect(visor.close).not.toHaveBeenCalled() + }) + + test('en el móvil no se abre: se cierra al crearlo (tfjs-vis lo crea abierto)', () => { + screen(true) + showTrainingVisor() + expect(visor.open).not.toHaveBeenCalled() + expect(visor.close).toHaveBeenCalled() + }) + + test('en el móvil, si el visor ya estaba en la página, se queda como lo tenga el usuario', () => { + screen(true) + showTrainingVisor() + visor.close.mockClear() + showTrainingVisor() + expect(visor.open).not.toHaveBeenCalled() + expect(visor.close).not.toHaveBeenCalled() + }) +}) diff --git a/tests/core/trainingWorker.test.ts b/tests/core/trainingWorker.test.ts new file mode 100644 index 0000000..2c21af9 --- /dev/null +++ b/tests/core/trainingWorker.test.ts @@ -0,0 +1,102 @@ +import { describe, test, expect, beforeAll } from 'vitest' +import * as tfjs from '@tensorflow/tfjs' + +import { trainingWorkerApi } from '@core/training/training.worker' +import { modelFromArtifacts } from '@core/training/buildModels' +import { DEFINITION_ERROR_PREFIX, type DenseTrainingRequest_t, type TrainingProgress_t } from '@core/training/trainingTypes' +import type { WorkerTaskContext_t } from '@core/workers/workerProtocol' + +// Las funciones del worker de entrenamiento, llamadas directamente (en un worker de verdad las llama exposeWorker) + +/** Dos clases separables: la clase es 1 si x0 + x1 > 1 */ +function classificationRequest(rows = 120): DenseTrainingRequest_t { + const X = new Float32Array(rows * 2) + const y = new Float32Array(rows * 2) + for (let row = 0; row < rows; row++) { + const x0 = (row * 37 % 100) / 100 + const x1 = (row * 61 % 100) / 100 + X.set([x0, x1], row * 2) + y.set(x0 + x1 > 1 ? [0, 1] : [1, 0], row * 2) + } + return { + backend : 'cpu', + X, + rows, + features : 2, + y, + yShape : [rows, 2], + layerList : [{ units: 8, activation: 'relu' }, { units: 2, activation: 'softmax' }], + compile : { idOptimizer: 'train-adam', idLoss: 'losses-categoricalCrossentropy', idMetrics: ['metrics-categoricalAccuracy'], learningRate: 0.05 }, + testSize : 0.2, + seed : 42, + numberOfEpoch: 3, + } +} + +function contextOf(progress: TrainingProgress_t[], cancelled = () => false): WorkerTaskContext_t { + return { progress: (data) => progress.push(data as TrainingProgress_t), cancelled } +} + +describe('worker de entrenamiento', () => { + + beforeAll(async () => { + await tfjs.setBackend('cpu') + }) + + test('clasificación: avisa de cada lote y cada época y devuelve el modelo, el historial y la evaluación', async () => { + const progress: TrainingProgress_t[] = [] + const result = await trainingWorkerApi.trainDense(classificationRequest(), contextOf(progress)) + + const epochs = progress.filter((p) => p.kind === 'epoch') + expect(epochs.map((p) => p.kind === 'epoch' && p.epoch)).toEqual([0, 1, 2]) + expect(epochs[0]).toMatchObject({ totalEpochs: 3, logs: expect.objectContaining({ loss: expect.any(Number), val_loss: expect.any(Number) }) }) + expect(progress.some((p) => p.kind === 'batch')).toBe(true) + + expect(result.history.epoch).toEqual([0, 1, 2]) + expect(result.history.history.loss).toHaveLength(3) + // 20 % de validación: 24 de las 120 filas + expect(result.evaluation?.labels).toHaveLength(24) + expect(result.evaluation?.predictions).toHaveLength(24) + + // El modelo viaja como datos y se reconstruye en el hilo principal + expect(result.artifacts.weightData).toBeDefined() + const model = await modelFromArtifacts(result.artifacts) + const output = model.predict(tfjs.tensor2d([[0.9, 0.9], [0.1, 0.1]])) as tfjs.Tensor + expect(output.shape).toEqual([2, 2]) + tfjs.dispose([output]) + model.dispose() + }, 30_000) + + test('regresión: un número por fila y sin evaluación de clases', async () => { + const request = classificationRequest(60) + const y = new Float32Array(60).map((_, row) => request.X[row * 2] * 3 + request.X[row * 2 + 1]) + const result = await trainingWorkerApi.trainDense({ + ...request, + y, + yShape : [60], + layerList: [{ units: 4, activation: 'relu' }, { units: 1, activation: 'linear' }], + compile : { idOptimizer: 'train-adam', idLoss: 'losses-meanSquaredError', idMetrics: ['metrics-meanAbsoluteError'], learningRate: 0.05 }, + }, contextOf([])) + expect(result.evaluation).toBeUndefined() + expect(result.history.history.loss).toHaveLength(3) + }, 30_000) + + test('para cuando se le pide (el modelo se queda como esté)', async () => { + const progress: TrainingProgress_t[] = [] + let stop = false + const context: WorkerTaskContext_t = { + progress: (data) => { + progress.push(data as TrainingProgress_t) + if ((data as TrainingProgress_t).kind === 'epoch') stop = true + }, + cancelled: () => stop, + } + const result = await trainingWorkerApi.trainDense({ ...classificationRequest(), numberOfEpoch: 20 }, context) + expect(result.history.epoch.length).toBeLessThan(20) + }, 30_000) + + test('una arquitectura que no vale se distingue de los fallos del worker', async () => { + const request = { ...classificationRequest(), layerList: [{ units: 2, activation: 'no-existe' }] } + await expect(trainingWorkerApi.trainDense(request, contextOf([]))).rejects.toThrow(DEFINITION_ERROR_PREFIX + 'activation:') + }) +}) diff --git a/tests/core/workers.test.ts b/tests/core/workers.test.ts new file mode 100644 index 0000000..5d8ffee --- /dev/null +++ b/tests/core/workers.test.ts @@ -0,0 +1,112 @@ +import { describe, test, expect, vi, afterEach } from 'vitest' +import { createWorkerClient } from '@core/workers/workerClient' +import { exposeWorker, type WorkerScope_t } from '@core/workers/exposeWorker' +import { transferablesOf, type WorkerApi_t, type WorkerTaskContext_t } from '@core/workers/workerProtocol' + +/** + * Worker de mentira: lo que el cliente le manda llega a `exposeWorker` (como dentro de un worker de verdad) en otra + * vuelta del bucle de eventos, y sus respuestas vuelven al cliente + */ +function fakeWorkerOf(api: WorkerApi_t, transfers: Transferable[][] = []) { + return class FakeWorker extends EventTarget { + private listener: ((event: MessageEvent) => void) | null = null + terminated = false + constructor() { + super() + const scope: WorkerScope_t = { + postMessage : (message, transfer) => { transfers.push(transfer); setTimeout(() => this.dispatchEvent(new MessageEvent('message', { data: message }))) }, + addEventListener: (_type, listener) => { this.listener = listener }, + } + exposeWorker(api, scope) + } + postMessage(message: unknown) { setTimeout(() => this.listener?.(new MessageEvent('message', { data: message }))) } + terminate() { this.terminated = true } + } +} + +describe('workers', () => { + + afterEach(() => vi.unstubAllGlobals()) + + test('cada petición recibe su respuesta, aunque terminen en otro orden', async () => { + const api = { + slow: async (n: number) => { await new Promise((r) => setTimeout(r, 20)); return n * 2 }, + fast: (text: string) => text.toUpperCase(), + } + vi.stubGlobal('Worker', fakeWorkerOf(api)) + const client = createWorkerClient(() => new Worker('x')) + const [slow, fast] = await Promise.all([client.call('slow', 21), client.call('fast', 'hola')]) + expect(slow).toBe(42) + expect(fast).toBe('HOLA') + }) + + test('los errores del worker llegan a quien llama', async () => { + const api = { fail: () => { throw new Error('mal') } } + vi.stubGlobal('Worker', fakeWorkerOf(api)) + const client = createWorkerClient(() => new Worker('x')) + await expect(client.call('fail', undefined as never)).rejects.toThrow('mal') + await expect((client as ReturnType>).call('nope', undefined as never)).rejects.toThrow('Unknown worker request: nope') + }) + + test('los buffers del resultado se transfieren en vez de copiarse', async () => { + const transfers: Transferable[][] = [] + const api = { pixels: (n: number) => new Float32Array(n) } + vi.stubGlobal('Worker', fakeWorkerOf(api, transfers)) + const client = createWorkerClient(() => new Worker('x')) + const pixels = await client.call('pixels', 8) + expect(pixels).toHaveLength(8) + expect(transfers[0]).toEqual([pixels.buffer]) + const buffer = new ArrayBuffer(4) + expect(transferablesOf({ a: new Uint8Array(buffer), b: 'x', c: buffer })).toEqual([buffer]) + }) + + test('una tarea larga manda progreso antes de su resultado y para cuando se le pide', async () => { + const api = { + count: async (limit: number, { progress, cancelled }: WorkerTaskContext_t) => { + let i = 0 + for (; i < limit && !cancelled(); i++) { + progress({ step: i }) + await new Promise((r) => setTimeout(r, 5)) + } + return i + }, + } + vi.stubGlobal('Worker', fakeWorkerOf(api)) + const client = createWorkerClient(() => new Worker('x')) + const steps: unknown[] = [] + expect(await client.call('count', 3, { onProgress: (data) => steps.push(data) })).toBe(3) + expect(steps).toEqual([{ step: 0 }, { step: 1 }, { step: 2 }]) + + const controller = new AbortController() + const call = client.call('count', 1000, { signal: controller.signal, onProgress: () => controller.abort() }) + const done = await call + expect(done).toBeLessThan(1000) + }) + + test('los buffers anidados (pesos de un modelo) también se transfieren', () => { + const weights = new ArrayBuffer(8) + const shards = [new ArrayBuffer(4), new ArrayBuffer(4)] + expect(transferablesOf({ artifacts: { weightData: weights, modelTopology: { a: 1 } } })).toEqual([weights]) + expect(transferablesOf({ artifacts: { weightData: shards } })).toEqual(shards) + // Un array largo de números no se recorre + expect(transferablesOf({ values: Array.from({ length: 1000 }, () => 1) })).toEqual([]) + }) + + test('al pararlo, lo pendiente falla', async () => { + const api = { wait: () => new Promise(() => undefined) } + vi.stubGlobal('Worker', fakeWorkerOf(api)) + const client = createWorkerClient(() => new Worker('x')) + const call = client.call('wait', undefined as never) + client.terminate() + await expect(call).rejects.toThrow('Worker terminated') + }) + + test('sin workers (jsdom) usa el camino del mismo hilo, o falla si no lo hay', async () => { + vi.stubGlobal('Worker', undefined) + const api = { double: (n: number) => n * 2 } + const create = vi.fn() + expect(await createWorkerClient(create, api).call('double', 4)).toBe(8) + await expect(createWorkerClient(create).call('double', 4)).rejects.toThrow('Web Workers are not available') + expect(create).not.toHaveBeenCalled() + }) +}) diff --git a/tests/explainability/beeswarmLayout.test.ts b/tests/explainability/beeswarmLayout.test.ts new file mode 100644 index 0000000..8b4aa7b --- /dev/null +++ b/tests/explainability/beeswarmLayout.test.ts @@ -0,0 +1,26 @@ +import { describe, test, expect } from 'vitest' +import { beeswarmLayout, shapColor } from '../../src/core/explainability/beeswarmLayout' + +describe('beeswarmLayout', () => { + // 3 instancias × 2 features: la feature "b" tiene más efecto (|SHAP| medio mayor) + const shap = [[0.1, -0.9], [0.0, 0.8], [-0.1, 0.7]] + const values = [[1, 10], [2, 20], [3, 30]] + + test('un punto por instancia y feature, con la feature más importante en la fila de arriba', () => { + const { points, order } = beeswarmLayout(shap, values, undefined, ['a', 'b']) + expect(points).toHaveLength(6) + expect(order).toStrictEqual([0, 1]) + // Cada punto queda cerca de su fila (el desplazamiento no invade la de al lado) + for (const point of points) { + const row = point.feature === 'a' ? 0 : 1 + expect(Math.abs(point.y - row)).toBeLessThan(0.5) + } + }) + + test('el color va de azul (valor bajo) a rojo (valor alto) y el tooltip usa el valor legible', () => { + const { points } = beeswarmLayout(shap, values, [['x', 'p'], ['y', 'q'], ['z', 'r']], ['a', 'b']) + const featureB = points.filter(({ feature }) => feature === 'b') + expect(featureB.map(({ color }) => color)).toStrictEqual([shapColor(0), shapColor(0.5), shapColor(1)]) + expect(featureB.map(({ value }) => value)).toStrictEqual(['p', 'q', 'r']) + }) +}) diff --git a/tests/explainability/kernelShap.test.ts b/tests/explainability/kernelShap.test.ts index 1435be6..3a912d3 100644 --- a/tests/explainability/kernelShap.test.ts +++ b/tests/explainability/kernelShap.test.ts @@ -3,7 +3,7 @@ import * as tfjs from '@tensorflow/tfjs' import { KernelSHAP } from '../../src/core/explainability/webshap' // Modelo lineal con dos salidas: para un modelo lineal y un background de una fila, -// el valor SHAP exacto de cada variable es w_i · (x_i − bg_i). +// el valor SHAP exacto de cada variable es w_i × (x_i − bg_i). const W = [ [2, -1, 0.5, 3], [-1, 4, 1, 0], diff --git a/tests/explainability/lstsq.test.ts b/tests/explainability/lstsq.test.ts new file mode 100644 index 0000000..68a90ec --- /dev/null +++ b/tests/explainability/lstsq.test.ts @@ -0,0 +1,34 @@ +import { describe, test, expect } from 'vitest' +import { matrix } from 'mathjs' +import { lstsq } from '../../src/core/explainability/webshap/explainer/lstsq' + +// Mínimos cuadrados ponderados: (X'WX)⁻¹ X'WY. Con datos sin ruido, la solución es exacta sea cual sea el peso +const X = [[1, 0], [0, 1], [1, 1], [2, 1], [1, 3]] +const beta = [2, -1] +const Y = X.map((row) => [row[0] * beta[0] + row[1] * beta[1]]) + +describe('lstsq (KernelSHAP)', () => { + + test('con un peso por muestra (W diagonal) recupera los coeficientes', () => { + const w = matrix([[1], [2], [0.5], [3], [1]]) + const result = lstsq(matrix(X), matrix(Y), w).toArray() as number[][] + expect(result[0][0]).toBeCloseTo(2, 10) + expect(result[1][0]).toBeCloseTo(-1, 10) + }) + + test('con W completa da lo mismo que con su diagonal', () => { + const weights = [1, 2, 0.5, 3, 1] + const full = weights.map((value, i) => weights.map((_, j) => (i === j ? value : 0))) + const fromVector = lstsq(matrix(X), matrix(Y), matrix(weights.map((value) => [value]))).toArray() as number[][] + const fromMatrix = lstsq(matrix(X), matrix(Y), matrix(full)).toArray() as number[][] + fromVector.forEach(([value], i) => expect(fromMatrix[i][0]).toBeCloseTo(value, 10)) + }) + + test('con ruido, el peso decide qué muestras pesan más', () => { + // La última muestra se aleja de la recta; con poco peso apenas mueve la solución + const noisyY = [...Y.slice(0, 4), [Y[4][0] + 10]] + const light = lstsq(matrix(X), matrix(noisyY), matrix([[1], [1], [1], [1], [0.001]])).toArray() as number[][] + const heavy = lstsq(matrix(X), matrix(noisyY), matrix([[1], [1], [1], [1], [100]])).toArray() as number[][] + expect(Math.abs(light[1][0] - beta[1])).toBeLessThan(Math.abs(heavy[1][0] - beta[1])) + }) +}) diff --git a/tests/explainability/shapSampling.test.ts b/tests/explainability/shapSampling.test.ts index cd87dc9..767ba84 100644 --- a/tests/explainability/shapSampling.test.ts +++ b/tests/explainability/shapSampling.test.ts @@ -89,7 +89,7 @@ describe('shapSampling — utilidades de muestreo para explicabilidad SHAP', () }) describe('minShapSamples', () => { - test('garantiza al menos 2·segmentos + 2 muestras', () => { + test('garantiza al menos 2 × segmentos + 2 muestras', () => { expect(minShapSamples(36, 50)).toBe(74) expect(minShapSamples(14, 150)).toBe(150) }) diff --git a/tests/helpers/n4l.ts b/tests/helpers/n4l.ts new file mode 100644 index 0000000..1874875 --- /dev/null +++ b/tests/helpers/n4l.ts @@ -0,0 +1,26 @@ +import * as fs from 'fs' +import { vi } from 'vitest' +import type { TFunction } from 'i18next' + +import { builtinN4LPackage, n4lPackageByKey } from '@core/n4l/catalog' +import MODEL_N4L from '@pages/playground/0_TabularClassification/models/MODEL_N4L' + +// Las direcciones de la aplicación (VITE_PATH + /n4l/…) se sirven desde public/ +export const toPublicPath = (url: string) => 'public' + url.replace(import.meta.env.VITE_PATH, '').split('?')[0] + +/** fetch que lee de public/ (los paquetes, sus modelos y sus textos) */ +export const stubPublicFetch = () => vi.stubGlobal('fetch', async (input: string | URL | Request) => { + const url = input.toString() + return new Response(fs.readFileSync(toPublicPath(url)), { + headers: { 'content-type': url.endsWith('.json') ? 'application/json' : 'application/octet-stream' }, + }) +}) + +export const keyT = ((key: string) => key) as unknown as TFunction<'translation', undefined> + +/** El modelo de clasificación tabular de un paquete de public/n4l/, por su clave (IRIS, CAR…) */ +export function n4lTabularModel(key: string) { + const found = n4lPackageByKey('tabular-classification', key) + if (found === undefined) throw new Error(`No hay paquete tabular-classification con la clave ${key}`) + return new MODEL_N4L(keyT, () => {}, builtinN4LPackage(found.entry)) +} diff --git a/tests/models/MODEL_IMAGE_KMNIST.test.ts b/tests/models/MODEL_IMAGE_KMNIST.test.ts deleted file mode 100644 index a52598f..0000000 --- a/tests/models/MODEL_IMAGE_KMNIST.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { describe, test, expect, vi, beforeAll } from 'vitest' -import * as fs from 'fs' -import * as tfjs from '@tensorflow/tfjs' -import type { TFunction } from 'i18next' - -import MODEL_IMAGE_KMNIST, { - KMNIST_PRETRAINED_TEST_ACCURACY, - LIST_OF_IMAGES_KMNIST, -} from '../../src/pages/playground/3_ImageClassification/models/MODEL_IMAGE_KMNIST' -import fixture from './fixtures/kmnist-test-samples.json' - -// Las URLs de la app (VITE_PATH + /models/...) se sirven desde public/ -const toPublicPath = (url: string) => 'public' + url.replace(import.meta.env.VITE_PATH, '') - -const toResponse = (url: string) => { - const body = fs.readFileSync(toPublicPath(url.split('?')[0])) - return new Response(body, { headers: { 'content-type': url.endsWith('.json') ? 'application/json' : 'application/octet-stream' } }) -} - -/** Imagen de KMNIST (trazo blanco sobre negro) como la ImageData opaca de un carácter oscuro sobre fondo claro. */ -const toImageData = (base64: string): ImageData => { - const pixels = Buffer.from(base64, 'base64') - const data = new Uint8ClampedArray(pixels.length * 4) - pixels.forEach((value, i) => { - data.fill(255 - value, i * 4, i * 4 + 3) - data[i * 4 + 3] = 255 - }) - return { data, width: 28, height: 28, colorSpace: 'srgb' } as ImageData -} - -// Capas que sabe propagar la explicación con LRP (applyLRP) -const LRP_LAYERS = ['Conv2D', 'MaxPooling2D', 'Dropout', 'Flatten', 'Dense'] - -describe('MODEL_IMAGE_KMNIST — modelo preentrenado', () => { - const t = ((key: string) => key) as unknown as TFunction<'translation', undefined> - const iModelInstance = new MODEL_IMAGE_KMNIST(t) - let model: tfjs.LayersModel - - beforeAll(async () => { - vi.stubGlobal('fetch', async (input: string | URL | Request) => toResponse(input.toString())) - await tfjs.setBackend('cpu') - model = await iModelInstance.ENABLE_MODEL() - }, 30_000) - - test('recibe imágenes de 28x28 y da una probabilidad por carácter, con capas que LRP sabe explicar', () => { - expect(model.inputs[0].shape).toStrictEqual([null, 28, 28, 1]) - expect(model.outputs[0].shape).toStrictEqual([null, iModelInstance.CLASS_LABELS.length]) - expect(model.layers.map((layer) => layer.getClassName()).filter((name) => !LRP_LAYERS.includes(name))).toStrictEqual([]) - }) - - test('la precisión que anuncia la descripción es la medida al entrenarlo, y es de al menos un 95 %', () => { - const metadata = model.getUserDefinedMetadata() as { testAccuracy: number, classLabels: string[] } - expect(KMNIST_PRETRAINED_TEST_ACCURACY).toBe(metadata.testAccuracy) - expect(metadata.testAccuracy).toBeGreaterThanOrEqual(0.95) - expect(metadata.classLabels).toStrictEqual(iModelInstance.CLASS_LABELS) - }) - - test('clasifica imágenes de test de KMNIST', async () => { - let hits = 0 - for (const sample of fixture.samples) { - const { index } = await iModelInstance.CLASSIFY(model, toImageData(sample.pixels)) - if (index === sample.label) hits++ - } - expect(hits).toBeGreaterThanOrEqual(fixture.samples.length * 0.9) - }) - - test('existen las imágenes de ejemplo', () => { - expect(LIST_OF_IMAGES_KMNIST.filter((image) => !fs.existsSync('public/assets/' + image))).toStrictEqual([]) - }) -}) diff --git a/tests/models/MODEL_LYMPHOGRAPHY.test.ts b/tests/models/MODEL_LYMPHOGRAPHY.test.ts deleted file mode 100644 index d3b0fea..0000000 --- a/tests/models/MODEL_LYMPHOGRAPHY.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, test, expect, vi, beforeAll } from 'vitest' -import * as fs from 'fs' -import * as tfjs from '@tensorflow/tfjs' -import type { TFunction } from 'i18next' - -import MODEL_LYMPHOGRAPHY from '../../src/pages/playground/0_TabularClassification/models/MODEL_LYMPHOGRAPHY' -import { DataFrameApplyEncoders } from '../../src/core/dataframe/DataFrameUtils' -import type { DatasetProcessed_t } from '../../src/core/types' - -// Las URLs de la app (VITE_PATH + /models/...) se sirven desde public/ -const toPublicPath = (url: string) => 'public' + url.replace(import.meta.env.VITE_PATH, '') - -// En jsdom danfo descarga los CSV por XHR: se leen del disco -vi.mock('danfojs', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - readCSV: (source: string | File, options?: object) => actual.readCSV( - typeof source === 'string' ? new File([fs.readFileSync(toPublicPath(source))], 'data.csv', { type: 'text/csv' }) : source, - options, - ), - } -}) - -const toResponse = (url: string) => { - const body = fs.readFileSync(toPublicPath(url.split('?')[0])) - return new Response(body, { headers: { 'content-type': url.endsWith('.json') ? 'application/json' : 'application/octet-stream' } }) -} - -describe('MODEL_LYMPHOGRAPHY — el modelo preentrenado recibe la entrada con la que se entrenó', () => { - const t = ((key: string) => key) as unknown as TFunction<'translation', undefined> - const iModelInstance = new MODEL_LYMPHOGRAPHY(t, () => {}) - let model: tfjs.LayersModel - let dataset: DatasetProcessed_t - - // Misma preparación que ModelReviewTabularClassification: encoders del dataset, sin escalar - const predictClass = (values: Record) => { - const vector = DataFrameApplyEncoders(dataset.data_processed!.encoders, values, iModelInstance.DATA_DEFAULT_KEYS) - .map((item) => parseFloat(item.toString())) - const output = (model.predict(tfjs.tensor2d(vector, [1, vector.length])) as tfjs.Tensor).dataSync() - return iModelInstance.CLASSES[output.indexOf(Math.max(...output))] - } - - beforeAll(async () => { - vi.stubGlobal('fetch', async (input: string | URL | Request) => toResponse(input.toString())) - await tfjs.setBackend('cpu') - model = await iModelInstance.LOAD_LAYERS_MODEL({ onProgress: () => {} }) - dataset = (await iModelInstance.DATASETS())[0] - }, 30_000) - - test('cada ejemplo del selector se clasifica con la clase que anuncia', () => { - const expected = [ - '00-tc.lymphography.normal find', - '00-tc.lymphography.metastases', - '00-tc.lymphography.malign lymph', - '00-tc.lymphography.fibrosis', - ] - expect(iModelInstance.LIST_EXAMPLES.map(predictClass)).toStrictEqual(expected) - }) - - test('acierta en casi todo el dataset (con la entrada equivocada no pasaba del 30 %)', () => { - const { dataframe_original, data_processed } = dataset - const columns = dataframe_original.columns - const target = data_processed!.column_name_target - const classKey: Record = { - 1: '00-tc.lymphography.normal find', - 2: '00-tc.lymphography.metastases', - 3: '00-tc.lymphography.malign lymph', - 4: '00-tc.lymphography.fibrosis', - } - const rows = dataframe_original.values as Array> - const hits = rows.filter((row) => { - const values = Object.fromEntries(columns.map((column, index) => [column, row[index]])) - return predictClass(values) === classKey[values[target]] - }).length - expect(hits / rows.length).toBeGreaterThan(0.9) - }) -}) diff --git a/tests/models/N4L_IMAGES.test.ts b/tests/models/N4L_IMAGES.test.ts new file mode 100644 index 0000000..7109047 --- /dev/null +++ b/tests/models/N4L_IMAGES.test.ts @@ -0,0 +1,236 @@ +import { describe, test, expect, beforeAll, beforeEach } from 'vitest' +import * as fs from 'fs' +import * as tfjs from '@tensorflow/tfjs' + +import { builtinN4LPackage, n4lPackageByKey } from '@core/n4l/catalog' +import { isImageDataset, n4lLayersModels } from '@core/n4l/format' +import { n4lImageExamples, n4lImageRuntime } from '@core/n4l/imageClassification' +import { loadModelClass } from '@core/models/modelRegistry' +import { trainedModelPackage } from '@core/n4l/exportTrained' +import { importN4LPackage, listLocalPackages, MemoryPackageStore, openLocalPackage, setN4LPackageStore, setN4LTextsRegistry } from '@core/n4l/localPackages' +import { packN4L } from '@core/n4l/source' +import { loadN4LLayersModel } from '@core/n4l/tfjsModel' +import { buildImageModel } from '@core/training/buildModels' +import { MAP_IC_CLASSES } from '@pages/playground/3_ImageClassification/models' +import type MODEL_N4L from '@pages/playground/3_ImageClassification/models/MODEL_N4L' +import { FEATURED_FORMS } from '@pages/playground/3_ImageClassification/models/characterForms' +import { imageLayersOf, n4lLayersOf } from '@pages/playground/3_ImageClassification/models/n4lLayers' +import { keyT, stubPublicFetch } from '../helpers/n4l' +import mnistFixture from './fixtures/mnist-test-samples.json' +import kmnistFixture from './fixtures/kmnist-test-samples.json' +import cifar10Fixture from './fixtures/cifar10-test-samples.json' + +// Los paquetes de clasificación de imágenes de public/n4l/: MNIST, KMNIST y CIFAR-10 (un modelo de TF.js con su +// sprite) e ImageNet (MobileNet, que descarga la librería). Sus modelos, abiertos como en la página del modelo, aciertan +// con imágenes de prueba que no vieron al entrenar. + +/** + * Imagen de prueba como la ImageData opaca que clasifica la página: en gris (trazo blanco sobre negro), con el trazo + * oscuro sobre fondo claro, como el lienzo; en color (alto, ancho, RGB), tal cual + */ +const toImageData = (base64: string, { width, height, channels }: { width: number, height: number, channels: number }): ImageData => { + const pixels = Buffer.from(base64, 'base64') + const data = new Uint8ClampedArray(width * height * 4) + for (let i = 0; i < width * height; i++) { + for (let c = 0; c < 3; c++) data[i * 4 + c] = channels === 1 ? 255 - pixels[i] : pixels[i * 3 + c] + data[i * 4 + 3] = 255 + } + return { data, width, height, colorSpace: 'srgb' } as ImageData +} + +/** El tamaño de un PNG, de su cabecera (IHDR): ancho y alto en los bytes 16 a 23 */ +const pngSize = (file: string) => { + const png = fs.readFileSync(file) + return [png.readUInt32BE(16), png.readUInt32BE(20)] +} + +// Capas que sabe propagar la explicación con LRP (applyLRP) +const LRP_LAYERS = ['Conv2D', 'MaxPooling2D', 'Dropout', 'Flatten', 'Dense'] + +const entryOf = (key: string) => n4lPackageByKey('image-classification', key)!.entry +const dirOf = (key: string) => `public/${entryOf(key).path}/` + +beforeAll(async () => { + stubPublicFetch() + await tfjs.setBackend('cpu') +}) + +describe.each([ + { key: 'IMAGE-MNIST', fixture: mnistFixture, minAccuracy: 0.98, image: { width: 28, height: 28, channels: 1 }, exampleSize: 280 }, + { key: 'IMAGE-KMNIST', fixture: kmnistFixture, minAccuracy: 0.95, image: { width: 28, height: 28, channels: 1 }, exampleSize: 280 }, + { key: 'IMAGE-CIFAR10', fixture: cifar10Fixture, minAccuracy: 0.85, image: { width: 32, height: 32, channels: 3 }, exampleSize: 128 }, +])('Paquete .n4l de $key', ({ key, fixture, minAccuracy, image, exampleSize }) => { + let instance: MODEL_N4L + let model: tfjs.LayersModel + + beforeAll(async () => { + const ModelClass = await loadModelClass(MAP_IC_CLASSES, key) + instance = new ModelClass(keyT) as MODEL_N4L + model = await instance.ENABLE_MODEL() + }, 30_000) + + test('su modelo recibe sus imágenes y da una probabilidad por clase, con capas que LRP sabe explicar', () => { + expect(instance.IMAGE).toStrictEqual(image) + // Las de gris se pueden dibujar; las de color, no (se sube una foto) + expect(instance.DRAWABLE).toBe(image.channels === 1) + expect(instance.TEST_IMAGES).toBe(true) + expect(model.inputs[0].shape).toStrictEqual([null, image.height, image.width, image.channels]) + expect(model.outputs[0].shape).toStrictEqual([null, instance.CLASS_IDS.length]) + expect(model.layers.map((layer) => layer.getClassName()).filter((name) => !LRP_LAYERS.includes(name))).toStrictEqual([]) + }) + + test('sus métricas son de las imágenes de prueba de su conjunto (las que siguen a las de entrenamiento)', () => { + const { section, dataset } = n4lImageRuntime(entryOf(key)) as Extract, { kind: 'sprite' }> + const [{ metrics }] = n4lLayersModels(section) + expect(metrics!.test_images).toBe(dataset.rows - dataset.train) + expect(metrics!.test_accuracy).toBeGreaterThanOrEqual(minAccuracy) + }) + + test('clasifica imágenes de prueba como la página del modelo', async () => { + let hits = 0 + for (const sample of fixture.samples) { + const { index } = await instance.CLASSIFY(model, toImageData(sample.pixels, image)) + if (index === sample.label) hits++ + } + expect(hits).toBeGreaterThanOrEqual(fixture.samples.length * 0.9) + }) + + test('su sprite: tantas imágenes y clases como dice el manifiesto', async () => { + const sprite = await instance.SPRITE() + const entry = entryOf(key) + const dataset = entry.datasets.find(isImageDataset)! + expect(sprite).toMatchObject({ numElements: dataset.rows, numTrain: dataset.train, numClasses: instance.CLASS_IDS.length, image }) + expect(pngSize(dirOf(key) + dataset.file)).toStrictEqual([image.width * image.height, dataset.rows]) + expect(fs.statSync(dirOf(key) + dataset.labels).size).toBe(dataset.rows * instance.CLASS_IDS.length) + }) + + test('una imagen de ejemplo por clase (las de los dígitos y los caracteres, escritas con una fuente)', () => { + const examples = n4lImageExamples(n4lImageRuntime(entryOf(key)).section).filter(({ old }) => old !== true) + expect(examples.map(({ expected }) => expected)).toStrictEqual(instance.CLASS_IDS) + expect(instance.LIST_IMAGES_EXAMPLES()).toHaveLength(instance.CLASS_IDS.length) + for (const { file } of examples) expect(pngSize(dirOf(key) + file), file).toStrictEqual([exampleSize, exampleSize]) + }) + + test('su red por defecto: la primera capa recibe las imágenes y no se puede quitar; la última da una salida por clase', () => { + const layers = instance.DEFAULT_LAYERS() + expect(layers[0]).toMatchObject({ _class: 'conv2d', _protected: true, inputShape: [image.height, image.width, image.channels] }) + expect(layers.at(-1)).toMatchObject({ _class: 'dense', units: instance.CLASS_IDS.length, activation: 'softmax' }) + // Y de vuelta al manifiesto (al guardar un modelo entrenado en un .n4l), igual + expect(n4lLayersOf(layers)).toStrictEqual(entryOf(key).tasks[0].training!.layers) + expect(imageLayersOf(n4lLayersOf(layers), instance.IMAGE)).toStrictEqual(layers) + }) +}) + +describe('Paquete .n4l de KMNIST: cada carácter de hoy con sus formas antiguas', () => { + test('cada clase es un carácter con cómo se lee y el kanji del que viene; sus formas antiguas, las hentaigana de Unicode', async () => { + const ModelClass = await loadModelClass(MAP_IC_CLASSES, 'IMAGE-KMNIST') + const instance = new ModelClass(keyT) + const forms = instance.CHARACTER_FORMS()! + expect(forms.map(({ char }) => char)).toStrictEqual(instance.CLASS_IDS) + expect(forms.map(({ reading }) => reading)).toStrictEqual(['o', 'ki', 'su', 'tsu', 'na', 'ha', 'ma', 'ya', 're', 'wo']) + // Los ejemplos: el de hoy de cada uno, sin las formas antiguas (que van con su carácter) + expect(instance.LIST_IMAGES_EXAMPLES()).toStrictEqual(forms.map(({ modern }) => modern)) + // Las 68 hentaigana de Unicode de estas diez sílabas, sin repetir + const images = forms.flatMap(({ old }) => old.map(({ image }) => image)) + expect(images).toHaveLength(68) + expect(new Set(images).size).toBe(images.length) + for (const { char, old } of forms) { + // Las de los ejemplos, de kanji distintos (お solo tiene tres, dos de 於) + const featured = old.slice(0, FEATURED_FORMS).map(({ origin }) => origin) + if (char !== 'お') expect(new Set(featured).size, char).toBe(FEATURED_FORMS) + for (const { image, origin } of old) { + expect(origin, image).toMatch(/^\p{Script=Han}$/u) + // Del bloque de las hentaigana (U+1B000–U+1B12F), y de 112x112 + expect(Number.parseInt(image.match(/([0-9A-F]+)\.png$/)![1], 16), image).toBeGreaterThanOrEqual(0x1B000) + expect(pngSize('public' + image.replace(import.meta.env.VITE_PATH, '')), image).toStrictEqual([112, 112]) + } + } + }) + + test('MNIST no tiene formas antiguas', async () => { + const ModelClass = await loadModelClass(MAP_IC_CLASSES, 'IMAGE-MNIST') + expect(new ModelClass(keyT).CHARACTER_FORMS()).toBeNull() + }) +}) + +describe('Paquete .n4l de CIFAR-10: fotos en color', () => { + test('cada clase, con su nombre en el idioma de la página (las que no lo tienen, como en el conjunto)', async () => { + // Como i18next: el texto del paquete en español o, si no está, el valor por defecto + const texts = (id: string) => JSON.parse(fs.readFileSync(`${dirOf(`IMAGE-${id.toUpperCase()}`)}locales/es.json`, 'utf8')) + const t = ((key: string, options?: { defaultValue?: string }) => { + const [namespace, path] = key.split(':') + const value = path.split('.').reduce((node, part) => (node as Record | undefined)?.[part], texts(namespace.replace('n4l-', ''))) + return typeof value === 'string' ? value : options?.defaultValue ?? key + }) as unknown as typeof keyT + const cifar = new (await loadModelClass(MAP_IC_CLASSES, 'IMAGE-CIFAR10'))(t) + expect(cifar.CLASS_IDS).toStrictEqual(['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']) + expect(cifar.CLASS_LABELS).toStrictEqual(['avión', 'automóvil', 'pájaro', 'gato', 'ciervo', 'perro', 'rana', 'caballo', 'barco', 'camión']) + const mnist = new (await loadModelClass(MAP_IC_CLASSES, 'IMAGE-MNIST'))(t) + expect(mnist.CLASS_LABELS).toStrictEqual(mnist.CLASS_IDS) + }) + + test('propone con qué empezar a entrenar (con los valores de la aplicación apenas aprendería con 5.000 fotos)', async () => { + const cifar = new (await loadModelClass(MAP_IC_CLASSES, 'IMAGE-CIFAR10'))(keyT) + expect(cifar.DEFAULT_TRAINING()).toStrictEqual({ learningRate: 0.001, epochs: 20 }) + const mnist = new (await loadModelClass(MAP_IC_CLASSES, 'IMAGE-MNIST'))(keyT) + expect(mnist.DEFAULT_TRAINING()).toStrictEqual({ learningRate: undefined, epochs: undefined }) + }) +}) + +describe('Paquete .n4l de ImageNet: MobileNet', () => { + test('lo descarga la librería (MobileNet V2) y sus fotos de ejemplo están en el paquete', async () => { + const runtime = n4lImageRuntime(entryOf('IMAGE-MOBILENET')) + expect(runtime).toMatchObject({ kind: 'mobilenet', model: { format: 'tfjs-mobilenet', version: 2, alpha: 1 } }) + const ModelClass = await loadModelClass(MAP_IC_CLASSES, 'IMAGE-MOBILENET') + const instance = new ModelClass(keyT) + expect(instance.DRAWABLE).toBe(false) + const examples = instance.LIST_IMAGES_EXAMPLES() + expect(examples).toHaveLength(9) + expect(examples.filter((url) => !fs.existsSync('public' + url.replace(import.meta.env.VITE_PATH, '')))).toStrictEqual([]) + }) + + test('un paquete que no se sabe usar dice por qué', () => { + const entry = entryOf('IMAGE-MNIST') + const big = { ...entry, datasets: entry.datasets.map((dataset) => ({ ...dataset, image: { width: 128, height: 128, channels: 3 } })) } + expect(() => n4lImageRuntime(big)).toThrow(/hasta 64×64/) + const rgba = { ...entry, datasets: entry.datasets.map((dataset) => ({ ...dataset, image: { width: 28, height: 28, channels: 4 } })) } + expect(() => n4lImageRuntime(rgba)).toThrow(/channels 3/) + expect(() => n4lImageRuntime(builtinN4LPackage(n4lPackageByKey('tabular-classification', 'IRIS')!.entry).manifest)).toThrow(/image-classification/) + }) +}) + +describe('Paquete .n4l de imágenes: un modelo entrenado en la aplicación, en su propio .n4l', () => { + beforeEach(() => { + setN4LPackageStore(new MemoryPackageStore()) + setN4LTextsRegistry(() => {}) + }) + + test('lleva el conjunto, sus ejemplos y su red; se abre después como un paquete más', async () => { + const ModelClass = await loadModelClass(MAP_IC_CLASSES, 'IMAGE-KMNIST') + const instance = new ModelClass(keyT) as MODEL_N4L + const layers = instance.DEFAULT_LAYERS() + const { manifest, files } = await trainedModelPackage(builtinN4LPackage(entryOf('IMAGE-KMNIST')), 'image-classification', { + model : buildImageModel(layers), + layers : n4lLayersOf(layers), + classes: instance.CLASS_IDS, + number : 3, + metrics: { acc: 0.5 }, + }, (_language, name) => `${name} (#3)`) + expect(manifest).toMatchObject({ id: 'kmnist-model-3', version: '1.0.0' }) + const [section] = manifest.tasks + // Sin «input»: las imágenes las recibe como están en su conjunto + expect(section.models).toStrictEqual([{ id: 'trained', format: 'tfjs-layers', path: 'models/trained/model.json', dataset: 'kmnist', metrics: { acc: 0.5 } }]) + expect(section.training!.layers).toStrictEqual(entryOf('IMAGE-KMNIST').tasks[0].training!.layers) + expect(n4lImageExamples(section)).toHaveLength(78) + expect(Object.keys(files)).toEqual(expect.arrayContaining(['data/kmnist_images.png', 'data/kmnist_labels_uint8', 'examples/0.png', 'examples/forms/1B09E.png'])) + expect(Object.keys(files).filter((file) => file.startsWith('models/')).sort()).toStrictEqual(['models/trained/model.json', 'models/trained/model.weights.bin']) + + await importN4LPackage((await packN4L(files, 'uint8array')).buffer as ArrayBuffer) + expect((await listLocalPackages('image-classification')).map(({ id }) => id)).toStrictEqual(['kmnist-model-3']) + const pkg = await openLocalPackage('kmnist-model-3') + const runtime = n4lImageRuntime(pkg.manifest) + expect(runtime.kind).toBe('sprite') + const model = await loadN4LLayersModel(pkg.source, n4lLayersModels(runtime.section)[0].path) + expect(model.outputs[0].shape).toStrictEqual([null, 10]) + }, 60_000) +}) diff --git a/tests/models/N4L_QUALITY.test.ts b/tests/models/N4L_QUALITY.test.ts new file mode 100644 index 0000000..89a6cd8 --- /dev/null +++ b/tests/models/N4L_QUALITY.test.ts @@ -0,0 +1,132 @@ +import { describe, test, expect, vi, beforeAll } from 'vitest' +import * as fs from 'fs' +import * as tfjs from '@tensorflow/tfjs' + +import { builtinN4LPackage, N4L_CATALOG } from '@core/n4l/catalog' +import { DataFrameApplyEncoders } from '@core/dataframe/DataFrameUtils' +import MODEL_TABULAR from '@pages/playground/0_TabularClassification/models/MODEL_N4L' +import MODEL_REGRESSION from '@pages/playground/1_Regression/models/MODEL_N4L' +import { seededRandom } from '@core/clustering/kmeans' +import { isTableDataset, n4lLayersModels } from '@core/n4l/format' +import { loadN4LLayersModel } from '@core/n4l/tfjsModel' +import { prepareSeries, readSeries } from '@core/timeSeries/series' +import { evaluateSeriesModel } from '@core/timeSeries/seriesModel' +import { initialPrep } from '@pages/playground/5_TimeSeries/timeSeriesConfig' +import { keyT, stubPublicFetch, toPublicPath } from '../helpers/n4l' + +// Cada modelo ya entrenado de los paquetes de public/n4l/, con su conjunto preparado según el manifiesto (como lo +// prepara la página del modelo: codificado y, si su «input» es «scaled», escalado). Así se comprueba a la vez que el +// modelo es bueno y que el paquete lo configura bien: un preprocesado o unas clases equivocadas lo hunden. + +vi.mock('danfojs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readCSV: (source: string | File, options?: object) => actual.readCSV( + typeof source === 'string' ? new File([fs.readFileSync(toPublicPath(source))], 'data.csv', { type: 'text/csv' }) : source, + options, + ), + } +}) + +beforeAll(async () => { + stubPublicFetch() + await tfjs.setBackend('cpu') +}) + +const withTask = (task: string) => N4L_CATALOG.flatMap((entry) => entry.tasks + .filter((section) => section.task === task && section.models.length > 0) + .map((section) => ({ entry, section }))) + +/** + * La partición de prueba de Scripts/train_regression_models.mjs (con su misma semilla y el mismo barajado): las filas + * con las que no se entrenó cada modelo de regresión + */ +function testRows(count: number, seed = 1, testSize = 0.2) { + const random = seededRandom(seed) + const order = Array.from({ length: count }, (_, row) => row) + for (let i = order.length - 1; i > 0; i--) { + const j = Math.floor(random() * (i + 1)); + [order[i], order[j]] = [order[j], order[i]] + } + return order.slice(0, Math.round(count * testSize)) +} + +describe('Paquetes .n4l: los modelos de clasificación tabular aciertan con la configuración del paquete', () => { + test.each(withTask('tabular-classification').map(({ entry }) => [entry.id, entry] as const))('%s', async (_id, entry) => { + const instance = new MODEL_TABULAR(keyT, () => {}, builtinN4LPackage(entry)) + const model = (await instance.LOAD_LAYERS_MODEL({}))! + const [dataset] = await instance.DATASETS() + const { encoders, scaler, column_name_target } = dataset.data_processed! + const { dataframe_original } = dataset + const rows = dataframe_original.values as Array> + const hits = rows.filter((row) => { + const values = Object.fromEntries(dataframe_original.columns.map((column, index) => [column, row[index]])) + let vector = DataFrameApplyEncoders(encoders, values, instance.DATA_DEFAULT_KEYS).map((value) => parseFloat(value.toString())) + if (instance.MODEL_INPUT() === 'scaled') vector = scaler.transform(vector) as number[] + const output = (model.predict(tfjs.tensor2d([vector])) as tfjs.Tensor).dataSync() + return output.indexOf(Math.max(...output)) === instance.CLASS_INDEX(values[column_name_target]) + }).length + const accuracy = hits / rows.length + console.info(`${entry.id}: ${(accuracy * 100).toFixed(1)} % de aciertos (${hits}/${rows.length})`) + expect(accuracy).toBeGreaterThan(0.9) + }, 60_000) +}) + +describe('Paquetes .n4l: los modelos de regresión dan, con la configuración del paquete, las métricas de su manifiesto', () => { + const cases = withTask('regression').flatMap(({ entry, section }) => n4lLayersModels(section).map((model) => [`${entry.id}/${model.id}`, entry, model] as const)) + + test('todos tienen sus métricas con datos que no vieron al entrenar', () => { + expect(cases.length).toBeGreaterThan(0) + for (const [name, , model] of cases) expect(Object.keys(model.metrics ?? {}), name).toEqual(['test_r2', 'test_mae', 'test_baseline_mae']) + }) + + test.each(cases)('%s', async (name, entry, entryModel) => { + const instance = new MODEL_REGRESSION(keyT, () => {}, builtinN4LPackage(entry)) + const datasets = await instance.DATASETS() + const file = entry.datasets.filter(isTableDataset).find(({ id }) => id === entryModel.dataset)!.file + const dataset = datasets.find(({ csv }) => file.endsWith('/' + csv))! + const [{ model }] = (await instance.MODELS(dataset.csv)).filter((item) => item.model_path!.includes(`/models/${entryModel.id}/`)) + const { X, y } = dataset.data_processed! + // Las filas de prueba, preparadas por la aplicación (codificadas y escaladas según el manifiesto) + const rows = testRows((y.values as unknown[]).length) + const inputs = rows.map((row) => (X.values as number[][])[row]) + const actual = rows.map((row) => Number((y.values as unknown[])[row])) + const predictions = Array.from((model!.predict(tfjs.tensor2d(inputs)) as tfjs.Tensor).dataSync()) + const mean = actual.reduce((sum, value) => sum + value, 0) / actual.length + const mae = actual.reduce((sum, value, index) => sum + Math.abs(value - predictions[index]), 0) / actual.length + const residual = actual.reduce((sum, value, index) => sum + (value - predictions[index]) ** 2, 0) + const total = actual.reduce((sum, value) => sum + (value - mean) ** 2, 0) + const r2 = 1 - residual / total + console.info(`${name}: con ${rows.length} filas que no vio, R² ${r2.toFixed(3)} y error medio ${mae.toFixed(3)} (manifiesto: ${entryModel.metrics!.test_r2}, ${entryModel.metrics!.test_mae})`) + expect(predictions.every(Number.isFinite)).toBe(true) + expect(r2).toBeCloseTo(entryModel.metrics!.test_r2, 2) + expect(mae).toBeCloseTo(entryModel.metrics!.test_mae, 2) + }, 60_000) +}) + +describe('Paquetes .n4l: los modelos de series temporales dan, con la preparación del paquete, las métricas de su manifiesto', () => { + const cases = withTask('time-series').map(({ entry, section }) => [entry.id, entry, section] as const) + + test('cada serie tiene su modelo ya entrenado', () => { + expect(cases.map(([id]) => id)).toEqual(['airline-passengers', 'melbourne-temperatures', 'sunspots']) + }) + + test.each(cases)('%s', async (_id, entry, section) => { + const [model] = n4lLayersModels(section) + const dataset = entry.datasets.filter(isTableDataset).find(({ id }) => id === section.datasets[0])! + const column = (is: (role: string, type: string) => boolean) => dataset.columns.find(({ role, type }) => is(role, type))!.name + const [header, ...rows] = fs.readFileSync(`public/${entry.path}/${dataset.file}`, 'utf-8').trim().split(/\r?\n/).map((line) => line.split(',')) + const { values } = readSeries(header, rows, column((role) => role === 'Target'), column((_role, type) => type === 'Date')) + // Como la página del modelo: la ventana, la prueba y la diferencia de `forecast` + const prepared = prepareSeries(values, initialPrep(values.length, dataset.frequency, section.forecast).prep) + const network = await loadN4LLayersModel(builtinN4LPackage(entry).source, model.path) + const { errors } = await evaluateSeriesModel(network, values, prepared) + expect(errors.oneStep.mae).toBeCloseTo(model.metrics!.test_mae, 2) + expect(errors.oneStep.rmse).toBeCloseTo(model.metrics!.test_rmse, 2) + expect(errors.recursive.mae).toBeCloseTo(model.metrics!.test_recursive_mae, 1) + // A un paso, mejor que repetir el valor anterior + expect(errors.oneStep.mae).toBeLessThan(model.metrics!.test_naive_mae) + network.dispose() + }, 60_000) +}) diff --git a/tests/models/N4L_TABULAR.test.ts b/tests/models/N4L_TABULAR.test.ts new file mode 100644 index 0000000..eaf9444 --- /dev/null +++ b/tests/models/N4L_TABULAR.test.ts @@ -0,0 +1,115 @@ +import { describe, test, expect, vi, beforeAll } from 'vitest' +import * as fs from 'fs' +import * as tfjs from '@tensorflow/tfjs' + +import { DataFrameApplyEncoders } from '../../src/core/dataframe/DataFrameUtils' +import type { DatasetProcessed_t } from '../../src/core/types' +import type MODEL_N4L from '../../src/pages/playground/0_TabularClassification/models/MODEL_N4L' +import { n4lTabularModel, stubPublicFetch, toPublicPath } from '../helpers/n4l' + +// En jsdom danfo descarga los CSV por XHR: se leen del disco +vi.mock('danfojs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readCSV: (source: string | File, options?: object) => actual.readCSV( + typeof source === 'string' ? new File([fs.readFileSync(toPublicPath(source))], 'data.csv', { type: 'text/csv' }) : source, + options, + ), + } +}) + +/** El modelo del paquete, su conjunto preparado y cómo predice la página del modelo (encoders del dataset, sin escalar) */ +async function setup(key: string) { + const iModelInstance = n4lTabularModel(key) + const model = (await iModelInstance.LOAD_LAYERS_MODEL({ onProgress: () => {} }))! + const dataset = (await iModelInstance.DATASETS())[0] + const predictOutput = (values: Record) => { + const vector = DataFrameApplyEncoders(dataset.data_processed!.encoders, values, iModelInstance.DATA_DEFAULT_KEYS) + .map((item) => parseFloat(item.toString())) + const output = (model.predict(tfjs.tensor2d(vector, [1, vector.length])) as tfjs.Tensor).dataSync() + return output.indexOf(Math.max(...output)) + } + const { dataframe_original, data_processed } = dataset + const rows = (dataframe_original.values as Array>).map((row) => { + const values = Object.fromEntries(dataframe_original.columns.map((column, index) => [column, row[index]])) + return { target: String(values[data_processed!.column_name_target]), output: predictOutput(values) } + }) + return { iModelInstance, model, dataset, predictOutput, rows } +} + +beforeAll(async () => { + stubPublicFetch() + await tfjs.setBackend('cpu') +}) + +describe.each(['IRIS', 'CAR', 'LYMPHOGRAPHY'])('paquete .n4l de clasificación tabular %s', (key) => { + let context: Awaited> + beforeAll(async () => { context = await setup(key) }, 30_000) + + test('acierta en casi todo su conjunto, contando la clase real con CLASS_INDEX', () => { + const { rows, iModelInstance } = context + const hits = rows.filter((row) => row.output === iModelInstance.CLASS_INDEX(row.target)).length + expect(hits / rows.length).toBeGreaterThan(0.9) + }) + + test('cada ejemplo del selector se clasifica con la clase que anuncia', () => { + const { iModelInstance, predictOutput } = context + const announced = iModelInstance.LIST_EXAMPLES_RESULTS.map((result) => iModelInstance.CLASS_INDEX(result)) + expect(announced.every((index) => index >= 0)).toBe(true) + expect(iModelInstance.LIST_EXAMPLES.map(predictOutput)).toStrictEqual(announced) + }) + + test('la entrada son las columnas de entrada escaladas entre 0 y 1, y las clases siguen el one-hot de y', () => { + const { dataset, iModelInstance } = context as { dataset: DatasetProcessed_t, iModelInstance: MODEL_N4L } + const { X, y, dataframe_y, classes } = dataset.data_processed! + expect(X.columns).toStrictEqual(iModelInstance.DATA_DEFAULT_KEYS) + const values = (X.values as number[][]).flat() + expect(Math.min(...values)).toBeGreaterThanOrEqual(0) + expect(Math.max(...values)).toBeLessThanOrEqual(1) + const decoded = (y.values as number[][]).map((row) => classes![row.indexOf(1)]) + expect(decoded).toStrictEqual((dataframe_y.values as Array).map(String)) + }) + + test('el formulario, los valores iniciales y la red por defecto salen del manifiesto', () => { + const { iModelInstance, model } = context + expect(iModelInstance.FORM.map(({ name }) => name)).toStrictEqual(iModelInstance.DATA_DEFAULT_KEYS) + expect(Object.keys(iModelInstance.DATA_DEFAULT)).toStrictEqual(iModelInstance.DATA_DEFAULT_KEYS) + const layers = iModelInstance.DEFAULT_LAYERS() + expect(layers.at(-1)).toMatchObject({ _class: 'dense', activation: 'softmax' }) + expect(model.inputs[0].shape).toStrictEqual([null, iModelInstance.DATA_DEFAULT_KEYS.length]) + }) +}) + +describe('las clases de cada paquete', () => { + test('CAR: «good» no tiene salida en el modelo (tiene tres) y no se cambia por vgood', async () => { + const { iModelInstance, model, rows } = await setup('CAR') + expect(model.outputs[0].shape).toEqual([null, 3]) + expect(iModelInstance.CLASS_INDEX('good')).toBe(3) + expect(rows.some((row) => row.output === 3)).toBe(false) + for (const target of ['unacc', 'acc', 'vgood']) { + const outputs = rows.filter((row) => row.target === target).map((row) => row.output) + const counts = [0, 1, 2].map((output) => outputs.filter((value) => value === output).length) + expect(counts.indexOf(Math.max(...counts))).toBe(iModelInstance.CLASS_INDEX(target)) + } + }, 30_000) + + test('LYMPHOGRAPHY: el código del CSV y los nombres de cada clase llevan a su salida', () => { + const iModelInstance = n4lTabularModel('LYMPHOGRAPHY') + const keyOf = (target: unknown) => iModelInstance.CLASSES[iModelInstance.CLASS_INDEX(target)] + const ns = 'n4l-lymphography:classes.' + expect(['1', '2', '3', '4'].map(keyOf)).toStrictEqual(['1', '2', '3', '4'].map((code) => ns + code)) + expect(['normal', 'metastasis', 'malign lymph', 'fibrosis'].map(keyOf)).toStrictEqual(['1', '2', '3', '4'].map((code) => ns + code)) + }) + + test('IRIS: la clase con o sin prefijo, y el nombre exacto gana a uno que termina igual', () => { + const iris = n4lTabularModel('IRIS') + expect(iris.CLASS_INDEX('Iris-virginica')).toBe(2) + expect(iris.CLASS_INDEX('0 Iris-setosa')).toBe(0) + expect(iris.CLASS_INDEX('Setosa')).toBe(0) + expect(iris.CLASS_INDEX('rosa')).toBe(-1) + const car = n4lTabularModel('CAR') + expect(car.CLASS_INDEX('acc')).toBe(1) + expect(car.CLASS_INDEX('unacc')).toBe(0) + }) +}) diff --git a/tests/models/fixtures/cifar10-test-samples.json b/tests/models/fixtures/cifar10-test-samples.json new file mode 100644 index 0000000..c137ed6 --- /dev/null +++ b/tests/models/fixtures/cifar10-test-samples.json @@ -0,0 +1,105 @@ +{ + "source": "CIFAR-10 test set (test_batch), 32x32x3 uint8 (alto, ancho, RGB): de las im\u00e1genes de prueba del sprite de public/n4l/cifar10.n4l", + "samples": [ + { + "index": 0, + "label": 3, + "pixels": "nnAxn28vpXQzpnY1oHAunG0ponMvn3Etnm8sn3EpoXQpoG80oW8xpnUpqXUtqncsp3UoonEmoG8noHArnG0slWstlmstlGorlWssj2UnjGIrjWEpj2EmiV8kflskdFUhmHAzl24on3ItpnQ4onAxoHErpHUvonIto3QunG4mm28pn242o3E0qncpq3Uoq3MhqXMeoG8hmnApl3MykW41i2g3jGY0jWQwlWkyk2YukWYtjmEmj2IiiF8ffVsgd1gil24vl20hnm8kp28woGoqo3MspXUtpXUto3MronMrnnIwnW05oW8zpnMmp3IlqXEjqnQnn3IvkW82eWAxblo0Yk4yZU0vclUyeFYwhmA3j2czjGMnjmMji2Iigl8ieFkhm2som24goG0frnAsp24rp3UuqXgwqXcwpXMspXUtp3s5v5JfsYJLnW8ponMvpHI2nnA6lW9DaFAvZ1dBYlpMXFpUUEtCSj8yVkY0Uz4ncVUthGIujGYrjGUniGMnf14km2spnHIwoXMxqnIvqXIro3EoqXgvpnQspHEppHQqrYA79takw5xrl3I4km88jmxHb1AyTjUfVUU4cWdicG5vanJ2YWZpXV5dSkhDVE5GVUkvaVMtgGAwimUuhV4kgV0klG02hWhAgmQ5k3A1oXMspXEnp3Qpp3Mpo28lpXQno3YqtIpVnXpOgGY6YUsrQjIfRTorQjgtWVNMdnFuenl4d3p6cnR0XmBgY2RhW1tWOjovQzolbFQxjGk6imIshl8of2Q5bV9QLyURWEocmXUwqnYrqHMoqnYrqXUqpnQlpHgnk2s0gWI7f2xLZFdGREM5TlNISEtAU1RKhIJ5ko6EfHZsaWNaa2Zec29nVVNNP0dFLi8nTz0khGI6jWMwhl0ng3NaY2BcKismRkApj284p3UqpXIkqHQnq3cxoXEzjG0zeF4xgm5NkINrdGpdWFdPW19YVVhSTU1FfHZro5mMiHxwZl1RamJYZF1UVVFKNjw6MTUxOS8ga1MyimcziGEnqqGQZ2lpNjo7fHlxmXxSoXEro3UppnoypXlCrodfcVk7fWlOnY15nI+AeW9lVlBKUlFNVFVSUE5JUUc9in1wkod7cWddV09GU01FVlJMR0lDODk1KCMbSjsjhWo7iWcttLCjhouPXmRpmpqVrpVwnnQznHQvmXY8z7SS7dbGz7SmnIN3rpmRlIN9fW5rXVVPVlRPSkpHOzk1TEQ6iX1wj4V6hXxyamJZVlFKV1VOVFVOS0xHMjErKB4PX0sshGc5t7evbHR6jpeepamosZx6m3Ayn3Yzelkv1cWz7eDi3L+8pIeDt5+bnImEfWxoeG9oTkxFUFBNLSwoW1VNr6WanZOJm5OKa2RcV1NNZ2ZgWFhPTk9JOzs7KSQhOy4faFEuvL+9ZGx0h5CZqq+yu6eIpng7rXs3hl0sdV9Qwra8x6ukqo6FuaGXvaufhndqdWtfZmJZVFRPJiYifXlx0snAoJiOkouCXVlSU1BLXl1YaGheVVdRSUtONzU3PjcwTDgavcLCWmBpf4aQr7S5rpyFpntEsns1n20vYUQsqJqYqJB+iXJeuqaU2Mq3oJWBe3FieHJpc3JtMjIvlpOMwruym5WMe3ZvW1hTVFNPVFRQX19VVldRVFdZSUlJT0pASTcYvcDBXV9nmJqjubzAd25iiGpCrXw6p3QyZ0gnk4R4kX1np5V/va6b4tjItKydjYN1fnVrdXJtR0dEmpiTurWulZCIcm5oV1VQUFBMSElGUFBIY2ReZGVjWlhRYVlFXkkiwsTEbGtwqKesurq8aW1tY1lDnHc+p3o3ZEoic2pYintnxrmpvrSprKWfkYyMmo+Gkoh9Z2RfR0dGmJiVs6+qiYV/goB6bm1pVVZTW11bX2BabW5oc3RvZGBQYVU1dV8vxcXFhIGIrKeuuLK1gomOTlNNjHhYm31Nc140gnhdj4N05t3T8uzmkYqJh4KCg3lweXBlbGhfX1hLkIZ2qJ+SmJOKcGxlV1VQR0hEV1hXaWhjcG1jeG5dZ1Y2eWAwiGgwy8vMkpKgqKSyv7a8qKqsTlZafn1+in5xinlSYFAlmo+FraObopiNjIR1cWpYcWpaZWVcaWVXcFo6q49onIptlI1+h4J2bWlhTkxIT09NXl1eZVtSa1M3fVgtl2w3kGgu1tfXo6a0pKe4t7jCsLa6XmZpYGBmnJWRlIlval09gXRpdmlfcmZZdGlZZltJc25iVltYZWdfkIBmdmBARDgggHhphX5zS0U9PDgzOjg1R0ZBZl1OdF5Aj3BElnRAjG421NPNsrjAp6+9rbXBsLi8fIOFVlhgjYuPmZSNh4BvaFpQTUA3hnlsfG9ggXVkk4+FVVxdXGBdlot4hHVddW1ca2NWS0Q6QDs0LCknQT48VkUohWk7m3c+oHg2mnMtl28ux8C0u727q7C1rrO5sba4kJWYVlpjd3mEenyCiYiHkIZ+RjszgXZsbGFWkYZ7uLCodHZ2SUtJg3dniXxphoF2WVZOMzEsNDMyLzE0WlpdeVs8o3ZEq3lApHE0nm8ylWsupZySw8G7s7Kvsa2stbW0mJ2gY2dvg4eSq6+5Z2lvXVpXUE1JXVpWenZ0sq2tv7axlpSUZGRlWU5CV00/PD05LjQ2Ji4zGCEpLjlFPEdTbGRLkH1SkHtMgG09f3FFeGk/dXh8w8jIsbKwsqmotbOzipCTU1dblpmf9ff6297hhYyQho2TlZyksLbAvsTQwsDFqKy1fYWPbm1tPT4+IzE6IjZEMUZXOlFmPVVuOlRvRWN6SGV3Tmh4RWBwO1xwN1pzT2mFr8XVrrfAsKyxsbG2jJKWbXBx09PR/fz3/P380ODofI+dcoSVfI2idIWceoWYaHyURF13RFdoPFJlNFRvMlRuM1VzOF19OF6DM1uCK2CHM2iNO2yOMGGEK2GJKl+EKVmHYImokKi8qK68srbApaqupaak9vXt/fvx4+fkboiZPFhvNVBpMUxpMUtrMEhlLU9zKlF4LlFxKlJ0JlZ9Llp9Lll+K1eAKlmELl2LLl6JMmCJN2CHNV6GM1+LLVqFHVuNHVeCO2aGg5mwprO/hIiJwr21/vry8fX1jZ+vPV5/MlR2MlR3M1V5MVN4MlR0L1Z1KlR1J1JzIk9xI1N4J1Z9JlV9KlmCLVyGOGeRPmeOO2WOOGaSMmOQLl6MM2eVMG+iHl6MIlV8SWqIgJSngIiP19XR//35u8bNQl12NluAMlh9NFp/NFp/LlN5LVJzK1JxKVFwJFBxJ1N1KFZ7KFmDK1yGLl+KO2yWPm6YQG2TO2yVNmyaMmmYRnunU4m2NHKlI2OTH1aCKVN6Ql9+gJGk4OXq8PX3fI+ZOlxyMVd7OF6DNlyBLFJ3LFJ3L1N3LlR3K1N3K1Z7LFh/LFqDLWGNNmqWOm6aNmmWLmGNK1+MJFuKM2yeSYKyVYq2TH2pMm6iI2KVHVmKI1aFLFN+TmqKytvp0+TqYX6MQWh+Nl6BMFd8OmGFMFd7KFB0LVJ3L1R6MFd+L1mCLlmEM2GMJ1yKJ12LMGaUL2WTJ12LHFWFKGWZQ4G2Q36wLmKOM2CLMmyhI2GTIFyPIViNKViKLlR9aIWfqsXTQGR3NmF5NF6ANV+CPWeLOmSHNmCDLVN4Kk92KVB4LliCMVyHLlyIKl+LKF2KJ1yIJVqHKF2KLGaXP32yL26kH1qMDzxnM12IRHyxKmSUH1iJJluSJVeLK1mEKk9xR2uFMVlyH01pG0dpJlJ1MV2AOGSHOmaJNVyAOF6DPGOJOWOLNWGKMl+JLV6IJ1iDIVN9KluFPnCaT4SzSYO1OHSoJmGSDUBsKFV/PXSoMWaUI1WEK1uPJ1qLKlyGLFh9KFFwKlVzG0hoF0NmHkptG0dqHUlsJFBzL1Z4OF+APmWHQm2QS3ecRXGYMV+GK1h/K1h/PGmQVYKqbZzFXZG+PHOkGlKCHVJ+FEBrNmugOGmVLVmEK1aGKFmGKFyEKFd7JlFzJE9yGkVpFkJlHUlsGUVoHUlsEz9iEjpZIEZkL1d2PWiJSneYQm+RNWCDNF+CLVd7Q22RWYOnaZK2WYevMGORGE18IlSBFUNu" + }, + { + "index": 1, + "label": 8, + "pixels": "6+vr5+fn6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6enp6enp6enp6enp6enp6ejp6efp6Ofp5+np5uno6Ojq6Ofq6Ojo6enm6Onn6enp6Ojo6Ojo6Ojo6enp6enp6Ojo7u7u6+vr6+vr6+vr6+vr6+vr6+vr6+vr6+vr6+vr7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7erp7Orp7Ozq6uzq6uvt6uru6+zt7Ozr7Ozq7Ozs6+vr6+vr6+vr7Ozs7Ozs6+vr7e3t6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6+vr6+rq7Onn7Orn6+vq6uvs4+bp5+vu5+nr6urq6urq6urq6urq6urq6urq6+vr6+vr6urq7u7u6+vr6+vr6+vr6+vr6+vr6+vr6+vr6urq6urq6urq6urq6urq6urq6+vr6+vq6enm6Ojn5Obo3+LnusDF0djbz9LV5OTm7Ovr6urq6urq6urq6urq6+vr6+vr6+vr7e3t6urq6+vr6+vr6+vr6+vr6+vr6+vr6urq6urq6+vr6+vr6urq6urq6+vr6+vr7O7s6e3t2+Hmy9Lbo6yzw83Q1trd5uXo7evt6+vr6+vr6+vr6+zs7Ozs7Ozs7Ozs7+/u7Ovr7Ovr7Ovr7Ovr7Ovr6+zr6+vr6urq6+vr7ezs7ezs6uvs6Onq6+3t5efo0Njaws3SucbPrrzIpbO9uMTKz9fc4uTo7Ovt7Ozr7Ozr7Ozr7Ozs7e3t7e3t7e3t5OXl5OPk6Obn5+Tm6ujp7ezs7e3r7O3r7evs7evs7+zt7+3u4eXm4OTl6e3u3eLkt8XMobS+n7S/mrC+kKOxj5+rnKmxxs7T6e7v7O3q6+zp6+vr6+zs7O7t7e3t7+3u1Nze4Obp5uru4+jq5erq6u3s7e7r7u3s7+3u7+3u7+zt8O7vyczL297d6ezr1trawczSucnSuMnTrb/LpbbEn667orC5usfM5e/w6u/u6e7t6e7u6u/u7O/u7e/u7u7u2Orx3ezz4e724e/z4/Dw5+7t7O3r7uzr7uzt7uzt7e3t7+/vxcbE3N3a6ern5ufl0dXZ0dje2+Tr0Nrj0d3q0uDr2enw2uvx4fDz5O7w5O/w5vDw5vDv6/Dv7fDv7u7udoyVd4qUfI6ZiJuhrLy/4erp6+zp7ero7Onq6+vr6+3s6e3r1tjW4uTi6Oro7O3s5Obo4+br5+zx4ejv4e332enzydviuczTrL3Dp7O6p7S5usfJ3+vr6/Hv7PDv7vDvbYKNZ3mFbH2Jb3+Jkp+l3uXn4+Th5eLg7Ojp6urq5+zq5u3r5err5+vs6O3u5uvs5+zu5+3w5e3x3+juv87VpLi/kqWsiZyjhpWfgIyZeYWPlaKm2OTl6vHv6/Du7fDvw9TgvMrXx9PgyNPf0dnj3+Pn1dXT09HO2NXW3N7e2+Lh0t3b0dvf093h2OHm3OXp4ert4uzv4e3x2uftt8zQr8bLtcjPssLKusXTqrLEjpekucPK2+bp5/Du6vHv7PDvwc/ev8rZytPg1tnq3+Hx1tvjy9DQq66usbS3z9XWrri8YnB5XXJ+ZXmEb4GLeoqTiZihmaeuytjc3+zt2ujr3Onu3+rw2eLp3eTt1NvlxMvU3ubt2+Pq3ebp6O/y6/HycYKYb32TcX2NfYOXipGlqrbBv8nNvsfM0Nvi2Obqnqy3NkdcLUZbMUlbNUlaQlRiZnKBn6iz3ePp6u/x6e3x4+ft3+Tpz9PZytDU09rc1Nvfx87Ws7rEvMXN093j3efqPVFsRVZyP09kRFVme42bi5ukl52kw8jP1uTqzt/ko7S+Z3mKX3CDZXWHipeotcDPz9Tf3d7o29vjzcvUt7rDnqauk5qjg4qTfYWMgouQiJKYhY6XgImTipmgtsXLxdTYKDVNOkZeVWJ0f5CZhJecYGtud3N2o56hrbS2uMLFtsLGtcHIt8LKxtHZ2uTsyNLZrrW6n6WskZafhIiVdH2KYm97Xmp2Y297aXaAa3mCeoeRipehlqSuna64vM7VucvQDQ8jGh0vhoyXztjcipaWdnt7jYWGrKKitbW0z9HT3ODh5Orp4Oro5vHw4u7usL2+kJ+jipqijp6qkaOxmqu7laW2laW2mqu7na69oLG/rb7Mu8zZvs/assTQpbfBna+3BQUYOj5PyM/Z4ejvxc3Ux8/T1NTa4uDl5ebt6ez26O715u7v0d3c3+7v3e7x0uTqxtnktMjWwdjmvNXlvdTnwtbqwNTouMzgrMHUq7/RobXFkKWziJypg5KhgI+eipqlJy1HkZuzvszeusTYuMXZwNPlwtPmwtDjws7jv8vkwM/kvs/dscHPtMbXmrDBk6m8kaG4nKvDkqO6cYWccomhhJ20fpatb4eeXHOKW3CHXXKFXnSDaX2MeYWXgY2egY6ceoehorPPj6DCiZq9g5i7gJi+f5bAgpbBg5bAgJO+f5O9gZW9gZW8fJG6aH6jZHqaZniadoaqcICjXm2RXnCUXnWZV3CQU2eIUGGCU2eGXW+LZXWNbHmQc32SeYWUgpCcSVdtTFpxTVp6UF1/VGKGV2aOV2aTWmmWXm+YZnega3ylcYOsc4m1doi6doS0eIWvc4isboWoan+jZHebX22UVWWLT2GEUFx/UF6BTWSFUGSBUmJ6XGh+cXeKfYeSiJWcDRkpAwsZCRAjEhowEho0FRk4FBk6Fh49GiQ+IitGKjNNMDtXNEVqPEt5Qk1+Rk9+R1d/SFh+Q1F4PEhwN0NqNURoNUVnOUVmOUdpOU5uSFlzV2R3aHGAeHyIgoiNiZKVJC43CxAUCA0TICw1JC06FhkpCAseAwgYAQQRAAIPAAIPAAQUBg0qBRI4ARM8Axc+DR1HGCZRFSFNFR9MFSZOFixPHjJTJzpaOUZlVVp2cXOKe3uKdHN9enuAhouJmaCeIyktGhsaDRMSGykpR1FURkZMMTI5Gx8lDw8VBQULAgIHAAAHEREjOUBbHzJOCiQ+BB48BB4+Bx4/DiNFGStKKTdTPkdjVmF7enySkIOVhHiHcmlydW90hIaFkpiSrLOvEA8RDQoJBAoIAwwLLSwuQTQ5NisvJCEjEhIUBAQHAgIEAAEDBwgPdnWGoZ6zg4CUcHCDaWl9aWd8bWl/dmt+inOFmn6Ql36Nf2p0aVZbal5heHR0gYKBjpOQpKyluMK+KCgjDAoHAAMDAAQEDAYHHgwRIAwRFQoMBwYHAgEDAgECAwIDAAACRDpAtoCSzYKUxH+QwnuNw3eJu3GBrG56lmBqe0tTZ0JFX0dGaF1YenZxgYR+hI2HmKKeq7awucXCRU1AGh0VAQEBAQECBAEADAIFEgMJDAIFBAECAgAAAgAABAABAQEBIAwLmS07yy9Ewy5DvzBFszJDmzE7dyoxWyYqUTAuXk1HdW5mfX50fYB4gYeAkJmTorCrrbu3uMbEU15SLzQrAQEBAgECAgAABQECBwEFBAACAQAAAQAAAQAAAwAAAQIAGwMCjhkmzSA2xhkuqRkreRkkVR0iSiknVUI4ZlxSeXFpgHxzen5zeX92hIuDk52WpbOusL+7usnHXGZdNjwyBgcDAwIBAgIAAQMBAQMDAQICAQEBAQAAAQAAAQEBAAMCDwEAZhMcnR8vdREXSg0MOBsWSjo3Y1pRc3Njen5vfHxwe3txfYJ3gId+iJGJlJ+XorCrscC8vMrJV2NZKzMlExcLCwwECAoCBQsEAgoEAgcCAwQBAwQBAwQBAgMCAAYGBAUCKg0NRxUYNRsZOTIpUE0+cWJShHFlhn5xe35wdH1veIBzg4p+i5SJj5qRnKihqbiztsXBvMrJUmBSLjkkJCwWHyMRGx4PFhwPERoNEBcMEhUMExUNFBYOExcPExsUFx8VJSgbQDctV0ZDaFhRdGZVgHBYi3lpg3pudXprc39we4V3g4t/i5WKlKCXn6ykrr23ucjEu8rIVWVTPkswOkMmNz0lMzgjLzUhLjUiMDcmMTcoMzgpNTosNz4uO0MtREcwUVQ7aGBKdGdTf21chXRhf3lhf39rdnxqcn1seoN1gYh7iJGFjZiNlaKZnqujqLeytMO/usjH" + }, + { + "index": 2, + "label": 8, + "pixels": "nr7enrvai6bChJ66psHettDsu9Puwdjxx9vzzd310d70ztrr2uXw3+jx4+vy5u311dzj4unw5+716+/47PH56O/z6vHz6vHz7PL14ufr5uvv7vP36O3x5Ofq7e/z7vH2qsjlrMfil7DJiaC4rsffwdnwxdrwx9ruzt/z1+X32eX10tvo4enz5+716e/17fP42+Hm5Orv6O7z8vX79ff76u3u7O/u8vX08fX45Ons6+/z8/j86ezw6Ojs9vb69vf7rsnhsMjenbPHjqK1tcnbydzuzt/vx9bk0d3r3+n02uLs1Nvk4OXr5urv5uru7/T33eLl5Ons6e7x7/P26Ovs1dbX7Oro8/Hv9ff45+nr7vDy+Pr87e7x5uXo+vn79fT3tMvessfYoLPCk6SzusnWy9nk1OHrz9nh1t/l5Ovv3ePm1tnd3N3h5+js3+Lm8PT34OTm5Ofq6e3w5Ovusbi6rK+w5uTl8/Hx+Pj46Ojp7u7v+vr77u3u5OPk+ff49PLzus/fuczZpbXBk6GsvcnSzNbd2eHnz9XZ09fa5+3r3uLh1tfX2tnb5+Xo09TW6+zu4uPl4OHj6Ozu1OHkn6qwqK6y4ODl7ezv9/f35+fn6+vq9vb16Ofn6ufo+PX28u/wwdDcvs3Vqre/jpqkv8nOy9TV2+Lh09fV19rW6u7m3d/a1tfW1tfW5OXjx8fIzc3Oz9HQztDO6+/twczPcHyCnqet3uPm5unp9fb05eXh4uHb8e/o5OLd5+bn8/Hy6+jmxMzUv8fKrLO5hYuWv8LEysvJ3t3Z2dXQ39vT6+nb2tjQ1tTT19jU4+bdvLy5sLCvu767usC9zdTSu8DFeIGJiZedrLe4t7672+Dd3+Dc2NbO6+Xa4tvR4d7b8Ovn6+DYzM3TxcbJrq+zjIqTy8DF2svM4M7O4MzL6NTQ7d/S3NDG3NLN3NXO3djOycfAzc7LrLKzipWbZHF6U11qR1VkPlBeQVBYPEVJaGxvtre30c7K5N7X2tDG1MW5793O7NTBr62zqqitnZqgiYWMsKWquqyvr6ChxbOz0b671MK4zr200sO91MfDyb+5wcG6wcbEjpifaXmJWWuAW2yAVGh+U2h+Xm6ARU9aTlJYeXp8op+et6+srqOco5WJz76ww6+fcnN7c3R+cXJ7aGlwaW1ya25yb3BygH+Ai4eGkoiGl4yJm5OQnZeYk4+Sl56glqGndoaTZHeLY3iQY3iMVWyCVmyDVmZ4U1xoi4+VgICDmpeWmZGNdm5qbWpphIKAe3h1Qk5ZTFdmS1ZiRFJYU2NrWmlzVGFoWmRqXWVram12ZmpxZ29zanJ7a3aGcoSXbH+SWm2AWm1/W25/VWt4SGBvQldoX2x6cneAgISGbm9uk5CLx7+2fXhyZ291XGZtXmhwNUpYQVVoS19uTWJqb4COanqJVWJxRlFeXWh0cYGSX3F/XXN9bISUc4ula4alYXuXYniOX3OCYnR/YXd/WnF7VWhylZ6lu72/s7e0kpSOcG1kzMW4mpWMX2dtV2NsVWNsOlFkVmuCXnGESl1oZHWBZHOCTV1tVWZ2eImahZirf5WobIOXaYKbboilYn2aV3GLUWyCUWx9V3KBX3uMX3aGcH+Jqq+zw8LB0M7Lwb25f3ZwraKYsqegUFBUVWJpT2VtSmF4WW6GV2p+S11qUmJxRFRlR1lsUGR5WW6DZ3uRdoqhb4afZX6ZaoOhaYKeYnyVYHuSYn+TYn6RbYebcoaWjpmhtLW2uLSxv7i1wLe1oJeUhHp2qqCdUE1QPEhOQ1lgTWZ/T2WAUmZ9TmFyT190SFhxRlhzVmuGbYKfeY6ogZewhZ64iaO+iKS/h6G+g525kqvFlK3Ekqq+lqm4lKKso6mts7Gvta6oubCrsKilqqSjZWJjWldXSUZHNz9DO0tRYHuXXnaVan+aaHyRbX6Zg5SzhJi4iqDBkKfJmK/Nm7PPmrTQm7fRm7jSnrnUlK7Ilq3GnbLJnK/DkqCrd4CGgoWHko6LqaGbsamlqKKhp6aoaWxxRUZJYl9cVllaSFJWaoWlZX2fc4qng5iwgZSvh5q5kKbGj6fJkqrNlq7QmrPSmrbSmrnSmbnQl7XJkKu+gpiqhpiqi5qpf4uUXmZsdXh6kpCOn5uZp6Wno6KloqOnhIiOkJGTwLu1mpmYaWxvX3ydbIWqdo2ubYOdX3SNXXKPgZi2karKla/Ql6/TlrDRkK3Khqe/fqC1epqne5eiepCbhZagm6iylKCpg4yTk5idoqWnnJ6gnaOpl5uimZyhlZecn56epJ6WnZiWlJOUZoGiWXGUSWCARl15Vm6Kb4eke5SxjKTCj6nHgZ+8eJaydZKreJSqfpmshZ+sjaWwlqq0jqComaiwn6y1l6GqnaStpaivoaSsmaComJ6lmp6jkJKWg4SFeXl2fX19lZaZVnCPPVV1R2B/boemgJu8iqXFgpy6e5Owdo6pbI2jdperhKCyj6e5mK2+nK6/mau6lae0iZulkaKsmqixmaOtmqGsoKOvpKaymJ6kkJecfYKIaW90XGJnS1JXVlxihIqQaIWmZ4Sla4eoco+wc4+wdI+ue5azdo6qdIqkhqG4jam+kKu9j6m5jaW1hZeodYaWYnSBWWt2gpSdlqStl6OtmqOtmJ+rkZiidYCFYGxwWmZqUFtfQUtQR05USVBWQUhOY4Sla4ysb5Cxb4+vcpCud5OwfZezfpawdYukfZKrfZSrgZqtg5+vgpyrW25+PU5eOUtYOEpVc4SOlKOsi5migo+Ycn6IX211VmdsU2RoSVpeOkxQPEtPS1JYMzk/GyEnPl58aImmdJSycpKvdJKvdZGtZoGaW3OLVGqCUWZ+TmN6cIeahZ2ugpqpYHKDTF1sU2VyVmhya32GbHyFYHF5WGpxU2ZtUWVsRlhfPU9WM0VLLT9FNENJLjU7HiUrGB8mOVZvYH2WaoagaYafa4mjaIWeQVx0NU1kO1JoQFlwRFxzboOXh5mshZaoc4SVYnODWGp3T2FrTmBqUGFqUWNqUGVsRl9kN09ULDxFMUBJLTxEKTlBIi83HiYsGyIoGB8lQVpxWnSKaIGXaYOabYmhbYqiT2qASWF3VWyBWHSIYnyQan6SYnGEU19yRFRlQVNiRlllSlxnUWJtUmRsSFxjM0pQKUNILEVLPUpVN0JNJzM9Iy46ICs0HiYtGyMpGSAnQ1x0V3CIaYKaZ3+XZnyUY3iPWG6EUWZ8TGF2RVpnO1BbOUxXOktWP1BbQlRjRltlSF9lRFljPlFeNklSLkFIL0FIMUNKLD1FOEVOLjpEHio0HCgyHSozGSgwGCMvHiUwNkxgOk9kQVZqOk5jN0pcMkVWLUBSLD9RLkFSM0ZPN0pROk1UPlFXQFJbPlFeOlBYM0lNJjtEJTdEMERMMUNKMD9IKjZAJjI7KTY/IC02GygxHCgyGykxGSgwHCc0HyUwHi07HSs5Gig2Gyo3HzE8IDQ9ITU+JzpEMURONEdPNUhPM0ZNLkFIKDtEJjpFKDtCJjg9LD9HQlVhN0lSKTlBJTM8JC84JS85Hyw1GygxGicwGygxHCkyHioyISoyFx0jISsyHygwGyQsHCYtHCwxHjA1HzE1IDI3IzU6ITQ7HjE4HjE4IjU8JztCKT5HLT1EKjc7NEVLSV5oMUJLHiw1Iy44Ji86ICgzGycxGicwGygxHSozHikyJi41GiAlDRIUHygtHicsGiMoGiQpGScsGSkuGikuGyswHS4zIDM5JTg/KDpBKj1EKT1EKDxEKjc9Jy4yLjxCQFVdJjY/HCgxJC44HiUwHSQvGiYvGSYvGygxHCozISs0JSguCQ0OBAcFFyInGyYrGSQpHCgtHiwyIC82IjE4JTM7JzY+JzlAKDtCJzlAJjlAIzc9HjM6ISsxHB8kJDA1OU5VJDI7HikyHSUwHSMvHSMvGCUuGCUuFyQtGykyJC02ExQYBAYDBQcDHCkvHisyIC00Ii82ITA4IjA4IzA4JTE6JjI6JjM3JDE1Ii0yHigtGCInDxoeDBEUCAgLExshLT9IICw2GSEsGyItGyItHCMuGCMsFSIsFCIrIiw0GR8lBQYIBAUDBwgH" + }, + { + "index": 3, + "label": 0, + "pixels": "m5yVp7C7sLPBvsDNsbnKpqu3qK21pq20qq+2s7O9u7bBu7jAu7nAu7jAuLa9uLW9trO6tLO5uLe9urnAu7rBu7rBvLvAvb2+u7u7u7u7vLy8w8PDycXKycTRysrUwLermZudo7PMq7jXu8Pjs77gm6K+mp+zn6Szn6OzpaW7q6nDr7DDqau7q66+oqS0pae3qqy8pKa3pqi4paa3p6m5ra+/qau8qKm8qaq+ra7Cvr/TyszgzM7fytDey9fjvb63m5qZoLLJqLnVuMTbu8vfrsHVsLLEvKi4tqCxs6/Dsb7TvsTUwMPQwsXSvL7MubzKwcTRwsPRwcLQwsPRw8TSxcbUwcHQv7/Qv8DQxcTVzs3ez83f0M7aztDXzNfgvb+4l5qmnbLPprzTscPetMriucXcx7zJxYCDtmx3zJiezZqmxpux0p6yxZWnxJWmy5Srzae3z6Gy0qOyy626z6i50qO6xa60zJ+l0LzPxtDkzMzcyc7d0czgz83fztTmwLy6l5qnnrHLqLvKrr/ascbgtcThv73WxH6Ot4CZwouYvWp4uWuBxHOBuXh+uXZ8ynGDx3eGx3KEyHKCwH6Kw3aIx3CIvoiNvHB7yaC6x8vjycnaxM7Zzs7ezM3cz9bjxL65lJeknK7Jp7vLrr3Zq8XcrsjaxLfRw5OlwKnEvqi1vZGcuKW0u6qzvZKgvZWjv52svrS/w7LBu7C+xr3JwLC/vLPAwLzGwbG+zcTUztDhy8/h0dDh1NDf0NHh0djoxL68lJikmazGpbnIrr3ZqMLZsMbWy5Osw2BovJWevJelu5CmvpivtpilwnmQxYCXw4ugxJyywZetyKq9zaK2xpaqxa23xZatyaS5xZymyKayxszcw9LixdPdy8/gz9Tnw7y8mZupm6zJo7bHrLvYrMLavLXLx3eS0WVvxHuGvoOVvYOdv3iQwZKbvIePu4ePxH+QynuTwnuOxIOUznuOwm1/yYSNxHuOyJ+wtXuJu4SVyL/RycfcyMnZxMncx9Dkvbq6oKGxn6/Oo7THrLnZrsDbsLrNsKvBvq/FtKK4r6W3sKy7sKa4ta/Aqqy6rK27tqq9u6zAsrLCtbLCu6+/saOyvKy6tLK8u77Ix6zBxLDGvMjWvM3bxcjbwMndwtHkuLm5q6y6p7fUorTFrLrWqr7Xq8DWtMLcsLfSm6C5nKW7lqK2nKO6lp+2kp60maS5nqK6pqfBpq7GpKzDnaK4naC1oqO2nKW2prbGyMjex8bevMrdvc3fxcrfwcrewtDjtri3r7G8tMTeqLrIsL7YrcDXscHUtsHWrrfMnKO1oKe4n6W2mp+wn6S1o6a4qKq8ray/qqi9pKa6oKa4oqu5oKi2qK24p6u6rLLJwsffw8bdxMfcxMfbxcjbv8jcwdDjt7i4tbe/u8zissPPu8jgt8ncqrvRrr7Xtsbes8LZs8HXtMHWtcHXuMHZu8LbwcbfwcbfwcbfwMPdvMPbucbauMXYusTWwMTZwMXbu8nbvMvbwMnZvcnWvsrXv8jbxNHjuru6ubm8vs3cusbUq7LOmaa1hI2ZlZqswcTZxsriv8rhusfdvMXcv8Xewcffw8nhxMriw8nhwMfdvsbcvMTavMTZvsbbwMfcv8bav8fZwcrcw8vexc7gys/gys7gzNTmwb27urq9wtDfvMjWnqXBhJCddHx+Xl9jbWtzkY+dsbPGwsfdwsfdv8XawcbcxMnfx8zix8zix83gyM7hxszfxMncxMndx83gxs3gxczfxMvexMvexMvexsrdxcrdxs/iube3urq9xdTixNDexszpws7cuMHEjY+SXFtaVFFUaGVxjo6hs7XKw8bayczgzM/jzM/kzM/izM/hzM/gx8rcwsXXwsXXwsbYv8XZvcXYvsXYvsXYvsXYv8TXvsXawMzhtbW2uLi7x9blxtLgyM7qxdHhyNThyc/asbOzdXRzVFNYXV1qgICRra7Aysvd0NLkzc7hyszfyMrbx8rax8nZw8bWxMfWxcnZw8nbwcjbw8rdwsncv8fav8bZvcbcvsvisrS3ubq+ydfpy9be0NXpzdbkztbi0NTg1tnhr6+1XFtiTElQW1ZbaWVqjIqStbXAy8zZztDgysvhxcfdwsbawcfZwsnawsnawsjZwsjaw8rdwcndv8ndwcrdvsjcvszjtLa8u7u/zNjqz9jd1tnp1Nvn1Nnj09bi0NPdy8zVfHuCR0RJV1JPVE9LVFFQY2FkhIKIp6WtvrzIy8nXy8rcw8TZwMHZxcffxMbewsbdwsfdwMjbv8jbwcnav8fbwMzjt7a9vry9z9noz9XZ1tbk1Njj09jh09bi0NLc09TdiYiQSEZKV1NQU05KVFBMVlBOU01MWVNTa2Zkg36Bm5eho5+wtrLJy8nhzMziysvfxsncwsjZv8bXwcfXwMXZv8nhtrS7v7u70tro0dbX19Xh1dfg1Njh1Nfj1djizMzVcXB3Ly0yOjc4Pzo7TEVFV01NXVFSWlBQUE1IRkZCPj4/OjtBTU9benyFn6CitLW4wsTMyc3ayM3fyMvdxMjdxMrjubS8v7y30Njnz9Le09Hf0dPf0tbm0dTk1NThnZqiZV9iQTo8JSEnMzA1RD5DSkFEWE1OW1JRVlRSVVRTSUhINzg5Li8xPj8/SEhDTk5La2tthYSLnp6ouLXGw8HXxMrfurbDuriwytLiy87i0c/ez9HeztPi0dTiyMjUlZGbjIWLl4+WZGFqLS01NTI5Mi4zYFpenJaaoJ6hgH+CSEdJYmFjcHByWVhaQkFDQ0NFg4KGpqWro6Kprai3t7XFvMXQsrC+ubevydLhys3h0tDf0tPf0NTe0dXe0dLe0tHe09Hg19Tkvb/MkJSfkpOflJOgqKazysjWztDcwMPPmp2po6aysrXBsbTAn6KtnJ+rsrTDv8HSwsXWxMPYwcHRvMfSsLG9sK6mvMTUwMPXxMLRwMLOvL7MubvJt7nHtrjHsrXDs7fFrbXCqrLAqrDBq67Cra3EqarEoKTCoabEp6zKparIoabEparIqrDNqq/OoKXFmJ3Alpu/nZ3Fo6PFpK/JnJ61cnBlY2x4bnCCa2l4Zmd2YWRwXmFrXWBqWFxlVVpiWF5mUFdjTVRiTlNlU1dsZWeAcXOQbHCSam+Sa3CTbHGUbnOWb3SYcXaedXqkd3umeHyod3uoeHmoeXqleoSnfHySenVvbXOCcXGGdXCGc3GKcG+IcnGJcXGIb2+EcHCGb2+DbW5+bm5/bW2Abm6DbGuDc3OKcHOGaWx/a26BbG+Bam2AZWh8aGt+am2Ba26CbXCEbXCEZ2R3Zl9zXmJzZWVgeHFoYWZxa2l4cGp4bWp6aGZ2YmFsXl1kXl9gXV5bWFlVVlVZUlJYT05VUE9XTk5WUFBWT09PSEdGRURDQ0NCQkFBQUE/QUE8QEE7QUI8QkI8QEE7Qzw2PzcyNUc/TWRLW1Q9Nzw3QUE9RUA5QkA6QkA/Pz47PTw2QkI4QEAzPD0vOTgvOTkwPDwyPT0xPz8yP0AzQkM3QEE1OjsvODgtOTouOzsyPDw3Ojo2OTk0ODg0OTg0NDgwMUg6S3VoXIBoXVNEPDs9Qj9BRD48Qz8+Q0E9QD03QT85RUM9QT44Pjw3Ozk6Ozo7Ozo4PDw4PT02QEE5P0Q7OkA3OD40Nz0zNzwzOD40OD00OTozOjo1OD03NUE5QVtLXYhxYYl4UWNLWU8+OTU0PT07OTk1OTc5Ozs5OTo0Ozw2PD02OjwyODkwNjcyPDw5PT44Oz00PT81QUM5PT82Ojw0OTszPD42PD43PUA1PT8wQj4yPjw0OUc9Rm5fYY58WXdlO08+Q0oyWVI+PDo1P0I6PkE3Pj87Pj49Pj48Pz48Pj85PT43QUE6Uk9LVE9MUUxITkpEUU1FWFRLVFBKVVBLU05JUExGQz86Qj43QEE1NEIzOFZFVnxrZ41/TGZbOUI6PUA2S0UzXE5APDQzPTozPDouPzozQjo4Qzs5QTk1Qjo0QzszQToySEU+SUdASUc+SEY8RkU5SUg8Skg+S0lAS0pAS0lAQD81QD80PkQ3QVpGVoBnWIBpQFhIOUI1PD8yQEE0SUQy" + }, + { + "index": 4, + "label": 6, + "pixels": "QUQyRlFAMEAuHi4eFyEWKDkkLEs3LVA5LVM7KEY2ChQMDyISLEcrNUssM0YxMEIyQVc6WnhNXXxRW3lNX35TUWxOPFQ4N1I5cIhhb4FdKTsfRFs6TWBBM0MpNkw1Q1dCRVA6T2ZRPEo5Hi8dKTgjQVw9MVQ7MVQ8MVhAIz4vBxIHGTAbQV04RVw+N007MUkvTWtEVXVKU29KUGpEV3VOUWxRN00zO1M8g5dveYtgHy0VL0EnOEctNkIsQVpFPVFCSV9IVG1XSFhGKTgjQFQ1SmlIMlY8NlpBNlxFIDUmCxQHJDwjPFk0Q1hBL0IwJzwhS2dDTWZCO04yPlQ3U3JNVXJSMEItP1Y+i550gI9jFyMQKTcmRlQ/TmJLSWJNMDszWHReS2RMUGRQNkkvUG1HRGZIN1hBP2BKOl5IHC0eERoMJTgiK0EoM0M0KDYjJzceVWpLYnVXS2FERmJFVnZRVHJNMkUuRFtDjqB3iZZrL0AqS11JZHhfXX5gQV5EJjIiX3hhWWhPb4BqQl08UXJLPV5EPVpIRF5MPl1JFicYDxoMFiQRHy8cIzclM0kzP1Y7SGlIS3FPSGtLR2VHTWdHU21JM0otTmdNlaKAnKyBV3BSV3RVY4FeX4RhS2dJWGxQUmlSU2ZNUmJLTWJDR189OllFQFtNOU49O1hDFCMTERsNHCsWMk0sPV07R2pHR2xJRWdIQ2VIRGRJOE41KTkiU25JRmI+TmZNnKeIrLqTYoJgWX9bXoFcb5BucIRoY3hcRV5IQGBGIDAZO08zSFo+SmRPSV1PMT8yMUo4Eh0PHSYYPlo2Un5JVYFLVoJNP2M+IjoiNEczX3NgKzkqGSUWXntYVXFITmpKpreVtMGhbY1oa4xsbIlrg6CDVmVRLzsrO1Y/NVQ7GS8VRmlGUWdNTmFIUF5LPUc6KDgpChQINUkvXotRV4pLWIxLS3I+GSkSDRoGLUEnXHNZOU9AMjsqZX1eWXhIYoxTkLCDs8OieJZyfJR4fJB2gJuFND80GBgVRGJJL041MUoxZoxod5V5WXJYP1A5T1xGQkczIiwXUXFHYJBTWYhOWoZPKT8iDhcHNEUoXHxRQ148R1Y+b3BQcYtjbptbc6VdiKpznLGNeZZ4f5Z5fJJ5c458HykhFhYUTXRWNVE6N044cpR2gKODe5t/QVRAN0UzT1E7UlpAb4lhbo5jaopeRV06FCENJTgcXHxTaY9dU3NJYYBQdpdieJxpc5xfXIFKkKd0k62EfZh3f5p+d5R/X3llDhYNFxgXVXhbOk87Nkk1cJF0gaWEhKaHZH9nMUEwJzYgVHJLaI5gbX9hfX5mXV1KP0cyU2xJYYdaXoVSaJJZbqFhbZxif6VsVXVHOVcxmKl3lq98e5d3fJyKcpF7XXRbDBMKFRcUbHtlNUUzMkIva4pufqGBg6iHgKWHS19IM0suW4xUVYpSa3BPim1ebmZWgYh1k6KHhJl4eJpmcZddd4dedXxcc4VYWnZKXYhYoL2EjapzcZJ2fZ2NeZR3ZXdbDhQLCQsHYGpYKjkoKzwoXHlgaodrgKSDgq2Ld5h3eJBre5Nmcn9XiXZZlHNfblxKaWZRhItsko12h4pugIVkhnRdjHhmeGtVfndXd4hfmLB8ka54Y4dlapFxgqF7Y3JZEhoPKCsgYXRfQlU/O043WXRcZH9kb4xuhayLiKuJk5l7jHxhloJlkXhcjndaiHZYg3FWf25WfWlVe2xYiHdkk31sl4NyjnpsnIFuiHVfkpBtkKJ1bY1rcJpzgqaAXHBYMkExU19MaYRqSGBFS2NHX3hgaIJoXnJWhaWGhaiHj4t0h2tXgGhRhXBYk3xgloFgoI5umIRqkXpikHdfhGtXh29cinNhinZroo1/pZCAo456f3tefpJ0d593dp16X3BcO0g1TV5GXnlgRFpARF1AW3ZcZX9nYnxfe5d5g6aFk5mBwauWinlkT0UzfGtYk3xlk3tiootxtJuDq5B3mIBlkHdfkHpgeWdTlINxs6eYtJ+UoIx4gIBie6B8cJV2P0s5GiINVGhIWHBXT2RMSmRHWX5abo1zeJh8eJV4gaOCeIpuuKOOwKaWV0c6cmRUnIV0pIt3po14moFsoYhxt6CFtp6Gu6OJrZd+lH1nj35utamfw7GjjnpjfI9ya491LD0qKTMhdotrW3BWWXBYZ4NkYIFddJN1ZHxjb5B1aolpco9ugHlmu6ibqJmLjHprmX9vrJKBrJOBp418pIt3nYRto4p2oYZxpY92q5l8nIZxoZGDkYJ1p5KDcnpjaoZpSmRIKjonXm9XZXlfYXZgeJV4eo5zco1tTmFHX3tjW3ZWc49sbn5jgXlqzLuwp5GCiW5eoIh7mYJ1s5qJuqGNqpSBspqIs5eDnIZvopZ4pZF5nIZ1jHtraGFQSFdDVGdIWXdRRmFDcoZubohta4dwepd9YG9XWnpYTGVISF1HZH1ebYZkf5l5V2BJjH1zvamYn4h2ppKHtKCUrpaFrZSCvqaUvKeVoo19mYBxopB5oZF6mYRylYJxS0s6Sl5OQlM9Plc4cJVziqmKd5R3aox0WXBZTl5DWXlYR2hIPFQ8Z4JmS2ZIX3RXco1tQko3f3ZltaOSrpuNvqqcuqWYq5WIuJ2MwaeYpJKGoIl7q5N/pZF8kn9ti3xpaG1dXHFiTWBNXndicJx6c6F3fph+XndhOkgyZ31daoFgTGVGSGNLX3lgXnhaQVs7eJp2Y31hW11JoZaDxLWivKmXtqKWwa2jp5GEp49/qo99oId2moFuoYt1kX1pinhmbnVeUWZPaYFriKuObZpwZJlqb4hwUmhRRlI3aHtZcYhcXnZORWJFVHNZdJZ3bY1rVXVTfZR2f4Frm5V9uq2XyLOcu6WUu6ibsZ+UnY9+lH5soot7pIx4po11oohylYVmeXpUYW1WeJiBc6R5YZZjYZVpZX1iXG9WjJZ4tL+al6x3e55fVXlFTG9OZ5FzfJl+WnNXVGlOkpR9r6GLrZqEyKyWvKGNrZuOrZySn41+n4l5rJOEo4h2rY97pIlzi4xYg3tSg4ZvcJx5X5VlZJ5qYJVnd5V0kKKIwMin0dy2wtGfnb13f6pgbJNcapFmXnpaan1mb4hvfItwr5+IsJaDxaSPuJuGqpuOsJ+WpY6AnIV1xamcr5OEo4h3k39mg35ZemtOZXJTZJpqYI9ga6BxZpxsbotsdIltip1xqb6SxdWmxNeeoL97iLBpgalmY4RSXHVViqOMkq2Rn5d+tJqGqY97jnxojYFzr5mKspiJppGDvKOWs5WKl3xqj3dhmoNvcGBKOkotW5FgZZVlZpdpSXhLW3NYV29VSmE3a4ZWpb+Luc+Xv9OXo8F+hrFogK1oapFXZn9XdpBvhI9ukoZudGhSTUk1Y1xLoYt5tpuMt6GRn4p4rZSBp456nIN0h3ViXlU+KzwgW5JhXJFiRG9BTW1AUWpSX3JcMkEiLEAgX3hLlLJ1psOGu9WcrsqNkLltfq1icplXaI5ScpZad41ba31fUWxSUmBGnY55tpqLqZCBsqGPqZWAln9rmINxbGJOLDEdP2E/YZNjRWxHUHZHVnVCWnRaX3BWND4jFSYNHCkPbYdOkrRysMeUytSitcyLjrdvf7JieKthd6Rbcp5WgqFxgZ14dotqkIdzqY1+n4d2rZmHtJyHmH5qd2dPREIqLDsmVXxbM1Qscohgp8WZaoNTX39cW3tWOU8tNE4lGCUNMUIfd5VXnL96u9CWy9ututaem8J6jbh1hbRydKVddZ9cbYdNd31Vi3tnmYNxn4p+p5OFnIdzfXJbZWxOQU8yRFU7QFs8N04qkKxsqsmGeo9iXn1SS2hHIDQYSWs4LkMkITAXNk4jc5dUlr12sMuSw9mlwtqlsc2Wm8OCiLRvkrZ5i6VsZXRCXl4/d3piZWFOX1lFYFlGaW9Wg5Z1dopsa4JgbYZigJ94j7V0mrx7aoFZTmZBIzMbGCgRTHNAQWA0KDodGykPO04leKBZiLVklrl0sM+WwNqqt9KYpcSIus6cz9amqrR5a3xFVnFKQlYvVWZHcIRmjKB/qbqclaeLiaeDiaeClrSTj7OImrmSgJx1" + }, + { + "index": 5, + "label": 6, + "pixels": "s3ZTi2A9TTEaWDskjWBBnV9DnFQ6l1M2nF8/nmFBkFM0l1o7l1w+iFI1eUsudk80fltHbFBBVDsrVDInYjcvYjgvXjgtUzMmWjwvVjgtVDMqYDoydUxFVzUuTC8pTS8puIJhhVg1gFk6kmlGn2xGn2BDnl1Ep2hNpWVEomJBmVo4mls5llQ0llc5iE8yfUgugVI8bUg0Wj0rUjImXTcvYjgvXjcsWDMoTisgTCgeWzUrakE4dktDYj01WzozWjkxtIRkmGhHsIFcqnpRpGxEmFk5m19EpGpOomJAqmlHomI/n147nFU0l1Awkk8xjEwwklU7fEwyWDYhRyoeVTMrYjowZz81a0I4ZTwzbUI4b0M5b0I4b0M5ZT41XTgvXzkxr4Fgrn9fuIhhtYRZqHBJmFo3pGhJo2lIpmVBs3FOp2VCqGZCrmdDolo3n1c2pF0/l08viU4uWTMaOh8SSCoiWjMpYzkvaz41dUY9gE1EfUtAeUo+aTwwYTctbUM6b0U8r4Bcrn9hp3lUrH9Xom1JoWM/sHJMr3JLsm9Ksm9Ks3BLtHFLsGxDqGM7oFk1pFw7rV47nFk0eE4zRSweQicfWjQpYzguXi4naTUufEM7f0c9e0k9cEI0aDswcUU6dEc8tYllroNmkGhHqn9ZqXZRpmpGsHFMs3RMtHNMtHVRtHROtXFHsG1ErmlDn1o1llQxtWpDr2hBm2dIdE85YDorfU0+g1JCcD0ydT44eD82ekM4eUY6eUk8eEg9dkY8fEtBwJh4nHdZimZJsodjr3pTrnVQsHNRr29LuHlRtHtXunxVuHBCu3NMu3FPrWZDmVw1pmQ8rWVArW1Kp25NllxBlVdAlFtBeUMvcz41dUA2bTgtbzsweEU6ekg9e0o/gE5CuZN1fVk7nHhbq35brXhRr3ZRr3JPuHlUvIBXt3pWwXxWwnNIvXNNuW1MuGxKpmQ/pGVCrGhJsW1MsGpJqmZHiUsvj1c4ekgvazssbjwxYC4jZzUqdUI3dkQ5e0k+fUtAm3ZclW9Un3hboHJRrHdTrXRPsnVQtHdQu4BYunpTum9Jv21Gu3NRr2dIrGFDoF49ml5Dl1lBpmFGsGRGt21Pm19ApnJPhVk8aD4saDotcEA0d0c7dkY6ekg9ekg9fUtAmndhmHFYk2lMqXhasnxbsnpWt3tTqm9HsHZPvHtSxn1UwXlTrnZYp21TpWVNqW9VnWlRjFU+klI5qWBGs2pQoGRIq3pZjWdLXz0raD4xdUc6d0k8dEc6e0s/dkQ5fUtAhmRRcEgwn3JWsX5irnhZuH9buHxSun5Uun9bwoFUv4BQsHtQm3lenndlp3hnu5B+roNrk2NJhk83l1hDoF9LnGFMm2xRfFtESi4gZj4xaT0vZjsta0AzdUY6e0k+f0xBQSIUWzQfrn9jnWlNk11AsXpWv4RavoNavIFfsHNFrHhFsIxfuKaPrpeIlHRno4V5sI12mm5ShVY/lWFQmGBSlVxNg1ZCUDEhQiohYTwwZz4wZjwuZz4wcUI2eEU7fUo/FQQAXEAyv45wsX1cvIxuypp6vYxptoRis39gnGtIpXtUvJx3yLKdrpN9mHdfclNJX0A0f1tHeFNBiWRUl29giFxPck1BTjEqQCklSS8lWTcpYjkpYjstcUM4dUI5dkQ6LBgUY0g8qHphrXtcyJx9w5Z4vI9wu41vpXdZlWpMtI9uwqCAuZd/qIFkqIBimndsa01EknRjkXNiim1bnHtqf1pMZEQ6SC0pOSMhQCsjUzMlYDcmYjsuaj40bDoybz41aUU7dlJGdUo6n3BYxJZ7vpF1tIZqu49zrYNmrYRnxqGCwZx9q31fpXJQtIVmvJeJrpGDu6CMrZJ+s5iEoIFvgF1OaUtASC8qQy8rRTAoVzgqbEQyYzwvZDwyYTYuZjkxildJcUE1aDsynXBexph+xJZ8tIZsqH1itI9yv5t9y6eKzaWI0pt7v4RixI9xyKCMwKKPu56JvJ+KvqGMqIl1mXhpcVRJUDkzRjMvQCsjYEAyh19NeFFDWjctWjYtYjkyllhIik5Bc0A6k2ZWvpB3u411sIFplmxTq4tux6WJ06+Txp2C056CwoZrvoZty5+Hv5qEupR/uJN+vZiDvpqHpod3ZEk9RjEqLx4aOCMbaks8j2dVlW9hXD0zSiwkXjkzm1ZHm1dIkldRpXRmvY94wJN8v5F6kWlQnIBj0rOXqYVqlWxUwJF8wot5snplqHlcqX1jtYdzqnxop3llmnJedVhIQyofKxgRIhMOMR0VaEk6j2ZVnHVoalBGPycfUC4ppVxPolxOik1EpnZkxJyGvpmIupF9iWJLdFxHyaqTnXRbqXph0qWOtoNxgEs3j2JIfEw1k2FPf1VFYUAyUjYqOBsULxENMxsWKxoUQCgjaUU3nXVgnX9ve2RbOSQeQSgjqV5RllRIeDwynm5YvpyHvqOZvpuKmHNdPCcfmXxvvJR/uYlxw5V8pXFckFdHzpyNsXhniVBBZT0zPSchNyckMxgZRyIkUC4sNx8aSi0rbkU2oHhgsJmJjntzNiIeMiAaqmFToF1SlllPpnJfupaCvKKWupiGmnViIA0KMR0XfmRWknRjm3NljFZMjElCwHx0zIZ6nFtOYS8nPhsXSTEuSTIvUjEvVzIuOhkUPh4ba0I0pn1nvKKSp5aJSDgvMyAZsmpcq2hcl1dOnGNTtY17spaHo4FufFdGJA8MHQsIKBYQNyUdTjYvYzk0ZSklgj44kFNGe0g5XzYrNxoSNCAZMyMcPCIdVTMsTighTSsmZj4xmXBeu5uMsZ6NWUo9Nx8YtXBhq2hdkk9GmFpOqXtrp4l2lXNgaUIwTy8lXkI6QigiLhcTLxsTRyYfXCwmeEU7WjYnNx8TOCYbKR0SIxkRIhYRHg8KNx8YUjEqVjMsYTowd05ArYZ4rpSAaldGPB8YsW1enFhNnllSo2BYnGlboIFrlHNfiV5Lj2FKdkc3ZjYwazw5bkI6bT41fUtDZzwzLxoQEQoEEAkDEw4IGBEOHBMTDgsHEwwGKxcRQR8XYDowYzsvjF5RrYhzhWlXQyMbnltLi0Y7p2BXtnBpl2BTjGhSq4l1wJN+rHVVdDoihUU5iEM+kkpCjUU9fz85ZTUuQSkkJRkXIBMSGQ0NGAwPEQkOCg0MDxIOFAwHQiQcYT42TiceYjQolGhVnHloaUc+oFtNpFxNrmJRq2JWnmFViFZFlGlXsYZwuI5vk2tPqXxkl2FPf0Q7i0lDjk5FfUk6Zz4zTSsmPyYgKxwVIRYRGA4MEQsGGhQOHxQPPioiSDApMhQPSCUfWjgueFhMiGRaoFtPo15Rp2FSp2JVsXFlqG9gjFtKeEw5q4Rtj25XdlA6glE+e0c9nF9YpmNakVREfEg7aT01WzgvTjMqTDUsQisjOCAYQysjRi4mQSgdQSUbSSgfZEA5e1pSUTAnakI4nFdMn2BXjFBKk1JKtHFmqm1fmWJTe0g5i1xNnHNjc0U3fkY6g0o/nl5UqGBXolhNf0U5d0c8e0xDeEpEcEI7aDwxaT0xd0s/dEk8aUAxaD8wbUEzekw/hl5UXDYtaDovpGBVnmFae0NAi0xFrWlenFpOjU5BjFBEjVdMeUg8gkxCoWJal1dKnVxOpl1TqFpRkE9DilRHj1VMhEZAgUI7hUg5ik0+lFdIj1NEiVJChlBAhE8+eEMyZDUpc0Y9k15Tjkk9lVRLkFFJqGVcp2FXoVtRnlhOnltQpWldkFlMl1tQqWNZoVlKoF1Mnl1OolpQmVhKkVVFiUk+fzw1jUlAlVJCllREnltLn11NllZIlFdIj1VEe0Myd0Q4i1dOn2RZmFNGpmBRs2pauXFkp2BWp19VqmBXqF9Vp2ZWpGlXrW1dsmhaqVtKnVpGiVI/hUo8klJCj048jE0+iEo+jE1Bl1VGmFdHnVxMpmRVnFlNmVpOkFRHhU4+g01BkFdNmVpPn1xPsmtdt3Ffq2hZi1JGfUI5kU1Gn1xRol9Ti1FAlVtHnFpHnlhKmFtMg009cz0vhEY4jk0/lFZIj1JGkFNFnVxMnFtLoWBQp2VWn1xPlFdJnFtOnFxPllpMmVtPmFdJ" + }, + { + "index": 6, + "label": 1, + "pixels": "oCUNuTEL0TkO2ToK5kIJ9k4K+VAF9lEC+FYD81ID5kkB3UIC2kEE3UMG2EMFxzgAvDIBuzIAuEAjtHNWpjQWkDgXeTIdiycIahYNZiIbZi4nTyQdXh0TZRIIWxUGXhMF4UMN70gM8k0K5kQE6EMH9UoI80gD60IA7UQE5kAC2DkBzTQByTICyzYEyDcEui4BrykBqyoBoScQfykTjigHjSMGeh4GhyEHdiIhUi4uJR4XNBsWXxwTaxUIYRYEZBIG/EgH+UQE8UgD3D4A2ToE4j0E3zgB1jEA1TAEzy0EwysEuCgEsyYEtioGsysFpyYDnyIEmCMDlB4MgRwJgCMEjCEHgB8GciIKVzAoKCIjBA0NJg4MYxUPcxQGaRMDaREG6TgB4TYD3j0I0zwL0z4SyzAEyCsDwCQDuyMFtyMGriIIpCAHoB8IpSEJoCIGmSAGkR0HjR4FjBsKih0JfSAEfRwKfx0QaSUXOyoeJRIWGgsRNw8OcBYPeBMGcBAFbREIzzkMwzkTz0IdyTsavjQXtCQGsyAHqxsIoxwHnx0ImRwJkhoIkRoJlxoKkxwHjR4IhxwJiBwHgxwIhxwHgRwIejAlhENAWionOhkQPRIQMA0OVhkVdRsOeB8PchMNbREJtjsYqzoeqi8WoiEMmRoJnBoGnxkJlxYIkBcFjRkFjBoJihkKixgLjRgKihsHih8Jhx0KjB4LhiELih4HjCEUiV1VZl5dRTw7SykiPhsOQx4TdCwggSsXgC0bcBgQbhMJjSIMiBwLiBcKhhQHiBYIhhcIjBYKhRUHhxYGiRYFixkKjRoOjxgNkhkMjh0KkSMMkSAJkR8OiiMOjx4HjjMla1lWLzc8ISUoSDg1SygcbCscfy0chCQUhB4QbxcGcBUHdhEDfREGgBAGgRIHiBYLgxcKihYMhBYJiBgJjBcIkBoMkxsOlhkOnhsSmh0QmScTkigQlS0VkzMalDAWgEExQkA+DRIUEQsKUCIedSUagB8QeiANexkJgBYIchYEcBUHcxEHfhIKhBIJhRIIixULhxYKjxcOiRcLixkNkRgMlRwOmB4PlCUTmjgkozMiqjsonjskojognTcilDYicz0zLCgrDhEPHhAJaRoUixkMiBgJfhsKdxoIehcIdBUIbxQIdhMMgBIMiBILiBIIjRUMiBQKkRYOjRgNjRgOkxkOmiAUpTEinT4nmkwxojkopzQmmzEgky4bkTInijoyYzg2ODE7LjA0NywmbSkjfCMVehkLfhkMcxkGdBgJdRQLbhQKfRQMhBILixMLiRIJjhUMiBUKkBUNjBcNixkNkBkQliQbmTUogzEgi0IykD4ymEo/pmhYuol306ah1ri0gHx5XGhxRUtUKiEiVTgyXz0xYyYdcxkRcBgJbxkKcRIMaxMKhRUJiRIKjhQOihMLjRgOiBgMjhYNihgMiRkMjx0SiB8YhDAnjlVNtpeTybKvy7660s3Izs3Iz8rSwMXKorKxvdDVkpieKhYcGxgTKCUiZ0ZGciglbRUKahYJbBELaBEJjBQIixQKjxYPixUNjxgQjBgOihkNiRoOhxkMhSAYkEI+pHBsq5COoJuiiYyTc3V9amRuXVheS0dUOz1Kb3V+3OjxydXXX05UDQ8MBwoJPjI0dEZJYxoZZRUNaREJZBAIkBQLihYLjxkPjBYOkhcRkhcQghkMhxoOghoUkUhEjGdnbltdXlBWXFZfMTQ9ExIZHREWMiIjGQ8REhAXeHyJ0d3r0uDrnZunJiQqBgcHExYXRDtCRSEoUhMRYxIJXxAHkRgPixcNkhsSjhYOkBgQjhkSeRMLgBUShTc2f1VTVDo7RCkuVj1EUk5TLjI3FhgbEwsMMisnHh4cQUlMr7/IydjozdHny83gZmdzEA4WEhATFhcaIxsfOBYWTxQNWBIIjxoQixYNlBoTkBcOihkOhCUeizw5gzQ3dUxPQjQ1SDg5Vjs8alBSTk1OKC4yIiYpJCMjRklHc3x8tsTIy9/nxdjmzdnsw9LdbHZ+PTlEJRUaEg4OGB8gT0dJZD4/UxEJjhkRixQOkxkTkBcRhSEYcjUvhGBdeVxcUUlPWV1iPD48RUI9VVFMREdHU1pem6KmwMTG29/i7fX66/X81+Pt1+Tw097ncnl8MCUqXTtKNREcFAkMQUhMi4yVj3V+VBMRjxkSjRUQjhgSiRoVdCgkRSwqOjU4Q0VIUVhgS1JYHSUkHCkkJDEtGSAijJSa8vv/7Pb66/L54+n03OLt2+Ht3+LulYuWOh8nOQsVVBkuTig7TkNNhYWOoaKup5ejWyImjxYRjBMQiBYQhiYijV1cR0ZJLS48NDZCQ0tUISYsFxgcFhshLzg+KTE3m6Ou2ePwx9bhvs3Zv8vZ0Nrn3OXv3+TuraOxZ0pWXTlFc1pqh4CSlZWkmJeklJahpaCpWTM3jxMNjA8KfiYgtXx9va+0TFpiISQ1Kyo4OT9IFRccEAsOFxUbOUBJQk9Znqq5wtDgtsfVs8XVxNPkydbjws7Xztnh3uPys7HAl5ilnKi0lae1l6KwlpqmkpefiIiNQioqjBIMhQoHmmVl6tzltb7JWm97Ji8+Ki45NDlBCwoPCwkJCw4PFB8mMUJPoLG/uszasMLQucrbucbYc3yKRU9YWmZtoay4xNPkt8jaqrjJoLG/mam1k5ymiIyTTUpNJhEOgg4NgBQYo4SLo6Wzi5aiaoCNLTdFLjQ9HB4jAwMECQoLDxYbHi02NkhWorTCtMbUrL7Mvs3bcXuIFRkkFBogFR4iMDhAlaOxu8rdq7jMjp6thZOfgIiQQ0RJFQ0PJxENfAoJhCMnZ1NbGiExSFNgbIKPND5MMDU+EhMVBwcHCxAVO0hRWmx5Y3WDpbfFsMLQscPRqbfBKi84HR4mLzE3JisuDhQZRk9ZlaGyiJSpdYSVdYGNPEBIDgoOFQkIMBgUeQoFfCEiSTc7HiMwO0ZTcoiVRE5cHyQtDQ8PDhETGCIqSFhkT2FvbH6Mu83bu83bv9Dei5igGyAmKyszHiAlGx8jHCAkGx8nbHWChJGke4qbWWNuFhcdFQwMKhkWOyEebQoHZhUXRzY6P0FNPEdUcYiUTVdlHCEqEBUWHycrMD9KR1dlRlZkiJqovc/ds8XTtMbUdIGJHyUrNjhANTc/KSw0GxwjDg8VSE1WhZOifIuaPENOEg4TIhQSMhwYOx8cVwcJUQ4VPS83PD5MOkVSaYCMS1ZlFRwlFB4hLjxDTF5sYG9/YW9+kaKwpLbDo7TCqrzJcX+HICkwOTxGR0tWMTVBJSMuEQ8VKSwybHqDYG97ISYxDAcLHQ0KKBALMhYUSQsLSREXQCcxPDtJOUZXX3WEV2h4Lz1LPVFdYnmGiZ+xpbfIqbnIsMPPt8nUtsfVtsbWfIiUIio1NjxIYGZxXGJuMzRAGxwiERUYRk9VO0VMDBAWBgMHEgcJHQwNKBYWSRMPSRQWRR0lTkNOQUlXWWdzRVVgLzxINEVSPFBdSltpVmRyW2h3YHF9YnF+YG17Ym18U1lmICUwPEFMO0BLPkJOHR8pFBcbBAgJERQYCg4QAwUGBwYICgYKEQsPIRgZSxcVUxwfSB0jNiUrLSwyJywwDxYZBAcMAwoOAgoOBQwRBwwRBw0UCBAYChEaCxAZCw8YDQ8UCAkNQkNKQ0ROLzA7ODhBDxASAgQDAgMFAQMEAwQDBgYFCgkJDw4NIBkaUCEhWSUoUScsLyAlFRceChIXEBkeGSAlDhccChUZDhccDhccDhcbDhUYDhMXDA8TCgsPCQoJBgcGFxgcPj5HSEdTKikvBwgIAwQCBAUFBQUFBQYEBwkGCw4LFRgVIR0cSSMlTyUpSSkwNzI7LjxJL0NPO1FcOk1ZGiw4ESQvGS04HDA7HzE5ICwwHScrHCMoGB0jFRsbEBUVDBAVFBchFhklCAoQBgkICAsIBwkJCAoKCAsKCw4NDxQSGx8dHx4cRSosSCoxTDtGTldlWG2AU2+ASGZ2OFJjIDdHJj5OK0VUKkdVL0pXM0hTMkZRMUNPLDtHJjM8HisxHCkxIi86Iiw4ExggDBITDhQTEBYYDxUYDRMVEhYZGhwfHiAiHR4c" + }, + { + "index": 8, + "label": 3, + "pixels": "FxMXExUcFRATQS8opINxvJNzt5Ntso50qodxrIlnupBquo5puI1pt4xptoxpt49rtIxqpH5jf2BMXEk6a19Ubl1WmYJywqSJw5t8yZx9xZt8xp19yZ5/yJt9x5h6xZd4FxQYExQbFREULh8amXpqyqGCv5t2spJ8pIp9nohyqYttt5V1uph4uJZ2tJJyspd5tJ+FrZaDinVqVklESkE+alhRtJyMzq+Wz6iK1amM0KuJzq2Iz6yIzaiFzKSByqOAFxQYFBQaFxQXHxUSf2ZYyKKDuZd0qIx7n42LnpWNmoh0oot0spqBspl/s5h9sp+EtaaOvquatqGYfW1pRzo3cmFZxbGf0bee1bOX2LKX1bGS07KO1LGO062L0KmIzqaEFxQYFRQZGBUZFxESY09FvZl8r4xqoIJzqJecqKSmpp2SlYd4qpmJuqaUv6mVw7CXw7CWyK+cvKGUjXZtY1JKkoV60sSx1sOp1b2h1Led1LSY1bOV2bOW2bGU162R1quOGRUZFxQYFxUZFRMXSDgzqoltpYJgl3dor5yht7K4ubOym5KNkoR8nYuAqZSGvKeTxa+XxKmWspiJjXhseW1grKeY086329K13dGz2cmu2cOo2b+k1rqg1Lac0bGYzqyTGhYaGxYaGhcbFxYcMSYjj3NZpIJfmnhmqZKWwrnByMPHpp6fgnZ0fWxmgGtil4R2pZKCpY+DlIF3j4R6k4+EtrenvL6myceq1M+y2dG31cyz29G33NG318qx18ev08KpHhgaGhMWGxUZGRQaJR4dfXFctKGAq5R7qZeTxbrDysLHs6qri4B+cWJeemljgnFqd2hghXRtemtljIB6ubKsy8rAv8CqycWw187D2s/E19HF29fK3NjF2ta/3Ne/4NrCXlhNMCkhHxgRJB0ZZGBYr66awbqbqJx+o5WMwLW+xr3Bw7q5rqSjkYSBjoF7hHZxalxYeWtnemxoi3x5wLSx0czGvbul1c698ubk7eDb7+fg6OTa0M261dO73tzE5eLNtLGVnpmAcm1WenVgsa+bvr2nvreZoJN3hXhvraGoxby/yMC/wri3ua2qp5qUkoN/gXNwgXNwhXd0jX98saajycW7vbyi3NjB8enf6+LV6OPP1dO7vbydx8am4eDE6ujSxcKhwLyesq+Surabwb+nw8Kpxb6fnZB1gHNoo5ibubGzv7a1wbe2w7a0sqSfl4qHcmZkgXZ0g3d1hnt5qqCewr2y0NCy6unM7OjY8OvW6+rLycunubuTu72W0NGw6+vPyseqxMClu7eewLulyMavzc2wxb+gl4pwlYh7r6WkuLCxvbW0wbi2u6+sqJqViHx5dWtqgHZ0gHd1gXh2p56ctbCmzc2v8PDR8/Pe8/TY7vLNztSpusCRu8CTwcaf3eC6zcmszcmuxcGpwLumy8mw0NGwwrydoJJ6qJuNv7axwbm5v7e2wbe2rJ+dkoR/d2tofHNzjoWEhXx7h359p56fsKqkv72j6uvO8/bg8fbZ7PLN1961usKSuMCOucCTxMqczsunzMmnyMWlwb2gxcSlx8akv7eZtKWPrJ+Rs6qjt7CuraWkrqSjrqKfmIqFg3h2jYWGpp+fjoeHmpKSqaGjrKWjv72o5ufN8PTf8fjc7/fW5OrHyNCjusOQuMGQwMeY0tCpysqixsSgv7mbycGjtKeIsZyDyrmkq6GSmpGIjoeEjoeFqKGfqJ6ek4mHnI+Sr6SnqaSilpWQpKKenpmYoJ2YxcOw5uTL8fLX8ffY9Pnd8vXa4ujFv8efw8yi196209Kuycykx8WiwLadz7+oqo54oX1t18GyvbWmurGnraahrKejvri2saqriYKEf3J4tKWprqqjlpiMoJ6Vr6umsK6kwb2q7OfM9fLT8vTV8/Xa+/vk7/LWyc+w1N274enH09SvxMigxcWhwbmf0b2qtZGEmnBo2cC3zse8xb62w724ubSwqqSiraeopqCjmImNo5KRuLClpqKSmJGFwLivtbGlr6iWzMOp7ujK8/HU9PXZ9/nd3+TE1d264uzH4uvH1tizwseftLaSta6UxbChxJuXm25txq2o1tDHwLq1rqikt7KurailoZucrqeqsqSmgG5ppJaIvbGfk4Z3p5qPtKuenJB+dmhQnZF219G37+7R6+3NztKv1t236vPJ5O3F19u1xs6kpqmFo56DtKOVyqelvpWXuaKfz8rC0s3HzcjE1tHNwby5rqiosKqsraGigXBoiXhpv62bmYd3o5OGyLqtq5uIh3NcdGJLkIRvuLKYwbyeu7mY0tSw7/PL6+/I2N23zdasrrOOpKGFua+fy7Ww0rOxwrGqv72x08/F2tTP4t3Z4dzZy8XGvri7s6uql4uDeWdaqJWFnox+p5eLwrGiqpSCrJN+moNvg3BgmYp2qZyEopd8uLGS3tm47OrH2N+50NqwwMahtLKVxcKvysK30b620si8urqqvbiqxb+5zMfC0cvJ1dDQz8jKtbGvsquklYd7kn9xr56Rt6idrpuMnINxq497o4l3lH5wqZSGtJ+OppN/oJB5rJ6EzMWm2uG91d23ytCttrebv7+ry8e6yb6xysKyysa0w7yswb6ywLqxsqukxsG8z8bDx7+908/Jy7+2ppSIu6mdsaCTm4d4k3tqpo18p46Aq5WKtp+Ur5iKnId4nIh3n4x6p5qC2d6919280da3ur6hs7OeyMO30Mi7yL6w0ca4182/0tHAurKkoZeLtrOmxLatwrWxy8XAz8S8vq6iuaWWm4Z2jnxrm4l5ppOFrJmOs6GWrZmNn4t9loN1not8not9j31s1tu61dq61tu7wMamqaqUxb+02tLH2c/F18vB2c7D1M/Aw7SoqpyRs66fw7Spv7CqvravwLWswLCjqpaGhG9djn1sp5aGqpiLqpiNs6GXrZqOnYp8nYp8k4ByhnNlfWpb1dq60da109m3ys+sqKqPwbyw2NLJ3tXP39TO3tPL08e9zbavwq6lwrqrybquxrWsxrqyxLarvKuemYV1hnJhm4l4q5qKp5WIppSKvauhsp+SpZKEo5CCjntthXNkiXZo09i4ztSyztSvytGpr7OSv72q08/G1c3K1s3I2M3FxrGrq4qIwqehzsO0yburybaqyLmtxbWosZ6QloJzkH1sno18p5aGnYx+n42CtaOZsJ2RqJWHmIV3loN1lYJ0kHxv0te4zNKwydCowcidtbuTvL6i0M7A0szIzca/zsS5oIOBelBSsZGN0MKzxrimwq6fwa6fuKWWppOEloN0i3hpnIt6oI9/mYh6m4l/oI6En4yAm4h6mIV3mIV3jHlrg3Bi0te4ytCsxs2ju8KUrrWGsreSzc261tHK0czAy8KypIGCg1FYtI6Myrqsu6uYtqGQtqGRqZWEnYl6i3hphnNkmYd3mol5kH5wl4V6jXtxg3BkjXpsnYp8m4h6loN1k4By0ta3yM2pwsietbyOqLB+qK+ExMay19TM1NDDx8CvvaCduI6Qy6qkuaiYrZuHrJWDo418m4V0k39vdmRUg3FhlINzkYBxjXttkH5yhHJmf2xfhXJklYJ0o5CCopCCnIl70NKxwsShvcCZtLeOoql3nqZ6vcCy09LM09HFxcC0wraqx7Sov6udrJmHo416pIx7noZ3k31tgm9ebVxLiXhokH5vkH5wkX9xkH5whHJkfGlchnRml4V3opCCn41+k4FzwsSjsbOQsLONtbmRn6Z0j5drs7WpzczI0M3Cx8K3wrqsvrOjtaaWpZKBnIVzoYh5lX5wiHJkcF1OcmFRiXhohXNlinhqkoBykoByg3Fjg3FjkH5wloR2lYN1lIJ0jXturLGOnaF+paqDsriPp658hYxfnJyRx8PAzsm+x8G3x7+ywraooJGChXFihGxci3NljHZofmpca1lLfm5fgnJjgXBhinhqlYN0jXttjHpskX9xjnxuiHVnjHpslYJ0mIZ3l517hoxokJdwm6F4nqZ0fYJXgoB2t7Guxb+1v7eut6+kpZqNgHBjZ1NFXkc5aVNGd2NXcF5RdWVYfG5geWxdfWxei3lrj35wi3lrjHpsgW9hfWtdhHNllYR2m4l7loR2" + }, + { + "index": 9, + "label": 1, + "pixels": "2dfR0tDKzdC/x8q22tfR1tHRz8rGvbmvu7irrqilppidqaCglp2VmqeajJqNj52Pp7Wkv8u82+HW3+Hb297R19vK4uXZ4eTW293QvsWxr7ihu8StyNC3qridobCVoqWV3uLU3eDU3OHS19nN2NXP4d3b08zIs6ujtLSlwL22vrK4vLG2x8TCzs3J0dDN2+DX5ezf6/Dj7PLj7PPk6e7d4uXU4eTT5efX5+ff1NbN0NTDzdK72N7Gt76qur+tyMW66uvm6erl5+rj6Ovi6erj7+/s2dbTraakpKaftLGtrai3t7G4vri8vLe/1M7P4N/g2tzb6+zl4+Pg4ejW5evW3+TQ1tnI4eDT6une6Ong5ubb2N3F0dm5ys680NHF09LG9fX19PT09PT08vPx9PTy8/Tx5OPjnpmvkpKonZuwg4Khn5+7kZCuiIqgoqK4n6C2qay5y83Vw8LQ09zK0d65y9O60NPE4uDU5ubX6enc5OXV1du7x8+p29/F4OLU1NTI9fX18/Tz9PT09PT09fX18fDxz83NdXCEY2KLbG2hWVuKa22nZGWfW1yLZGSbXFyNZmiOfH2mfHyZlZqktsKpucKpysnE6ePg4dzR4t7R4+PUzdOxwsug1dy44ujM3uHS9fX19PT09PT08/Pz9fb27evu2NTXfnuBSEdxWl2cW1+gZmmqZWeqZ2qqa26xY2anWVudWVmdW1uYXV2PfoGUvsWz2NnN6+bk593a39rO2NbBxMaqrrSTvcWg2eLA7O3f9fX18/Pz8/Pz9PT08fDx29bd2dXdnpy0UE+Dcne0hInEl5rPjJDIhIvLj5vZipbTgo7MeoDDcnnAeH6/bnKjm6Cm3eHN6enh6+nj4NrVxsCxwLqpp6WRq7CSzNSy6+za9PT08/Py8/Py9vf34+Lmx8HK19PZmZbAUVGGkpjCu7zgysjoz83qnqXXg43Og5DRgY7PjZbQg43KhI/Pn6fghIy0n6Oa19bM5eDc19HJ1NPE0dK8xcerq66Ssq+a3dzH9PT18/Pz9PTz9fX14+HjzsrR2tjfgn+uUVGHgoa6gITBgYfBuLndkZfMdHzBfYfJfIbKiZHNjpbNfYjGmaTck57QkI6jxsC81s/L29jR6eff3NfLuLGhpJ6LqZyUycSy8/Ly8/Lx9PTz8vLy5OPlvr3NqKjCbm6kU1OMhozBd4C9bna4j5PKgIfEc3zAeIHEfYXHg4vKkpfQfYbGlZ7Xm6TgjJG8xMHI6eXm8O/u8O/t6ebjyMG8yL6618zK3NfT7+jq8e/u9PPz9fT03NrfhYGggoCpX16cTk+GdHqxdHqzbHCsbXGua3CubXO0bHO3c3y7eIC+eH+8c36+iJDNlp7cj5nQp6rE0M7Z5OPm9fb28/T09PP09fP09fX09PT03s3T6ePm8vLy9PLy2NPYqaG2pZ++WViXPTxqQ0VuW16TZGagX2KeX2GfYmemYGaqYGipX2SjWl+eYWemaXGteX+9gYnGfoCvm5m32Nfg+Pj48/Pz9PT09PT09PT09PT00LzE39Xa7OTp49zhv7S9t6q0ta3DZGOfNzddODlcWFqNZWagb3K6Y2eoVliPVFWMUlWLVFWJXV2ScXOnbXCYYmWDcHaPgYaWrrC84uHj9fXz9PT09PT09PT09PT09PT0yLjDzLzH28rTw7XBqpikmoaVnI2iZmOJaGeWY2aqbG+yZmemc3a9dXjNXmCmVVaSWlyZamusen3AjJLTgISvaGqAbG6AfH+Klpigs7Oxw8O/1NLT7+7v9fX19PTz9PTzyLbC0sLPz73IqZiipJKclHuIk3+Oin6JgXyiXF2yammxXV6fWVqWXV2jVFWVTU+LTE6NUVOSUVSSUVWTT1GGSkt8S0x/UlOFZWWVe3qjjIqtj4qmv7zM9PT19PTz9PT00r3D4szQxKetd2VucGVxln2Luqm0wK65bGeFTU2aTU9/NzZXLStJLy9MPDtZPz5fOztcPz5gOzleNjRYMS9WMjBWPT1jQEBnR0ZtS0p0W1qPZ2Gbh4Cv4d/o9vb19PT1x663waSqtJehYFRlXVJgkXyIwKy1oZKhVlOASUmEXFeBYlqHaGSMT0t9T0x9R0RqJSE1HBcrHhosGxcnNDBNMi9HFhQjHBkoGBUgNTJQW1aRaGSXgHinzsrb9/f28/Pz08DKx7TBwrPCcWh8eGh4nYeSn46ZR0BJREFpWleHdGyDfHiUlZW4eXafgH2pZmKDTkZmYll2cGqEZGB6lJCvk5CqXFlvY2BzXlpvbGeRh4Kyjou1nJe7t7LF8vHy9fT03NHYyr3It6u4Zl5ybmJzpZKdhHaCHhwkOTZPYl+Va2eBU09jUlNvZWSBgYCdZF+EmZKxrqrBnpu3n565rKvIqKjBoqC6o6G9oJ61r6zHnJu2d3eXcm+Uh4Ci5OLo9/f229DZz8HMvLC7YltxU0xgjX+Lb2RxKig9OjVOSERwTElzPjldNTJVODVTQD1eXVl9oJy/fHefW1d/ZWKKdHGga2iVZ2OMZ2SPY2CKm5i9fnqfQz9jUU1zdnCa2dbi+Pj32crV0sPQx77HZV91ODNJWE5cXVNjPDhUODNLLidBPzxhRkRpPDlfNjNXQDtnQT1fY1+Gcm6iaWaZZ2WXZGOWYF+QXVyJYWCPZmSTb2yZZGCPSUZvUk9zcmyS1NDe+fn30cLMzcDOysDMdW6DU0xlRj5RUUlcRD9aMi5GIx0tKyg5MzBFREFiTUhvV1N9PztXNDBKR0NmUk1wSENnQDxiQ0BlPjteXVh9WFJzPDZSU05xbGmVcGuabGWJzMnU+vn4zcPRyr7QxbvOaGF1XVVpb2N6R0FWSUNePzpWKSY2JiMzIiAvS0hmY2CDjo2tT0xjHhktVk9kk4yednGCY155cm2KZmF8mZKrsqu7PzpLSkVfjYqrd3SYWlN1w8DP9vT6xr3dwrfWubDMV1JoMSw7bGN0YVlyY16AX1p8MzBBJyQ0JCEwKCY4Mi9GV1VsNzRLIBwwT0pfl5Gmf3uPeneRiIandHGPnJevn5yvNzNKNTJISkdiPjtUTkdowsDW8O77tq7XtK3UqaPJTUhjJSIvOzZEbGWAkIuwamaHPDpQKyg4IB4tHRooHBknHhorIR4vJyU3KiY8OjVQWFZuamh9eXWTenaQdXKLQz5cLytDMzBGMi5DMy9FUEtturjZ4d/7qKLPpaDPpJ7LfXidW1dzYFl1b2eFjYiqYFx+SkhlNzRIJCIwHhwoHhspHRspHx0tIyAyGBUnQD1Trq/Azc/ay8rcs7HHtbTJV1RrJiI0Kyg4MCw/Qj5aW1d+rqvS09H3opy8o5zAr6jOtLDYmJO/dnCabGaGjYihW1Z5U1FzTktoMC0+GRYhGBYiGRcjHRopJyMzJiIxR0VVpKSzuLnHsbHAqam+pqW7UU5gHhknHhomMS1CTktvX1yFqafRzsz1mpW/rKfGs63NpqHGko21dXGeZ2OEko6gV1NyVVN2Uk9vNjNGIB0nHhwmIR8sJSIxNjJETUhdVlFpZWF+a2aHeXSWjoqtiYWmPDdIHhsoIR0qNjJHTkxxW1mCpaTPx8bypqTOqabRnpvGlJC4j4urhYKjZ2OCcWyFT0xrUVBvS0hoPDhNKiYyJyQvKic1LCk5MC0/NjNIQT1XTUhoWlR4bmeRg3yoi4OwNTFFHRooJiEwNjJHRkVmW1l+qanUxMPuoqDHl5TCk5LCjY29iYeyhYKma2aGTkllSEVjTk1pRkJgPDhPMi8+Kig2Lis7MC0+MS5BMzBFOzZOQj1XTEZkWVR0ZV6BcWqPRUBXHRonIx8sNDBHPz1ZYmKFrq/furrolJPBjY28jo6+jIy8j4+9jIu8amiQPDlQQkBaSkpjQj9YNzRGOTdJNDFFNjNKOjZOOjZOOjZOQT1WRkJdSURhUEpmV1FtXVdyTUheJSEwJiMwNzRKSkhkg4Sts7botLXnkJLElZbHoKHQoqPNnp3IkpG7fnylPTpVOTdMOThMOjlOQ0FURkNURUJZSUZiSEVjRENeSUhjWVdyYl98Xlx9YV+BY2CAYV5/UlFwRURbQD5UR0Zgd3aUpKPMtrbhurnf" + }, + { + "index": 10, + "label": 0, + "pixels": "WnyVWnyVW32WW32WXX6XXoCZXoCZX4GaZIKaZ4GYaIKYaoSaa4WcbYibbYiabIeabIeZa4eZaYibcYebdoeccIidbYmYcYmUcIeTb4WUb4WWbISWa4aXZ4OUZICSZIGSXH+ZXX+YXoCZXoCZXoCZYIKbYIKbYIOcZoWdaYacaYacaoedaYacaoeba4iba4mbbImcbIqbcIqadYqedougcIyfbIueb4mddIqZeoyUhpaalqWskqWvcomXZ4KUZoSYXYCZXX+YXoCYXX+YXn+YX4GZX4GaYIKbZISbZ4abZ4abZ4abZYSZZoWZZoWZaIebaYmda4iacIeWcYebcYmfbouaa4mbbYefdoqYhZKVpq+pu8TDm6etcoWRZ4GTZYSYX4GbXX+YXoCZXoCZX4GaX4GaX4GaYIKbY4WbZYaaZIaaZIaaZIWaZIWaZIWaZoecZ4ieaYicboeYbYedbYicaYSKbISOcoeagZGcoautuL+5qbKyf42UboKOZ4KTZoSYYIOcXoCZXoCZX4GaYIKbYIKbX4GaYIKbYYSbYYWZYYWZYYWZYYWZYYWbYYWcYoWcY4adZIacaIacaIehaYWYWG1qYHBrgI6WpbG3usPFtLu8h5aeboSRaoOSZ4OVaIaYYYSdX4GaX4GaYIKbYYOcYYOcYIKbYIKbYYSaYISYYISYYISYYISYYISaYIObYISbYIScYYScY4ahY4akaIWWaXhvZW1dlZ2ZvcbGvMXKmqSubYSVZoSYZ4SWaISWaoaXYYSdYIGaYIKbYIKbYYOcYYOcYIKbYIKbYIObYIOZYIOZYIOZYIOZYYSYYYWZYoSaYoOcYYOeYIWhYoWda4WRgY6Jc3hpk5iLvMbDo7K7dYmcZIOcZoSab4aWcIaVaoSWYYOdX4GaYIKbYIKbYIKbYIKbYIKbYIKbYIKbYIKbYIKbYIKbYIKbYYWYYYaYY4WbZISdZIOfYYKbZ4SVfI+VhZGNe4F1hYp8p7SxfpOeZ4KZaYafb4aYlaSwkaKwaoOWYYOdX4GaYIKbYIKbYIKbYIKbYIKbYIKbYIKbYIKbYIKbYIKbYIKbX4WbYIacYoWcZIScZ4OaaoKTiJukp7OziY2Ef4N1dHxwgY6NcoeTaoOYdomZnqq0tcLMjaCvZoGWYYOdX4GaYIKbYIKbYIKbYIKbYIKbYYKbYIKbYIKbYIKbYIKbYIKbX4WeYIWeZIWbaIWYcIiYjJujt8HDvcG7jIp8gIBwaXFlbXl3cIKMd4ydo6y0w8fKprK7coeYZIGXYYSdYIKbYIKbYIKbYoSdYoSdYoSdYoSdYYOcYIKbYYKbYYKbYIKbYYSeZIWdbIiZfpOemamvvMLEzM/LubivioZ1g4Jwam9haG9pe4WKlaKtuLq9tLa4hpSgaICUZIOZYoSeYIKbYIKbYYOcYoSdYoSdYoSdYoSdYoSdYoSdYoSdYoSdYoSdZYSda4WZgJOemqWnsri1zc7Mzs7Ju7qvnZmJlJB9fHpocHBki4yJoaOnsLGymaCmcoeXaISaaIWbYoSdYIKaYIKbYIObYoScYoObY4SbY4SbY4ScY4ScY4ScZIScZIWcb4qghZioqra6n6KbgH90vr+6z9DJwcC2r66gpJ+LopuEl5GAjIV8koyIn6GjhZSgbYidaoefbIecZYWaY4OXY4SZYYSaZIedcIubdIqVe5CbeZCeeZGggJakgZWihpmlm6eyr7a8xsrHpqWbbWteoaKZzc7ExsW5ubervLimyMGrxr6rqZ+SeG1kXF5feImUcYqca4eca4ecY4ecYoWZY4WYYoSWbYmXfo6RlJqWr7a0sby+tsHFvcbJvcTGvsPExMTEvbu5t7Wwo6GXcnFlgYN2v8Gzzcy/xcC1xsKzyca0y8W1vbSnkYd9am1teYiQc4iVbIeZZ4ebXYqlYIedY4SXdI2aa3V0ZmdgnpuRwsO7x8rGztDNz9LP0NTS0tXV1tTTz8vJyMXAqKacc3Jld3psq6yexsW4w72xw76wwb6vv7ywv7uxvbiyj5eZc4SNcYeUbIeZZ4abXomhZ4WVkKSsr7e2n5WIqJ2Pr6earqujtLKqvrqyyMbBy8zJ0NLR1tTT08/N1dHMsa6lgYB0fH5wlJWHr66hrqmdrqmdnpuRkpKLjI6LhImJanh/boOPcYmXbIeZaIaaaIWUkqKmzdHKvbappZaHr6aaqqafoqKes7KsxMG70tDL09PP0NDMy8nHysbE0c7ItLKojo2AfX9xe31vnZyPlpGEfHdtU1FMTE5Obnh8c4OKcYaSb4eWbYeXa4eZaYeacYmTp7Kzu7uxi4R3b2lklJeYp7G2rLS5tby+wsnK0dXT0tLN0M7HzMjFzcrH0s/JtbKpjo2BdHZpbnBih4V4YFtPRj84KycnGR4jYnJ8coqZbIiZa4eZaoWYaYSXaIWYa4qafpKbfYmKaG9vYmx1dYmZfZWoh5mmjp+qna64tsDExcXCzsjAy8bDzcrIycXAs7CnjYyAamxfcXNleHZpRUA0OTMtJCElKTA5ZnyLaoqdZoabaIaaZ4SYZoKUZoOUZYieZ4SWaYKQbIKQa4OVZ4WcZ4aea4WZbIaYcY2egpWgrbKzzcjBysnHyMbGvrm0s7CqdHdyWGBbiIyEpqSamZSJjo2KZGpyYG56coucaYmdZYabZoWaZIKXY4CTY4CUZ4edZoWZZ4WZZ4SYZoSZZoWbZ4ecaYecZ4edZYeea4aXoa6zzMvGy8zMxsbGvri0r66tanN5WGduoKenysjBxMG4tbu9g5WhcYeUcIqaa4iaZoWaZYSZY4GWYX+UYYCVaIedZoWaZoWaZoWaZoWaZoWaaIebaIecZoeeZYifaoeZoa+1z83I0M3Kx8TCu7i2nqSpcoKPboGMqbK1y8zJwMG9naiscYeUbISSbIeYaYaZZoWZZYSZYoGWYH+UYICWaIedZoWaZoWaZoWaZoWaZoWaaIecaIecZoieZYifaYaYoa+10s/K08vFxcC8tLe6iJeja4OVb4SRpLC2yM7Otr2+hZScbYSSaoSUZ4SXZoSZZoWaZYSZYoGWYH+UYICWZ4ecZoWaZoWaZoWaZoWaZoWaaIecaIecZoeeZYifaYaYoa+1z8zHzcO6w7+8prG5dIueaIWba4STnKy1xNDVnay0cYaSa4WUaoeYZYSYZISaZYWaZYSZY4KXYH+UYH+VZ4acZoWaZoWaZoWaZoWaZoWaZ4ecaIecZoeeZIifaYaYnKqwyMW/x762vL2+jp+saoWaaYedaYSWip+qmqy1do2aa4aWbYiZaYeaZYWbYoWcZISaZIOYYoGWYH6TX36VZ4acZoWaZoWaZoWaZoWaZoWaZ4ecaIecZoeeZIifaYaZmaetwb+6w765rbS6d42eaoWbaoWaaoaYcomXcoiVaYaYaomcbYqcaoidZoieYoadY4OaY4GWYH+UXn2SXn2TZ4acZoWaZoWaZoWaZ4abZ4abaIecaIecZoeeZYieaoaWm6eswcC7wMC+maWuboeZa4ecaoWaaYeaa4aXbYeYZ4ebaIidbIqdaoqfZ4mfY4adYoKZYoCXX36VXXySXXyUZoabZoWaZoWaZoWaaIecaIecaIecaIecZ4eeaYidcYiWoayxwcTCtLy/gpSdb4eXaomdZ4idaIecaYabaYebaIecaYidaomeaYidZ4ecZYSaY4GaYX+ZX32WXXuUXHuVZYWaZYSZZoWaZoWaaIecaIecaIecaIecaYiccIyddouZjJujm6Wpk6GodomVb4iYa4meZoieaIecaIecaIecaIecaYidaYidZ4abZoWaZIOYYoCZYH6YXnyWXHqUW3qUZIOZZYSZZoWaZoWaaIecaIecaIecaIecbIeZb4eVbYORcYeTdImVdoqWcYeUbYiZaomdZoieaIecaIecaIecaIecaIecZ4abZoWaZYSZY4KXYX+XX32XXXuVWniSWnmTY4KYZIKXZYSZZoWaZ4abZ4abaIecaIeca4aXbYSSbISUbYmabYmcbYiYbYeXa4eaaYicZ4edaIecaIecaIecaIecaIecZ4abZYSZY4KXYYCWX36WXXuVXHqUWniSWXiS" + }, + { + "index": 11, + "label": 9, + "pixels": "///7/P34+/z3+f33+f33+/z3/Pv3+/r2+vv2+vv2/P34+/z3/P34/f35/f75/f75/f75/f35/P34/P34/f75/f75/f75/f75/P75/Pz4083LwL25+Pn0/v/6/f75/v/6+/34+Pn00tDN5ubi+v349vfyxr+8vraz9vXx+vr19/n0+/r2+vv1+Pv1+vz2+/v2+fv1+fv0+vv1+vv1+fv2+fz3+fv2+vv2+vz2+/j0tKSlkYKD8vXw+/34+/z3/P34+v34+Pn1vre12dPR/P742dnRn42JopCN5+Lf8/Pu9v327efk8/Hq9/vy+Pzz+/rz+fvz+vz09PTs9PLr+fz29/z2+Pv19/fz9/fx+/z0xra0noeH5ubf/P75+/z3/Pz4+Pz2+fr1wbm4yL+839bQm4iDjG1poIiDtamkv7ix9Pbts6ai183J/v32+fzz+/z08fHp9/fv0c/IysXA///7+Pr2/v355ODd0M3K8vTtr6GbiWhks6GY9fXw9vfz+fr1+fz2+Pj0vbGxhHZ3kXt3mXZriGJZfmJbj2tqlXl15uXYspuW08W/+fbx8vXw9PbwyMK51s7HysK9wLWy/Pj09vHv9/Xy2NLQxru92dHPhGtjmGlgmG9kysO56Oji9vbyxM3Lqq+wpZWUc1RSkmpjrH1vnG5hhWBZhV5ejWtppZGKnHZ1oYOAppGRopCQo5CMiXJpk3dtoIN7lXt3pY+MpouJq5mToI2IlXl3mX13kmharnpnqXZlnn1xs6ef8fHse4yRZ3V8jXt3m2hdqHFmqHZrp3NolmdeeV5XfWdgfmJdfWBdhWppj3h5jHZzjHJqlXxym3prn3pqiW1mh29sgGJhkX96pZaPdVZTfVRNnGxfn29gpnJloWZblXxz6+nkXGhxSlphhW9to2tgnXdqnop/oX50nXRqkHlwm4qEppeUp52crKiox8TEz8zLy8fFzsrIz8rGysPAx8LBxcLCxLzBv8DAw7+5iW5pimBVlW5fhnFqlHhvn2pblnZt5d3YRUpVJCs1Z09NpGRapXhuqpyWsqaeu6+puLe4t7i6tLe6t7m8sbKyycnJ1dXV3Nzd4ODg4ODh4OHh3d7e3t7e4t3i3eDhzsvGnHt1mGNSmmtbi3Vyl3t1o2VXmWlbwqygKCw3HSMsNzIyhXBptailu72+s7i5rbKyqa+xp6yvo6iqp6utpqmpxcfHxsbHrKytp6eooaGhsLCxu7u8qKano5+moKOns6yojG5ojV1RmmlWk3NimXVkn21cmWpYiW9jISYxHB8nUFJYh4yRqq+0sbS5pqiuoqWps7e4rbGxoqamo6ipoaenxcnKgIGDRENGUVFWSUpQhISLrq61bmtvY2RqYWNrn5iYpYyEqXhvs4FzooBupntsrGtYpGZSh2ZYISIuJCgwf4aLlpqfoqWqr7K3p6qvn6KmmJyelZmboqWnpqmrpqysrrKzQkNFeXh7mpqeh4iMn6CjxMXJqq2vrrK0q7Cyr7O0rK+tsKqqsayvpqimo42Ho2RSoGFNck9DHB0nNTlCg4uSjpSZo6arrrG2p6uwi4uPd3V4d3d7m5yfpqepqauwfH2DOTk/kJGXXV9mLy84eHiBlZuieYSMeYOMeIOMdYCKcH+Jd4WQipCclpqgp5iWi11MkVVGdlNJGhslSk5XfoSNkpedqayxrK+0pqiuipCUgYiJi42NoKGjpaiwqqqybGx0PT1Fg4OLPD1FIB0meXZ/nKKoe4ePZ3N+XGhzVGFrWmp0cH2Fnpufsqusq6KkZE5IeUpAf11XIiMta3B4gIeOk5mdp6quq6+zpqqtqJmTtpF8tY96rKCcoaiwqKqxhIWNREVNg4OKMTA4Hhklc3F5j5KZa3WBP0taOkZVMz5NNURST1lhlImIp5ybnZmgYE1OcUQ4Z0tAJCUuf4SIl5+ii5WUp6utp66wpKmns4d0v2hAumk/rJmPm6aopKepXF5pP0FLhomMLzA2GhkpWV1jeoGGVmFwLjtKLDZGLTRFLjlIQkpRgXh4gHt6gImOY1VVdUc5Uj42Jicxio+Upq6wi5aUpaiqpayupaqntIZuu2AuvWY3rJOMnaSpo6WoUlVfOTtGiY2RQUZLJSIzXl1kbnd7SlhkPElVQ05aTFRhQk5aTltlZ2t0ZmpxZ3V7V0xMfEU6VTk2T1FQkJWToq2ujpeWpKamqa2tpamnro59vXdRunpWqZSKnKSnoqaoWVxkOz5GkpaZhYmLZ2Zvc3F4VVphKzdEMjdDOD1LNTxKLzE9NDlJNDtMNz5MQEdPZVJSgFJGY1BCamhanpuRp6mnj5OVnaGho6enn6OjlpmXm5iRoJmQn5yboqaspamrZ2pxUVRbpKiqoaKngoOIgIGDlZaYend1fW1ihXZ1gYCHe4CBf4SGlJGQppKHrJWHkJGRXlVNVVRIdHhiraqburewlJmZlp6gl56hkpmck5qckpqbk5qblZucl5ycm5+heX2EdXh/vMDCx8nHtbe2oaSiwsTBysK/wJ2Sw6yhqrGuhZCPgouLkpWWmIyImIZ/h3t6d21jcnZigZyAprCinJ6cg4yMdHh5f36BiYmMjpKTkpmZlZudmJ2fmZ2fmp+igISKY2dvfoKInqGfoqeqq66qs5uMcmBgVFRaSERKNjU+KCszJigvJSgxMzdARENJZ0xIlpR9mqaDgKGFo6+llpqba3FyLCcrMSYsNSswNzM2QkFDUlBTZGJlfHp8hoWHUE9TQ0BHb252kJGRjYWCoKCgsop7Xzw2Qj9KPzpDPjhCQj5HRUNLR0VNSEdPTEdNa01JkJB2mqWChaKCprKiqKuoY2hpOzo9Ni40KiEoKyQqFA0THRYcIhshJR0iKCEjGxQXGBIYLikwh3dxqYR3nJCNq4l8ZkM8SENNSURNR0JMRUFKRUJJREBJQDtGPjhBYldQe4tve5Vuh6F4j6CAkJmHc3RxS0tOPjtBNS85QjpEGxQcHRYeHxggFg8WGA8VGhEZGBQcHhwmMy84QzE4QkBHYVhYUD4/OTM8NDA6Lis3Kyo2JiUuJiMsKyUtVE1RgYR0bYVkaYtjrq2SrqqRuLCgiH99e3Z6UU5UTkxVVVFZGxQcGRIaGhMbFxAYGxEaGxIdJyIvLSk4IBwpHh0jIBwoST5CnZKQNSswGBAXFhAZHhsjQ0JHTUtPJiElQTw+b3JncntkcYBj1bupzbOixKmajHlslY2KUE5Ub291enZ6HRQcGA8YGxIbGRAZHBIdIRgkKyYxTktWTktUISEmKSApQjM7cWhrKiEmGBAWFQ4UIBoeT0lKTEVJJR0kEAYPNScuppaVsaGZzLelv6qZrpmIjHxsbGFcLygtVVJaZWFoGhAZGQ8YHRMcGxEbGxEcIhkkODM8REFKZWJqNTE4HRUeGxEbFg4XGBEaFxAYFg8XGA8YGhAYFw0TJh0hUUhKf3d2vbWywLmyv7CmsaKYpZeNlYV6gW1kYEtIRjk6LycsFw0WFw0WGA4WFw0WGREcIBkkRD9IJCEpOzlAQ0FIIhwkLCQsQzxDNS41HRYeFA4WFg4ZGQ8cFAsTQjk6tK2pvLawubOtubKtvbCnsqWcp5qRn46Em4h9k391f21jaVdQWUdEUD47Sjg1Py0rNigqMSYrRD5FTEpTOzxGKCgxHBkgZGBmg36BcmxuaGJnMy00FA0YFQ4ZGxQZbmVisaegrqSesqahtqejw7GmuaidtKKXs56QtJyMsJiIq5ODqI9+ooh1n4RymX9skHZkhmtbdltPSDg5QD5ONTVEGhgiGxYfMyw0OjA5RDtCT0dNOzI4GhEXGxAWQDMzhHVtmIh8opKHrJqPspyTzLGdyK2ZyK2ZyKuYxqeUwaOQvZ6LuZuHtJeBtJeBtZiCsZN+rIx5ooBugWVZUT89Oy4zMSMpMSImMiElNCElNyMmOygnQS8pSDQuVj86bVVNiHBknYR2q5OCtJyLu6GRz7Kd0LSe0LOe0LGdzKuYyqmWyaiVxaWRwKCLwaGNwKCLwJ+KvpuHu5mFtpaBrY55oIBtmHlnlXZkkXJfjW1cjm5dknJflXVhm3tnnoBspohzrY96t5mFv6OQxaqXy7Cd" + }, + { + "index": 12, + "label": 5, + "pixels": "W0AeUjoeV0k7WVdTX1xQYlpHYVdEXlpLXF1UYl5VUUxCHBoTDw8KEhMQExMUExMUEBARDw8QDQ8NChAICg4KDQ0MDw4IGhgMHRkPGhUMJyIZGRQLEg0GFg0NFg8NEg0KXkEiTzgeWk47fHhqkIp2hXlgb2FHZV5HYmBRXlhPMCkjDgkGDAoHCwsJDg0OEA4QGBcYIB4gGhoaGxwYFhYUFhMPNDAgQz0kOC0YOS0YQzciPDEaKh0KJBMHPS4gLyQaXkInVkEoeGlSnI53m4pvk31dh3BPe2lMcmdRWE5BKSAWJyAZKiYgKCUfMTAgMzIhOjkpODcmLy0fHhwVJiEcHRUONSwbNy0VKRoHRzYdNSQMPy8UPy0VNiEOUkAqOy4gWUUqbFpDiHBYhWVIgl8/flg0fFUwflw8fGRKVUgzLyYTNjAePTgpXlpLVFE7VFE5PTojRUIrSkcwLScYMCccIBQLJRcLNigUOCcUSTgjOikVLBsJQi4YUDgiSDYhIBYISDwhXk44aUszaj4hhlY1e0kkbTsUdUYkcU0vWEYpPTMXQDkgS0UvY15KSEIzUkw/RT8yMSseMCobS0QtQDYkLyEXPi4fRDQfNiUVLx8ROCcaKBgKIA8ELhkOJBQIGRMFKyUQNicUPiMQUy0Yf1Eze0knaTURbjkVZjUQYUEZTzsbQjghV1E+S0U1VlBCUEo8QzwuR0E0TUg3WFI6QjopMigePjUlPjQeOioYHw8DKBoKJhoLHxQIFwoGHQ8IGxAGLyoaLh0LLxMDQx4Lb0IkdEUjZTMPaTQOaTMMaz0VWTobOCgUODEhQz8uTUc3RD4uSkQzS0U1Tkg2TEYwMSoaNCwgNC0dMysUSDgiOysYPzIeOCwbJRwNHBQGLSENIhYFRTwuRzIfRCMRQhkCYjYWbUAeZjYRbjwVcDsTbzcTYTUaPigVMCoZNDIgPDcnUkw8S0U1OTMjLigXUUs2PDQkKSEWNzAfKSEOJxcGPS0YNyoYMSYVKB8PHRUFMSQLLSAITzwscFdDhmROaEEnckkodksobUAbb0AYbDkRZzAMXzQZQiwaODIiOzkoUk08S0U1S0U1RD4uSUMzSUMuQDkoKiIXNC0dLCQQMiIPNSUQKh0LLSIRNCkaKh0SLBsNJhUIeFdCgWJNnoBriGlTf1o6dEwnbUIcckUcajsRZDYOclEyXU05QTorPzoqSEIzR0EyY11NX1lJa2VTZF5HQDkpLiYbKCISLSUPMyIONiYRKx0LKB0OMScYNScUNSEQJBEFoXhefl1Gh2xaj3VkkGxPflY0Zj4abkQeaT0VdlYuqpV2nJJ8c25ccmtae3VkfnhomJKCkIl6cmtacWtVc2xbeHBkbWZVVU05UUEuQzQfMyYSNigWNigTPCwQUj8fTDkdpH5kgmdOY0gzgV5Mn3JdmG9ae1tFcFA2dlM1l4NrvbKfraeUlZF6mpJ6sqWTsamYr6qYqqKSjIByjYZ1rKWVs6ucsqubrKSUn5WHf3ZjZFc+YUgsWTsfOyMMPykSV0UsoX1fk3RYfVlBkGRQkmlXjW9foYp8nIVzqZF6uqqZtquZopeDk4pxoZZ8rZuIrqKQsq2asqqarKCSrqaWt7CgraaWqaKSuLCisqmerKSTkYVsc1k8Y0MmUzwlQjEcNSgVo3xZn3dYo3ZcpnhiYUk0UUI0m46EtKebw7WkvK6dmohzg25ViXZcpJJ5k31mlodwt7CburKiua6iurKjvbemtq+fqaOStq6gtqyisqqcs6mUkXtkel5Gi3lgfXFaLCYVqH5crIBjrIBmkm5UOzMXMzAcioJ4samgwLqsqZ6LfmhOfF0+i25RmX9nhWpPi3hduK+Ywbmpwbesw7usxr+vxr+vvrenvLOmv7Srwrqux7+vs6GQknpnp5N9tamSY2FKsYFnsoVuqIVudmNHOT8aKy4ScmpcraWawL2uo5mFg2dJlWxGlW1Ojm5XhWRHnIVnw7ifxb6txr2zyMCxy8S0zca2w7yswLapyby1zMS6y8W5va+jjHVqiW9fqpqCgX9gtodzsYh0mYFoYF49RlUpOkIeYltIpJuOwLustKuXqZBzrINfmm9QjGdNiWVDsJh5yb+oxb2tyL6xyMCxy8W0zMW1v7mov7epyr64zMW8zMe9vbSrkX91c1ZFgWpRcWdEto57pYVueW1NU10zSV0tPk0jTE8zmI+BwbWsycOzxrultZ2DoIBlk25PjGc/sJp9w7ytwrirxLSjwbmpxb+vwburv7mpxb6wysO6ycO6xsC2t7GmkYV1dVpBg2FHe19CtpB9inJYWVkzS18wR14sPU0iLDIUcWxat6uhzcW6zsa3wbOgt6WOo4xwjW9Np5R9t7Cot6ykuamcvbWlvrioubOjwrysx8KzyMO2xLyvt6qcppOFkHhliWdNlmxTimRKoYBsZ1s8S1YsRV8uRFsrRVUqLjYWNTYfioV0xbuyzcO6wrqsu7WisqqUpJB4qJqKqaKcp56ZtqigvLWmsqyctrCgxb6ux8OyxcKxuK6cmoJwlXFeonhjondfo3RdlGlRgGxTU1MwR1ktRF0tRFkqRlcrRFArLDMUTU41raWYxbyyw72wsa6fpKGQpJqGnpWGmZKImZGJoZiPopyNmJKCq6aVxb+vx8KyyMO0rJ+OgGVSlm5YsYJrsYJrrn9pn3JbYVw+S1cwR1otSVstSVouSVouSlkwRFAqLjUXh4Juv7amxb2tqqGShHxtbWpXa2dUcWpaZF1QX1lNYFlLUUo8f3lqvLamxL6wzMK8r5+WdFlJh2JNsoZutolyt411r4hvT1cyRlguRVksSlsuTFwwS1swTFsySlkwLjkUaWZPvrakxryrqJuNd2xdQkYtNzwgP0EkPT8jNTkePD8lODkgQT4pmJF/wbisyr+5x7mvlIBweWFMoYNpt5J3sY1xrYhuSForRVgpRVoqR1ssSlkuSFUrTVkwTVkwNkAaW1hEvbWnwrqspJuNjIV2VV0+PkolP0oiS1crS1grR1crSlQqNDUTVkw4mIuDsaqjpJ2Vh392Z19Wb2NUm4RpnH5jonxjRlwqSFoqSVcoSlQnUFYwV1s4YWRBaGxJVlg4Z2BOvrWnu7KkoZiJopqLamZQT0wyT0wwWVg3WVc1Uk4sUk0qSUEkOCocQjU3R0VULy5AKSg5LCs9LSo1UEU9fWlbn39rRlstSlcsVFgwX185amVHc2xRdW5TfXZacmpReW9dxbmpua6doJWEmIx8c2NVaFZIYlFCY1FCYE09YEg2XUg0VUY1UEQ/MSs0GCA3FyE5GiQ8GiQ9GiI5HyAwOzI4b1xSS1g1VFo6ZWRGb2lObWJMbWFNb2JPcmZSal1KdmpXvrGfu66cl4t5fnFfblxOb1pOY05EYk1FZ1BKaExGZlBHWk9HPjo8ISYxFSYzFSc0FSc0FCYyFiY3GSI8HB4vKyUpW1tJaGhWbGlYaGNTZFxLZFpJZFpJZ11MX1VDZVdEs6SQva6ahXZiW004Y1dCc2ZVbmFTcWNae2xndGZjbGVeTE5JIioxFyQzFSczFCcyFCYyFig0FCU0FiA4GB81GB4uaWJYZ2JYZmNYYF1SX1hLXlZKX1dNYVhNYFRHdWZRsKKLr6ONal5KRDsmZl9IdG1YcmpYfXVlh35xfnhvYWJfJzA1EyEtEyM0EiE2EiI3FCM4Fyc7FyU7FiI2ESExFiE3amFYZ2BWZ2NYaGRYbWJYbGJcZl5caV1Zd2Zcl4Vvs6SMk4hzaWFPbWdWfXBggXNjgnVkgXVjfHFdenBgS0tNFB0xESAzEyIxEiA2EyI5FCM6EiI5FSE6FCI0DiUrFSA3cmdbcmhceG5ifXJmhHVmfXFmcGlhc2hei3lqpIx4o4t3gWxagW5fkH1wjnVqi3JmhnFjfWtdfW1ecGdcMjQ5FB4zFCM4FiQ1FSQ6FiU8GCY9FSQ7FSI5JC89JTI3Fh4ziHlqg3NkhXJkhnFjgmxbgXFhfnVodm1cfm1ZkXNkjmxejWxflnVok3Flj2xikG9mjHBojXZuiXdwSkVDHiQtFyU4FyU8GiY8GCc9GSg/GSg+FyY9GCc7UFRcTkhMHB8y" + }, + { + "index": 13, + "label": 7, + "pixels": "IyQfP0A3JykdFhoLNjYoHRoTHRoSIyAXJCEYHBkSEg8LBwQAEA0JGRYSFhMOExQRCw4MExMPHxwVOTEoS0I4NCYfIhMNIhMQJRYWIBARGQ8KGBEHGBEJEwsIDQUFEggJDQ4JGBoQMTMnLjAhUFFDQT41HhsTFxQLEg8GEQ4GDwwHCgcCDgsHMzAsIiAbGBgUEBIOCwsGDw0HIx4VNi4kNywkOS0nNionKBsbHRARFg4KEw8IEw0IDQcEDAYFEQoKNzkwEBIIHiAVJCcZQ0M3R0Q8T0xEY2BXRUI6FRILDgsFCAUBDAkEIh8aIR4ZHx0YICAbEA8KEA0IIyAYKSQcMSkiPTUvPDMwNiwtMScqQTs5OjYxGRURDAgFDwsIEw8NUVNILzEnJigcGBoOGBgPLiskRkM6QD00MS4lHxwTFBEMCwgEGRYRFRINGBUQNDErNzQuIB4XExAMISAaFhQOMCsmRD86Qjw6aWNkmJKVtLCxdXNxNjUzJCIgFxUSDw4LMDIlFhgOEBIKDhAICwoECwgCExAHEQ4GFBEKGRYNDgsFDAkEFxQOGRYSEg8LSkY/SkQ8FhMMExEMGRkUKCgjLCsmOTYybWpppKGjvru/xsTJkZGTmZmZf399EBENBQUBHyEULzEkFxgRBgcCCAgDDAkDFhMLFxQLGRYOHxwTDAkECQYCDQoFExALFBELOzUtWVFIGRQNCwoFERMPGx4bPD05hIWBl5iYr6+ylpabPz5EW1pf1dTXycnHSElEDg4KGx0PHR4SHR4WBwgDCAcDCAYBGxgQKSYdSkc+Qj82FRINDgsHCwgECwgDEQ4JJiAYS0M4KCMbBwYBCw0LKCsrf4F+sLKvp6mpzs7SjI2SQ0NKWVlfuLm85ufmfH55FhYTMzIpHBgPDgoEBwcCBwcECAgEEhELGxsSS0w/TE1BEREMHRwYERAMCAgDFRQPKCgeLy4iIyIbDg0OGxshW1ljpKGou7i+wr/E5uTom5mcNzY6OTo9e3x/3d7fl5mYGRoZIR8ZHxcODggBCwoFCQoJCQkHCgsGJSYeKy0hKSsfDA0JLS4pKismCgsHGRoVJiceKishGBkUIyMlZWRslJKerqiz0MvT4Nvh6ubqb2ttNzY3VFRUtra36OnpoaGiHB0cFxUPHBULEAoCERAMDQ4MDg4MDA0IKywlLC0jOTsxg4R+t7izv8C7goN+Li8rFBUPLS8mJCUhVlZXoqGouLW/xsDK19LZ8+/03trdSUVFNDIyPz8/iYmJ19fXjIyMGxwbFRMMHRYLIhwSJyciDg8OEREOFhcSMzQvVldQmZqU0NHL5ufi9/fz+fr12NnUmpuVi4yFi4yIoqKjr660z87U4dzk3dje/Pj72NTUQz88NDIwMTAvVFRSkpGPb29tGxoYIB4YKyQZNjAmMjEsFRYULC0oWFlUYGBea2towMC+3t/a9vfy/v/6+fr19/jz8PHs7u/r3t7dxMTFv7/Czs3R5eHn6eTp//z91dLQRkI+NzQwLSknGxgVIB0aNTEvFhQRNzUvU0xCV1FHQD86Q0RBeXp1d3h0QEA/aGhp0dHS8vPw+fr0+fr19fbx9PXw8/Pw7+/u4+Pi0tLSzs7O19bX1tHV7uns//z7u7i0QD04PDgzLCgkGhYTCQUDFxIPDAgGQ0E7eXJoc21jYGBbh4iFnZ6YdXZyPDw9Z2drzczR8/Ty9fbx7e7p8PHs8vPu9PXz9PP16urr3t7ez8/O0dHQvrq76OTk9/TxgX55NDEqMS0nHRYRJB4YJyEbNzEsEgwJS0lDeHFnZF5VhYWAq62onp+ZgYJ/Ozs9cG91zMvS5ubl8PHs3d7Z7u/q9PXw9/f2+Pf69vX26enpzs7M1dTSvrq73drZ7OnlYl9ZJyQdJyIbFxALGxQPMSokMislGRMPPj43SEc+YmFYqqukr6+omZiRh4eDMjIxVldZxsjL4eLf6+zm0NHM4+Tf8fLt9vby+vj1/fr48vDvycfHz8zM0MzL3dnX4N3aWlZTHBkUGBcRDw4JCgcDDQgFFxANIBkXISIbFBUNZGVdsrOro6KbpqOch4eBKisoJSgnhIeH19jV5ebhs7SvxsfC5ebh8vHr9/Tu+PTw9PDvsq6vpqKj497c7urn0c3KPzs4Eg8MDAwHBwgDBwcDDwsIKCIfNy8uDA0IFBUPaGljmZqUn56Xsa6ojYyHLCwpGx0cP0JCr7Gt4uPelJWQk5SPxMXA4N/Z6ufg8O3p8Ozri4eIe3Z43NjW9/PwnJiVEg4MDwsJCQkFBggDCgoFEA0JJB0bQjg3CQoGIiMeVFVPeHl0oqGbvru0lJSOKSkmGx4dJiopi4yJzc7JRkdDR0hCcXNtp6agw8C51tPP3NjXZmJkVlJTy8fF5eHejoqHFhIQDAkHBwcDBQcCCAgECwcFFhAONSsqFhYTODg1Ojs4WVlXo6KewL22pKSePj88BggHCg0NYWNfw8S/MTIuCAkFHB0YNzYwWFVPbmpmdHBvLCgpLystl5ORysbDz8vIgn58NTEvCAgEBAYCBgYCCwcECQMBGhAPJiYmOzs6JycmRUVFjo2KtbKsqqqkREVCCQsKDRAPLzAtqKmkRUZBAwQABgcDDAsHLCkiJSIeCwcGCQUGGBQWJiIgUU1KmZWSb2todXJvHR0ZAAEABgYCCQUDCwUDFw4MLy8vLCwsIyMjRUZGe3p2rKmjpqagOzs4LC4tY2dnKSondXZxUFFNBAUACQoFDAsGIR4YGRYSCgYGCwcIDAgKCwcGGxgWh4OAQj89XlpYLy8rAAAABgUCBgMBCgMCFAwJJSUnHR0eKystQkJDXFtYiIZ/fHx3JCQhMDIxj5OTMTMwTU1JXl9aDg4KDA0JDQwHGhcRFBENCwgGDgoKCwgJDQoIBgMAYV1bfHh1gn57S0tHAgMABQUBCQYEHxkXKyUgGhobGRkaLi4uODg5QEE/VFVQQ0Q/ERIOHR8bdHZzLS4tTk9Pe3x8GRoaCwwMDxALHyAWEhIKDQ0GDg0HDQ4HCxAKCgwHQz89hn9/h4KDX19dAwQABgcEDAsINjQwTUxIExMTFRUVHh4eISEhLS4sOzw4LC4pDg8KHB0YdnhzJykoLzExhYeHNDY1CgsLGhsVMDAmHh4VCwsEDAwECg0EDBQLJikjQzw7fHN2ko2QhoODExANCQcFCAYDCwkGGhcUFRUVGBgYFBQUEhISExQSGhsWGhsWGBkUGBkUdXVxOjo5ISAgb25uT05PEhERHRsXLywjLywkDgoGEA0GDAsECw8GSEdAWFBOhXt9pZ6gh4CAHhYUDwcFDQUEDgYFDAUEFhYWHh4eGRkZDQ0NEBAPCgkGCwoGDw8LFhURf356W1dWCAQEQT09bGdnJiEhFhANGxUQNS8nFg8IHBYOEg0HCQkDSUM9VEdEbWFhw729WE9PDgICFwsLHhERGg0NEwYGDQ0NEhISEhISDw8PFRQSCQYDCgcEDAkGEg8Nd3RwioOBFg4NIBkYZV5cRj89Fw4KHBIMIhgTIhgSIxkTJh0WFA0GLiEcTj07Z1lYqqOhU0lILyIiPjExSjw8UEJCTUBACQkJCgoKCAgICAgIDAoJCwYDCQQBCQQDCwYENjEusamnYlhWGQ4NRTo5f3RzLSAdLSAbPzIsQzUvVEZBUUQ+SDoyU0E7Z1JQX09Olo6LS0NBIBYVMCUkMykoQTc2Qjg3CAgICAgIBwcHBgYGCAUECwQCCgMCDAUDDwcFEQgHNiknPzEvUEJAYVNQq52agHFtOCcjPComNyYiQC4qNiUgPSsiWUI8YUlGTTs5Rj05Mi0qDQgGDAcECAMBCQQBCQMBCgoKCQkJBwcHBwcHCwgHGxQSHxgXJx8eNzAuMyopJBcVOionSDg2PS4rfW5rsJ+cXElFQzEtNCEdRTIvQC0oRzIqVz45STEuHw4MHRQRQ0A7FhUSAwMBAwMBBAQABQQBCwsLCAgIBgYGBgYGCQkHEhEOIB4aMy8sRkA+TENBTj06Tzw5SDUyNCIfPSooeWViXUlFSDMwRDAsPionPSglQysnTTQxQSsoLRsXJhgUIhgVDgkGBgYDBQcDBAQDBwQE" + }, + { + "index": 14, + "label": 9, + "pixels": "yKlLtY8xxqdEwaBCv5Q+u5JIrodNqpN1r52Q4dfI493Xsqip9/T6/Pr++vj99/X69fT39PP29fP39vT48vH27u307Oru4ujp8PD3+vn/+fj/+fj/+fj/+Pf/9vX99vX907dLwqE3x6lEtJI9t489upNCu48+sodDoXk7qo5cp5iAraKd0tXg0NXf1dnkzdLcrbjHpLLEorDGorDHlqnCjKK/jp+uhpSkwcTO9/X79PL69PP79PP78/L68vH58vH5zbNUxKc7zbJJy61Fv5s6tIpAsos6tIo7uZI7k4lqd3+Lk5eaeIyscouseI6vd46qaIOhZH6jY36kXXifV3SdUnCaTGuVXHGQtrzI9/b68vH38vL58/L68vH58vH58vH5vZxJtJQwx649vqI5v6I5xJ9CvpY+wppAuZU9ZW1vT2SCd4CINlJ+NVaDPFeAPFd5OFd6M1J6NlV+M1J6Lk55Kkt3IEdzSGOFfoSYs7fB6ezv8vL58O/38vH58vH58vH5yKVCu541xa87spIxsZY0ro80tpQ5vp06vJ07SFpZL0ZjZ291FzRfIkBrKT9nIzhdHzdeIEJrJ0p0J0h0JUZ1JEVzG0BvRGCDUmB4U1tukpqj4Ojr8PT37vH47/L47/D4zK4/u6Exxa87wqQ2vZ8vsZA0rZA1pIs9qZZLWl1hW2N7b3d9J0FlMEpvMkpyLUVuK0hyK0x3JEhxGz5rGj5tIERyGkBrQV18VWeBVWF6SlZrc4GMxMzS6/H27vL36vD1tJI4nXwmvKQ+pJdWkI9giYt1f4d+gImHl5mSfnd/opuZeoCKWXWfV3SeWXagWHahVXeeYnKRXm6NR2CILkVoHjRPGC5IPlVtSmJ/WmqGUWF/QlRrcXyIxsrPsLjAvMfOt5M2rIUigHRATFZkRllxRVpnQlhlZneHgY2QXWh5i5GUXGtvY3mKYXeIX3SJYHWJX3SIY256Ym+Cbn6ecXyRQUdUDA4TQUxfSl+BVWiFS2N/Sl56fYmXxMXIaXiJfIufv50wsY8tV1s5T1UlXVsnQkMhNT4ugo2JfIuJZXJ6hpWRY3Vyc4SCcIJ/boOCbYSBb4V/bX6AV2qDXG57eoiKZmx6GBocN0BSRlp9VGeFSmN/SV19fouc1NnbbHiIbXuPq4koj28rWl9DbHAvgIItU1UlSlVGlqWjcICAcX2BgY+NaX58coaCbIN/b4aFcomJdYmLb4SEWGt/aX5/t76ykpKVFxcXKjdGQ1h5VGeFSGB/Rlx+cYGaxs/UbXeKaHWLtJUpinItWWJMa3EpeXwrVlosYnBkmamlYXJ0e4aLcYKAcIGAdoODcIKBcIeHcoqKcomGbYCCT2N4aYB/zM/GpKOmGBgcJzZGQFZ4U2aFRl+ARV18bX6XuMLOaXWGaHWMsJMfgHEuT11FaW4rdnQkXWM2coSBnaikbHt7i5WZZXl1d4WFeIaGb4OBboWFboaGbYmBbIOER112aYB/y87Im5qiGhkjJTJIP1R5UGSCRF1/RV17d4qZvcbPZG+EXmyEoYUhaV80T1k/Zms9bHdCaHhegJSTnKildIF/jpecZnh7eIyJeYaFcYKAa4J+bYSAboiEZH2CSl9zX3Jvr7Gtl5ecGxskMztNSFt5SV+AQlp7QVl5g5ifytLSXGaDUmN/oowoYVxCW11GbX5lWpKNYHt+goyMfpGQU2dshpKWWWtsbYJ3doh/dYqBd5OIgJyQfJqQX3qAVmV7YW95e313e3t5FhUaLjlKP1V3Plh9OlR4OlN0anqEs769UGB7S156jHUlRVJdP05fQ1hoT2qEbHuJjpSchY2Rj5qei5ecZHJ8X3N/YHV9a31+cIeGdpKPcY2OVXCER1p/S2OIX3aEXmFhGRgdJC5JP1N1OlR4MUtzM055MkJdSVZsPU9sS195eV0jLEJoGjtzIzVmbniTeIGVoKWroKGiqa6qo6arlpqlVWuLK0d9Mkh0N0pyOVGBNlWHP12ESFl1WnyhgJ63VV9sOjg4LThTRl5/PVt/MVN6LlF6Jj9nLTtdN0hrVWiAeGAqR0haNEBmTmeRhYqdP0VdeHl1WltZent5cXRubm9omaKsMFCFHEJ4HD56GECEHEKDLEZ0QFRyVoKmiKi9UVZlTENFQEdZWWyIUG2KSWqJQ2SGQFh2RVRtR1hzYnGFPDMpOEBbLDheWW2RdXqOOz9Rb29qSEVEfnh3U1ROPT05qaOgZ3mRHEOALkh8SU5iIkSBIkl/MEt0TnaeeKG1R1ZsKjBBUFlkc4GSXHKHX3SKZHaOZHSHY3CAaXeGaXeFMjA3W2eCdYCQb3uORFV7P0dUdndugXt1mIyIVlBLRUI7jo2HSVyDFTx9KUV6QEBdIEF8K1WENU94XHOWhZWmZnB7SExTXGJjkpqUipKSipCRhYqMeX1/fIKBeH9+bHR1U09KZ3SFkJKUc3uHKER0S1ZfWFlNXltUZWFZVVVMUU5KUl1qLUd3YXGLZ3eSVGeJMFaGLlqGNlN5S1uCdHmOaW90Ojg3MS8vMC4rKCUkKSUlKygnOTo4MjM0Ojw6Q0U/UFREHDtsIzlvKENwKEqAW2d0W1tSHB0eDg8SSkxJZGRePFBuJkZ/j5ifqKObmpeMQ1+BK1qINFR6TmCAe4KDTk5SCAMGKSUiGRYWAAADERATHh8gWmBgTE5TWl1dPj45l5iLYXCOTmSJTGKGOUhgUlVcOjs6HhgcGREVJiYpdnJwQ1FsI0J8NVB4QVR3Rlt6L1GBLVyLRV1/UmKAb3V1cXNyMzIxKCQhLiwpIiIfICAeKy0sXmFdWVpWW1xRQD430cvC0Mq/wsK6sLGroJyMgnx0iIaCjoJ/hHRvWFhXVVRVPUFFM0BZMEx9KEmDG0J/H0aBLl2KSFx3UFlvXmNqcnZxUVVSJyYlSUdES0lFHhwcLi8uYmJaXWBXZWJURD0zy8i+0MzAzcW1vbiqwb6pU01JVE5OZV1XenNru7ivwr6ytrOnsLCpo6SkmqGkkZyqZXqbLFWAJ0BhPUpaZWtodXNpWVpYJycnRENAS0dDJCAiKiopeHdtaW1kbG9lUEwvn5qMvLSkvKyZs6OTzsm1j5GFbW9uX19iWlhXq6eczce3w76u4uDT4dnG5d7M5dvDm6GiLU94HzxpOUZXdHZup6SXY2VfJSUmJiQkKCYkIR8gGx0bg4J6YWVdXGJZXFc3MyonUEQ7aVtLbmBQhXtrpZyKqqGMr6iUycKx1Meyx7ibxLiZ39rE2tG63dvL3Ni/lJeXO1Z9Mkx0O0dTd3dtmJeJYWReKysnEA4IERALGxsUFRUSY2BbbmRWcWlQg3ZaOC0uOTAsQzwwSUIyPjkpJiAfKSMeOTQrVk1DcWNWfW9ZkoZtr6WQva+VzMOo2c2vk5GRTVVxYmNpWFdUgoJ4i4t8Xl9XOzknOzYWRD8ZRkIZTEcla2NLhXdbjoBhj4FkVExBUko5VEs8S0IxQz4sIB4cEg0UCQYOBAAGCAQECwkHDw0KHxoXMSkjRjoxWEpAR0E9LyotPzUxSEE8dnFnhod3YWFTSkUoWVQqbmY9cWlGfHFTj4BnjoFni35pintpX1Y9WE81S0EuOzMkMiogIx4YJBwZIxwaIhgZGBESBgYHBAQEAgICAwMDBQQFCQgIEwwKGxMPHRcWLyolcWxjgHx0cWxWbGU7bGk4cXFDeHdQgX9Wh35Wg3VZf3BbgXZdaFs/YFM3VkgwSkAoQjkkMyobMycdKiMcGRUREQ8JCgoJCAcICwoLDg0NEAwOEAsOGRIRJx8bNSsmSD02bmdZhHprg3dWhXlQfHJJdnFCdXFAe3VEhnxOfXFRem9Tf3tad2VUdWNNdWNKcF5EbVs/YFAxV0kuOzEfKiUYIR8SIhwUJx0XJB4YJyMYJiAZKiIeNSsnSUAyXFNAa11Gd2hKfW1NeWlKfm1Sg3JYjXxeiXtZeWpOfXBTeXFWd29WhYFnjoFzinhsi3hoi3poiXlmhHJUfm5IcWU6ZVs1VE42TUUwTUEpSkIqUUksWE0yW041VUk1Y1k8bmZBdWo8eWo7eGo9empHfm1RhXRYiHZci3pjgnNcg3VeeGxUeW1XhHle" + }, + { + "index": 16, + "label": 5, + "pixels": "X0xOXE1OWU1NVktLWU9OW1FOXlRUZFhfZFdfZ15fjYiCubGmuaeWuZ+TvbCvoqKgfm5reWVhcmFccGNea2FdLSQrCgAQEwUYKhEiMhAeIwYUGAMQCwAMHhwmr7e/4erwWkdJVkhIU0dHUUZGU0lKV0xOWlBRXVJRemllrpmQ1L6s28Srs5NxpX1jybat5+vps6qomoBso4JorY12pY18VkVAHxIZEAMVGQYgHAMeFwEZEQIWCQESAAANPD9Ppau9WEVHVEZGUkZGUUZFU0lMVktSUkhKeGxjvaCHw5d8rXldqHRVu5Z3waiXyMC84u3s29XTqo96nXNSo3JPoXRZjGJPc01GQCUvGwceGQQgFwIdEQEXCwARBQAMGBowf4ulVkdJVEhGVUVFVkNFU0VNSkROa11Yv6CDypp1uX5gsHBPqWdDqoBm1Ma8293e2eLm4uDgtKSdh2RSglI6aT4tbj4ycT4yakE5UDE1JQwfFgAcEAEbCQESBgAJChItYIKiXFBRVU5OWU1QX09Qbl1YiXNnuJN7yJhyyZFnw4Nlr21KpWVCqYBr0sa+4OPl1dvg3N7gycTCmHtthFNAZjUqVSooZzs0YTQmYjkxWDU7Jg0hDgAVBwERAwAIAQgwHUd6bGFhYlteY1pchndvuZuCzppzw4hgtH1bvIRdsG5PoWA9oGtNvKCU493Y4uXm1dne1tvey9DPpZCBjF1Ie0U4UCglWTQxXzIqUyUbYzgzUC81HAoVBgEOAQAMAAInBRpIcWZlaVtcgGxjupiAxZButnlTsHJOp25RlV5Hj088nmRFpIFk1MjA6+vr4+Tm1djcytLWxMvNq5iKi2BJhlVCYTsyTCYiYTMvVyojWC0kYDY3NBslBgARAAEWBAEXAgMVe3FpgW1it5R7v4tprXBRmmFHj1c+n2hOcj81dz4wmWZLtp6K5eLf5+no397czc7PvsTIvL+/nod7b0MyXjUsXDYwSSIdXTIuViojUSkjWC0qPSEpCgIWAQIdBAERBAIKioBtqpJ3vZBunWZGkFlBk1xJj1hAnGpPYDkudUs1p39h2MS23dfWysTCxry4vre3tra6tLSzjnVuVSokPhYaWDIyQiEeVjArWy0lTCMhTyUgOR4hCgIPAQITAwALBwAIppJ5wJ5/pXNThE0zg047jllIilY+oXFVXTktfldCs4tttJmFp5WRf25vjHp5saWmtrK4vbi+oo2RWjc1UCklakQ7PSAeRCQkXzEsSBsbSR4eKxQWBgAFAgEFBQADBwEExaaFxJdynWVJfUY0f00/hVNEh1c+pXdYYTUqckQ3l21ZiWlcXENDRjAzemZmu7Cxx8bJzMzPyMHIiXd7XD01b0o8PSUjMhkdWy4tSRgZVywuJhQWAgAEBwEHCAAFBgAFyKJ7yJNrnWNIgEk7fktCfUxAhldAoHNUYToqZEY5q5mM08vGqqCil4eJqJuayMTE19vc2+Dd2t/jzszSkYB6f2NUVkRDLBYdVywsUyEiVi8xGgsRAwAMCQENCgAKCQALvI5mx41poWdQgUs+fUg/e0g/gVI/mm5Tck07fmtixMPC1NfcycrOyMfJ09PU5ebo6+3u6+vt4eTn2N3fv8PBn5qUYVhcLhgeWCwpUygmLxQXDQEMBQENBAIDCQEGDAENu4tjuYBcpW5Yg09Cfkc9fUg/f04+lmhQlG5bnoqBvLu61Nfb19jc29ze5OXn8fL08/T28e/x5+Tm2Njayc7Stba4W1hiKBUeVCkmQhwZFwIHDgAMCAEMBQIECQEJDQERw5+BrHlap3JejFZIgkg8fkY9gEs+j15KnXdjn4x/r6+q0tbY3+Di4OHj4eLk8fL08vP27+3x7OHg2srHyL2/xb3BdXF+KRkmSyorLhQVDgAIDwAMDQAMCAIJCQENDgETzburr4VuqnVhl2BPh00/gUg+f0g+hFFAnnhkqJeIqKmiyc3M2drc2Nnb4uPm8/X29Pb57u3y49DLxaOXr4yFnoWDkYWPVEdVLxwiGAwWDAEODwALEAENCwIOCgEQDwIWzsvDxq2asYd2o3NklWBQh05HhE5Ge0s7oX9vx7utu8G3zNHP2drd4eTn6+/x8/b58fT25N7cvaSXr4R1lmZickhKgWptg3+CNTA3EQYUCwEODAENDQEODAEOCwESEAMXxsjDqq2ota+rtJeNo21dkFJJkFRIhVJAtpaH4NTGzs/C2NfS4uDg6Ors7O7w6+3u5ebo29PSsZeQgFZQWi4vUSgsd19emZeWV1ddHhUjCQAMBgAKBwAMCAANBQANDgAVzNHOh6WzepOju6unpXZpmFtOl1pKkWJP0bys597RysS6w7y22dXS0NDP2dnY4+Pi29va1M3NtZ2db0tMSycpVTY2f2tql5OTd3h+ODVBCwURNjE9ZGNtZ2hyOzxJFAwf1dvZfqXCgJay2cnIspaNm2xflWRTqox64NvQ4eDZ2tbS087M2tbUyMXCv7y50M3Lz83JvbizmIOCc1RUZ0xHalJNdWNhmZOUqauxbm96TUdTqqiyztPc093kwM3WXmNxxdLYbJW6w8TV+/Dv8Onkzr22wK6l4NXM6Ojj4+Ti5uXj5eTj4uPi19fWv726qKOgpJ2alYyGf3BremZgeGVceWphjYOAq6iqtba4srK2paauvL/HydHXzdjdxNbZrLrDp73MgJ7A7ebr/vr5///7/f34+Pjz8vHu7ezs6urq6Ojo4eHh3eDg1NfX0NDOw766rKOgopeVlouHk4R+iHdwjoJ7qaWhvr/AwsLCvLq5qq2ywsjOz9fc0NrextXXtcTLg6C5pK2/+PLw/f38/v77+/v49/j08/Px7vDy7O/x5ujq4ePl2d3ez9LRycnHvbe0rqWjqJ2coJSSnI2KkoF8nZCKxMC81NXW0tLTwsC/qqquyczQ1drd0dnbydTWucTMcpi80cjK/fPs+/79/P7+9vn48vTz7O/v5+vu4ebq29/j19zg0dfYw8fGr6+tnZiVm5KQlYmLhnl6gHBwd2VjppmU3djU4+Tl2NnZw8HAsbCyy8zO19rcztTUxs7QwMjSdpq+7tfN+/Ls+v39+Pn68vX26/Dz5Ort4OTo2d7h1dncz9PVvb/ApqSkmJSTlY+Mi4KAbWFjUURIVEVJgXNyyb6539nW3d3fzMzNtLCwqKWnzczO2drc0tbXxc3OwMjQk6fA+NbI+PHt/Pz89vLy6uvt5evv3+js3OLl19vdzM7Oubq4pqKgoJeWloyLgHd1WlFOPTIxWU1Qr6Gj0cO7xLatxry5x8TFuba2p6Ggp6Wn0dHU297f1NnZxs/OwMrOsbC78tDD9+rk+/f38u/w5+fn5Obn4ebm1NnYxcjFs7KupaGcoZiUi399Z1taSz8/PjIzSj9Bp5ia38vHuqOTsJyOqp6ZmpWTmpSSkouIpqanzdDR19zc2uLizNPTvcTJzLGs5MK379vU+vTx8vDx4uHg19bTx8fCtrWwq6Wgn5KNinVwY1BORDY3PS0zOik1NCQxPC85eWp0kX6DmIJ+pI+IkIGBe3J3cmhtZ11fsq6x0M3R1tbY1tnaw8jItbrA27Wm17ap2Ly07uXf5+jo0s/NvbeyrqSenouGhm1ob1BLZD87SzAyNSQuKBcmGQgcEQEVDgARDwIVEAQXHhMgPS40UEFINyw3JxsnKh0meW5zrqSp0szQ0tDUrbCzcnR8y7Ch1a+cyqWb07+039TM07+4uZuUlm9pgU9JilVMmWheoHZvZktPIBAeEAIUDAAQCQALCAAPCgAXCgAXCAAQBgAJBwAKBQAJCAAMCwIMOSwxraOo2dXbtre9dnh9JSAue15a0qqd06ugx6GR1a2f47ip1qiWwZGAsn90uod8xJePi2poJREXDAAMCwEQCQAPBwAJBwAICAAMBwANCAALCQIQCwIVCwIVCwMWCQASEwgWQjlFcW10dHR4LC0vCwMPZlVU0Lev17qwyKeUyKOO2LKc3Lee2rSb1aiY1KecupWSRCw0DgEMCwENCgERBwEPBQEJBgAFBgAEBgAGBwANCgEVCwIZCwEYCgEXCwIYDgQYBwAQEw0aJSErEQ0WFgsc" + }, + { + "index": 17, + "label": 7, + "pixels": "PICTRYadR3+WUX2QXIeVVIWOT3p9THFwRWtqRW9xS3R6RWp1U3KBXHOAZ3h9bHt7YHN0XHJzU2xsQl5dTmxqWHNqTWdaTWleTGphS2xlS2xkSWhcU3BnVm9sU2hsaXyFPoSTRomcT4qdV4aVVoWQToiNVIuKTHt3RW1sTG90UnN/T3WAVX+EYIGCcn9/YGVmSVtcVWtsUGhoQFxaSWZkVm9pUGdeTWVeUGpmT2xpRmRgQl1XT2hjV21sXnFzjZ6lPX6MRoSXVYyeYIqYXoeSSnyES4GASn13SHJwS2xyUG98XHiBZ3t6fIV+enZtTEtGNUZHSF5fSmJiSGRiRmNhV25qWWxoXXFvWnBwVnBwVG5vSmNhV21rdoqKh5iaucjLUIiWVoueYY6ga4yaeZSiY4KQSnN2Q3JuS3Z1SGlvS2pyYm1yg25siWhfalNEQD4yRFZVQFZXNk9OQV1bQl9cTGFfX3BudYiHcYaIdYuPiaGlZ3x/fpGTkqSlm6qrvcrLb5ejdJimjKy3hZ6mjqWykqm2do+RTnJ0THF6U2lyXV9kc15egldRbUY9VElCRFRSW3R4PFdUNlFIQlxURl5cT2NkXnBvd4qIi56fiZyjnbC7d42TfZSYdoqPbH6DlaSqjKKsjKGtpLvKnLLDmLHFoLjIlaWqe5CadYqbfXyGj3N1fFpVY0g7QjUrPkNGT2RxY4SRTW5xTWpkXXRubH59b4B/YnNvb4F4iZuVfIyPgpOba4OEZn9+aH5+cIOEkaKkla2whqCpfpurdpasY36XdICRiImUpqm6lpeph3F3nHRvcFJGQDclKiwhIyQoNj9QVnaIZ4iUfpieo7W3q7i4lqOifo6HZ3drf4+Dk6KdeYqJX3ZwWXBpZ3t2lqijorGtd5iaTWluQFZdWGhyc3WAmoOKn4KIp5emmI6edFxYeVZFVzgmQy4cZVJHVz89NCctN0hTZ3qIr73K2eTtx9DUiJOWcn9/ZHJpiJaLvMrDlqWiaHx3cISAdYaDqri1sb27TFtrVVFbfWNoqH17vIWAwYJ5tHl1s5WerqeweW9iZlM5Xj0ofkk8sHNpqG9ha0Y4PDUyU1JaoKCv2dzqwcjPkZmkho+ZfYeIpbCszdjVr7u8d4eLgZGWh5SZpK60u8PKeWVxk29wsHpywHdtvHRluXFgtmxnsZWUnKilhIB6cFE6j19Ht3dsyYF4vXlpomhTcEc6Rjo5cXN+zs7ezc3VsrK9tbnFp7G2v8vNzdfas7zCfoqUlJ+qnqiynaSuxsrUnG9sqHdorHVgqWpWpWxXp2pXp11ZkndwkqKZi4aIgVNAk1s/mWNUoW1jmGhclmZbhF5aTkZAVFRUtKuy2tXZxcDGxL/GwsfK0dnb1Nncvb/Fe4GLhoyWpqqytre92dndq3Bnpm1YnWVJmmFFlmJHlV1Hl1RGd1FFiId9i4eGfFdChFQ2aEAtXj81aFJMdmlsa213UVZRV0s9p4+I0MzLxsHFxLq+wcDB1tjY09LTvLm8gIOIdHZ7j4+Sw8HC2dbUpGdYm2FIm2VHmmZJiFc9fk0yhkozfUo3gGpgm5mWdFpKe1U9bVI+WUo+RT88QUVNRFNhOEJBXEpApIN7vbCqpKKjnZ2hoamqu8bHu8TFq7G0iI+Tb3V5am5wnZ6eu7u5mGVUlWNKk2BGkFxHfEw2ckcog04um19Hj2hdlJSQfGxnd1hNalZGYldLVFBOPDtBLjM5JS4yV0pRnXp+qo+Hdnd1XXF4aoWJbY2PdpSXf5aceYqRbn2EX2xweYKGnqWniFxIhldCg1I9eUg1cEIwdkYtlVUzrGVFm29fiIuKbnR2ZVpXY1JHZVJFXU5EXFBLUEhJSEpRXFVgjG50nnZugHNtYnR1co6ReJOaaIOKdZKYdI2VZ3mBXWpyanp/boWFg1lDf1I+eU04bkQvcEQwgkk0nVEwpVs6gFtKU1lfRFdgQUlJWVNKX05BZE4/XUlAYlVVWVFUYVZXiWxomWddn3JpjYR9doiFh5edgI2WeZGUaYSGWGduW2Nta3qCZYWIgFpGdlI+bUg0ZkAsdkkzhUwxj0wtj1M5el5WUlpkTVdoWWBoeoaAXF5VXExHYklJZ1RSeGhib1lRjWZap21eqWJZnXtyg5KGepGMfoqMgIyNbX99X2puXmNvb3iJdImbfFpHaVA7XEEsXjwqd004dkYqc0Aod0w8gm9rXGBoaG58WmBoVF1bf4F8dGhpXkpPWkdFdmFYhmdYk2ZVr3Rlsm5nnXp0qLClsLy1o6WhmJqUhoyHcnZ3YGJpYWVzcHqMdFZEW0o0TjwmX0AvcEs5VTUeVjUmZkpEfGppUk1MX2lrfX+CUD5Ab1haj4OFdHB0VUpMXEhBgWFRkmVUoWtfj2log3x+mp2fr6SnvK2nramao5+Zko+Nf39+fH59iY2OaE9BT0AtTDonaUk4aUY2SDIiQTEoVUdEdmViWkdBX19afHRwakVAdEpCbVdLYV9VUExLVEVBYktDfmNca1RRc3N1l5ude2NljV9ew6CT1Mm1z8rCysnExcfAxMW8yce7XUc+RzUnVkAwdFFBXTstQC8kLSkiPDw4bGBcXUI7YEY8XDsreUYsklw5iFozZkkqVks+T0Q9TUVDamtvW2dugouLgmximl1Mum5Wunxj2rih4NjJ1dbN1NbQ0tLL2NLHUz0zRzMnXEY5Wz0xPiYbJh0UIyQcS1FKaWdgRzgwWTsqcUQtg0ksjlAtiVAof00rcks4YFFAUFVIWmBbd29ybk5KglE9qGxMxH5YxnpXyIZr3L6s3tHG1c/LzczKz83JTTYsVDw0XkY+QiwjMCEbQDw4hYeAwse+q66nYl9aOSohVTsveFZLa0Q1Yz0pc0gyfE46XU05Qks5XF9SeV9YgE9BilU9nWtJtX1XwHpYu3RaxZ6L4MvA187KzMzLy8zKTDUqXEE6WUE9NCUfUUdGtq2w4tzY4+HY29vVvL69kpSOZ2ZfYFtbdGloaFpTXkk7XkY3ZVpQTEpCT0M2dldBhWtVhG9cl3hnpoFwl3NfhmZRmYBz1ca/1dPOys/Jys/FUDouWz85RjAsNComlpGR5dre39XT3tfP3drV3N3c3N/Wxsi9g4OAYFxZfHNshn1yYFxUbGdmSj8+STUpZ0wydXFeeX53g3h3hHV0bGZeSko+WE9JvLWy19jTzNHIztLDVUIzUzw0PiwnbWdjysrF2tbS2tbR2tbR29jT2tfS19XP3drV29jTvru2nJiShoN/b29ua2dlW1FLTz40VEEyZ15cbXB1b3Z3ZW1pWV5XPj45MS0uoJuc2dbU0c/K0c/JVEMzQzInYVVOxsO+2trV2NXQ2dbR2NXQ2dbR2dXQ19TP2NXQ2tfS3drV4N3YvLq2d3Z0n5yXysO7taidi3xwamFfW1teXmVjYWplU1dRPjs4OTU1qqal2NTR0M3H0s/IRzkpRToto52U393Y2djT2tfS2tfS2dbR2dbR2NXQ1tPO2NXQ2NXQ19TP2dbR3NrV0M7I19TN4d3T5+DW0sm+fHVvT01JRUpFT1VPTE1IOjUzRUE/vLi019TO0M3F09HGPTEfdnRk0dLH2tnU2NXR2NXQ19TP2dbR2dbR19TP19TP19TP2NXQ2tfS2dbR2NXP3dvR39zS3drR2tjP2tfOmZOKUE1EPUA3NjozODUzNCwtZmJezMnD1tPL0c7Dzsy/ZFpLwcOz2NzQ2NjS2dXR19TP09DL1NHM19TP1dLN1NHM19TP29jT3NnU2dbR2NXO29jN3drP3NrR2djQ2djRxsK3lZCEYWJXSUpDX1pYf3d2v7u22dbO0c/Fzsy/zsy9qqaf1tTO0tDK1dLN1tPO19TP1NHM1tPO2NXQ19TP2NXQ2tfS2tfS2tfS2NXQ2tbR3dbR3NXR3tjT39jU3NbS29fP2dbMxcO6vryzzsvD1tLL2dXQ09DJzsvBzMq+z82/zsvH09DM1dLN1tPO1tPO2dbR19TP2tfS3NnU29jT3drV29jT2NXQ29jS3NnU3NjT39fU39fU39fU4NjV4dnW39rT39zT39zT3drR3drQ3NnQ3NnT1tPN09DG0tDD1NLE" + }, + { + "index": 22, + "label": 4, + "pixels": "Iz1ZJUJdJ0ZhLkxoN1V1P1uCSWSTVG6eU22bT2qXTmmWTGeVR2SRPVqGMU92L05yLk90LE5yKkxsKEtpKE5pKE5nKk1oKElkKUdiKkdiK0ljK0hjKUZgKUNdKEBaJzxUM0tyO1Z7PFl9P12DRGGJQl+JSGSQUm+cUW+dTmuZTWuZSWeWRWSTQF+NMFB8K0t1LU91KUtvJUhoKEtpKU9sJ0xqKEtqK0trKUdnKEVkK0hnLUppKEVjJkJdJkBZJDxUPVWAPlmDQ1+IR2WQRGKOP16HQmGIRWaNQGGMPmCLPmCLPl+LQWKPQGGONFWDLU57LU92K01xKUxsKk1rKU5tKE5tKk1tLk9wLUprK0hoKkdnN1R0MU5tIj9aIz5WIjtSOlJ6MUxzNVJ4OVl/OVqAOFp+OFl8Nlp8MFZ6L1V5MFZ6NVp+O16FPF+JOVyINVeFNFZ9M1V5MVR0LE9tNVt4LFJvKUxqLU5tL05sL0xqLUtoR2SCOlh1JURdKEVdKENZL0hqKUVlKUhnKk1qLlJvMFRyLVBwLVRyLldzLlhzLVdyL1h1MVd4NVt+N1yEM1iCNFd9M1V6MVR1NFd1SG6IMVhxLlJsMlJuM1JtMlBqME5oUG6HOllyKUpiLkxkLUlfI0FfIkJcJ0hgKk9nKlJpLVRsLFJtLVVvL1lyL1lyLVdvMFlzL1lzNF98OV6CMVyBMlp9MVd6LlR1OVx5TXOJNFpvNFZvOVVyN1RvMlFpNVNrT2yEOFRsLUtiL09nK0thHT9cI0VeKk1iLFJoKFFnLFVrLFVrLFVtL1dxL1dxLlZwNFx2MV51MV94OF1+MmGCNF+AM1x/L1l7Ol15RGh8M1hsNVRuNk5vNVBvMU9rOlZySGF/NEtnOVFnM1JqKUtiIkRgJ0liKkxjJ01lJExlJ09oKFBpJ1BpKVFrKFBqLFRuM1t1MV52NWJ8QGKBNF9+Mlx7Nl2ALVV3Olx5PWB3LVFoMU9rQVp6PFV2MEtrOlJzQlh5MERkR151M1FrKUliI0VgJEZhJ0liJUtkIkpkJk5nKVBqJ09pKVFrKFBqKlJsMVhyLllyQWyFVXKQPWJ+OF98P2WILVN3Pl1+Olt3J0tmLUtoWHCQQVl5MUhqOk9yOUtvMUFjTmJ8MEtoK0llIEJcIEJcJUZiJUlmJEtnJ05qKE9rJk5pKVFrLFRuKlJsO2N9NWB5NFx2WHCOQ2N8QGV/PmOEL1N4QV2BN1d4KEtqMk9uVGyLOU9uN0prOEprNURmOUZoSFp2KUFhKkZkH0JZHT9aIEJfIkZlIkloJk5sKVBuJU1pKFBqLFRuLVVuTXSOOmR/LFJsRVl1PlpxO152OV19M1V7Q16FOFd8K05xOFZ3RV59N0xpOUllMkFdRFBtSFNwPExqJz5fKEJiI0RcJEVgI0NhJEdlI0lmJ01rKE9tJUxqJ09sJ1BsJ1BsPGOBOV98L1JvOk5rP1VuOldwOld1QF6DTmaLQVx/OVd5O1R0OExpM0diLUFcLD5bNkViQU1pPk1sKj9hKUFiJURdKUdiKUdiKUljKEplKU1pJkxqI0trJU9wJE9wIk1uKVFyN1l6N1l6PVV0RlVwQ1NuQE9oSF5/UWWHSFp4PFFwMEJeNUNdNkdiNU5vMEtvK0JjLj9dOEpqOU1tMkdnJ0VfKUdhK0ljK0pkK0xmK05qK1FuJ1BvJ1JwK1Z0J1NxKVRxLFR0MlZ5PFZ2UV55SlNpMDZJJTlYLEVpMUZmKUBhLD9fOElmSl58SmWIMk91LkZoLkBeNUloQFV0NEhnKEZgJ0VfLkxmLk1mLU5oLlFtMFVzK1RwKVZuL1tzLFlxK1lxKldzLlJzN05tQU5nOj1NMzE9L0JdKUpxKUVqK0ZqLEZqM0xvNU5wN1J1M1B1MUlrNUhmNUtpNEloNklpJkVfJEJcL01nL05oLE5oLlFtL1VzK1RwKVVsLFlwLFlwL1xyMldwLkhmMD9bN0FWQUBLSEBGQVFoKU10J0ZsKUVrKkhuLUtyL0xwMUxvNFF3N09xOk5sNU1rNUtqOEpqJEJcJEFbK0ljLEtkLU5oK05qLFJwKVJuJlJrJ1RtLVpyM1pzL0NbLTVRKi5GMzpIPz5GTEJER1NmJ0twLUtwL0luMk91Lk52LEpwMEpuOVZ7N09yPlJwNU9sO1JxPE1uJUNdKUhiKkhjKUhiLk9qLVBsLFJwJ1BuJlJuJVJuLVp2L1RvJCpBNS5IOjNINzpEMjM6PTQ2QElYMVFyNlJ0Nk9wN1R5NlZ9MlB2NVBzOld8OVJ0PFJwLkpnN09tM0NjJkZeKk1nLkxpME5rL1FuL1NxMFZ3K1V0KlhzKlh1K1l4MFh2LDpQIyEzLyg3NzNBNTQ/KycuOT1LP1FpPVNtMkxpNlZ6OlqCOVZ8NlJ1ME1wNlJ0NlFxJkRhLEVhLD1WKUlfKUtjL0xpNVJwMVNwLlFwMFV3Llh3LVt1Llx5K1l5Lll5OFNsJTBAHxwoLSc1LCo3JiMtPDtGTlRlUF1wQ1hzRGKHPV2IP1yEO1d5L0xtLUlqNFBxKUZjJj5XKztRK0hfLEhhL0djMUxpLk5qK01rL1NzLVVzLFlzL1x5LFh5LVl6L1d0NEtfJys2JiEpISArMi84Qz1FVFJdYGJzYW2HYHieS2mVQV6GQ1x9NE5uL0lpN1BvNE1nLEBYM0BXLUZeMkdgM0ZfL0hhJkVgJ0hlLU9uKU9tKFJuL1l2Lld5LVh6J1d3LVBoMDxILSkuFxYhMS43TEVLU05WY2FxZ26IWm+UR2OOOVR7OlNyNE1sPFV1NU1rOExkOEhfMz5VLkRdNUVeNENaLkZdJEFbJkVhJ0lmJ0xpJU5qLFRzLFN1KlR3JVV2K1FtMkNUMC41HRslJCEqQDxET1BcVllsW2aBTWOFPVl9N1JzNk1sOVBuQFh2LkRhLj1TOENZMjpRMENdMj1WM0BVMUdcKERdLEpkKkpmJkpnJUxpLVRzK1F0KE9yJlJyKk9uNkhfMzI9Ih8pIR8pLi87PkdZSVVuTF17PVZ1OFNwNk5qOE1qOE1qPlRxMENeNUBUO0JWNDpQMUJbMT1XMkBYLURbKkdfLUxnLU1rK09uKVFvMFd1L1RzK1BtKlJqLExuN0pnLDJBISEtHyArKTE/MUFaPlBtP1RxOlV0M1BsN1BpPVJtNE5nOFBqL0BZNj1MRUZTPT1KKztSMUFaLT1ZKkFaLEliK0tnK0xrM1h4L1Z1M1h1NVh0NFdvMlZqN1NwPU9sM0BTKi9AJy8/LD1QPVRzP1h5RF1+SGKFOlhzOVJqO1FpM1BlMkxjNkhgMz9QOj5KPT9JKjpRMEBZLDtXKT9ZLEhiLEplKUllM1ZzMld1MVRwOVp0N1ZwN1RtQVlrR1dqTlhxPUpmNEhiN1JwRGSKVXekaIq2WnifN1RsMkteNUtjLkhfK0RbL0VfLEReLj9VMD5SKjtSMEBZKDdTKj9aLkhiME1mKkliMFJsM1VyMlFtPVp0PllzPFRvQlhkSFdlVmB/RFp9Olh8Q2aNSXCbYYy+bpbKV3ehOFJqNU1eL0ZeKUFZJj1VKEBZJDxXKTpRKzlOKztSMUFaJjVRLEBdMUplM05mLUthL05nNVNwOFRwP1lyQVlzPFNtOlBhSFltU2GCUm6SPF6FVnqmbZW/Z5LBXoW3SWiTM0pnNkxiL0ZeJzxVJDpTJj9XGy5FHik7KDBBLT5VLz9ZJjVQLkFfMEdiLkdeLUpdMk9lPFdzP1hzO1JqPVNqN1BmQFZ0SVx/RVl5U3CQSWmRbY66ZYiuSG2RRGaPOlaALEBkMEZhMElgLUBZKT5WITxTFStEHixBKDNGLD1VLD1ZKTxaLkJiM0poK0ZgM09mPlt1QmGBS2iJSmKBRV14Q2B7WnSbUGiQRFx6R2B8Vm+QXXicPVt8Nld4Q2KJQFuDOlB2O1JwL0dhLEBcKD1YHjlQGDJMITJHJDZJLkJcNk1vPFd5PVR5SGCGRWOGS2iLSmiOTXOeYIWzZIOuT2qSUnSfXHymSWaJPlh0RFl0QFNqOk9nP1t8QmKNSmqWR2WMM09yMktpM0tpKUNkJz1bJTlQHDFFLjZDJjdB" + }, + { + "index": 25, + "label": 2, + "pixels": "ZGdKRFtBdKJthLV9g69/h7CGgrV7g755gL54hcJ/gcFyhMB5hL97gr58hcOAe7RxeZ9xeph1g6J8ibOFd6hza5dpM0VBMDtFaItseqhzbJRnaaFecK1dc65jda1qc6psYHhPc5xkfa9xgLV4hr5+gr58gb54iMOAhMJ6gsB4hsV4hsR5h8R7gMBygLx0fKd4gaJ9ibSDhbV/g7R/frJ0apBnLDU+OUVUV2xjU3BXZ5Jheq5wd69reK9uea5ydqxzeapsfLZwgL5vhMB4gb51hMJ3h8N9h8OAhMJ2g8B1iMV9gsB2e71vertogLl2hbF/hrV+g7Z6fq5zfapxgK9yXHpbJS44O0VSO0dTQE5Tcpxygrd4fLJxebFzeLBxebBzh8J3f71vfr5sgcBvfr1ugcFzgsJyg8J1icZ/i8iDiMd9gMBzebhtg7l5i7mFjrOIhrV8h7V9gq54fadwg651V3FWISgxOkNPOENRQEtVaY1ue7RxdK5nda9qdrBsd65zgcBvg8J2gb9zgb1vfr1sf79tgsNyiMd6ish/i8eCich+hsZ7isKBhrd5irODjbKIgbB2g7R5iLZ+hrB9iLF/UWlQIScwOUNPNT5NO0NTUmZjZ5lib6pfebJuc7Bodq5ufcBjiMN+icF9g711iMJ5i8d8iMZ2jcqDi8iBiMV/j8qJhsJ/iMN/gr5wgLh2hrl9grZ8grB/ha+AhbJ8jbmITWZPJCoyOkRQNDxMOUNUR1JgZYxierJsebBwca1ohLOFhsF9isCDhb92hr56g7x1gsJvicZ7jMiFicZ/iMZ7isd8g8J5isiCjsmIhcB9frx3hb+HgbV5iLOJgq9+ksGQU25XIysxOUVTN0FUNkJSQUpbTmFgbZt1gbOJeKp3mMGvjcKEib9+hMBwgLpzf7txhcJxjsmBisN9hsN7ks+FjcaBjL6DjMt9gMJxcrFmfLp1gr92g8F5ksaKk8OPkMORVnFaJio0OUNSOERXM0BQPERXQElaZYpzjMGSdq51sdXKicR6i8V9frlvcq9ef75rjMeAh8R5gL5yjceFmMeOiIdzonqAmZh0hMNth8V8g8F1g75xjcSHk8aVkMaRisOJWXhfKS4zN0RPNkVWMz9POEFTO0VWaYV4hb56kcaKxOfqh8R1icR6grxzgLhvgsFthcV0hMFyksiOjsiCj6J8klVVrVljuYV+jr19kc+Ljcl5i8h1gcFxiMCEiL+CicOCXH1aKiwyNkJOOUhXNUBQN0JUPENZTVxjgqyCtdTAsdLwh8B3hb94gLRvirt9h7+Agbt2isCDlsaYicN9iYtwkU1SnlJdtIOKkr+CkNCBjsx5ich3hsF4ib1/jsGHjMKEa45mMDM1NT5KO0lZNkBPNkJVOEBVRlFfp8W5scjhharghb17gLpzhrd4krqLh7mEgbR5gLd6hL16jMSCeHZjmkhUm1JghXF9hrOBi8h2jch5jsp/icV4jsR9ksaFi8CAfKN5O0U/NTtHO0tbNEJRNEJTMTpPU2F2utjfg6DOfaXefrptebRng7d3gat8fat1gLBvfbJrgsBtjsV+YnFejENOpU9YdWJigat8kc19ls+Cjcl5g8Bvi8Z1jMZ6kMWIf6t8PEZAOD9KO1xoMUNTMj5PLjhLcIeZo8TjUXa3gavigsBuf7hrhb14jL2Ejr+Cir98jMKAjMV6jch7VG1YeT5LlkJLYFlLhrtyktJ7lNCCkMt9kseDi8V4icZ6kciGe6pyOj45PkNLLlliLDpMLzZHOEJUkKzCd5vVOmCohKzmdLRgebRmgLlyjcCBh757jMOFkcmDkMh5jsZ9UmhTVTQ6WTEzMzU0bp9hi8h6hL9thcFzjsSFicJ6gcFrish6e6dvPTk4OTdBJD5KLThKKS9BWmd6kbLbRWy0OVyghKzpfrZvicGAjLuFh7N/hbl5iL96hsBqjMZ2j8p5S2NNSTA0QS0uHiAqTmRWicSAjMx1h8Rydq9ehb51gb5vebppdaNyPD9FMjhBLDQ9NEFUKDhRUGKFXH+8JkeQLESGh6vmhrxzjMCCjb5/g7h1hL5whMRnj8l8lMqDjsd6S15RNiYsMyYsJSo1Nz5HcJ1mhMdtl82Nj8WDhcFwgrxsg75pfqF5QUdRQk5XTVJiLUJSNj1WO1KNIkSIHz2ALEWGi67nfbhsgbZ5f7NvgLZrjMSAicN5hsRvisZ7j8aGQ1JIIx0kIyQsKiw0ODA5UGNTerNqjMCEk8KQgbFzgrFxfKFraWpgV0JQVUpUY2FvRj5LPjlPaWuRL1KcH0CHMEmFjbHkgb1wicB6jsGCjsR8jsSEh7x8gsJoe7hjgLptPU5CHx4mHiAmJicsQzQ4QURRcYxym7WNkpyBd3lgd3JmalBVXTI7XC81WCwySCcwNRokPzFDiHB3UWGWIkOQNEuHkLTmgL5ohb9zjcKAkcaFhrx5gbluisd1isJ1gbdrPks+HR0mGh0jJCUsQjQ6QUFVWVxsf3aBgXN/dl5obFFcc0VMcDM4ViwyWSQlRxwiMBghTDY7knBpaVxuHTJvOVCLlrnxebZkhL13isF+i72Ahb55h8RzjsZ9icF2fLNoPUs/ICErGR4kJiUuPDI+QEBVTlJmS05dYltsdWFuY1JeV0ROXUNMQzlHNyk5MxwlKRgeTjxAh2hjcVlXLzBORVyMl7v0gLZ4gLZ7gbl4iLuGfbZxgMBnjcKAisGCerFxPk1HISMsGx8lKSctNjA+OztOQkRTQ0VQVEpVVUNMSTpBS0dQV1BZQTU+Li9CKClHIxkqSzY5blhYXU1HSFI/aYyjlLn2ebJrf7lze7VrerJyfLRxdrRid7Ftgbl3eqx0NEA6HR4lHSAkKCUtMjA9OztQQkFUOjlGNys2MSUrMyowWlZhVVReLSozKSw8LDNRJCpFQjU2WVlDXXhKa5tbe6qujrTzcqxgc65ddrBpfbRzdq1sda9la6dedK1oc6JyMTk2HR8jHyMoJik2MzNFPj1WRkRgLy47IhkdHhYaKyguX11qSUlXIic7HyY8HiAuHSI4OERMbJVndKlkc61nd6SxiLDufrRycqdnaZ9YaJtSY5NQfK1tbaRgbaxVYI1UOTw9JigsISQtLjJCNjdHMjNCKCk3IR8mFRERGBQVRD5ERERMKS06Iic+HyY9FBQbFhUiLTpSZ492ib2Md6p5d6G3hKrpd7VkeK1oaZVRZo1UdaFmeq1lcqdgerdpaY1nNDc9LzI6JSYuLTM9LzRAHiErFxofFRMXDAoLJRscmHh1cVdWIyAnExYiFhksFBMYEhIaGhovUm9dcaRnbJ5veKLDgajiZ6JWc6xlcJxbeaVpfLRnb6tScqlbjcWHaY1pJCksJyosJCcsMDU+Jy03Gx8mFhgcEhEUDAwOFhUWYkhDnG5mbVJLRDUzOC81KScwLDY2QE9MXoZgfa56e6uHdp/Lg6ngY5lUW5dLaZ5ab6hgd69wc6poc6Nse693Y4taJCslGRsbHB4gKiwzJSgwFhofERMXERMTDw8PDhARGhcXUzcqi2NQpHxunnpzjnZ0b3ltZoVsdqh4badsbqKEdZ7Rh63hbJ9jWpBQXZRSX5dTc6RxfrB8b59ocKJrd6J4N0g1FxkYFhkWHB8fHSAjEhUYEBMVEBMSDhENEBEPDw8PIhoTcVM9imRKmG5aq4JxoHtxkYRzpq6MkJdkiJaIg5vLjbDgapdha5llbZ5oap1ceKxshrx8eK5vfbJ1hbmLU3lOHiQeEBMQFhkYGRseEBIUEhUWFxscFBoYDxIQDAwLPTAsimhYhmJIgFtAh2JMsXVkxpKBx5J/yn9pxYN5vIqSsqu6a5xebZlhcaBseKRpfLJrgbR1da1mbahfa6BldKVtOU06EBEREhUUFRgaExYYERUVFRkbFBgZEhAQPC8rjWtkoHhnhWNHcFAxd1M3jmBJkGNNmWhRq29avH1tyY5/yp+SWYxLeKBsfZZogZZqbpBcYYdVYpBZY5hccKFlfrJxZpNdMEUyGyYdEhgUHiAaJyEbJR8cMygmW0U/j2tfoHZmfFdAXUMjWUAjVT4lT0MoVUUpXUYqak0zfFtElXJeoHlk" + }, + { + "index": 26, + "label": 4, + "pixels": "a29ifIByf4N1hot7Zm5dS1ZISVVKWWNZY2leRkpAQ0Y9V1pRhYh/ztHGl5iKdXZoX2FUVFdLVlpPUFRLbnFojZCFkJSHZ2tcgoR2goR1cnFjY2BTdnRmYF9RUVFGRUU9WFxPbnJkfYFzhYp7YWpZQk5ANUE2P0o/XGNYRUk/P0I5TlFIdXdur7GmjI1/cnNlYGJVWFtPVlpQU1ZOXWBWam5jb3NmVFhJbnFheHppd3dnd3Vmj419XFtNREQ5PT01XGBSaW1edHdoeX5wUVhJPUY6ND81PEY9V19UUFVLQ0g+RktBYmddmp6TlJWIf4BzaWteWVxRVVlPWl1Vb3JpdnlvZ2peVVlLamxcf35thoRyhIBuqKORamZWSUc6PTwzX2RUbnFea2tZYWVZTFBDPUI4OUA4Rk5GZW5kXmZbUFdMTFJIX2Vbk5iNlZaKh4h8c3VqZGddYGRcYmRec3VvdnlxZmleXF5Tc3Jljot7lI18g3pmnpN9dGtYV1FCRkM3XmJReHdgeHReW11OV1lLSk1CR0tDVFpRbXRpXGFXTlJJTFFHYGRbkZSJjY6CfX5ybW9kZGddZ2tkYGNdcXNtc3ZuX2JXWVtQZWVZdXNmfndmfG9YjntfaF1IT0o8QEA1U1RCdW9WgnlfXVxLYGBQVVdKTlBGTVFHUVZKS01ESUtCTU9GWltSc3VrenpudXZqamxhX2FYXGBYWVxWam1ncXRsY2ZcWFpPW1xRYGBUaGJRc2JJh21MWk03QT0xNjcuTUs7amFJe21TZFxHY2BLUFJBQ0U6PkA5P0Q7Rkk+SEo+S01CUlNIWFpOY2RYaWtfY2VaVVdOT1FKVVhSZGliam5nX2JYU1NIUVFFUlFEV1FBY1U/fWJEUkMvOjUpMzIqTEs8YFZBdmJJdWRNYlxERUg2NDgtLzArLzUtOTwwPD8yQkQ3SUs/UFJGXmBTZGZaYGJYV1lQUlNMTVFJRk1GREpDR0tCSkk+SEY6TEk6UEs7Vkw7dl5GWEg2PzcsNDEqQUQ2WE05dF1DgmxUY1tGQUQzLzMoKy0mKC4lLTAmMDInNTYsPD40SEo/WlxPYGJWX2FWWVpRTk9IQ0Y/OD43NTs0PD82RUQ5Q0E1SEU2Tkk5WE8/hW1WZFVDRDwyNTIrREU5YVZCfmlOiHRaZV5LQUM1MDQqLjAnLDEmLTAmLzEoMzQsOjw0R0g/V1hNX2FVXmBVVlhPSUtEPUE6NDo0MjgxOTszRUM4RUI2SkY4UUw8X1RDhm5XZFVDRz80ODUtSUY6a2BNiHVbe2dMTUc3NzkwMjUtNTYsNjUrNDUrMzUqNTctOz01REVAU1RMYGFXYGJXVFZORUdCQEQ9NTo0MTQuOTcxSUI5S0Y8UUw+V1A+X1E8dF1FXlE9SUMzOzksPDsvW1FCeWZSdV1FVkk3QDovNzYrODotOz00PD4yRkg5REU1OTouPD43SUpEWFlQXl9UWFlOTU1FSUtDOz84NDgwOzwxTUk7SkY4UEY5WUk5Xk05X1E5WVI6Tks0QkAuMzYrQz4yXU9AcFxIdGNPZFdFWVI/T087OD0yOz0yXVtIZWJMUlE9QEI2SUtCVVVNXlxTZWFVbmlbVlZLQUM5QD8zU04+al9MXFJBWEo8VkU3UEEzUko4WVQ/VVI7R0YyNDUtNzYtSEQ3X1ZFW087Y1VBcWZOdG1TV1NCTks9WlI9bGRJb2lQREY2SEtBVlZPZWFZbmdZa2NRUEw/R0M4UUc8Z1RFc1pGXks6UEM0Rj0vPjYqRDovU0w8Tko4QD0uMjIqNDQsQ0M5VFRGQ0IxPjsqRUEzVU1BZlVEcWFOdGJLdGJJa11GT0g3REI8U1BLZV1VbF9TY1REXlFDWUs+VkY4VkU2WUw6Rz8vPzssQTwvR0A0SEAzUks6U007SEM1NjUuODgxSEg/WVlNQD4yNDAkLy0lMzIsQzksVkArXUMsXUMuV0AwTz4yTUA0VEU6W0g9XUU8WUE3WEQzW0MrYEYrYE43UU4+Pj0vOzgrQTwvSkM1TEU1W1RAYlxIVlJDOTgxODgxQkI4UU5BUUQyU0ArRjUjNyoeQS4gZUkyaEctYT8nVjgjSTAeTjUjUDYlUzcoWTosXz4vbEkyc1AzbU8yWkYwRTwwMy4lLiofNjEkSEExXVZCZmBHXlhCSUU1ODgvNzYvQD82Skg7UEc1WEYxQi8fJBMLKBMLVjonX0IpYEQpYUgtYUkwVT0rUTkpVz4tZkw3eVtEcVM4WUYtRz4qREAvR0IzNjEnMi4kOTQnRD4uU005Y11FYVtFTUg5PDowQkE4UE5EVVFFQjouQTIkMCEXGxAKIRMMRTUnQDUjOTIhQTgpWUs1QzMlPy8mSzosYEw1dVxFalhDTkQzPTkrQ0EzUUw8SEI1RD8yQTwvPzksT0k6X1dEXFRBS0Q2REA1SUY7WFRIYlxQPzkvPTElLyQbHBURIxcSSTstQDgnMy4hNi4lVUY1TTorTjktW0Y0b1Y7dlg/cFlCiHdfin9la2RKXFZAVE09SkM0QjstQTorSkMzWFA8WlI+TUc3VE5BVlFEYFpMaWFSST8zQTIlMCMZHxUQJBcRRjcpRDwsNjAlLiUgQDElUD0vVkE0Ykw6cVc9Y0YwSzQjh3NZwa6MwbCMfG9UWlA9SkEwRz4tS0IxUUg2W1I8XVU/UUo4i4R1iIBugnZgd2RLbFU+YUgyTDYlNiQZMSAWRTYqU0k9S0U8Ni4oKR0XRTYqV0U2YUw6YEk1RC4gLh4YYE08rJd23Mifn49xcGVQYVhGaF9Nc2pYbmRSbmVPcWhSZl5LvquRuqSGq5FvmntUmHdUkXFSf2JHZk02UDonVUY7i4F6mJKKa2VcHxUSPC8lYU4/Y009Qi8iJRkUHRMTRDUpj3xf2cifzcGiuLGds66eurWmwbytsKqbrKOSs6mXpJyMqItoq45oqo5np4xlq5BspoxpnYJhjXJTdFs/aFdJtq6o1NDLm5eOJhoXJxgTPisiRC8lLx8YFxAPFQ4PNCQdemVM0LuT4tOy7unY8e/l7u3l6+nh5+Xd5eLc6eXf0c7JpIpmrJJrrpVurJZwq5Rvpo5rnYVkkXhZgWlNcmBQurKt3t3Ysq+nOS0nJBgSLBwUMyAYLBwXGRERFQ0PLBsXbVU/w6mB3cqo7ufY9PHq9PLs8/Lr8/Ls8/Pu8OzmzMW9pYtmr5Vtsplxs5x1p5BunIVlkXpdhW9UeWNLh3Zny8S97u3ny8i9WU5AKx8YIxQPIxMPIBEOGhAOFgoNLRoUak83up923c6z7+nd9PHr9PHs9PLs9PHt8unh1MGwm4Jspotmr5Rur5dxr5dzoYxsk31ghW9Ud2JIa1dCmYyA19PO9vbv3trMinxnOywhIBIPGQ0OFgwOFw0NFQkLNiIYdVk+vqN+5NvL8e7n9PPu9PLu9PPv9fLu4NHFp4lzaUYspYlnqo9sq5Juq5RxnIdnjXhbfmlNblpAY087j4R70tHO9ffy6+jbv7CYYU48Lh8XGA4PFAwPFQsMHA4NSzMhiWpKwaWH5ODT8fDq9PTw9fTw9fTw9fPt08W2knVeWjgfnIBgnoRioolnqJFvmIJjiXNVemRJa1Y+X0w4in50z87L9fj18/Lp4tjEmIJnVUIwKhwWGg8OHw8MMx0UZkYrlG1KsJB22NLH7u3n9fTw9fTx9fTw9fPu1sy/lHxnWzwlj3NUkndYmH9fn4dokHlbg2tOdV5EaVVAZlhLtK6p4+Lh9vf39/f09PHovKyVemNNSjIkNiAZPSEYUS0gaD4ocEkwdVlIrqWg5OHe9fTy9vXz9/bz9vTx5t7UqJWCZ0w1iGtNhWpNhmxSiG5WgGdNd15EZlA6aFdInJSM4uDe9fX0+Pj4+Pj39/bzu7GlcVpMSy4jUjUtZEM2VzcoTCwdPSIVOSckeXF31tPU9fTy9/b0+Pf19/bz9fDoxbalgWpUfWBEcVU7bFE6dFpEdVtDZ084WEQza19VyMPB7+7t9/f39/f39/f39Pf1x8nCbGVbRjsxa2BXno+CW0k+aVhOZVdQPjIxbmZs0s/Q9PPx9vXz9/b09/b19/Xw1cq9k4Bt" + }, + { + "index": 35, + "label": 2, + "pixels": "QklUQkdRQENLOzxDPj9EMC80Li4wLissIh4dKSQhHRsZEREQDQ4PDREUFBkcIyotIyQrMDA4OzxDNjY+MzM7QkNIVlhWW1xSXF1OXlxPYVxUZl9TZl9PaGFRaGFRaGFRMzlDNztEMTM6Nzg+MzM5JCQoMTAyNDEyGRUUGRQSFxQSFhUVGBkaFxkcGR0hHiMoIiMtOTlEOztGLy86KSk0MTI8QkZLVllXU1VMVldMX15UXVhLXVZGXldHX1hIYFlJMTU/NzpDMDE3MTE2JCQoKSkuKCgqKygpIh4dGhUSIBwaIB4eJSQmKywwHyImJSgtLy86OjpGKio2Kio2NjZCMDI/NTtIREhPUVZUWl1VS0xCSEI2TEM2TkU3TUQ2TkU4KCs0MDE4Pj1DKCcsJSQoLS0xOTk7KSYnKCQjLSglNDAuLissNjQ2NTU5NTY7LzE3NTVAMjI+Li46SUlVPj5JMjRDLzVFPkJOUVVZSk1JOz0zQjowQjUrPjIoPDAmPzIpSUtSTE1TQ0JHIiAjGxkdKSgtNzc5OTY3LSkpUUxJSURDOzc4R0VHQT9EPj5DODk/MjI7Kio0KSkyMDA5ISIrJCYxJio4OjxJQEJKQUJCPj44OzMrNSggMiUcMCMbMiUdKCkwQ0JIPjxBKCUoFBIVIyInMTAyPDk6Qj09YVxZVE5NSUNETkpMUU9TNzY7LS0yLS4yHB0hGBgdDQ4TDQ4SDQ8UGRskMzM+ODZCQD1BPzw5OS8oNCUeMSMbMCIaMSMcCwwSEhEWNTM3OzY5Ih8hFBQZKSgqNzQ1S0dGZWBdamJiY1xeXFdaVlJXLSsxIyIoJSYnFxgZEhQUEBESCgsMDxARERETGxghMi45QTtCQDk5Oy8qNicgMSEaMCEaMCEbEAkMDwIFGBISMzExOjY3IiAiIB4gMC4vTkxLV1VUdnFvfXl5YV9iVFNYMzM4IR8kIB8gGBYXDAkLBgMEBgMDBQMCBwcIHxwhMy00PDQ4Qjg4PjIuNigjLyEbLyAaMSIbIRAPNhwdJR8bMC0rRTs9Pjk5LCkpOzo6YGBhg4SGbWxpgYJ/ZWlshYqOODk+IB8gHRsbHhkaEwoMIBQVJBgWDwkJBwgMISEjNTAvMiknLSIeKh8bLSAeLiAcMCEbNCIbY1FRloWCU1JLRTo6XElOPDg3NTMyTk5OhYaHpqmqfX56bG1qeX1/n6SqTE1TFhYXHyUhIiMfLSQhOSslWUk/LCIeHh4jMzI0ODMyNCsoMygjLCAbLB8bLh8aMiIaNCIaW0RASTMsLyEaOyUjbFVXYV9bQ0NBPT09iIqLoqapn6Cetri2cnh6iZCVV1leHB0fIy8nKSskHBAKHAgENBoROikhNzg8S0tNPzo5KSAeKR4aKx4YLR8ZMCAZNSQbOicdXz4zQxMMLAIAOhoPZldOdHRudndzbG5tpqqtub3Bury7xsnJjZSYiI+Wa291RkdLNj43KiUdJw8IJAIARhwTSC8oRkZKWllbTklJLCMhJxwXKBsTLR4WNCIZOSYcQS0hgFpJdCQYXRIJTyoYcnBcoKGZqaulpqmouL3AztPZz9LTub29qbG2oKixc3mAZ2ltYmJeTDw1QB0TTR8WWisjUDQyRUVJT05QSURENCsoKR4aLB8WMSEXOCcbQC0gSTQmm35sgjUmiDMkZkMuk5mDuLuwxMfAur+9w8jNztTcxcnLjZOUrre9kZukgYiQgYOIcm1sWUU/PRkQSyEZVC8sVUFER0hMRURGQDs7OjEuLiIdMiQZOCcaQC4gSDQlUDopkYuBfVhHaTInWz80pqmcvMC0ur+3s7m30Nfb2N/nyc/RytHTqLK5l6KrnKOskJSahoeGZFhROyIZMRkUQDM1QD1ER0hNRkVHSERDPzY0MiciOCkeQC4gSTYmUTwrV0Euq7q5iJGAWEc9bllbs6+tw8i7srivt7271t3h0NnixszQ2uDjlZ+mqLO8naSth4uRjZWSaWdePjIpKiQgOkVJOEZNP0FFSklLSENCQDc0Oy8qQjMmSTcoVEAwW0YzYUo1z9rht8LAenlzi4N8ysa6y8q5ra6iqKun1trew8rSvsbH6fHxmKGmqrK5kJebf4WFiomChoF5WlRPWFZWOT9FLjc9OTw+SEdKT0hJSj03SjssUD4qWEMuXks0Y1I4aVg8iIyTl5mfi4yKkJGFt7ekt7akm5uOj5CK1dbYxcjPtLm57PLxrbK2qa2yipCRf4N/gn13eHNuTkpKREJGKyoxLjA1Njs7PDs+UElJUkU8V0cyYU43alY/bl1EcmNHdGdIQ0RJYWNohIeHa29nmZ2QsLOlqqyimZqVzc3MqKequru48PLwtLW4q6ywiYuLjI6JiYqJdXZ2XV1fWVhcLi0zJygsLjExQT9AUUpHW09DZlhDcF9Jd2ZRe2xUfnBWfXJVWFdYZGVprbG0tLu3usO6x83FztLLqKmkT01KlJCO0M7J9vbzzs3Pm5qdODc2gIF9kZeahImPe36DamtwU1JXY2NnKSsqPz07V1BJZl1NdWlRf3FchnhkiX1miH5khn5ihIKAdXV5l5ufr7e2u8XAydDL2N3YqKijHBkWn5qU6OXf9fTx3tzesK6xHx4dfn56maKnfoaNa3B2U1RaSUdNPDo+MDAvVFFMZ2JVdGxYgXheiX5ojoRujodvi4ZriYVoPj47JygsQUVJZWxsl5+cwsjEu766wsO+qKag0MzG8e/q8/Lw4eDk0c/VeHd3j5CNh46SgoiOSk5TICAlFxYbJSInMi8uY2BXd3NhgntiiYFmjodukYxyj4xxjIxtiYpqJSclKy0wQURIKC0rHCAbW11Zw8S/q6ymvL235ubf9PTx7u7xzs7V19bfrK2wjY+PpqioODk6Hh4hLi0yKikvHhsgNTEvYFxPfXljiIRnjYdqkY5xk5N0kZNyjJBsiY9pIicnKy4yQUJFNDUyMzErNDItS0pFvL24293Z7PDs6/Dw4+ftwsbR3uHt2Nzkqq2wTEhEOjUxPzw8OTg8JiUsHhsiPjg2aWVXgX1ji4hpkIxuk5Jxk5ZykJRvi5Jph5FlNTo5MzU3RkZHbmxncm5lWlVLPTsxNzcui42H2N3W1drYt7u/mZ2kubzEeX2COTw8PTcuTkhBREA9NTM1IiImKSgoXVlPe3hkiodqkY9skY9tkZNtkJZtjZNpiZFkhpBhTU9HNzczUE1KkIyHurarfntpeHVkXltLIB4RR0U3e3lxZGFcQj88Ozc0DgsJSEU/cW9jaGZeSUdEKyomKSggQUEuf31hkpFwlJRul5dvl5dtlplulJptkZdqjpRmi5JjZ2ldQUA4OzgzQz45iIR7g4BybmpcV1RGT0w+Ih4RMSwkNC8pFA8LGhQQRUA6YVxWVFFJQD04HxsZDwwGMC4eZWRJk5BvoZ96pKN8o6J4o6J2oaN2n6J1nKBzm55xmZxvfX9xQEA0HRsTJB8ZKycgLCogIR4WCQYCGhcPHRsRPDkyOjcwMS4oLCgiKyciDgsJHBcWHxkXEAwIGxgNUE42kY9voqB8rqyGrauErauCrayAq6yAqap+p6h8pqh8pKZ5jZB+YmNSKScaIx8ZJiEeHBgUFhMPDAgGBwMBBgMBGBURGhcTFxQQCQYDBQIACgcFFA0RIxscIBkQRkErfntZo6F5q6mCtLKKtbOKtLKJtLOJtrSJtLSIsrGFsbCErq6CmZyFgIFrUE8/Ix4YHxoZGRcVDAoIBAIBAwEBBAIBAQAAAgAAAQAAAgEABQQBBgMDGRIZIBoZIh4PcG5Pnp5zrq+AtbWKt7iMtreLt7iNuLmPurqPubqOuLiMt7eLtraKoKSIjpF1ZGNPNjIrIB0cFBQSCwsJCQgHAQEAAAAAAgIBAgEAAQAAAQAAAwMBBAMDFBEWGxkUNTUfjI9prbKBsbeDtryLtryNt72OuL2Rub+Tur+Sur6QuL2PuLyPt7uOpauLmZx7eHhhSUU+LysrJCQiExMRDw8OBwYFAQEAAwMBAQEAAQEAAwMCCgoICQkIExMVHR8UTVI0oKd6sLmEsr2HtMCLtcGOtsKRt8KUuMOWusOVusKTuMGSuMCRt7+Q" + } + ] +} \ No newline at end of file diff --git a/tests/models/fixtures/mnist-test-samples.json b/tests/models/fixtures/mnist-test-samples.json new file mode 100644 index 0000000..8e39cf3 --- /dev/null +++ b/tests/models/fixtures/mnist-test-samples.json @@ -0,0 +1,105 @@ +{ + "source": "MNIST test set (las filas de prueba del sprite de public/n4l/mnist.n4l), 28x28 uint8, trazo blanco sobre fondo negro", + "samples": [ + { + "index": 0, + "label": 7, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFS5n5c8JAAAAAAAAAAAAAAAAAAAAAAAAAAAAADe/v7+/vHGxsbGxsbGxqo0AAAAAAAAAAAAAAAAQ3JIcqPj/uH+/v765f7+jAAAAAAAAAAAAAAAAAAAAAAAEUIOQ0NDOxXs/moAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABT/dESAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAW6f9TAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgf7uLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAO/n+PgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIX+uwUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAnN+DoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB+/rYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABL+/A5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAT3f6mAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy/7bIwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJv7+TQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH+D+cwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIX+/jQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD3y/v40AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB5/v7bKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAef7PEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 1, + "label": 2, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHR9q///ll0AAAAAAAAAAAAAAAAAAAAAAAAAAKn9/f39/f3aHgAAAAAAAAAAAAAAAAAAAAAAAKn9/f3VjrD9/XoAAAAAAAAAAAAAAAAAAAAAADT6/dIgDAAGzv2MAAAAAAAAAAAAAAAAAAAAAABN+9IZAAAAevj9QQAAAAAAAAAAAAAAAAAAAAAAAB8SAAAAANH9/UEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHX3/cYKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEz3/ec/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAACA/f2QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACw9v2fDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZ6v3pIwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxv39jQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATvj9vQwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE8j9/Y0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIb9/a0MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4/f0ZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+P39KxQUFBQFAAUUFCWWlpaTCgAAAAAAAAAAAPj9/f39/f39qI+m/f39/f39/XsAAAAAAAAAAACu/f39/f39/f39/f359/epdXU5AAAAAAAAAAAAAHZ7e3um/f39m3t7KQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 2, + "label": 1, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAm/m0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAV/xSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIfxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC30lgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABU/j8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyt8LAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIP7YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF/+wwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACM/k0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA57c0IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfP+lAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKv+UQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABjo1wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB4/p8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAl/6OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOT+QgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD37/kIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACN/s0DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK1/55AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABcawCgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 3, + "label": 0, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAuW/cofAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAl+/v9awAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVxfv7/WsAAAAAAAAAAAAAAAAAAAAAAAAAAABuvvv7+/2pbT4AAAAAAAAAAAAAAAAAAAAAAAAA/fv7+/v9+/vcMwAAAAAAAAAAAAAAAAAAAAAAtv/9/f396t79/f0AAAAAAAAAAAAAAAAAAAAAP939+/v7k00+gPv7aQAAAAAAAAAAAAAAAAAAIOf7/fvciQoAAB/m+/NxBQAAAAAAAAAAAAAAACX7+/28FAAAAAAAbfv9+yMAAAAAAAAAAAAAAAAl+/vJHgAAAAAAAB/I/fsjAAAAAAAAAAAAAAAAJf39AAAAAAAAAAAgyv/9pAAAAAAAAAAAAAAAAIz7+wAAAAAAAAAAbfv9+yMAAAAAAAAAAAAAAADZ+/sAAAAAAAAVP+f7/eYeAAAAAAAAAAAAAAAA2fv7AAAAAAAAkPv7+909AAAAAAAAAAAAAAAAANn7+wAAAAAAtt37+/u0AAAAAAAAAAAAAAAAAADa/f1JSeT9/f/9/f39AAAAAAAAAAAAAAAAAAAAcfv7/fv7+/v9+/v7kwAAAAAAAAAAAAAAAAAAAB/m+/37+/v7/ea9IwoAAAAAAAAAAAAAAAAAAAAAPo79+/v7+/1rAAAAAAAAAAAAAAAAAAAAAAAAAAAASK77rUdIHgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 4, + "label": 4, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMuAAAAAAAAAARh0AAAAAAAAAAAAAAAAAAAAAAHnnAAAAAAAAAJSoAAAAAAAAAAAAAAAAAAAAAATD5wAAAAAAAABg0gsAAAAAAAAAAAAAAAAAAABF/IYAAAAAAAAAcvwVAAAAAAAAAAAAAAAAAAAt7NkMAAAAAAAAAMD8FQAAAAAAAAAAAAAAAAAAqPc1AAAAAAAAABL//RUAAAAAAAAAAAAAAAAAVPLTAAAAAAAAAACN/b0FAAAAAAAAAAAAAAAAAKn8agAAAAAAAAAg6PpCAAAAAAAAAAAAAAAAAA/h/AAAAAAAAAAAhvzTAAAAAAAAAAAAAAAAAAAW/KQAAAAAAAAAAKn8pwAAAAAAAAAAAAAAAAAACczREgAAAAAAABb9/WsAAAAAAAAAAAAAAAAAAACp/MdVVVVVgaTD/PxqAAAAAAAAAAAAAAAAAAAAKar1/Pz8/Ojn+/z8CQAAAAAAAAAAAAAAAAAAAAAAMVRUVFQAAKH8/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB//PwtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP39AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/8/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/PQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA6OxvAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALNCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 5, + "label": 1, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATf5rAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE+P+/gkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFH+/qUBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfL/v5JAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA1/v76AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhv7+tAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMT++DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADr+/u0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABv/v6EAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAo/7uHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPPz+3wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE/+/poAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACj/u41AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAc/P7SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVv7+gwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGn+6hQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACv/swFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0/7EAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA57+oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAanWsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 6, + "label": 4, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWwIYgAAAAAAAAAAAPTQUAAAAAAAAAAAAAAAAR6/qpAAAAAAAAAAAP3PElAAAAAAAAAAAAAAAUvf2TAAAAAAAAAAAAi/1kAAAAAAAAAAAAAAAARv39FQAAAAAAAAAAK/6tDQAAAAAAAAAAAAAAFpn9YAAAAAAAAAAAK+f+XAAAAAAAAAAAAAAAAKP/zAsAAAAAAAAAAGj+ngAAAAAAAAAAAAAAAACi/bIFAAAAAAAACYPt/QAAAAAAAAAAAAAAAAAAov39v69GRkZGhcX9/akAAAAAAAAAAAAAAAAAADPk/f3+/f39/f79/dsjAAAAAAAAAAAAAAAAAAAAEUGJ/uiJiYks/f2hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIv7OFQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKD9RQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFX+8TIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACe/qUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA5/QyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaP7oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAND9nQANHgAAAAAAAAAAAAAAAAAAAAAAAAAAAADQ/ZpbzKEAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0P3+/ZodAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2+gBcGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 7, + "label": 9, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOlcEFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABb4P39EwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAc6/79/aYSAAAAAAAAAAAAAAAAAAAAAAAAAAAAkP3+/f397nMGAAAAAAAAAAAAAAAAAAAAAAAAH/H90Ln9/f3nGAAAAAAAAAAAAAAAAAAAAAAAAE/+wQAIYtv+/8kSAAAAAAAAAAAAAAAAAAAAAABW/VAAAAC2/f6/DAAAAAAAAAAAAAAAAAAAAAAAr/2bAAAA6v3+hwAAAAAAAAAAAAAAAAAAAAAAAFb90ChVpvvt/uwqAAAAAAAAAAAAAAAAAAAAAAAS7v3+/f25JNj9mAAAAAAAAAAAAAAAAAAAAAAAAETw//6RCACG/t8jAAAAAAAAAAAAAAAAAAAAAAAARJ6ODAAACa/9oQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABY/eISAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAqb9fgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAw9f0mAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHP+rAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAV2v4uAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB7+pQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAuvQqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA7fTgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 8, + "label": 5, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAES8vLxCBVS8AAAAAAAAAAAAAAAAAAAAAAABLmdn9/f3X9v39AAAAAAAAAAAAAAAAAAAAI470/P39/f39/f39/QAAAAAAAAAAAAAAAAAAAD/9/f39/f391aqqqqoAAAAAAAAAAAAAABSESAA57uPuqHxFFAsAAAAAAAAAAAAAAAAAAAvO/U4AACAAHgIAAAAAAAAAAAAAAAAAAAAAAAax/YQKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyF/ekPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABc/d8cAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlv2uAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOr99n8xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//f39+5NbeVUqKlUcAAAAAAAAAAAAAAAAAAAAi/39/f39/f39/f396KgAAAAAAAAAAAAAAAAAAAM12t77/f39/f39/f38fAAAAAAAAAAAAAAAAAAAAAAAQ0jI/f39/f39/a8AAAAAAAAAAAAAAAAAAAAAAAAAeP35mDOk/f2vAAAAAAAAAAAAAAAAAAAAAAAAADL9/f28/P39lAAAAAAAAAAAAAAAAAAAAAAAAAAJp/39/f36rwsAAAAAAAAAAAAAAAAAAAAAAAAAABe05/3dgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF2VFgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 9, + "label": 9, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkOInJx18lAAAAAAAAAAAAAAAAAAAAAAAAAC2Y6v7+/v7++tOXBgAAAAAAAAAAAAAAAAAALpnw/v7jpoX7yP7l4WgAAAAAAAAAAAAAAAAAmer+/ruOCAAAvyjG9t/9FQAAAAAAAAAAAAAIfv3+6YALAAAAANIrRv7+/hUAAAAAAAAAAAAASPP+5DYAAAAAAyB04fL+/6IFAAAAAAAAAAAAAEvw/t9tirKyqdL75/7+/ugmAAAAAAAAAAAAAAAJr/T9//7++/7+/v7+/KsZAAAAAAAAAAAAAAAAAAAQiMOwkpnI/v7+/pYQAAAAAAAAAAAAAAAAAAAAAAAAAAAAov7+8WMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAdvr+/loAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZPL+/tMHAAAAAAAAAAAAAAAAAAAAAAAAAAAANvH+/vI7AAAAAAAAAAAAAAAAAAAAAAAAAAAAAIP+/vRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA35/v6YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzk/v7QCAAAAAAAAAAAAAAAAAAAAAAAAAAAAABO//7+QgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0f7+iQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOP/6RkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABx/2wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 10, + "label": 0, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPQMqdsF2dj0AAAAAAAAAAAAAAAAAAAAAAAAOs/Xs8v7+/v7161QAAAAAAAAAAAAAAAAAAAAAl/7+/tXAsrK0/v7xLgAAAAAAAAAAAAAAAAAAK+v+4kAcDAAAAoD8/60RAAAAAAAAAAAAAAAAADj+/WsAAAAAAAAAhvr+SwAAAAAAAAAAAAAAAAA//p4AAAAAAAAAAADd/p0AAAAAAAAAAAAAAAAAwv5nAAAAAAAAAAAAlv7VAAAAAAAAAAAAAAAAItzvOgAAAAAAAAAAAFT+1QAAAAAAAAAAAAAAAH7+qwAAAAAAAAAAAABU/tUAAAAAAAAAAAAAAADW7zwAAAAAAAAAAAAAVP7VAAAAAAAAAAAAAAAA1scAAAAAAAAAAAAAAFT+1QAAAAAAAAAAAAAAC9vHAAAAAAAAAAAAAABU/tUAAAAAAAAAAAAAAGL+xwAAAAAAAAAAAAAAov7RAAAAAAAAAAAAAABi/scAAAAAAAAAAAAAM+7+SwAAAAAAAAAAAAAAYv7HAAAAAAAAAAAAM6X+wwQAAAAAAAAAAAAAAELxxwAAAAAAAAAAA6f+4zcAAAAAAAAAAAAAAAAA1tUUAAAAAAAumMr+/j8AAAAAAAAAAAAAAAAAANb+zLS0tLS06/7+6pwKAAAAAAAAAAAAAAAAAABRzf7+/v7+/v786ngAAAAAAAAAAAAAAAAAAAAAABrS/v7+/v6ZaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 11, + "label": 6, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfM/bAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAeW/Px9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB1/Lo4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjfx2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJr3MgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABr9xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACW/cQAAAAAAAAAOVVVJgAAAAAAAAAAAAAAAAAA4f1gAAAAAACX4vP8/O59AAAAAAAAAAAAAAAACuXiAAAABDbl/f/qr+H/5B8AAAAAAAAAAAAAAG78lgAAGoD8/OOGHAAAsvw4AAAAAAAAAAAAAACf/HEAAJb9/LorAAAAAI38OAAAAAAAAAAAAAAAufxxACbt/ZcGAAAAAACNygYAAAAAAAAAAAAAAMb9cgCT/aMAAAAAAAAAmsUAAAAAAAAAAAAAAADF/HEArPy8AAAAAAAAGv2rAAAAAAAAAAAAAAAAxfxxABPn93oTAAAAAMj0OAAAAAAAAAAAAAAAGt78cQAAGcv8wQ0ATMj5fQAAAAAAAAAAAAAAAAC5/bMKAAAATCMdmv30fQAAAAAAAAAAAAAAAAAAHNH9xFI5OYPF/P3WUQAAAAAAAAAAAAAAAAAAAAAZ2Pz8/P38/PycEwAAAAAAAAAAAAAAAAAAAAAAABBni/CMi4soAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 15, + "label": 5, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADOE1v3+/cuiKQAAAAAAAAAAAAAAAAAAAGaOy8v9/P38l0YAAAAAAAAAAAAAAAAAAAAAAAD+/fTLjmZSAAAAAAAAAAAAAAAAAAAAAAAAAAAArPzLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABXf6h4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAev0yAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHv+WzMzMwoAAAAAAAAAAAAAAAAAAAAAAAAAABXf/fz9/P2sUgAAAAAAAAAAAAAAAAAAAAAAABXW/cuiZmbL3/79MwoAAAAAAAAAAAAAAAAAAAA9/asAAAAAABRwwP3UKQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmy+ozAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABTV6FIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPsvqcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU1fwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJn9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACnp1AAAAAAAAAAAAAAAAHFcAAAAAAAAAAAAAB+t9CgAAAAAAAAAAAAAAFL9lwAAAAAAABVmZrfp1FEAAAAAAAAAAAAAAABS//3qmJnBrf3+/f7VjhQAAAAAAAAAAAAAAAAAAEeXl+j91MCXgzIyCgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 17, + "label": 7, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABK+f7+/vWnp4gZUDwAAAAAAAAAAAAAAAAAAAAAaP7+/v7+/v7++f78xXFHJwAAAAAAAAAAAAAAAAVjh2lpcsDAwOn+/v7+/vaBAAAAAAAAAAAAAAAAAAAAAAAAAAAtcnLL/v7+8A8AAAAAAAAAAAAAAAAAAAAAAAAAAAAACCOb/v6CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJP7xIgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHP+/nYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLz/vARAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABv/v6LAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAl8/70KAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUsP7+cQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjP7+3AIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWP3+8y0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/H+/lMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEPP+/pMFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAm/+/ssFAAAAAAAAAAAAAAAAAAAAAAAAAAAAADr+/v5UAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA7t/v/CBAAAAAAAAAAAAAAAAAAAAAAAAAAAAABS/v7CGwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ+bBHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 18, + "label": 3, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwpkpIwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyB/f39+qMSAAAAAAAAAAAAAAAAAAAAAAAAAACF/f39/f395UYAAAAAAAAAAAAAAAAAAAAAAAAAZf38kWZr7f33gAoAAAAAAAAAAAAAAAAAAAAAALX9pwAAAD3r/f2jBQAAAAAAAAAAAAAAAAAAAAD//SsAAAAAOsH9/aQEAAAAAAAAAAAAAAAAAAAAu/0gAAAAAAA37P39VgAAAAAAAAAAAAAAAAAAAJL9IABkvldXV5P9/XsAAAAAAAAAAAAAAAAAAABe/U4o+P39/f39/f3fVA8AAAAAAAAAAAAAAAAADlwMI/D9/f39/f39/f30WQoAAAAAAAAAAAAAAAAAAABLobP9/f39/f39/f3RKwAAAAAAAAAAAAAAAAAAAAADEBAnJhAQkfP9/bkwAAAAAAAAAAAAAAAAABQ6AAAAAAAAAAA60f39twAAAAAAAAAAAAAAAE3d908AAAAAAAAAAA3b/fBIAAAAAAAAAAAAAABa9/38OQAAAAAAAAAANfv9vwAAAAAAAAAAAAAAAHT9/TsAAAAAAAAAAGP8/ZEAAAAAAAAAAAAAAAAOvP3dniYAAAAAb9P2/f2RAAAAAAAAAAAAAAAAAAzd9v37+fn5+f39/f3IEwAAAAAAAAAAAAAAAAAAAF+35P39/f39/cN8FwAAAAAAAAAAAAAAAAAAAAAAABglikp+WCUHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 21, + "label": 6, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMbT99DIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALj8/OikAAAAAAAAAAAAAAAAAAAAAAAAAAAAAELq/IgmOAAAAAAAAAAAAAAAAAAAAAAAAAAAABPs/LAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABM/Pw4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAi/2tAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFtT8RQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHT98DIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACd/c4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA5v1mAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOf/tIq0/f/93mEDAAAAAAAAAAAAAAAAAAAAAADm/fz8/PzT/Pz8dQAAAAAAAAAAAAAAAAAAAAAA5v3wt1lFB0Wr/PxVAAAAAAAAAAAAAAAAAAAAAIf9mQAAAAAADdf8dAAAAAAAAAAAAAAAAAAAAAB0/c4AAAAAAACb/HQAAAAAAAAAAAAAAAAAAAAAav/TBwAAAAAx6f10AAAAAAAAAAAAAAAAAAAAAACf/JoJAAAexfz8XwAAAAAAAAAAAAAAAAAAAAAAEeP8mkZR5PzjggAAAAAAAAAAAAAAAAAAAAAAAAAy4/z8/fy5MgAAAAAAAAAAAAAAAAAAAAAAAAAAADCz/L51BgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 30, + "label": 3, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABVxwf79/v3+rFIAAAAAAAAAAAAAAAAAAAAAAAC3/fz9/P38/fzzKAAAAAAAAAAAAAAAAAAAAAAAy//pt2bLy+r9/pcAAAAAAAAAAAAAAAAAAAAAAFGXMgAAACnB/P1vAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAvV/v3LAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHvV/P38UQAAAAAAAAAAAAAAAAAAAAAAAAAAADP9/v3+lxUAAAAAAAAAAAAAAAAAAAAAAAAAAAAK1P38/ejfelIAAAAAAAAAAAAAAAAAAAAAAAAAAAB73/79/v3+RwAAAAAAAAAAAAAAAAAAAAAAAAAAABQyg9X8/cAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVov79ZgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFcv9/D0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIT9/lsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFY79/OkeAAAAAAAAAAAAAAAAAAAAAAAAAAAAKdb9/tUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAo/P9/KwKAAAAAAAAAAAAAAAAAAAAAAAAC62t/f/94FEAAAAAAAAAAAAAAAAAAAAAAAAAAIT8/fz9qxQAAAAAAAAAAAAAAAAAAAAAAAAAAACZ/fTLUgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAXMB6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 35, + "label": 2, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACR9v9r//v7xMwAAAAAAAAAAAAAAAAAAAAAAAMz5/f39/f39/frrAAAAAAAAAAAAAAAAAAAAWPH7/eGOMQwMDGn9/W8AAAAAAAAAAAAAAAAAX+H9p3EOAAAAAAAQ0/11AAAAAAAAAAAAAAAAW+79qhwAAAAAAAAAAJb9dQAAAAAAAAAAAAAAYvvaMAUAAAAAAAAAAACW/XUAAAAAAAAAAAAAAHD9cAAAAAAAAAAAAAAJuPISAAAAAAAAAAAAAAAULQUAAAAAAAAAAAAAQ/3wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAG+r4aQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALJ39hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC739yxsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC5z99k0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAC5z9ykQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC5z94kcAAAAAAAAAAAAAAAAAAAAAAAAeISGMo7r94iYAAAAAAAAAAAAAAAAAAAAAAAxR9P39/f39/f26RhcAABacTQAAAAAAAAAAAFDD/f39/f346qb4/f3wlkmQaDMAAAAAAAAAAAf4/f39/f3yaQAAa/L9/f31oAAAAAAAAAAAAAA5+v39/feHFQAAAAAVdbe3MAAAAAAAAAAAAAAAAHl7sIcQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 61, + "label": 8, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKy8vAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJbPn9/dDPz8+VQQ0AAAAAAAAAAAAAAAAAAAAJuP79/f3+/f39/v3VGQAAAAAAAAAAAAAAAAA3y/7+x39/PF1URJfe/qEAAAAAAAAAAAAAAAAAiv39xxMAAAAAAAAAm/3TAAAAAAAAAAAAAAAAAIr9/REAAAAAAAAASvH90wAAAAAAAAAAAAAAAABp/f1mAAAAAAAAIuX9/aAAAAAAAAAAAAAAAAAAAJX+5SgAAAAmmf7+/rQZAAAAAAAAAAAAAAAAAAATxv7PCSJI6/394IsNAAAAAAAAAAAAAAAAAAAAABHT/dfw/v3qgBEAAAAAAAAAAAAAAAAAAAAAAABm5f39/eRNDQAAAAAAAAAAAAAAAAAAAAAARqr+/v7+/v53AAAAAAAAAAAAAAAAAAAAABqC5v79/blzQNP9+BUAAAAAAAAAAAAAAAAAAKbo/f33oi4NB1v1/f44AAAAAAAAAAAAAAAAAACA/f390l1/n8z9/f3kDwAAAAAAAAAAAAAAAAAAAIbx/v/+/v7+/v7kIgAAAAAAAAAAAAAAAAAAAAAAG3OMzs7Oz857DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + }, + { + "index": 84, + "label": 8, + "pixels": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABksAYrmyXhMAAAAAAAAAAAAAAAAAAAAAAA9vw+5eAND5/v50AAAAAAAAAAAAAAAAAAAUMmvF9rcZAABR9f75WwAAAAAAAAAAAAAAABJU5v7+3VYAAAF9/f6yNQAAAAAAAAAAAAAAAACF/v7ZdgQAAD7K/vGDCAAAAAAAAAAAAAAAAABr9P7VLQAAAD7w/twdAAAAAAAAAAAAAAAAAAAs9v7RMQAAAB/x/t0bAAAAAAAAAAAAAAAAAAAAX/7+NwAAABHG/tocAAAAAAAAAAAAAAAAAAAAABvb/umQJyrM/s0KAAAAAAAAAAAAAAAAAAAAAAAAc/j+/vTp/t8YAAAAAAAAAAAAAAAAAAAAAAAAAAAmVKj1/v7+z3MJAAAAAAAAAAAAAAAAAAAAAAAAAAAO7P7mo+3001ABAAAAAAAAAAAAAAAAAAAAAAAAY/7+YwAAJeH+gggAAAAAAAAAAAAAAAAAAAAAAEf+5QwAAAACqv4zAAAAAAAAAAAAAAAAAAAAAABg/v4SAAAAAFH+xgAAAAAAAAAAAAAAAAAAAAAAUP7+EgAAAACD/ncAAAAAAAAAAAAAAAAAAAAAAAXW/k4AAAABt/Q/AAAAAAAAAAAAAAAAAAAAAAAAQP3fGAACfv6yAAAAAAAAAAAAAAAAAAAAAAAAAABX7t53sf7ZGwAAAAAAAAAAAAAAAAAAAAAAAAAAABKaxMRlGQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" + } + ] +} \ No newline at end of file diff --git a/tests/pages/DatasetsDownloads.test.ts b/tests/pages/DatasetsDownloads.test.ts index 261a487..2e6e306 100644 --- a/tests/pages/DatasetsDownloads.test.ts +++ b/tests/pages/DatasetsDownloads.test.ts @@ -1,18 +1,81 @@ import { describe, test, expect } from 'vitest' import * as fs from 'fs' +import { TASK_DATASET_OPTIONS, type TaskOption_t } from '../../src/TASK_OPTIONS' +import { EXTRA_DATASETS } from '../../src/pages/datasets/extraDatasets' +import { DATASET_VARIABLES, N4L_VARIABLES, variableTables } from '../../src/pages/datasets/datasetVariables' +import { datasetKey } from '../../src/pages/analyze/projectDatasets' -// Los enlaces de descarga de la página de datasets apuntan a ficheros de public/datasets +// La página de datasets descarga los mismos CSV que usan los modelos, más algunos extra: todos deben existir en public/ describe('Datasets — enlaces de descarga', () => { - const source = fs.readFileSync('src/pages/datasets/Datasets.tsx', 'utf8') - const block = (from: string, to: string) => source.slice(source.indexOf(from), source.indexOf(to)) - const downloads = (text: string) => [...text.matchAll(/url_download: "([^"]+)"/g)].map((m) => m[1]) + test('los ficheros de los datasets de los modelos existen', () => { + const files = Object.values(TASK_DATASET_OPTIONS as Record) + .flat() + .flatMap((option) => option.info?.files ?? []) + expect(files.length).toBeGreaterThan(0) + expect(files.filter((file) => !fs.existsSync('public/' + file))).toStrictEqual([]) + }) - test.each([ - ['clasificación tabular', block('tabular_classification_datasets_list', 'regression_datasets_list'), 'public/datasets/'], - ['regresión', block('regression_datasets_list', '// @formatter:on'), 'public/datasets/01-regression/'], - ])('%s: todos los ficheros existen', (_task, text, base) => { - const files = downloads(text) + test('los ficheros extra existen', () => { + const files = Object.values(EXTRA_DATASETS).flat().map(({ file }) => file) expect(files.length).toBeGreaterThan(0) - expect(files.filter((file) => !fs.existsSync(base + file))).toStrictEqual([]) + expect(files.filter((file) => !fs.existsSync('public/' + file))).toStrictEqual([]) + }) + + test('cada dataset tabular tiene su tabla de variables', () => { + const files = [ + ...Object.values(TASK_DATASET_OPTIONS as Record).flat().flatMap((option) => option.info?.files ?? []), + ...Object.values(EXTRA_DATASETS).flat().map(({ file }) => file), + ] + // Las de los paquetes .n4l, de su manifiesto + expect(files.filter((file) => variableTables([file]).length === 0)).toStrictEqual([]) + }) + + test('las variables coinciden con las columnas y los valores ausentes de los CSV', () => { + for (const table of [...DATASET_VARIABLES, ...N4L_VARIABLES]) { + const columns = table.variables.map(() => ({ missing: 0 })) + for (const file of table.files) { + const [header, ...rows] = fs.readFileSync('public/' + file, 'utf-8').trim().split(/\r?\n/).map((line) => line.split(',')) + expect(header.map((name) => name.trim()), file).toStrictEqual(table.variables.map(({ name }) => name)) + rows.forEach((row) => header.forEach((_, i) => { if (['', '?', 'NA', 'NaN', 'nan'].includes((row[i] ?? '').trim())) columns[i].missing++ })) + } + expect(columns.map(({ missing }) => missing), table.files[0]).toStrictEqual(table.variables.map(({ missing }) => missing)) + } + }) + + test('cada dataset de los modelos tiene su fuente original', () => { + const missing = Object.values(TASK_DATASET_OPTIONS as Record) + .flat() + .filter((option) => option.info !== undefined && option.info.source === undefined) + expect(missing).toStrictEqual([]) + }) + + test('las clases de los conjuntos de práctica son las de su columna objetivo', () => { + for (const { file, classes } of Object.values(EXTRA_DATASETS).flat().filter(({ classes }) => classes !== undefined)) { + const target = variableTables([file])[0].variables.find(({ role }) => role === 'Target')!.name + const [header, ...rows] = fs.readFileSync('public/' + file, 'utf-8').trim().split(/\r?\n/).map((line) => line.split(',')) + const column = header.map((name) => name.trim()).indexOf(target) + expect(new Set(rows.map((row) => row[column].trim())).size, file).toBe(classes) + } + }) + + test('cada conjunto tiene su frase en /datasets, en todos los idiomas', () => { + const lookup = (translation: unknown, key: string) => + key.split('.').reduce((node, part) => (node as Record | undefined)?.[part], translation) + const keys = [ + ...(['tabular-classification', 'regression', 'image-classification', 'clustering', 'time-series'] as const).flatMap((task) => + (TASK_DATASET_OPTIONS as Record)[task].filter(({ info }) => info !== undefined) + .map(({ value, summary }) => summary ?? `datasets.summary.${task}.${value}`)), + ...Object.values(EXTRA_DATASETS).flat().map(({ file, summary }) => summary ?? `datasets.summary.extra.${datasetKey(file)}`), + ] + // n4l-:clave está en los textos del paquete (public/n4l/.n4l/locales/); el resto, en los de la aplicación + const text = (language: string, key: string) => { + const [, id, packageKey] = key.match(/^n4l-(.+):(.+)$/) ?? [] + return id === undefined + ? lookup(JSON.parse(fs.readFileSync(`public/locales/${language}/translation.json`, 'utf-8')), key) + : lookup(JSON.parse(fs.readFileSync(`public/n4l/${id}.n4l/locales/${language}.json`, 'utf-8')), packageKey) + } + for (const language of ['es', 'en', 'ja']) { + expect(keys.filter((key) => typeof text(language, key) !== 'string'), language).toStrictEqual([]) + } }) }) diff --git a/tests/pages/Lab.test.tsx b/tests/pages/Lab.test.tsx new file mode 100644 index 0000000..e25f119 --- /dev/null +++ b/tests/pages/Lab.test.tsx @@ -0,0 +1,47 @@ +import { afterEach, describe, expect, test } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { MemoryRouter } from 'react-router' + +import Lab from '@pages/lab/Lab' + +// jsdom no dibuja en un canvas (getContext da null): se comprueba lo que dice la página +function renderLab() { + render() +} + +describe('Lab: el laboratorio 2D', () => { + afterEach(() => cleanup()) + + test('sin entrenar, lo dice; con una época, cuenta cómo va (para quien no ve el plano)', () => { + renderLab() + expect(screen.getByTestId('Test-Lab-Summary')).toHaveTextContent('pages.lab.not-trained') + fireEvent.click(screen.getByTestId('Test-Lab-Step')) + expect(screen.getByTestId('Test-Lab-Summary')).toHaveTextContent('pages.lab.summary') + // y el lector de pantalla lo oye + expect(screen.getByRole('status')).toHaveTextContent('pages.lab.summary') + }) + + test('«Prueba esto» pone sus datos y su red y explica qué enseña', () => { + renderLab() + fireEvent.click(screen.getByTestId('Test-Lab-Experiment-xor-line')) + expect(screen.getByTestId('Test-Lab-Experiment-xor-line')).toHaveAttribute('aria-pressed', 'true') + expect(screen.getByTestId('Test-Lab-Lesson')).toHaveTextContent('pages.lab.experiments.xor-line.lesson') + expect(screen.getByLabelText('pages.lab.data.dataset')).toHaveValue('xor') + expect(screen.getByText('pages.lab.network.none')).toBeInTheDocument() + }) + + test('cambiar la red la empieza de cero; cambiar la tasa de aprendizaje, no', () => { + renderLab() + fireEvent.click(screen.getByTestId('Test-Lab-Step')) + fireEvent.change(screen.getByLabelText('pages.lab.training.learning-rate'), { target: { value: '0.3' } }) + expect(screen.getByTestId('Test-Lab-Summary')).toHaveTextContent('pages.lab.summary') + fireEvent.click(screen.getByRole('button', { name: 'pages.lab.network.add' })) + expect(screen.getByTestId('Test-Lab-Summary')).toHaveTextContent('pages.lab.not-trained') + }) + + test('siempre entra algo en la red: la última característica no se puede quitar', () => { + renderLab() + fireEvent.click(screen.getByLabelText('pages.lab.features.y')) + expect(screen.getByLabelText('pages.lab.features.x')).toBeDisabled() + }) +}) diff --git a/tests/pages/MenuSelect.test.tsx b/tests/pages/MenuSelect.test.tsx new file mode 100644 index 0000000..41c5d08 --- /dev/null +++ b/tests/pages/MenuSelect.test.tsx @@ -0,0 +1,88 @@ +import { fireEvent, render } from '@testing-library/react' +import { MemoryRouter, Route, Routes, useLocation } from 'react-router' +import MenuSelect from '@pages/menu/MenuSelect' +import N4LBreadcrumb from '@components/breadcrumb/N4LBreadcrumb' + +function LocationDisplay() { + return

    {useLocation().pathname}

    +} + +const renderAt = (path: string, ui: React.ReactElement | null = null) => render( + + + } /> + } /> + 404

    } /> + +
    + +
    , +) + +describe('MenuSelect', () => { + test('una tarjeta por dataset y cada una abre su playground', () => { + const { getByTestId } = renderAt('/select-dataset/tabular-classification') + expect(getByTestId('Test-MenuSelectDataset-Open-IRIS')).toHaveAttribute('href', '/playground/tabular-classification/dataset/IRIS') + expect(getByTestId('Test-MenuSelectDataset-Open-UPLOAD')).toHaveAttribute('href', '/playground/tabular-classification/dataset/UPLOAD') + }) + + test('las migas de pan terminan en la página de selección', () => { + const { getByTestId } = renderAt('/select-model/regression') + expect(getByTestId('Test-Breadcrumb')).toHaveTextContent('breadcrumb.models') + }) + + test('sin datasets (detección de objetos) lleva a la 404', () => { + expect(renderAt('/select-dataset/object-detection').getByTestId('location')).toHaveTextContent('/404') + }) + + test('tarea desconocida lleva a la 404', () => { + expect(renderAt('/select-model/no-existe').getByTestId('location')).toHaveTextContent('/404') + }) +}) + +describe('N4LBreadcrumb', () => { + // El nombre de cada modelo, en los textos de su paquete .n4l + const MODEL: Record = { 1: 'n4l-car:tasks.tabular-classification.name', 2: 'n4l-iris:tasks.tabular-classification.name' } + + test('en el playground enlaza a la página de la tarea y a la selección, y permite cambiar de modelo', async () => { + const { getByTestId, getByText, findByText } = renderAt('/playground/tabular-classification/model/IRIS', + ) + + expect(getByText('header.home').closest('a')).toHaveAttribute('href', '/') + expect(getByText('pages.index.tabular-classification.1-title').closest('a')).toHaveAttribute('href', '/task/tabular-classification') + expect(getByText('breadcrumb.models').closest('a')).toHaveAttribute('href', '/select-model/tabular-classification') + + // El desplegable enseña el modelo abierto y lista los demás de la tarea: son enlaces + fireEvent.click(getByText(MODEL[2])) + const car = await findByText(MODEL[1]) + expect(car.closest('a')).toHaveAttribute('href', '/playground/tabular-classification/model/CAR') + expect((await findByText(MODEL[2], { selector: '.dropdown-item' })).closest('a')).toHaveAttribute('aria-current', 'page') + fireEvent.click(car) + expect(getByTestId('location')).toHaveTextContent('/playground/tabular-classification/model/CAR') + }) + + test('del modelo preentrenado se puede ir a entrenar con su dataset, y al revés', async () => { + const model = renderAt('/', ) + fireEvent.click(model.getByText(MODEL[2])) + expect(await model.findByTestId('Test-Breadcrumb-OtherKind')).toHaveAttribute('href', '/playground/tabular-classification/dataset/IRIS') + model.unmount() + + const dataset = renderAt('/', ) + fireEvent.click(dataset.getByText('n4l-auto-mpg:tasks.regression.name')) + expect(await dataset.findByTestId('Test-Breadcrumb-OtherKind')).toHaveAttribute('href', '/playground/regression/model/AUTO_MPG') + }) + + test('sin el otro lado no hay enlace: CSV propio y detección de objetos (no tiene datasets)', async () => { + const upload = renderAt('/', ) + fireEvent.click(upload.getByText('pages.menu-selection-dataset.0-tabular-classification.csv')) + // Subir un CSV va primero y separado de los datasets de ejemplo + expect(await upload.findByText('pages.menu-selection-dataset.example-datasets')).toHaveClass('dropdown-header') + expect(upload.queryByTestId('Test-Breadcrumb-OtherKind')).not.toBeInTheDocument() + upload.unmount() + + const detection = renderAt('/', ) + fireEvent.click(detection.getByText('datasets-models.2-object-detection.list-models.2-option-4')) + await detection.findAllByRole('button') + expect(detection.queryByTestId('Test-Breadcrumb-OtherKind')).not.toBeInTheDocument() + }) +}) diff --git a/tests/pages/ModelReviewForms.test.tsx b/tests/pages/ModelReviewForms.test.tsx new file mode 100644 index 0000000..0f3b36b --- /dev/null +++ b/tests/pages/ModelReviewForms.test.tsx @@ -0,0 +1,174 @@ +import { describe, test, expect, vi } from 'vitest' +import { useState } from 'react' +import { fireEvent, render, screen } from '@testing-library/react' +import * as dfd from 'danfojs' + +import type * as _Types from '@core/types' +import { DataFrameTransformAndEncoder } from '@core/dataframe/DataFrameUtils' +import { F_FILTER_Categorical, F_MAP_LabelEncoder } from '@core/nn-utils/utils' +import type MODEL_N4L from '@pages/playground/0_TabularClassification/models/MODEL_N4L' +import type { TabularInstance_t } from '@pages/playground/0_TabularClassification/models/_model' +import ModelReviewTabularClassificationPredictForm from '@pages/playground/0_TabularClassification/ModelReviewTabularClassificationPredictForm' +import ModelReviewRegressionPredictForm from '@pages/playground/1_Regression/ModelReviewRegressionPredictForm' +import RegressionPredictionInfo from '@pages/playground/1_Regression/RegressionPredictionInfo' +import { TRANSFORM_DATASET_PROCESSED_TO_STATE_PREDICTION } from '@pages/playground/1_Regression/utils' +import { n4lTabularModel } from '../helpers/n4l' + +describe('ModelReviewTabularClassificationPredictForm', () => { + + function TabularForm({ iModelInstance, onChange }: { iModelInstance: MODEL_N4L, onChange: (data: TabularInstance_t) => void }) { + const [data, setData] = useState(iModelInstance.DATA_DEFAULT) + return setData((prev) => { + const next = typeof action === 'function' ? action(prev) : action + onChange(next) + return next + })} /> + } + + test('cada campo con el nombre traducido del atributo, el del CSV y su tipo', () => { + render( {}} />) + // Etiqueta con la clave de TABLE_HEADER (el mock de i18n devuelve la clave) asociada a su desplegable + const buying = screen.getByLabelText('n4l-car:columns.Buying') + expect(buying.tagName).toBe('SELECT') + expect(buying).toHaveValue('vhigh') + expect(buying.parentElement).toHaveTextContent('Buying: pages.playground.form.type-categorical') + }) + + test('los números se guardan como número y un campo vacío no muestra NaN', () => { + const onChange = vi.fn() + render() + const sepal = screen.getByLabelText('n4l-iris:columns.sepal_length') + expect(sepal.parentElement).toHaveTextContent('pages.playground.form.type-decimal') + fireEvent.change(sepal, { target: { value: '6.3' } }) + expect(onChange).toHaveBeenLastCalledWith(expect.objectContaining({ sepal_length: 6.3 })) + fireEvent.change(sepal, { target: { value: '' } }) + expect(sepal).toHaveValue(null) + }) +}) + +describe('ModelReviewRegressionPredictForm', () => { + + // Un conjunto de datos mínimo con un atributo entero, uno decimal, uno categórico, una columna que el modelo no usa + // y la variable objetivo + /** dropId: la columna "id" se descarta al procesar (el procesado tiene menos columnas que el original) */ + function makeDataset({ dropId = false } = {}): _Types.DatasetProcessed_t { + const dataframe_original = new dfd.DataFrame({ + rooms: [2, 3, 5], + area : [55.5, 80.25, 120], + city : ['Jaén', 'Granada', 'Jaén'], + id : [101, 102, 103], + price: [100, 150, 300], + }) + const dataset: _Types.Dataset_t = [ + { column_name: 'rooms', column_role: 'Feature', column_type: 'Integer', column_missing_values: false }, + { column_name: 'area', column_role: 'Feature', column_type: 'Continuous', column_missing_values: false }, + { column_name: 'city', column_role: 'Feature', column_type: 'Categorical', column_missing_values: false }, + { column_name: 'price', column_role: 'Target', column_type: 'Continuous', column_missing_values: false }, + ] + const dataset_transforms = dataset.filter(F_FILTER_Categorical).map(F_MAP_LabelEncoder) + // Como en los modelos, el dataframe procesado tiene las mismas columnas que el original + const transforms: _Types.DataFrameColumnTransform_t[] = dropId ? [...dataset_transforms, { column_name: 'id', column_transform: 'drop' }] : dataset_transforms + const { dataframe_processed, encoder_map } = DataFrameTransformAndEncoder(dataframe_original, transforms) + const dataframe_X = dataframe_processed.drop({ columns: dropId ? ['price'] : ['id', 'price'] }) + const scaler = new dfd.MinMaxScaler().fit(dataframe_X) + return { + is_dataset_upload : false, + is_dataset_processed: true, + path : '', + csv : 'test.csv', + info : '', + container_info : '', + dataset, + dataset_transforms, + dataframe_original, + dataframe_processed, + data_processed : { + dataframe_X, + dataframe_y : dataframe_original['price'], + X : scaler.transform(dataframe_X), + y : dataframe_original['price'], + scaler, + encoders : encoder_map, + column_name_target: 'price', + }, + } + } + + function RegressionForm({ dataset, onChange }: { dataset: _Types.DatasetProcessed_t, onChange: (prediction: _Types.StatePrediction_t) => void }) { + const [prediction, setPrediction] = useState<_Types.StatePrediction_t>(TRANSFORM_DATASET_PROCESSED_TO_STATE_PREDICTION(dataset, 0)) + return setPrediction((prev) => { + const next = typeof action === 'function' ? action(prev) : action + onChange(next) + return next + })} /> + } + + test('solo los atributos del modelo, con su tipo y el rango que toman en los datos', () => { + render( {}} />) + expect(screen.getAllByRole('spinbutton').length + screen.getAllByRole('combobox').length).toBe(3) + // La variable objetivo es lo que se predice y "id" no lo usa el modelo + expect(screen.queryByLabelText('price')).toBeNull() + expect(screen.queryByLabelText('id')).toBeNull() + expect(screen.getByLabelText('rooms').parentElement).toHaveTextContent('pages.playground.form.type-integer, pages.playground.form.range') + expect(screen.getByLabelText('area')).toHaveValue(55.5) + expect(screen.getByLabelText('city').parentElement).toHaveTextContent('pages.playground.form.type-categorical') + }) + + test('con columnas descartadas al procesar, la instancia se prepara igual y el formulario no las pide', () => { + // Antes el dataframe procesado se creaba con los tipos del original y fallaba si tenían distinto número de columnas + const dataset = makeDataset({ dropId: true }) + const state = TRANSFORM_DATASET_PROCESSED_TO_STATE_PREDICTION(dataset, 2) + expect(state.input_1_dataframe_processed.columns).not.toContain('id') + expect(state.input_1_dataframe_original['id'].values[0]).toBe(103) + render( {}} />) + expect(screen.queryByLabelText('id')).toBeNull() + expect(screen.getByLabelText('rooms')).toHaveValue(2) + }) + + test('al cambiar un valor se codifica y se escala la entrada del modelo', () => { + const onChange = vi.fn() + render() + fireEvent.change(screen.getByLabelText('rooms'), { target: { value: '5' } }) + const afterRooms: _Types.StatePrediction_t = onChange.mock.lastCall![0] + expect(afterRooms.input_1_dataframe_original['rooms'].values[0]).toBe(5) + // rooms va de 2 a 5: 5 escalado es 1 + expect((afterRooms.input_3_dataframe_scaling.values[0] as number[])[0]).toBeCloseTo(1) + fireEvent.change(screen.getByLabelText('city'), { target: { value: 'Granada' } }) + const afterCity: _Types.StatePrediction_t = onChange.mock.lastCall![0] + expect(afterCity.input_1_dataframe_original['city'].values[0]).toBe('Granada') + expect(typeof afterCity.input_2_dataframe_encoding['city'].values[0]).toBe('number') + }) +}) + +describe('RegressionPredictionInfo', () => { + + const prediction = (result: number[]): _Types.StatePrediction_t => ({ + input_0_raw : [4, 113, 24], + input_1_dataframe_original : new dfd.DataFrame([[4, 113, 24]], { columns: ['cylinders', 'displacement', 'mpg'] }), + input_1_dataframe_processed: new dfd.DataFrame([[4, 113, 24]], { columns: ['cylinders', 'displacement', 'mpg'] }), + input_2_dataframe_encoding : new dfd.DataFrame([[4, 113]], { columns: ['cylinders', 'displacement'] }), + input_3_dataframe_scaling : new dfd.DataFrame([[0.2, 0.116]], { columns: ['cylinders', 'displacement'] }), + result, + }) + + test('sin predicción, la espera', () => { + render() + expect(screen.getByText('pages.playground.generator.waiting-for-prediction')).toBeInTheDocument() + }) + + test('el valor predicho de la variable objetivo y, con el valor real, el error', () => { + const { rerender } = render() + expect(screen.getByTestId('Test-RegressionPrediction-value').textContent).toMatch(/^24[.,]194$/) + expect(screen.getByText('pages.playground.1-regression.predict.predicted-value')).toBeInTheDocument() + expect(screen.getByTestId('Test-RegressionPrediction-actual')).toBeInTheDocument() + expect(screen.getByTestId('Test-RegressionPrediction-error')).toBeInTheDocument() + rerender() + expect(screen.queryByTestId('Test-RegressionPrediction-actual')).toBeNull() + expect(screen.queryByTestId('Test-RegressionPrediction-error')).toBeNull() + }) +}) diff --git a/tests/pages/ModelReviewTimeSeries.test.tsx b/tests/pages/ModelReviewTimeSeries.test.tsx new file mode 100644 index 0000000..de99dc8 --- /dev/null +++ b/tests/pages/ModelReviewTimeSeries.test.tsx @@ -0,0 +1,49 @@ +import { describe, test, expect, beforeAll, afterAll, vi } from 'vitest' +import { fireEvent, render, within } from '@testing-library/react' +import { MemoryRouter } from 'react-router' +import * as tfjs from '@tensorflow/tfjs' + +import ModelReviewTimeSeries from '@pages/playground/5_TimeSeries/ModelReviewTimeSeries' +import { stubPublicFetch } from '../helpers/n4l' + +// jsdom no dibuja en un canvas: las gráficas, con lo que describen para quien no las ve +vi.mock('react-chartjs-2', () => ({ + Line: ({ 'aria-label': label }: { 'aria-label': string }) =>
    , +})) + +const prefix = 'pages.playground.time-series.review.' + +describe('Modelo ya entrenado de una serie (/playground/time-series/model/…)', () => { + beforeAll(async () => { + stubPublicFetch() + await tfjs.setBackend('cpu') + }) + afterAll(() => { vi.unstubAllGlobals() }) + + test('como en las demás tareas: su ficha, la serie y un formulario con la ventana que predice un valor', async () => { + const { findByTestId, getByTestId, queryByTestId } = render( + , + ) + // La ficha: el resumen de la red, el paquete, cómo predice lo que no vio y la descripción + expect(getByTestId('Test-ModelCard')).toHaveTextContent('n4l-airline-passengers:tasks.time-series.name') + expect(getByTestId('Test-TimeSeries-TestMetrics')).toHaveTextContent(prefix + 'metrics-seasonal') + expect(getByTestId('Test-TimeSeries-TrainYours')).toHaveAttribute('href', '/playground/time-series/dataset/AIRLINE-PASSENGERS') + + // El formulario empieza con el primer valor de la prueba (1958-08): los 24 meses anteriores + const form = await findByTestId('Test-TimeSeries-PredictForm', {}, { timeout: 10_000 }) + const inputs = within(form).getAllByRole('spinbutton') + expect(inputs).toHaveLength(24) + expect(within(form).getByLabelText('1956-08')).toHaveValue(405) + expect(within(form).getByLabelText('1958-07')).toHaveValue(491) + + fireEvent.click(getByTestId('Test-TimeSeries-PredictButton')) + const result = await findByTestId('Test-TimeSeries-PredictResult') + expect(within(result).getByTestId('Test-TimeSeries-PredictValue').textContent).toMatch(/\d/) + expect(within(result).getByTestId('Test-TimeSeries-PredictActual')).toBeInTheDocument() + + // Con un valor cambiado ya no es el de la serie: sin valor real + fireEvent.change(within(form).getByLabelText('1958-07'), { target: { value: '600' } }) + fireEvent.click(getByTestId('Test-TimeSeries-PredictButton')) + await vi.waitFor(() => expect(queryByTestId('Test-TimeSeries-PredictActual')).toBeNull()) + }, 30_000) +}) diff --git a/tests/pages/PageHome.test.tsx b/tests/pages/PageHome.test.tsx index f240106..db33a1b 100644 --- a/tests/pages/PageHome.test.tsx +++ b/tests/pages/PageHome.test.tsx @@ -1,8 +1,13 @@ import { fireEvent, render } from '@testing-library/react' import { MemoryRouter } from 'react-router' import Home from '@pages/_home/Home' +import { sectionId } from '@components/divider/sectionId' describe('Page Home', () => { + beforeEach(() => { + localStorage.clear() + }) + test('App / HOME', async () => { const { getByTestId, findByTestId } = render() expect(getByTestId('Test-InitialMenu')).toBeInTheDocument() @@ -11,4 +16,53 @@ describe('Page Home', () => { fireEvent.click(getByTestId('Test-InitialMenu-LinearRegression')) expect(await findByTestId('Test-GoTo-SelectModel-LinearRegression')).toBeInTheDocument() }) + + test('al elegir una tarea, la página baja hasta sus tarjetas con el foco en su separador (al entrar, no se mueve)', async () => { + // El scrollIntoView vacío de tests/setupTests.ts (jsdom no lo tiene), sin lo de las pruebas anteriores + const scroll = vi.mocked(Element.prototype.scrollIntoView) + scroll.mockClear() + const { getByTestId, findByTestId } = render() + expect(await findByTestId('Test-GoTo-SelectModel-LinearRegression')).toBeInTheDocument() + expect(scroll).not.toHaveBeenCalled() + + fireEvent.click(getByTestId('Test-InitialMenu-Clustering')) + expect(await findByTestId('Test-GoTo-SelectDataset-Clustering')).toBeInTheDocument() + const divider = document.getElementById(sectionId('hr.tasks')) + expect(scroll).toHaveBeenCalledTimes(1) + expect(scroll.mock.contexts[0]).toBe(divider) + expect(divider).toHaveFocus() + }) + + test('series temporales: como la clasificación tabular, sus modelos ya entrenados y diseñar una red', async () => { + const { getByTestId, findByTestId } = render() + fireEvent.click(getByTestId('Test-InitialMenu-TimeSeries')) + expect(await findByTestId('Test-GoTo-SelectModel-TimeSeries')).toHaveTextContent('pages.index.time-series.1-button') + expect(getByTestId('Test-GoTo-SelectDataset-TimeSeries')).toHaveTextContent('pages.index.time-series.2-button') + }) + + test('recuerda la última tarea elegida al volver a la home', async () => { + const first = render() + fireEvent.click(first.getByTestId('Test-InitialMenu-LinearRegression')) + first.unmount() + + const { findByTestId } = render() + expect(await findByTestId('Test-GoTo-SelectModel-LinearRegression')).toBeInTheDocument() + }) + + test('?task= (la miga de pan de la tarea) abre esa tarea y la recuerda', async () => { + localStorage.setItem('selected-task', 'tabular-classification') + const first = render() + expect(await first.findByTestId('Test-GoTo-SelectModel-LinearRegression')).toBeInTheDocument() + first.unmount() + + const { findByTestId } = render() + expect(await findByTestId('Test-GoTo-SelectModel-LinearRegression')).toBeInTheDocument() + }) + + test('con ?task= se puede elegir otra tarea', async () => { + const { getByTestId, queryByTestId } = render() + fireEvent.click(getByTestId('Test-InitialMenu-TabularClassification')) + expect(queryByTestId('Test-GoTo-SelectModel-LinearRegression')).not.toBeInTheDocument() + expect(localStorage.getItem('selected-task')).toBe('tabular-classification') + }) }) diff --git a/tests/pages/Pages.test.tsx b/tests/pages/Pages.test.tsx index a4581bb..b8830da 100644 --- a/tests/pages/Pages.test.tsx +++ b/tests/pages/Pages.test.tsx @@ -1,9 +1,15 @@ -import { render, waitFor } from '@testing-library/react' +import { fireEvent, render, within, waitFor } from '@testing-library/react' +import { MemoryRouter } from 'react-router' +import { vi } from 'vitest' import { renderApp } from '../setup/utils' import Glossary from '@pages/glossary/Glossary' import Datasets from '@pages/datasets/Datasets' describe('Tests for Pages', () => { + beforeAll(() => { + // jsdom no implementa scrollIntoView (el glosario lo usa para llevar la vista al apartado abierto) + Element.prototype.scrollIntoView = vi.fn() + }) test('App / Home', async () => { const { getByText, debug: _debug } = renderApp({}) @@ -20,9 +26,20 @@ describe('Tests for Pages', () => { }) test('App / Glossary', async () => { - const { getByText, debug: _debug } = render() + const { getByText, debug: _debug } = render() expect(getByText(/pages.glossary.title/i)).toBeInTheDocument() - // _debug() + }) + + test('App / Glossary lleva al apartado del enlace de ayuda', async () => { + const scrollIntoView = vi.mocked(Element.prototype.scrollIntoView) + scrollIntoView.mockClear() + const { container } = render( + , + ) + // La vista va al grupo del editor de hiperparámetros + const group = container.querySelector('#glossary-editor-hyperparameters') + expect(group).not.toBeNull() + expect(scrollIntoView.mock.contexts).toContain(group) }) test('App with lazy load / Glossary', async () => { @@ -32,11 +49,108 @@ describe('Tests for Pages', () => { }) test('App / Datasets', async () => { - const { getByText, debug: _debug } = render() + const { getByText, debug: _debug } = render() expect(getByText(/datasets.title/i)).toBeInTheDocument() // _debug() }) + test('Datasets: cada CSV se abre en el AED; con varios ficheros, uno por fichero', async () => { + const { getByTestId, getByText, queryAllByText } = render() + expect(getByTestId('Test-DatasetAnalyze-iris')).toHaveAttribute('href', '/analyze?dataset=iris') + // Ya no hay columna de referencia: el enlace a la fuente va en el modal de información + expect(queryAllByText('datasets.dataset-reference')).toHaveLength(0) + // Regresión: el vino tiene dos CSV (tinto y blanco) + fireEvent.click(getByText('pages.index.regression.1-title')) + expect(getByTestId('Test-DatasetAnalyze-wine-quality-red')).toHaveTextContent('wine-quality-red') + expect(getByTestId('Test-DatasetAnalyze-wine-quality-white')).toHaveAttribute('href', '/analyze?dataset=wine-quality-white') + }) + + test('Datasets: el botón de información abre un modal con los datos y la descarga', async () => { + const { getByTestId, findByRole } = render() + fireEvent.click(getByTestId('Test-DatasetInfo-IRIS')) + const modal = await findByRole('dialog') + expect(modal).toHaveTextContent('n4l-iris:tasks.tabular-classification.name') + expect(modal).toHaveTextContent('pages.menu.info.rows') + expect(modal.querySelector('a[download]')).toHaveAttribute('href', expect.stringContaining('iris.csv')) + }) + + test('Datasets: el modal de un CSV tiene sus datos y sus estadísticas; el de imágenes, no', async () => { + const { getByTestId, getByText, findByRole } = render() + fireEvent.click(getByTestId('Test-DatasetInfo-IRIS')) + const modal = await findByRole('dialog') + const tabs = within(modal).getAllByRole('tab').map((tab) => tab.textContent) + expect(tabs).toEqual(['datasets.dataset-details', 'datasets.variables.title', 'datasets.data.title', 'datasets.data.describe']) + fireEvent.click(within(modal).getByRole('button', { name: /close|cerrar/i })) + + fireEvent.click(getByText('pages.index.image-classification.1-title')) + fireEvent.click(getByTestId('Test-DatasetInfo-IMAGE-MNIST')) + const imagesModal = await findByRole('dialog') + expect(within(imagesModal).getAllByRole('tab').map((tab) => tab.textContent)).toEqual(['datasets.dataset-details']) + }) + + test('Datasets: cada conjunto se entrena desde su tarjeta, y se prueba su modelo si lo hay', () => { + const { getByTestId, queryByTestId, getByText } = render() + expect(getByTestId('Test-DatasetTrain-IRIS')).toHaveAttribute('href', '/playground/tabular-classification/dataset/IRIS') + expect(getByTestId('Test-DatasetModel-IRIS')).toHaveAttribute('href', '/playground/tabular-classification/model/IRIS') + // Uno de práctica: en la página de subir datos, ya cargado (como en el AED, por su clave) + expect(getByTestId('Test-DatasetTrain-n4l/wine.n4l/data/wine.csv')).toHaveAttribute('href', '/playground/tabular-classification/dataset/UPLOAD?dataset=wine') + expect(queryByTestId('Test-DatasetModel-n4l/wine.n4l/data/wine.csv')).toBeNull() + // Regresión: Salary, con su modelo ya entrenado (en su paquete .n4l) + fireEvent.click(getByText('pages.index.regression.1-title')) + expect(getByTestId('Test-DatasetTrain-SALARY')).toHaveAttribute('href', '/playground/regression/dataset/SALARY') + expect(getByTestId('Test-DatasetModel-SALARY')).toHaveAttribute('href', '/playground/regression/model/SALARY') + }) + + test('Datasets: un dataset extra explica para qué sirve', async () => { + const { getByTestId, findByRole } = render() + fireEvent.click(getByTestId('Test-DatasetInfo-datasets/hepatitis-c.csv')) + expect(await findByRole('dialog')).toHaveTextContent('datasets.extra-text') + }) + + test('Datasets: los del agrupamiento se agrupan (sin modelo) y su información no espera a ningún modelo', async () => { + // La pestaña, desde la dirección (/datasets?task=clustering) + const { getByTestId, queryByTestId, getByText, findByRole } = render() + expect(getByTestId('Test-DatasetTrain-IRIS')).toHaveAttribute('href', '/playground/clustering/dataset/IRIS') + expect(getByTestId('Test-DatasetTrain-IRIS')).toHaveTextContent('datasets.clustering.run') + expect(queryByTestId('Test-DatasetModel-IRIS')).toBeNull() + expect(getByText('datasets.clustering.examples-title')).toBeInTheDocument() + // Los de práctica, en la página de subir datos del agrupamiento, con su frase de agrupamiento + expect(getByTestId('Test-DatasetTrain-n4l/breast-cancer.n4l/data/wdbc.csv')) + .toHaveAttribute('href', '/playground/clustering/dataset/UPLOAD?dataset=wdbc') + expect(getByTestId('Test-Dataset-datasets/hepatitis-c.csv')).toHaveTextContent('datasets.summary.clustering.hepatitis-c') + fireEvent.click(getByTestId('Test-DatasetInfo-WINE')) + const dialog = await findByRole('dialog') + expect(dialog).toHaveTextContent('n4l-wine:tasks.clustering.summary') + expect(dialog).toHaveTextContent('datasets.clustering.examples-text') + }) + + test('Datasets: las series temporales se entrenan, se analizan y se descargan', async () => { + const { getByTestId, getByText, findByRole } = render() + expect(getByText('datasets.time-series.examples-title')).toBeInTheDocument() + for (const key of ['AIRLINE-PASSENGERS', 'MELBOURNE-TEMPERATURES', 'SUNSPOTS']) { + expect(getByTestId('Test-Dataset-' + key)).toHaveTextContent(`n4l-${key.toLowerCase()}:tasks.time-series.summary`) + expect(getByTestId('Test-DatasetTrain-' + key)).toHaveAttribute('href', '/playground/time-series/dataset/' + key) + expect(getByTestId('Test-DatasetModel-' + key)).toHaveAttribute('href', '/playground/time-series/model/' + key) + } + expect(getByTestId('Test-DatasetAnalyze-airline-passengers')).toHaveAttribute('href', '/analyze?dataset=airline-passengers') + // Sus filas son meses o días, y no tienen columnas de entrada: se predicen con sus valores anteriores + expect(getByTestId('Test-Dataset-AIRLINE-PASSENGERS')).toHaveTextContent('pages.menu.info.series.month, pages.menu.info.target') + expect(getByTestId('Test-Dataset-MELBOURNE-TEMPERATURES')).toHaveTextContent('pages.menu.info.series.day, pages.menu.info.target') + fireEvent.click(getByTestId('Test-DatasetInfo-SUNSPOTS')) + const dialog = await findByRole('dialog') + expect(within(dialog).getAllByRole('tab').map((tab) => tab.textContent)) + .toEqual(['datasets.dataset-details', 'datasets.variables.title', 'datasets.data.title', 'datasets.data.describe']) + }) + + test('Datasets: la pestaña de variables enseña las columnas del CSV', async () => { + const { getByTestId, findByRole, findByTestId } = render() + fireEvent.click(getByTestId('Test-DatasetInfo-datasets/hepatitis-c.csv')) + fireEvent.click(await findByRole('tab', { name: 'datasets.variables.title' })) + const table = await findByTestId('Test-DatasetVariables') + expect(table).toHaveTextContent('GGT') + expect(table).toHaveTextContent('datasets.variables.roles.Target') + }) + test('App with lazy load / Datasets', async () => { const { getByText, debug: _debug } = renderApp({ path: ['datasets'] }) await waitFor(() => expect(getByText(/datasets.title/i)).toBeInTheDocument()) diff --git a/tests/pages/Regression.test.tsx b/tests/pages/Regression.test.tsx index 25c3872..f916ac6 100644 --- a/tests/pages/Regression.test.tsx +++ b/tests/pages/Regression.test.tsx @@ -15,26 +15,19 @@ describe('Regression', () => { await waitFor(() => { expect(getByTestId('Test-InitialMenu')).toBeInTheDocument() }) - const Button_InitialMenu_Regression = getByTestId('Test-InitialMenu-LinearRegression') - await waitFor(() => fireEvent.click(Button_InitialMenu_Regression)) - - // Seleccionamos el botón de Modelos de Regresión lineal + // Seleccionamos el botón de Regresión y después el de sus modelos preentrenados + await waitFor(() => fireEvent.click(getByTestId('Test-InitialMenu-LinearRegression'))) const Button_GoTo_SelectModel_Regression = await waitFor(() => getByTestId('Test-GoTo-SelectModel-LinearRegression')) await waitFor(() => fireEvent.click(Button_GoTo_SelectModel_Regression)) - // Esperamos a que se cargue el menu de selección de modelos + // Esperamos a que se cargue la galería de modelos y abrimos AUTO_MPG await waitFor(() => getByTestId('Test-MenuSelectModel')) - - // Cambiamos el selector de los modelos a AUTO_MPG - const Select_SelectModel = await waitFor(() => getByTestId('Test-MenuSelectModel-Select')) - await waitFor(() => fireEvent.change(Select_SelectModel, { target: { value: 'AUTO_MPG' } })) - - // Cargamos la nueva página con el modelo de regresión lineal con el conjunto de datos de AUTO_MPG - const Button_Submit_GoTo_ModelReviewRegression = await waitFor(() => getByTestId('Test-MenuSelectModel-Submit')) - await waitFor(() => fireEvent.click(Button_Submit_GoTo_ModelReviewRegression)) + const Link_Open_AUTO_MPG = await waitFor(() => getByTestId('Test-MenuSelectModel-Open-AUTO_MPG')) + await waitFor(() => fireEvent.click(Link_Open_AUTO_MPG)) await waitFor(() => expect(getByTestId('Test-ModelReviewRegression')).toBeInTheDocument()) // debug_ModelReviewRegression() - }) + // Carga cuatro páginas perezosas seguidas: con todos los ficheros de tests en paralelo (en CI) pasaba de los 5 s + }, 30_000) }) diff --git a/tests/pages/Settings.test.tsx b/tests/pages/Settings.test.tsx new file mode 100644 index 0000000..cb2029c --- /dev/null +++ b/tests/pages/Settings.test.tsx @@ -0,0 +1,204 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest' +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import { MemoryRouter } from 'react-router' +import Settings from '@pages/settings/Settings' +import { resetAllSettings } from '@pages/settings/storedSettings' +import { getGuideSettings, resetGuideSettings, updateGuideSettings } from '@components/guide/guideSettings' +import { readConsent } from '@core/analytics' +import { isStepByStepEnabled, resetStepByStep } from '@components/neural-network/stepByStep/stepByStepSetting' + +// La voz del navegador, de mentira: jsdom no tiene speechSynthesis +class FakeUtterance { + text: string + constructor(text: string) { + this.text = text + } +} +const synth = { speak: vi.fn(), cancel: vi.fn(), getVoices: (): SpeechSynthesisVoice[] => [] } + +const section = (id: string) => within(screen.getByTestId('Test-Settings-' + id)) + +// El ancho de la pantalla: en las pantallas anchas, pestañas; en el móvil, la lista de apartados (jsdom no tiene matchMedia) +const setWide = (wide: boolean) => vi.stubGlobal('matchMedia', (query: string) => ({ + matches: wide && query.includes('min-width'), media: query, addEventListener: () => {}, removeEventListener: () => {}, +})) + +function renderSettings() { + render() +} + +describe('Settings', () => { + beforeEach(() => { + localStorage.clear() + resetGuideSettings() + document.cookie = 'n4l-accept-cookies=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/' + setWide(true) + vi.stubGlobal('speechSynthesis', synth) + vi.stubGlobal('SpeechSynthesisUtterance', FakeUtterance) + }) + afterEach(() => { + cleanup() + vi.unstubAllGlobals() + }) + + test('el tema: el elegido se recuerda y "como el sistema" lo olvida', () => { + renderSettings() + const select = section('appearance').getByLabelText('pages.settings.appearance.theme') + expect(select).toHaveValue('system') + + fireEvent.change(select, { target: { value: 'dark' } }) + expect(localStorage.getItem('theme')).toBe('dark') + expect(document.documentElement).toHaveAttribute('data-bs-theme', 'dark') + + fireEvent.change(select, { target: { value: 'system' } }) + expect(localStorage.getItem('theme')).toBeNull() + }) + + test('la voz de las guías: los mismos ajustes que usa la guía', () => { + renderSettings() + const speech = section('speech') + fireEvent.click(speech.getByLabelText('pages.settings.speech.auto')) + expect(getGuideSettings().auto).toBe(true) + fireEvent.change(speech.getByLabelText('pages.settings.speech.rate'), { target: { value: '1.5' } }) + expect(getGuideSettings().rate).toBe(1.5) + + // Y al revés: lo que cambia la guía se ve aquí + act(() => updateGuideSettings({ voice: false })) + expect(speech.getByLabelText('pages.settings.speech.voice')).not.toBeChecked() + expect(speech.getByTestId('Test-Settings-SpeechTest')).toBeDisabled() + }) + + test('las guías, también las de entrenamiento, vuelven a empezar desde el principio', () => { + localStorage.setItem('n4l-guide-progress.train.tabular-classification.CAR', JSON.stringify({ step: 5, open: false, savedAt: 1 })) + localStorage.setItem('n4l-guide-progress.regression.WINE', JSON.stringify({ step: 3, open: false, savedAt: 1 })) + renderSettings() + const tutorials = section('tutorials') + fireEvent.click(tutorials.getByText('pages.settings.tutorials.guides-reset')) + expect(Object.keys(localStorage).filter((key) => key.startsWith('n4l-guide-progress.'))).toEqual([]) + expect(tutorials.getByRole('status')).toHaveTextContent('pages.settings.tutorials.done') + }) + + test('Paso a paso está oculto por defecto y se activa desde aquí', () => { + resetStepByStep() + renderSettings() + const learning = section('learning') + const toggle = learning.getByLabelText('pages.settings.learning.step-by-step') + expect(toggle).not.toBeChecked() + fireEvent.click(toggle) + expect(isStepByStepEnabled()).toBe(true) + expect(toggle).toBeChecked() + }) + + test('las cookies se aceptan y se rechazan desde aquí', () => { + renderSettings() + const privacy = section('privacy') + expect(privacy.getByText('pages.settings.privacy.status-undecided')).toBeInTheDocument() + fireEvent.click(privacy.getByLabelText('pages.settings.privacy.analytics')) + expect(readConsent()).toBe('accepted') + fireEvent.click(privacy.getByLabelText('pages.settings.privacy.analytics')) + expect(readConsent()).toBe('rejected') + }) + + test('los apartados son pestañas verticales: la abierta sale de la dirección (#privacy) y al cambiarla se apunta', () => { + render() + const tablist = screen.getByRole('tablist', { name: 'pages.settings.sections' }) + expect(within(tablist).getAllByRole('tab')).toHaveLength(9) + expect(screen.getByRole('tab', { name: 'pages.settings.privacy.title' })).toHaveAttribute('aria-selected', 'true') + fireEvent.click(screen.getByRole('tab', { name: 'pages.settings.learning.title' })) + expect(screen.getByRole('tab', { name: 'pages.settings.learning.title' })).toHaveAttribute('aria-selected', 'true') + expect(screen.getByRole('tab', { name: 'pages.settings.privacy.title' })).toHaveAttribute('aria-selected', 'false') + }) + + test('en el móvil, la lista de apartados con su resumen; al tocar uno se abre solo y se vuelve a la lista', () => { + setWide(false) + render() + const list = screen.getByRole('navigation', { name: 'pages.settings.sections' }) + expect(within(list).getAllByRole('link')).toHaveLength(9) + expect(screen.queryByTestId('Test-Settings-appearance')).toBeNull() + fireEvent.click(screen.getByRole('link', { name: /pages\.settings\.privacy\.title/ })) + expect(screen.getByTestId('Test-Settings-privacy')).toBeInTheDocument() + expect(screen.queryByTestId('Test-Settings-List')).toBeNull() + fireEvent.click(screen.getByTestId('Test-Settings-Back')) + expect(screen.getByTestId('Test-Settings-List')).toBeInTheDocument() + }) + + test('sin un apartado en la dirección (o con uno que no existe), el primero', () => { + render() + expect(screen.getByRole('tab', { name: 'pages.settings.appearance.title' })).toHaveAttribute('aria-selected', 'true') + }) + + test('restablecer todo borra los ajustes de la aplicación y nada más', async () => { + localStorage.setItem('theme', 'dark') + localStorage.setItem('language', 'ja') + localStorage.setItem('tf-backend', 'wasm') + localStorage.setItem('n4l-guide-progress.regression.WINE', JSON.stringify({ step: 3, open: false, savedAt: 1 })) + localStorage.setItem('tabular-classification.joyride-CAR', '{}') + localStorage.setItem('n4l-step-by-step', 'true') + localStorage.setItem('n4l-download-warning', 'always') + localStorage.setItem('n4l-downloads-accepted', '["object-detection/COCO-SSD"]') + localStorage.setItem('n4l-learning-path', JSON.stringify({ started: true, done: ['train'] })) + localStorage.setItem('otra-web', 'no se toca') + updateGuideSettings({ auto: true }) + document.cookie = 'n4l-accept-cookies=true;path=/' + + await resetAllSettings() + expect(Object.keys(localStorage)).toEqual(['otra-web']) + expect(isStepByStepEnabled()).toBe(false) + expect(getGuideSettings().auto).toBe(false) + expect(readConsent()).toBeNull() + }) + + test('los datos guardados: los modelos descargados, cada uno con lo que ocupa, y borrarlos (preguntando antes)', async () => { + // Cache Storage de mentira, con FaceMesh descargado (3 MB) + const models = new Map([['https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/a.data', new Response('x', { headers: { 'content-length': String(3 * 1024 * 1024) } })]]) + vi.stubGlobal('caches', { + keys : async () => (models.size > 0 ? ['n4l-models-v1'] : []), + open : async () => ({ keys: async () => [...models.keys()].map((url) => new Request(url)), match: async (request: Request) => models.get(request.url) }), + delete: async () => models.clear(), + }) + render() + const row = within(await screen.findByTestId('Test-Settings-Stored-pretrained')) + // En total y en la lista, con un enlace a su página + expect(row.getAllByText('3 MB')).toHaveLength(2) + expect(row.getByRole('link', { name: 'datasets-models.2-object-detection.face-mesh.title' })) + .toHaveAttribute('href', '/playground/object-detection/model/FACE-MESH') + + fireEvent.click(row.getByRole('button', { name: 'pages.settings.data.pretrained.delete' })) + expect(row.getByText('pages.settings.data.pretrained.question')).toBeInTheDocument() + fireEvent.click(row.getByRole('button', { name: 'pages.settings.data.delete-confirm' })) + await act(async () => {}) + expect(models.size).toBe(0) + expect(row.queryByText('3 MB')).toBeNull() + expect(row.queryByRole('link')).toBeNull() + expect(row.queryByRole('button')).toBeNull() + }) + + test('los datos guardados: borrar un modelo descargado deja los demás', async () => { + const megas = (count: number) => new Response('x', { headers: { 'content-length': String(count * 1024 * 1024) } }) + // FaceMesh (3 MB, en dos ficheros) y COCO-SSD (2 MB) + const models = new Map([ + ['https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/a.data', megas(2)], + ['https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/b.wasm', megas(1)], + ['https://storage.googleapis.com/tfjs-models/savedmodel/ssdlite_mobilenet_v2/model.json', megas(2)], + ]) + vi.stubGlobal('caches', { + keys: async () => (models.size > 0 ? ['n4l-models-v1'] : []), + open: async () => ({ + keys : async () => [...models.keys()].map((url) => new Request(url)), + match : async (request: Request) => models.get(request.url), + delete: async (request: Request) => models.delete(request.url), + }), + }) + render() + const list = within(await screen.findByTestId('Test-Settings-SavedModels')) + const faceMesh = within(list.getByRole('link', { name: 'datasets-models.2-object-detection.face-mesh.title' }).closest('li')!) + fireEvent.click(faceMesh.getByRole('button', { name: 'pages.settings.data.pretrained.delete-one' })) + expect(faceMesh.getByText('pages.settings.data.pretrained.question-one')).toBeInTheDocument() + fireEvent.click(faceMesh.getByRole('button', { name: 'pages.settings.data.delete-confirm' })) + await act(async () => {}) + expect([...models.keys()]).toEqual(['https://storage.googleapis.com/tfjs-models/savedmodel/ssdlite_mobilenet_v2/model.json']) + const rest = within(screen.getByTestId('Test-Settings-SavedModels')) + expect(rest.queryByRole('link', { name: 'datasets-models.2-object-detection.face-mesh.title' })).toBeNull() + expect(rest.getByRole('link', { name: 'datasets-models.2-object-detection.coco-ssd.title' })).toBeInTheDocument() + }) +}) diff --git a/tests/pages/Task.test.tsx b/tests/pages/Task.test.tsx new file mode 100644 index 0000000..b2e5cd2 --- /dev/null +++ b/tests/pages/Task.test.tsx @@ -0,0 +1,66 @@ +import { describe, test, expect } from 'vitest' +import { render, within } from '@testing-library/react' +import { MemoryRouter, Route, Routes } from 'react-router' + +import Task from '@pages/task/Task' + +const renderTask = (task: string) => render( + + + } /> + 404

    } /> +
    +
    , +) + +describe('Página de una tarea (/task/)', () => { + test('elige entre los modelos ya entrenados y diseñar una red; cada modelo o conjunto se abre desde aquí', () => { + const { getByTestId, queryByText } = renderTask('regression') + expect(getByTestId('Test-Breadcrumb')).toHaveTextContent('pages.index.regression.1-title') + + const pretrained = within(getByTestId('Test-Task-Pretrained')) + expect(pretrained.getByText('pages.task.pretrained-title')).toBeInTheDocument() + expect(pretrained.getByTestId('Test-Task-Choose-model')).toHaveAttribute('href', '/select-model/regression') + expect(pretrained.getAllByRole('link').map((link) => link.getAttribute('href'))).toContain('/playground/regression/model/AUTO_MPG') + + const design = within(getByTestId('Test-Task-Design')) + expect(design.getByText('pages.task.design-title')).toBeInTheDocument() + expect(design.getByTestId('Test-Task-Choose-dataset')).toHaveAttribute('href', '/select-dataset/regression') + // Los conjuntos de ejemplo y subir uno propio + const hrefs = design.getAllByRole('link').map((link) => link.getAttribute('href')) + expect(hrefs).toEqual(expect.arrayContaining(['/playground/regression/dataset/SALARY', '/playground/regression/dataset/UPLOAD'])) + expect(queryByText('pages.task.only-pretrained')).toBeNull() + }) + + test('identificación de objetos solo tiene modelos ya entrenados, y se dice', () => { + const { getByTestId, queryByTestId, getByText } = renderTask('object-detection') + expect(getByTestId('Test-Task-Pretrained')).toBeInTheDocument() + expect(queryByTestId('Test-Task-Design')).toBeNull() + expect(getByText('pages.task.only-pretrained')).toBeInTheDocument() + }) + + test('el agrupamiento solo tiene conjuntos de datos (sin red): se agrupan', () => { + const { getByTestId, queryByTestId, getByText } = renderTask('clustering') + expect(queryByTestId('Test-Task-Pretrained')).toBeNull() + expect(within(getByTestId('Test-Task-Design')).getByText('pages.task.cluster-title')).toBeInTheDocument() + expect(getByText('pages.task.only-cluster')).toBeInTheDocument() + }) + + test('una tarea que no existe lleva a la página 404', () => { + const { getByText } = renderTask('no-existe') + expect(getByText('404')).toBeInTheDocument() + }) + + test('las series temporales: sus modelos ya entrenados y entrenar con una serie de ejemplo o con una propia', () => { + const { getByTestId } = renderTask('time-series') + expect(within(getByTestId('Test-Task-Pretrained')).getAllByRole('link').map((link) => link.getAttribute('href'))) + .toContain('/playground/time-series/model/MELBOURNE-TEMPERATURES') + const hrefs = within(getByTestId('Test-Task-Design')).getAllByRole('link').map((link) => link.getAttribute('href')) + expect(hrefs).toEqual(expect.arrayContaining([ + '/playground/time-series/dataset/AIRLINE-PASSENGERS', + '/playground/time-series/dataset/SUNSPOTS', + '/playground/time-series/dataset/UPLOAD', + '/select-dataset/time-series', + ])) + }) +}) diff --git a/tests/pages/TimeSeries.test.tsx b/tests/pages/TimeSeries.test.tsx new file mode 100644 index 0000000..11b7b73 --- /dev/null +++ b/tests/pages/TimeSeries.test.tsx @@ -0,0 +1,62 @@ +import { describe, test, expect, beforeEach, afterEach, vi } from 'vitest' +import { fireEvent, render, within } from '@testing-library/react' +import { MemoryRouter } from 'react-router' + +import TimeSeries from '@pages/playground/5_TimeSeries/TimeSeries' +import { stubPublicFetch } from '../helpers/n4l' + +// jsdom no dibuja en un canvas: las gráficas, con lo que describen para quien no las ve +vi.mock('react-chartjs-2', () => ({ + Line: ({ 'aria-label': label }: { 'aria-label': string }) =>
    , +})) + +const prefix = 'pages.playground.time-series.' + +const renderPage = (dataset: string, search = '') => render( + + + , +) + +describe('Series temporales (/playground/time-series/dataset/…)', () => { + beforeEach(() => { stubPublicFetch() }) + afterEach(() => { vi.unstubAllGlobals() }) + + test('la serie del paquete con su preparación: las primeras ventanas, y sin datos suficientes no se entrena', async () => { + const { findByTestId, getByTestId, getByLabelText, queryByTestId } = renderPage('AIRLINE-PASSENGERS') + expect(await findByTestId('Test-TimeSeries-Summary', {}, { timeout: 5000 })).toHaveTextContent(prefix + 'frequency.month') + // La del manifiesto: ventana de 24, estación de 12 y un 20 % de prueba + expect(getByLabelText(prefix + 'prep.window')).toHaveValue(24) + expect(getByLabelText(prefix + 'prep.season')).toHaveValue(12) + const rows = within(getByTestId('Test-TimeSeries-Windows')).getAllByRole('row') as HTMLTableRowElement[] + expect(rows.slice(1).map((row) => row.cells[0].textContent)).toEqual(['1951-01', '1951-02', '1951-03']) + expect(rows[1].cells[2]).toHaveTextContent('145') + // La red del manifiesto: Dense de 32 y la salida + expect(getByTestId('Test-TrainButton')).toBeEnabled() + + fireEvent.change(getByLabelText(prefix + 'prep.window'), { target: { value: '120' } }) + expect(getByTestId('Test-TimeSeries-TooShort')).toBeInTheDocument() + expect(queryByTestId('Test-TimeSeries-Windows')).toBeNull() + expect(getByTestId('Test-TrainButton')).toBeDisabled() + }) + + test('al diferenciar, la red ve los cambios: el primer ejemplo empieza un valor después', async () => { + const { findByTestId, getByTestId, getByLabelText } = renderPage('AIRLINE-PASSENGERS') + await findByTestId('Test-TimeSeries-Windows', {}, { timeout: 5000 }) + fireEvent.click(getByLabelText(prefix + 'prep.difference')) + const rows = within(getByTestId('Test-TimeSeries-Windows')).getAllByRole('row') as HTMLTableRowElement[] + expect(rows[1].cells[0]).toHaveTextContent('1951-02') + // Marzo de 1951 (178) menos febrero (150) + expect(rows[2].cells[2]).toHaveTextContent('+28') + }) + + test('una serie propia: desde /datasets (?dataset=…) se carga con su columna de valores y la de fechas', async () => { + const { findByLabelText, getByTestId } = renderPage('UPLOAD', '?dataset=daily-min-temperatures') + expect(getByTestId('Test-TimeSeries-Upload')).toBeInTheDocument() + expect(await findByLabelText(prefix + 'upload.value-column', {}, { timeout: 5000 })).toHaveValue('Temp') + expect(await findByLabelText(prefix + 'upload.date-column')).toHaveValue('Date') + // Cada día: la estación por defecto es una semana + expect(await findByLabelText(prefix + 'prep.season')).toHaveValue(7) + expect(getByTestId('Test-TimeSeries-Summary')).toHaveTextContent(prefix + 'frequency.day') + }) +}) diff --git a/tests/pages/WebcamDeviceInfo.test.tsx b/tests/pages/WebcamDeviceInfo.test.tsx new file mode 100644 index 0000000..c5799bb --- /dev/null +++ b/tests/pages/WebcamDeviceInfo.test.tsx @@ -0,0 +1,133 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest' +import { act, render, screen, within } from '@testing-library/react' +import WebcamDeviceInfo, { type DetectionStats_t } from '@pages/playground/2_ObjectDetection/WebcamDeviceInfo' + +// Sin GPU ni navegador de verdad: lo que leen de ellos /debug y TF.js, fijo (Firefox, que no tiene userAgentData) +vi.mock('@pages/debug/diagnostics/collectDiagnostics', () => ({ + probeSystem: async () => ({ + userAgent : 'Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0', + brands : null, + platform : 'Linux x86_64', + mobile : null, + architecture : null, + platformVersion : null, + cores : 8, + memoryGB : null, + devicePixelRatio : 1, + screen : '1920×1080', + language : 'es-ES', + secureContext : true, + crossOriginIsolated: false, + }), + probeWebGL: () => ({ + webgl2 : true, + renderer : 'WebKit WebGL', + unmaskedRenderer: 'NVIDIA GeForce GTX 980', + software : false, + }), +})) +vi.mock('@tensorflow/tfjs', () => ({ + getBackend: () => 'webgl', + memory : () => ({ numTensors: 12, numBytes: 3 * 1024 * 1024 }), +})) + +const prefix = 'datasets-models.2-object-detection.interface.device-info.' + +const DEVICES = [ + { deviceId: 'camara-portatil-123456', label: 'Integrated Camera', kind: 'videoinput', groupId: 'g1' }, + { deviceId: 'camara-usb', label: '', kind: 'videoinput', groupId: 'g2' }, +] as MediaDeviceInfo[] + +// Un vídeo con la cámara del portátil emitiendo (lo que se lee de él) +const video = { + videoWidth : 1280, + videoHeight : 720, + clientWidth : 640, + clientHeight: 360, + srcObject : { + getVideoTracks: () => [{ + label : 'Integrated Camera', + readyState : 'live', + getSettings : () => ({ width: 1280, height: 720, frameRate: 30, facingMode: 'user', deviceId: 'camara-portatil-123456' }), + getCapabilities: () => ({ width: { min: 1, max: 1920 }, facingMode: ['user'], deviceId: 'camara-portatil-123456' }), + }], + }, +} as unknown as HTMLVideoElement + +function renderInfo(getVideo: () => HTMLVideoElement | null, stats: DetectionStats_t = { predictions: 0, totalMs: 0 }) { + render() +} + +// El valor de un dato: el
    que sigue a su
    +const valueOf = (label: string) => screen.getByText(label).nextElementSibling?.textContent + +// Como en el navegador: se abre y jsdom avisa (toggle) en una tarea aparte +async function open() { + const details = screen.getByTestId('Test-WebcamDeviceInfo') as HTMLDetailsElement + await act(async () => { + details.open = true + await vi.advanceTimersByTimeAsync(0) + }) +} + +describe('WebcamDeviceInfo', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + afterEach(() => { + vi.useRealTimers() + }) + + test('cerrada no lee nada; al abrirla, con la cámara apagada, lo dice y enseña el resto', async () => { + const getVideo = vi.fn(() => null) + renderInfo(getVideo) + expect(getVideo).not.toHaveBeenCalled() + + await open() + expect(screen.getAllByText(prefix + 'camera-off')).toHaveLength(2) + expect(valueOf(prefix + 'model')).toBe('COCO SSD') + expect(valueOf(prefix + 'backend')).toBe('webgl') + expect(valueOf(prefix + 'predictions')).toBe('—') + // Firefox no tiene userAgentData: el navegador sale del user agent + expect(valueOf(prefix + 'browser-name')).toBe('Firefox 153') + expect(valueOf(prefix + 'gpu')).toBe('NVIDIA GeForce GTX 980') + // Las cámaras, también la que no tiene nombre (sin permiso los navegadores no lo dan) + expect(screen.getByText('Integrated Camera')).toBeInTheDocument() + expect(screen.getByText(prefix + 'unnamed')).toBeInTheDocument() + expect(screen.queryByText(prefix + 'in-use')).not.toBeInTheDocument() + }) + + test('con la cámara encendida, sus datos y capacidades, la que está en uso y cómo va la detección', async () => { + const stats = { predictions: 0, totalMs: 0 } + renderInfo(() => video, stats) + await open() + + expect(valueOf(prefix + 'name')).toBe('Integrated Camera') + expect(valueOf(prefix + 'resolution')).toMatch(/1,?280 × 720/) + expect(valueOf(prefix + 'aspect')).toMatch(/^16:9/) + expect(valueOf(prefix + 'facing')).toBe(prefix + 'facing-user') + expect(valueOf(prefix + 'state')).toBe(prefix + 'state-live') + // Capacidades: los rangos como mínimo – máximo, sin los identificadores + expect(within(screen.getByText('width').closest('dl')!).getByText('facingMode')).toBeInTheDocument() + expect(screen.getByText('width').closest('dt')?.nextElementSibling?.textContent).toMatch(/^1 – 1,?920$/) + expect(screen.queryByText('deviceId')).not.toBeInTheDocument() + // La cámara del vídeo es la que está en uso + expect(screen.getByText(prefix + 'in-use').closest('dt')).toHaveTextContent('Integrated Camera') + + // Un segundo después, 10 predicciones de 50 ms + stats.predictions = 10 + stats.totalMs = 500 + await act(async () => { + vi.advanceTimersByTime(1000) + }) + expect(valueOf(prefix + 'prediction-time')).toBe('50 ms') + expect(valueOf(prefix + 'predictions')).not.toBe('—') + }) +}) diff --git a/tests/pages/analyzeProjectDatasets.test.ts b/tests/pages/analyzeProjectDatasets.test.ts new file mode 100644 index 0000000..4b13532 --- /dev/null +++ b/tests/pages/analyzeProjectDatasets.test.ts @@ -0,0 +1,48 @@ +import { describe, test, expect } from 'vitest' +import * as fs from 'fs' + +import { PROJECT_DATASETS, datasetKey, datasetVariables, defaultTarget, fileName, projectDatasetByKey, taskDatasetFiles } from '@pages/analyze/projectDatasets' + +describe('Conjuntos de datos de /analyze', () => { + + test('cada CSV tiene su clave para la dirección (/analyze?dataset=…) y no se repiten', () => { + const keys = PROJECT_DATASETS.map(({ file }) => datasetKey(file)) + expect(new Set(keys).size).toBe(keys.length) + expect(datasetKey('n4l/iris.n4l/data/iris.csv')).toBe('iris') + expect(projectDatasetByKey('iris')?.file).toBe('n4l/iris.n4l/data/iris.csv') + expect(projectDatasetByKey('no-existe')).toBeUndefined() + expect(projectDatasetByKey(null)).toBeUndefined() + }) + + test('los CSV de cada tarea: un mismo fichero puede ser de varias (el vino se clasifica y se agrupa)', () => { + expect(taskDatasetFiles('clustering')).toEqual(expect.arrayContaining(['n4l/wine.n4l/data/wine.csv', 'n4l/breast-cancer.n4l/data/wdbc.csv'])) + expect(taskDatasetFiles('tabular-classification')).toContain('n4l/wine.n4l/data/wine.csv') + expect(taskDatasetFiles('regression')).not.toContain('n4l/wine.n4l/data/wine.csv') + // Todos son del proyecto: se pueden pedir por su clave (/datasets → ?dataset=…) + for (const file of taskDatasetFiles('clustering')) expect(projectDatasetByKey(datasetKey(file))?.file, file).toBe(file) + }) + + test('todos los CSV existen en public/ y no se repiten', () => { + const files = PROJECT_DATASETS.map(({ file }) => file) + expect(new Set(files).size).toBe(files.length) + for (const file of files) expect(fs.existsSync('public/' + file), file).toBe(true) + }) + + test('cada CSV tiene su ficha de variables, con las mismas columnas y un objetivo', () => { + for (const { file } of PROJECT_DATASETS) { + const variables = datasetVariables(file) + expect(variables, file).toBeDefined() + const header = fs.readFileSync('public/' + file, 'utf8').split(/\r?\n/)[0].split(',').map((name) => name.replace(/^"|"$/g, '').trim()) + expect(variables!.map(({ name }) => name), file).toEqual(header) + expect(variables!.some(({ role }) => role === 'Target'), file).toBe(true) + } + }) + + test('el objetivo por defecto es el de la ficha y, sin ficha, la última columna', () => { + // En california-housing el objetivo no es la última: así se ve que no se toma la última sin más + expect(defaultTarget(['class', 'a', 'b'], [{ name: 'class', role: 'Target', type: 'Categorical', missing: 0 }])).toBe('class') + expect(defaultTarget(['a', 'b'])).toBe('b') + expect(defaultTarget([])).toBeNull() + expect(fileName('n4l/auto-mpg.n4l/data/auto-mpg.csv')).toBe('auto-mpg.csv') + }) +}) diff --git a/tests/pages/cocoSsdFaceApi.test.ts b/tests/pages/cocoSsdFaceApi.test.ts new file mode 100644 index 0000000..beee6c8 --- /dev/null +++ b/tests/pages/cocoSsdFaceApi.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, test } from 'vitest' +import type { TFunction } from 'i18next' +import type * as coCoSsdDetection from '@tensorflow-models/coco-ssd' + +import MODEL_4_COCO_SSD from '@pages/playground/2_ObjectDetection/models/MODEL_4_COCO_SSD' +import MODEL_5_FACE_API from '@pages/playground/2_ObjectDetection/models/MODEL_5_FACE_API' + +// t con la clave y sus valores, para ver qué se escribe +const t = ((key: string, values?: Record) => { + const shown = Object.entries(values ?? {}).filter(([name]) => name !== 'defaultValue').map(([, value]) => value) + return shown.length > 0 ? `${key.split('.').at(-1)}:${shown.join(',')}` : key.split('.').at(-1) +}) as unknown as TFunction + +/** Un lienzo de 640 × 480 que no dibuja: guarda cada texto escrito, dónde y el color de lo último rellenado */ +function recordingContext() { + const texts: Array<{ text: string, x: number, y: number }> = [] + const fills: string[] = [] + const state: Record = { canvas: { width: 640, height: 480 } } + const ctx = new Proxy(state, { + get: (target, property) => { + if (property in target) return target[property] + if (property === 'measureText') return (text: string) => ({ width: text.length * 6 }) + if (property === 'fillText') return (text: string, x: number, y: number) => texts.push({ text, x, y }) + if (property === 'fill') return () => fills.push(String(target.fillStyle)) + return () => undefined + }, + set: (target, property, value) => { + target[property] = value + return true + }, + }) as unknown as CanvasRenderingContext2D + return { ctx, texts, fills } +} + +const object = (name: string, x: number, score = 0.9): coCoSsdDetection.DetectedObject => + ({ class: name, score, bbox: [x, 100, 80, 160] }) + +describe('MODEL_4_COCO_SSD: cada objeto con su nombre y su confianza', () => { + test('los de la misma clase, numerados de izquierda a derecha y del mismo color; los demás, sin número', () => { + const model = new MODEL_4_COCO_SSD(t as never) + const { ctx, texts, fills } = recordingContext() + model.RENDER(ctx, [object('person', 400, 0.8), object('dog', 250), object('person', 50, 0.95)]) + const tags = texts.map(({ text }) => text) + expect(tags).toEqual(expect.arrayContaining(['numbered:person,1', 'numbered:person,2', 'dog', 'score:95', 'score:80'])) + // La persona de la izquierda (x = 50) es la 1 + const first = texts.find(({ text }) => text === 'numbered:person,1') + expect(first?.x).toBeLessThan(200) + // Dos colores: uno para las personas y otro para el perro + expect(new Set(fills.filter((fill) => fill.startsWith('#'))).size).toBe(2) + }) + + test('con la webcam en espejo, los recuadros se reflejan', async () => { + const model = new MODEL_4_COCO_SSD(t as never) + model._modelDetector = { detect: async () => [object('cup', 100)] } as never + const video = { videoWidth: 640 } as HTMLVideoElement + const [plain] = await model.PREDICTION(video) + const [mirrored] = await model.PREDICTION(video, { flipHorizontal: true }) + expect(plain.bbox).toEqual([100, 100, 80, 160]) + expect(mirrored.bbox).toEqual([460, 100, 80, 160]) + }) +}) + +const face = (x: number, width: number, expressions: Record) => ({ + detection: { score: 0.99, box: { x, y: 120, width, height: width } }, + age : 33.6, + expressions, +}) + +describe('MODEL_5_FACE_API: cada cara con su edad y sus expresiones', () => { + const EXPRESSIONS = ['neutral', 'happy', 'sad', 'angry', 'fearful', 'disgusted', 'surprised'] + const expressions = { neutral: 0.2, happy: 0.7, sad: 0.05, angry: 0.05, fearful: 0, disgusted: 0, surprised: 0 } + + test('su edad y, a la derecha de la cara, las siete expresiones con su porcentaje, siempre en el mismo orden', () => { + const model = new MODEL_5_FACE_API(t as never) + const { ctx, texts } = recordingContext() + model.RENDER(ctx, [face(200, 200, expressions)]) + const written = texts.map(({ text }) => text) + expect(written).toEqual(expect.arrayContaining(['face', 'age:34'])) + expect(written.filter((text) => EXPRESSIONS.includes(text))).toEqual(EXPRESSIONS) + expect(written.filter((text) => text.startsWith('percent:'))).toEqual(['percent:20', 'percent:70', 'percent:5', 'percent:5', 'percent:0', 'percent:0', 'percent:0']) + expect(texts.filter(({ text }) => EXPRESSIONS.includes(text)).every(({ x }) => x > 400)).toBe(true) + }) + + test('una cara pequeña: también las siete, a su derecha', () => { + const model = new MODEL_5_FACE_API(t as never) + const { ctx, texts } = recordingContext() + model.RENDER(ctx, [face(300, 60, expressions)]) + const names = texts.filter(({ text }) => EXPRESSIONS.includes(text)) + expect(names).toHaveLength(7) + expect(names.every(({ x }) => x > 360)).toBe(true) + }) + + test('una cara en el borde derecho: el panel, pegado al borde, sin salirse del dibujo', () => { + const model = new MODEL_5_FACE_API(t as never) + const { ctx, texts } = recordingContext() + model.RENDER(ctx, [face(500, 130, expressions)]) + const percents = texts.filter(({ text }) => text.startsWith('percent:')) + expect(percents).toHaveLength(7) + expect(percents.every(({ x }) => x <= 640)).toBe(true) + }) + + test('varias caras: numeradas', () => { + const model = new MODEL_5_FACE_API(t as never) + const { ctx, texts } = recordingContext() + model.RENDER(ctx, [face(20, 80, expressions), face(400, 80, expressions)]) + expect(texts.map(({ text }) => text).filter((text) => text.startsWith('face'))).toEqual(['face-number:1', 'face-number:2']) + }) +}) diff --git a/tests/pages/debugDiagnostics.test.ts b/tests/pages/debugDiagnostics.test.ts new file mode 100644 index 0000000..4af8739 --- /dev/null +++ b/tests/pages/debugDiagnostics.test.ts @@ -0,0 +1,232 @@ +import { describe, test, expect } from 'vitest' +import { + classifyStatus, + findGraphicsFeature, + GRAPHICS_FEATURES, + parseGraphicsFeatureStatus, +} from '../../src/pages/debug/diagnostics/graphicsFeatureStatus' +import { + buildRecommendations, + describeWebGLRenderer, + type Diagnostics_t, + type WebGPUAdapterInfo_t, +} from '../../src/pages/debug/diagnostics/collectDiagnostics' +import { median } from '../../src/pages/debug/diagnostics/benchmarkBackends' + +// Sección copiada de chrome://gpu (Chrome 152, Linux con NVIDIA) +const GPU_STATUS = `Graphics Feature Status +======================= +* Canvas: Hardware accelerated +* Direct Rendering Display Compositor: Disabled +* Compositing: Hardware accelerated +* Multiple Raster Threads: Enabled +* OpenGL: Enabled +* Rasterization: Hardware accelerated +* Raw Draw: Disabled +* Skia Graphite: Disabled +* TreesInViz: Disabled +* Video Decode: Hardware accelerated +* Video Encode: Software only. Hardware acceleration disabled +* Vulkan: Enabled +* WebGL: Hardware accelerated +* WebGPU: Hardware accelerated +* WebGPU interop: Disabled +* WebNN: Disabled` + +describe('parseGraphicsFeatureStatus', () => { + + test('lee todas las líneas de la sección y reconoce cada una', () => { + const parsed = parseGraphicsFeatureStatus(GPU_STATUS) + expect(parsed).toHaveLength(16) + expect(parsed.find((p) => p.name === 'WebGL')).toMatchObject({ status: 'Hardware accelerated', statusClass: 'hardware' }) + expect(parsed.find((p) => p.name === 'Video Encode')).toMatchObject({ statusClass: 'software' }) + // Todas las líneas que da este Chrome tienen descripción + expect(parsed.filter((p) => p.feature === undefined)).toEqual([]) + }) + + test('del informe entero se queda solo con la sección "Graphics Feature Status"', () => { + const report = 'Graphics Feature Status\n=======================\n* WebGL: Hardware accelerated\n* WebGPU: Disabled\n\n' + + 'Problems Detected\n=================\n* Accelerated video encode has been disabled: Disabled Features: video_encode\n\n' + + 'Version Information\nData exported: 2026-10-01T12:00:00.000Z\nChrome version: Chrome/152.0.7977.82' + expect(parseGraphicsFeatureStatus(report).map((p) => p.name)).toEqual(['WebGL', 'WebGPU']) + }) + + test('también vale pegar solo las líneas, con o sin viñetas', () => { + expect(parseGraphicsFeatureStatus('WebGL: Hardware accelerated\n• WebGPU: Unavailable').map((p) => [p.name, p.statusClass])) + .toEqual([['WebGL', 'hardware'], ['WebGPU', 'unavailable']]) + }) + + test('las líneas desconocidas se leen sin descripción', () => { + expect(parseGraphicsFeatureStatus('* Future Thing: Enabled')).toEqual([ + { name: 'Future Thing', status: 'Enabled', statusClass: 'enabled', feature: undefined }, + ]) + }) +}) + +describe('classifyStatus y findGraphicsFeature', () => { + + test('clasifica los estados de chrome://gpu', () => { + expect(classifyStatus('Hardware accelerated')).toBe('hardware') + expect(classifyStatus('Hardware accelerated but at reduced performance')).toBe('reduced') + expect(classifyStatus('Software only, hardware acceleration unavailable')).toBe('software') + expect(classifyStatus('Software only. Hardware acceleration disabled')).toBe('software') + expect(classifyStatus('Enabled')).toBe('enabled') + expect(classifyStatus('Disabled')).toBe('disabled') + expect(classifyStatus('Unavailable')).toBe('unavailable') + expect(classifyStatus('Something new')).toBe('unknown') + }) + + test('encuentra las líneas por su nombre o por los otros nombres que tienen en otras versiones', () => { + expect(findGraphicsFeature('webgl2')?.name).toBe('WebGL2') + expect(findGraphicsFeature('WebGL 2')?.name).toBe('WebGL2') + expect(findGraphicsFeature('OOP Rasterization')?.name).toBe('Out-of-process Rasterization') + expect(findGraphicsFeature('Nope')).toBeUndefined() + }) + + test('los nombres no se repiten', () => { + const names = GRAPHICS_FEATURES.flatMap((f) => [f.name, ...(f.aliases ?? [])].map((n) => n.toLowerCase())) + expect(new Set(names).size).toBe(names.length) + }) +}) + +describe('describeWebGLRenderer', () => { + + test('saca la API gráfica de ANGLE', () => { + expect(describeWebGLRenderer('ANGLE (NVIDIA, Vulkan 1.4.312 (NVIDIA NVIDIA GeForce RTX 5070 (0x00002F04)), NVIDIA)')) + .toEqual({ angleBackend: 'Vulkan', software: false }) + expect(describeWebGLRenderer('ANGLE (NVIDIA Corporation, NVIDIA GeForce RTX 5070/PCIe/SSE2, OpenGL 4.5.0 NVIDIA 580.178.04)')) + .toEqual({ angleBackend: 'OpenGL', software: false }) + expect(describeWebGLRenderer('ANGLE (Intel, Intel(R) UHD Graphics 620 Direct3D11 vs_5_0 ps_5_0, D3D11)').angleBackend).toBe('Direct3D 11') + expect(describeWebGLRenderer('ANGLE (Apple, ANGLE Metal Renderer: Apple M2, Unspecified Version)').angleBackend).toBe('Metal') + }) + + test('reconoce los renderizadores por software', () => { + expect(describeWebGLRenderer('ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)')) + .toEqual({ angleBackend: 'Vulkan', software: true }) + expect(describeWebGLRenderer('llvmpipe (LLVM 20.1.2, 256 bits)')).toEqual({ angleBackend: null, software: true }) + expect(describeWebGLRenderer('NVIDIA GeForce GTX 980, or similar')).toEqual({ angleBackend: null, software: false }) + }) +}) + +const NVIDIA: WebGPUAdapterInfo_t = { vendor: 'nvidia', architecture: 'blackwell', device: '', description: '', fallback: false, features: [], limits: {} } +const AMD: WebGPUAdapterInfo_t = { ...NVIDIA, vendor: 'amd', architecture: 'rdna-2' } +const SWIFTSHADER: WebGPUAdapterInfo_t = { ...NVIDIA, vendor: 'google', architecture: 'swiftshader', fallback: true } + +type Overrides_t = { [K in 'system' | 'webgl' | 'webgpu' | 'wasm' | 'tfjs']?: Partial } + +/** Un navegador sin problemas: WebGL en la GPU, WebGPU con la NVIDIA, WASM con hilos */ +function makeDiagnostics(overrides: Overrides_t = {}): Diagnostics_t { + const base: Diagnostics_t = { + collectedAt: '2026-10-01T00:00:00.000Z', + system : { + userAgent : '', + brands : null, + platform : 'Linux', + mobile : false, + architecture : null, + platformVersion : null, + cores : 32, + memoryGB : 8, + devicePixelRatio : 1, + screen : '1920×1080', + language : 'es', + secureContext : true, + crossOriginIsolated: true, + }, + apis : [], + webgl: { + webgl1 : true, + webgl2 : true, + vendor : 'WebKit', + renderer : 'WebKit WebGL', + unmaskedVendor : 'Google Inc. (NVIDIA)', + unmaskedRenderer : 'ANGLE (NVIDIA, Vulkan 1.4.312 (NVIDIA GeForce RTX 5070), NVIDIA)', + version : 'WebGL 2.0', + shadingLanguageVersion: null, + angleBackend : 'Vulkan', + software : false, + majorPerformanceCaveat: false, + maxTextureSize : 16384, + maxRenderbufferSize : 16384, + floatColorBuffer : true, + extensions : [], + }, + webgpu: { api: true, highPerformance: NVIDIA, lowPower: NVIDIA, preferredCanvasFormat: 'bgra8unorm', wgslLanguageFeatures: [] }, + wasm : { supported: true, simd: true, threads: true, sharedArrayBuffer: true, threadsUsable: true, binaryInUse: null, threadsCount: null }, + media : { decode: [], encode: [], cameras: 1, cameraPermission: 'prompt' }, + tfjs : { + version : '4.22.0', + appBackend : 'webgl', + savedBackend : null, + defaultBackend : 'webgl', + activeBackend : 'webgl', + registered : ['webgl', 'cpu'], + initialized : ['webgl'], + menuAvailability: { webgl: true, webgpu: true, wasm: true, cpu: true }, + numTensors : 0, + numBytes : 0, + numBytesInGPU : 0, + webgpuAdapter : null, + flags : {}, + }, + } + return { + ...base, + system: { ...base.system, ...overrides.system }, + webgl : { ...base.webgl, ...overrides.webgl }, + webgpu: { ...base.webgpu, ...overrides.webgpu }, + wasm : { ...base.wasm, ...overrides.wasm }, + tfjs : { ...base.tfjs, ...overrides.tfjs }, + } +} + +const levels = (d: Diagnostics_t) => buildRecommendations(d).map((r) => r.level) +const texts = (d: Diagnostics_t) => buildRecommendations(d).map((r) => r.text).join('\n') + +describe('buildRecommendations', () => { + + test('sin problemas solo hay mensajes buenos', () => { + expect(levels(makeDiagnostics())).toEqual(['success', 'success']) + }) + + test('WebGPU con SwiftShader avisa y explica cómo usar la GPU en Linux', () => { + const d = makeDiagnostics({ webgpu: { highPerformance: SWIFTSHADER, lowPower: SWIFTSHADER } }) + expect(levels(d)).toContain('warning') + expect(texts(d)).toMatch(/SwiftShader/) + expect(texts(d)).toMatch(/#enable-vulkan/) + }) + + test('navigator.gpu sin adaptador', () => { + expect(texts(makeDiagnostics({ webgpu: { highPerformance: null, lowPower: null } }))).toMatch(/no adapter/) + }) + + test('dos GPU distintas: dice cuál usa TF.js', () => { + expect(texts(makeDiagnostics({ webgpu: { lowPower: AMD } }))).toMatch(/two GPUs.*nvidia.*amd/s) + }) + + test('WebGL por software es grave', () => { + const d = makeDiagnostics({ webgl: { software: true, unmaskedRenderer: 'ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device), SwiftShader driver)' } }) + expect(buildRecommendations(d)[0]).toMatchObject({ level: 'danger' }) + }) + + test('WASM sin aislamiento de origen cruzado corre en un hilo', () => { + expect(texts(makeDiagnostics({ wasm: { threadsUsable: false } }))).toMatch(/single thread.*Cross-Origin-Opener-Policy/s) + }) + + test('TF.js con otro backend que el del menú, y un guardado que no se pudo usar', () => { + const d = makeDiagnostics({ tfjs: { appBackend: 'webgl', activeBackend: 'webgpu', savedBackend: 'wasm' } }) + expect(texts(d)).toMatch(/running on "webgpu" but the backend menu says "webgl"/) + expect(texts(d)).toMatch(/saved choice is "wasm"/) + }) + + test('sin contexto seguro no hay WebGPU ni cámara', () => { + expect(buildRecommendations(makeDiagnostics({ system: { secureContext: false } }))[0]).toMatchObject({ level: 'danger' }) + }) +}) + +describe('median', () => { + test('impar, par y desordenado', () => { + expect(median([3, 1, 2])).toBe(2) + expect(median([4, 1, 3, 2])).toBe(2.5) + }) +}) diff --git a/tests/pages/detectionSummary.test.ts b/tests/pages/detectionSummary.test.ts new file mode 100644 index 0000000..911b3cf --- /dev/null +++ b/tests/pages/detectionSummary.test.ts @@ -0,0 +1,30 @@ +import { describe, test, expect } from 'vitest' +import type { TFunction } from 'i18next' + +import I_MODEL_OBJECT_DETECTION from '@pages/playground/2_ObjectDetection/models/_model' +import { detectionSummary, detectionText } from '@pages/playground/2_ObjectDetection/detectionSummary' + +// t con las claves y lo que se interpola, para ver qué frase sale +const t = ((key: string, values?: Record) => (values?.list ? `${key}: ${values.list}` : key)) as unknown as TFunction + +// Un detector de clases (como COCO-SSD): usa lo que trae la clase base para la explicabilidad +class FakeDetector extends I_MODEL_OBJECT_DETECTION {} +const model = new FakeDetector(t as never) + +describe('detectionSummary: lo detectado en texto', () => { + test('una etiqueta por clase, con su mejor puntuación, de la más segura a la menos', () => { + const items = detectionSummary(model, [ + { class: 'dog', score: 0.81 }, + { class: 'person', score: 0.6 }, + { class: 'person', score: 0.92 }, + ]) + expect(items).toEqual([{ label: 'person', score: 0.92 }, { label: 'dog', score: 0.81 }]) + // Intl pone un espacio que no se parte antes de «%» + expect(detectionText(t, items, 'es')).toMatch(/^datasets-models\.2-object-detection\.interface\.detections\.detected: person \(92\s%\), dog \(81\s%\)$/) + }) + + test('sin detecciones lo dice', () => { + expect(detectionSummary(model, [])).toEqual([]) + expect(detectionText(t, [], 'es')).toBe('datasets-models.2-object-detection.interface.detections.nothing') + }) +}) diff --git a/tests/pages/faceMesh.test.ts b/tests/pages/faceMesh.test.ts new file mode 100644 index 0000000..a95477f --- /dev/null +++ b/tests/pages/faceMesh.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, test } from 'vitest' +import type { TFunction } from 'i18next' +import type * as faceLandmarksDetection from '@tensorflow-models/face-landmarks-detection' + +import MODEL_2_FACE_MESH from '@pages/playground/2_ObjectDetection/models/MODEL_2_FACE_MESH' +import { personSide } from '@pages/playground/2_ObjectDetection/models/drawing' + +const PREFIX = 'datasets-models.2-object-detection.face-mesh.render.' +const t = ((key: string, values?: Record) => + values?.count === undefined ? key : `${key}:${values.count}`) as unknown as TFunction + +/** + * Una cara de `width` píxeles centrada en x = 320, sin espejo: el ojo derecho de la persona (33, 133) a la izquierda + * de la imagen, el izquierdo (263, 362) a la derecha y la boca (61, 291) debajo. El resto de puntos, en el centro + */ +function face(width: number): faceLandmarksDetection.Face { + const half = width / 2 + const keypoints = Array.from({ length: 478 }, () => ({ x: 320, y: 240 })) + const at = (index: number, x: number, y: number) => { keypoints[index] = { x: 320 + x * half, y: 240 + y * half } } + at(33, -0.7, -0.3); at(133, -0.3, -0.3); at(263, 0.7, -0.3); at(362, 0.3, -0.3); at(61, -0.4, 0.5); at(291, 0.4, 0.5) + return { + keypoints, + box: { xMin: 320 - half, xMax: 320 + half, yMin: 240 - half, yMax: 240 + half, width, height: width }, + } +} + +/** Un lienzo de 640 × 480 que no dibuja: guarda cada texto escrito y dónde */ +function recordingContext() { + const texts: Array<{ text: string, x: number }> = [] + const ctx = new Proxy({ canvas: { width: 640, height: 480 } } as Record, { + get: (target, property) => { + if (property in target) return target[property] + // Las claves son largas: cada texto, del ancho de un nombre como «Ojo izquierdo» + if (property === 'measureText') return () => ({ width: 80 }) + if (property === 'fillText') return (text: string, x: number) => texts.push({ text, x }) + return () => undefined + }, + set: () => true, + }) as unknown as CanvasRenderingContext2D + return { ctx, texts } +} + +function render(faces: faceLandmarksDetection.Face[], { mirrored = false } = {}) { + const model = new MODEL_2_FACE_MESH(t as never) + model._mirrored = mirrored + const { ctx, texts } = recordingContext() + model.RENDER(ctx, faces) + return texts +} + +const xOf = (texts: Array<{ text: string, x: number }>, key: string) => texts.find(({ text }) => text === PREFIX + key)?.x + +describe('personSide: el lado de la persona de lo que MediaPipe llama derecha o izquierda', () => { + test('sin espejo, el mismo; con la webcam en espejo, el contrario', () => { + expect(personSide('right', false)).toBe('right') + expect(personSide('left', false)).toBe('left') + expect(personSide('right', true)).toBe('left') + expect(personSide('left', true)).toBe('right') + }) +}) + +describe('MODEL_2_FACE_MESH: lo que se escribe sobre cada cara', () => { + test('una cara grande: su nombre con los puntos, y los ojos y los labios fuera del recuadro', () => { + const texts = render([face(240)]) + expect(texts.map(({ text }) => text)).toEqual(expect.arrayContaining([ + PREFIX + 'face', PREFIX + 'points:478', PREFIX + 'eye-right', PREFIX + 'eye-left', PREFIX + 'lips', + ])) + // El ojo derecho de la persona, a la izquierda de la imagen, fuera del recuadro; el izquierdo, a la derecha + expect(xOf(texts, 'eye-right')).toBeLessThan(200) + expect(xOf(texts, 'eye-left')).toBeGreaterThan(440) + expect(xOf(texts, 'lips')).toBeGreaterThan(440) + }) + + test('con la webcam en espejo, el ojo de la izquierda de la imagen es el izquierdo de la persona', () => { + const texts = render([face(240)], { mirrored: true }) + expect(xOf(texts, 'eye-left')).toBeLessThan(200) + expect(xOf(texts, 'eye-right')).toBeGreaterThan(440) + }) + + test('una cara pequeña: solo su nombre, sin los de las partes', () => { + const texts = render([face(90)]).map(({ text }) => text) + expect(texts).toContain(PREFIX + 'face') + expect(texts.filter((text) => /eye|lips/.test(text))).toEqual([]) + }) + + test('varias caras: numeradas', () => { + const texts = render([face(240), face(90)]).map(({ text }) => text) + expect(texts.filter((text) => text === PREFIX + 'face-number')).toHaveLength(2) + expect(texts).not.toContain(PREFIX + 'face') + }) +}) diff --git a/tests/pages/glossary.test.tsx b/tests/pages/glossary.test.tsx new file mode 100644 index 0000000..2108373 --- /dev/null +++ b/tests/pages/glossary.test.tsx @@ -0,0 +1,147 @@ +import { describe, test, expect, vi, beforeAll } from 'vitest' +import { act, fireEvent, render, screen, within } from '@testing-library/react' +import { MemoryRouter } from 'react-router' +import fs from 'node:fs' +import path from 'node:path' + +// Las fórmulas, sin KaTeX: aquí se comprueban la estructura y la búsqueda (y así el test no pinta unas 70 fórmulas) +vi.mock('@components/latex/N4LLatex', () => ({ default: ({ children }: { children: string }) => {children} })) +// jsdom no tiene canvas: la gráfica animada guarda sus puntos en el DOM para comprobar hasta dónde se dibuja +vi.mock('react-chartjs-2', () => ({ + Line: ({ data }: { data: { datasets: Array<{ data: Array<{ x: number, y: number }> }> } }) => ( +
    + ), +})) + +import Glossary from '@pages/glossary/Glossary' +import { GLOSSARY_SECTIONS, GLOSSARY_UI_KEYS, glossaryKeys, matchesSearch, normalizeSearch } from '@pages/glossary/glossaryTerms' +import { ACTIVATION_FUNCTIONS, activationCurve, activationRange, activationX } from '@pages/glossary/activationFunctions' + +const LANGUAGES = ['es', 'en', 'ja'] +const translations = Object.fromEntries(LANGUAGES.map((language) => [ + language, + JSON.parse(fs.readFileSync(path.resolve(__dirname, `../../public/locales/${language}/translation.json`), 'utf8')), +])) +const lookup = (object: unknown, key: string) => key.split('.').reduce((value, part) => (value as Record | undefined)?.[part], object) + +const allTerms = GLOSSARY_SECTIONS.flatMap((section) => section.groups.flatMap((group) => group.terms)) + +describe('datos del glosario', () => { + + test('cada término tiene un ancla distinta', () => { + const ids = allTerms.map((term) => term.id) + expect(new Set(ids).size).toBe(ids.length) + }) + + test('todos los textos existen en los tres idiomas', () => { + for (const language of LANGUAGES) { + const missing = [...glossaryKeys(), ...GLOSSARY_UI_KEYS].filter((key) => typeof lookup(translations[language], key) !== 'string') + expect(missing, language).toEqual([]) + // Las características de las activaciones son objetos de textos + for (const term of allTerms.filter((item) => item.characteristicsKey !== undefined)) { + expect(typeof lookup(translations[language], term.characteristicsKey!), `${language} ${term.characteristicsKey}`).toBe('object') + } + } + }) + + test('la búsqueda no distingue tildes ni mayúsculas y pide todas las palabras', () => { + const text = normalizeSearch('Número de Épocas (Number of Epochs)') + expect(matchesSearch(text, 'epocas')).toBe(true) + expect(matchesSearch(text, 'NÚMERO épocas')).toBe(true) + expect(matchesSearch(text, 'épocas adam')).toBe(false) + }) +}) + +describe('activaciones animadas', () => { + const value = (key: string, x: number) => ACTIVATION_FUNCTIONS[key].fn(x) + + test('cada función da lo que dice su fórmula', () => { + expect(value('linear', -2.5)).toBe(-2.5) + expect(value('sigmoid', 0)).toBe(0.5) + expect(value('hard-sigmoid', -3)).toBe(0) + expect(value('hard-sigmoid', 3)).toBe(1) + expect(value('hard-sigmoid', 0)).toBe(0.5) + expect(value('relu', -1)).toBe(0) + expect(value('relu6', 7)).toBe(6) + expect(value('leaky-relu', -1)).toBeCloseTo(-0.01) + expect(value('elu', -1)).toBeCloseTo(Math.exp(-1) - 1) + expect(value('tanh', 0)).toBe(0) + expect(value('soft-plus', 0)).toBeCloseTo(Math.LN2) + expect(value('mish', 0)).toBe(0) + expect(value('selu', 1)).toBeCloseTo(1.0507009873554805) + }) + + test('todas las activaciones con gráfica se pueden animar', () => { + const withImage = allTerms.filter((term) => term.id.startsWith('activation-') && term.image !== undefined) + expect(withImage.length).toBeGreaterThan(0) + for (const term of withImage) expect(ACTIVATION_FUNCTIONS[term.activation ?? '']).toBeDefined() + }) + + test('el deslizador va de -6 a 6 y la curva se dibuja hasta x', () => { + expect(activationX(0)).toBe(-6) + expect(activationX(0.5)).toBe(0) + expect(activationX(1)).toBe(6) + const curve = activationCurve(Math.tanh, 0) + expect(curve[0]).toEqual({ x: -6, y: Math.tanh(-6) }) + expect(curve.at(-1)).toEqual({ x: 0, y: 0 }) + expect(curve.every((point) => point.x <= 0)).toBe(true) + // El eje y es fijo y cubre toda la curva + const [min, max] = activationRange(ACTIVATION_FUNCTIONS['relu6'].fn) + expect(min).toBeLessThan(0) + expect(max).toBeGreaterThan(6) + }) +}) + +describe('página del glosario', () => { + beforeAll(() => { + Element.prototype.scrollIntoView = vi.fn() + }) + + test('enseña todos los términos con su enlace y los filtra al buscar', async () => { + render() + expect(screen.getAllByTestId('Test-GlossaryTerm')).toHaveLength(allTerms.length) + expect(document.getElementById('glossary-optimizer-adam')).toHaveTextContent('Adam') + + // En los tests t devuelve la clave: "adam" solo aparece en el título del optimizador + await act(async () => { + fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'Adam' } }) + }) + const titles = screen.getAllByTestId('Test-GlossaryTerm').map((term) => term.id) + expect(titles).toContain('glossary-optimizer-adam') + expect(titles).toContain('glossary-optimizer-adamax') + expect(titles).not.toContain('glossary-activation-relu') + expect(screen.getByTestId('Test-GlossaryResults')).toHaveTextContent('pages.glossary.results') + + await act(async () => { + fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'no-existe-este-termino' } }) + }) + expect(screen.queryAllByTestId('Test-GlossaryTerm')).toHaveLength(0) + expect(screen.getByTestId('Test-GlossaryResults')).toHaveTextContent('pages.glossary.no-results') + }) + + test('la gráfica de una activación va en pestañas: la imagen primero y la animación con su deslizador', async () => { + render() + const relu = within(document.getElementById('glossary-activation-relu')!) + expect(relu.getByRole('tab', { name: 'pages.glossary.plot-tabs.image' })).toHaveAttribute('aria-selected', 'true') + expect(relu.getByRole('img', { name: 'pages.glossary.plot' })).toBeInTheDocument() + expect(relu.queryByRole('slider')).not.toBeInTheDocument() + + await act(async () => { + fireEvent.click(relu.getByRole('tab', { name: 'pages.glossary.plot-tabs.animation' })) + }) + const slider = relu.getByRole('slider') + expect(slider).toHaveAttribute('min', '0') + expect(slider).toHaveAttribute('max', '1') + expect(slider).toHaveAttribute('step', '0.01') + // Los números en el idioma del navegador (coma o punto decimal) + fireEvent.change(slider, { target: { value: '0.75' } }) + expect(relu.getByTestId('Test-GlossaryAnimationValue')).toHaveTextContent(/x = 3[.,]00 → ReLU\(x\) = 3[.,]00/) + // La curva llega hasta la x del deslizador + expect(relu.getByTestId('Test-ChartLine')).toHaveAttribute('data-last-x', '3') + fireEvent.change(slider, { target: { value: '0.25' } }) + expect(relu.getByTestId('Test-GlossaryAnimationValue')).toHaveTextContent(/x = [-−]3[.,]00 → ReLU\(x\) = 0[.,]00/) + + // Softmax no tiene gráfica: sin pestañas + expect(within(document.getElementById('glossary-activation-softmax')!).queryByRole('tab')).not.toBeInTheDocument() + }) +}) diff --git a/tests/pages/glossaryGuide.test.ts b/tests/pages/glossaryGuide.test.ts new file mode 100644 index 0000000..c59f67b --- /dev/null +++ b/tests/pages/glossaryGuide.test.ts @@ -0,0 +1,34 @@ +import { describe, test, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import path from 'node:path' +import type { GuideTranslate_t } from '@components/guide/buildGuideSteps' +import { glossaryGuide } from '@pages/glossary/glossaryGuide' +import { GLOSSARY_SECTIONS } from '@pages/glossary/glossaryTerms' + +const LANGUAGES = ['es', 'en', 'ja'] +const translations = Object.fromEntries(LANGUAGES.map((language) => [language, + JSON.parse(readFileSync(path.resolve(__dirname, `../../public/locales/${language}/translation.json`), 'utf8'))])) +const lookup = (language: string, key: string) => + key.split('.').reduce((node, part) => (node as Record | undefined)?.[part], translations[language]) + +describe('guía del glosario', () => { + test('cada paso señala un término que existe (o el buscador, el índice o un enlace) y tiene texto en todos los idiomas', () => { + const termIds = new Set(GLOSSARY_SECTIONS.flatMap(({ groups }) => groups.flatMap(({ terms }) => terms.map(({ id }) => id)))) + for (const language of LANGUAGES) { + const missing: string[] = [] + const t: GuideTranslate_t = (keys) => { + const list = Array.isArray(keys) ? keys : [keys] + const found = list.find((key) => typeof lookup(language, key) === 'string') + if (found === undefined) missing.push(list.join(' | ')) + return found === undefined ? '' : lookup(language, found) as string + } + const steps = glossaryGuide(t) + expect(missing, language).toEqual([]) + expect(steps.length).toBe(18) + for (const { target } of steps) { + const term = target.match(/^#glossary-([^\s]+)/)?.[1] + if (term !== undefined) expect(termIds, target).toContain(term) + } + } + }) +}) diff --git a/tests/pages/glossaryTarget.test.ts b/tests/pages/glossaryTarget.test.ts new file mode 100644 index 0000000..5669e63 --- /dev/null +++ b/tests/pages/glossaryTarget.test.ts @@ -0,0 +1,25 @@ +import { describe, test, expect } from 'vitest' +import { glossaryTarget } from '../../src/pages/glossary/glossaryTarget' +import { GLOSSARY_ACTIONS } from '../../src/CONSTANTS_ACTIONS' + +describe('glossaryTarget', () => { + test('los pasos de datos llevan al término de su tarea', () => { + expect(glossaryTarget(GLOSSARY_ACTIONS.TABULAR_CLASSIFICATION.STEP_1_UPLOAD_AND_PROCESS)).toBe('task-tabular-classification') + expect(glossaryTarget(GLOSSARY_ACTIONS.REGRESSION.STEP_2_DATASET)).toBe('task-regression') + expect(glossaryTarget(GLOSSARY_ACTIONS.IMAGE_CLASSIFICATION.STEP_2_DATASET)).toBe('task-image-classification') + // Las series temporales, a su grupo de conceptos (ventana, diferenciar, líneas base…) + expect(glossaryTarget(GLOSSARY_ACTIONS.TIME_SERIES.STEP_2_DATASET)).toBe('time-series') + }) + + test('los editores y la tabla de modelos llevan a su grupo de términos', () => { + expect(glossaryTarget(GLOSSARY_ACTIONS.TABULAR_CLASSIFICATION.STEP_3_0_LAYER_DESIGN)).toBe('editor-layers') + expect(glossaryTarget(GLOSSARY_ACTIONS.REGRESSION.STEP_3_LAYERS)).toBe('editor-layers') + expect(glossaryTarget(GLOSSARY_ACTIONS.IMAGE_CLASSIFICATION.STEP_4_HYPERPARAMETERS)).toBe('editor-hyperparameters') + expect(glossaryTarget(GLOSSARY_ACTIONS.TABULAR_CLASSIFICATION.STEP_5_TABLE_OF_MODELS)).toBe('metrics') + }) + + test('sin acción o con una desconocida no se abre nada', () => { + expect(glossaryTarget(null)).toBeNull() + expect(glossaryTarget('otra-cosa')).toBeNull() + }) +}) diff --git a/tests/pages/handSign.test.ts b/tests/pages/handSign.test.ts new file mode 100644 index 0000000..2e3c4ec --- /dev/null +++ b/tests/pages/handSign.test.ts @@ -0,0 +1,115 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import type { TFunction } from 'i18next' +import type * as handPoseDetection from '@tensorflow-models/hand-pose-detection' +import { createHandSignEstimator, HandSignsSSL } from 'handsign-multilingual' + +import MODEL_6_HAND_SIGN from '@pages/playground/2_ObjectDetection/models/MODEL_6_HAND_SIGN' +import { detectionSummary } from '@pages/playground/2_ObjectDetection/detectionSummary' + +// t con la clave y la letra, para ver qué etiquetas salen +const t = ((key: string, values?: Record) => (values?.sign ? `${key}:${values.sign}` : key)) as unknown as TFunction + +// Una mano sintética (como en las pruebas de handsign-multilingual): una L, con la palma a la cámara, vista como una +// mano derecha sin espejo. Cada dedo sale de su base hacia su ángulo y, doblado, gira hacia la palma +const BASES = [[0.35, -0.25], [0.3, -1], [0.1, -1.05], [-0.1, -1], [-0.3, -0.9]] +const L_HAND = [{ angle: 45, turns: [0, 3, 6] }, { angle: 90, turns: [0, 3, 6] }, { angle: 90, turns: [0, 90, 180] }, { angle: 90, turns: [0, 90, 180] }, { angle: 90, turns: [0, 90, 180] }] +const LENGTHS = [0.45, 0.3, 0.25] +const PIXELS = 100 + +function landmarks(): number[][] { + const points = [[0, 0, 0]] + L_HAND.forEach(({ angle, turns }, finger) => { + const [dx, dy] = [Math.cos((angle * Math.PI) / 180), -Math.sin((angle * Math.PI) / 180)] + let point = [...BASES[finger], 0] + points.push(point) + LENGTHS.forEach((length, joint) => { + const turn = (turns[joint] * Math.PI) / 180 + point = [point[0] + dx * Math.cos(turn) * length, point[1] + dy * Math.cos(turn) * length, point[2] - Math.sin(turn) * length] + points.push(point) + }) + }) + return points +} + +/** + * La L como la da hand-pose-detection, con la muñeca en `x` píxeles. Sin espejo, una mano derecha se etiqueta «Left»; + * con la webcam en espejo (`mirrored`), «Right», y se ve reflejada + */ +function hand(x: number, { mirrored = false } = {}): handPoseDetection.Hand { + const points = landmarks().map(([px, py, pz]) => [mirrored ? -px : px, py, pz]) + return { + keypoints : points.map(([px, py]) => ({ x: x + px * PIXELS, y: 360 + py * PIXELS })), + keypoints3D: points.map(([px, py, pz]) => ({ x: px / 10, y: py / 10, z: pz / 10 })), + handedness : mirrored ? 'Right' : 'Left', + score : 0.98, + } +} + +// Un lienzo que no dibuja: solo comprueba que RENDER no falla +const fakeContext = () => + new Proxy({ canvas: { width: 640, height: 480 } } as Record, { + get: (target, property) => (property in target ? target[property] : property === 'measureText' ? () => ({ width: 20 }) : () => undefined), + set: () => true, + }) as unknown as CanvasRenderingContext2D + +function model({ mirrored = false } = {}) { + const instance = new MODEL_6_HAND_SIGN(t as never) + // Lo que hace ENABLE_MODEL en español, sin el detector de MediaPipe + instance.signLanguage = HandSignsSSL + instance.signEstimator = createHandSignEstimator(HandSignsSSL, { minScore: 0 }) + instance._mirrored = mirrored + return instance +} + +/** Un fotograma cada 50 ms (20 por segundo, como la página): lo dibujado y, como la página, el texto de lo detectado */ +function play(instance: MODEL_6_HAND_SIGN, positions: number[], options = {}) { + return positions.map((x) => { + vi.advanceTimersByTime(50) + const predictions = [hand(x, options)] + instance.RENDER(fakeContext(), predictions) + const summary = detectionSummary(instance, predictions).map(({ label }) => label) + return { views: instance._lastViews?.views ?? [], summary } + }) +} + +const still = (x: number, frames: number) => Array.from({ length: frames }, () => x) +const slide = (from: number, to: number, frames: number) => Array.from({ length: frames }, (_, i) => from + ((to - from) * (i + 1)) / frames) + +describe('MODEL_6_HAND_SIGN: la letra de cada mano y las de movimiento', () => { + beforeEach(() => vi.useFakeTimers({ toFake: ['performance'] })) + afterEach(() => vi.useRealTimers()) + + test('la L quieta: se ve la L, en la pantalla y en el texto de la página', () => { + const instance = model() + const frames = play(instance, still(400, 12)) + const { views, summary } = frames[frames.length - 1] + expect(views).toMatchObject([{ letter: 'L', moving: false, side: 'right' }]) + expect(summary).toContain('ui.explain.labels.sign:L') + }) + + test('la L desplazándose hacia su lado (a la izquierda de la imagen sin espejo): LL, también en el texto', () => { + const instance = model() + const frames = play(instance, [...still(400, 10), ...slide(400, 250, 8), ...still(250, 4)]) + const moved = frames.find(({ views }) => views[0]?.letter === 'LL') + expect(moved?.views[0]).toMatchObject({ letter: 'LL', moving: true, score: 1 }) + expect(moved?.summary).toContain('ui.explain.labels.sign:LL') + }) + + test('con la webcam en espejo, la mano derecha se mueve hacia la derecha de la imagen: también LL', () => { + const instance = model({ mirrored: true }) + const frames = play(instance, [...still(250, 10), ...slide(250, 400, 8), ...still(400, 4)], { mirrored: true }) + expect(frames.some(({ views }) => views[0]?.letter === 'LL')).toBe(true) + }) + + test('hacia el otro lado, o quieta, no es LL', () => { + const instance = model() + const frames = play(instance, [...still(250, 10), ...slide(250, 400, 8), ...still(400, 4)]) + expect(frames.some(({ views }) => views[0]?.letter === 'LL')).toBe(false) + }) + + test('una imagen suelta: la letra de ese fotograma, sin esperar a los siguientes', () => { + const instance = model() + instance.RENDER(fakeContext(), [hand(400)]) + expect(instance._lastViews?.views).toMatchObject([{ letter: 'L' }]) + }) +}) diff --git a/tests/pages/layersGuide.test.ts b/tests/pages/layersGuide.test.ts new file mode 100644 index 0000000..6d8f4e2 --- /dev/null +++ b/tests/pages/layersGuide.test.ts @@ -0,0 +1,84 @@ +import { describe, test, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import path from 'node:path' +import i18next from 'i18next' + +import { layersGuide } from '@pages/playground/3_ImageClassification/layersGuide' +import { trainerGuide } from '@components/guide/trainerGuide' +import type { ImageLayer_t } from '@/types/types' + +const LANGUAGES = ['es', 'en', 'ja'] as const +const resources = Object.fromEntries(LANGUAGES.map((language) => [language, { + translation: JSON.parse(readFileSync(path.resolve(__dirname, `../../public/locales/${language}/translation.json`), 'utf8')), +}])) +const translator = async (language: string) => { + const instance = i18next.createInstance() + await instance.init({ lng: language, resources, interpolation: { escapeValue: false } }) + return instance.t +} + +// Las capas por defecto de MNIST y KMNIST +const LAYERS: ImageLayer_t[] = [ + { _class: 'conv2d', _protected: true, inputShape: [28, 28, 1], kernelSize: 3, filters: 16, activation: 'relu' }, + { _class: 'maxPooling2d', poolSize: 2, strides: 2 }, + { _class: 'conv2d', kernelSize: 3, filters: 32, activation: 'relu' }, + { _class: 'maxPooling2d', poolSize: 2, strides: 2 }, + { _class: 'conv2d', kernelSize: 3, filters: 32, activation: 'relu' }, + { _class: 'flatten' }, + { _class: 'dense', units: 64, activation: 'relu' }, + { _class: 'dense', units: 10, activation: 'softmax' }, +] + +describe('layersGuide: un paso de la guía por cada capa de la red de imágenes', () => { + test.each(LANGUAGES.flatMap((language) => ['IMAGE-MNIST', 'IMAGE-KMNIST'].map((dataset) => ({ language, dataset }))))( + '$language / $dataset: cada capa, en su paso y con sus números', async ({ language, dataset }) => { + const t = await translator(language) + const steps = layersGuide(t, language, dataset, LAYERS) + expect(steps.map(({ target }) => target)).toEqual(LAYERS.map((_layer, index) => `[data-guide="layer-${index}"]`)) + for (const { title, content } of steps) { + // Todo interpolado y con texto de verdad (no la clave) + expect(title + content).not.toMatch(/{{|}}|guide\.train/) + expect(content.length).toBeGreaterThan(60) + } + // La primera convolución recibe la imagen de 28×28 y saca 16 mapas de 26×26 + expect(steps[0].content).toContain('28×28') + expect(steps[0].content).toContain('26×26') + // La salida habla de dígitos o de caracteres, según el conjunto de datos + const className = t(`guide.train.3-image-classification.${dataset}.layer.class-name`) + expect(steps.at(-1)!.content).toContain(className) + }) + + test.each(LANGUAGES)('%s / IMAGE-CIFAR10: la primera convolución recibe una foto en color (tres mapas)', async (language) => { + const t = await translator(language) + const layers: ImageLayer_t[] = [{ ...LAYERS[0], inputShape: [32, 32, 3], filters: 32 }, ...LAYERS.slice(1)] + const steps = layersGuide(t, language, 'IMAGE-CIFAR10', layers) + for (const { title, content } of steps) expect(title + content).not.toMatch(/{{|}}|guide\.train/) + // 32×32 en color, 3 mapas; salen 32 mapas de 30×30, con 3 × 3 × 3 × 32 + 32 = 896 pesos + expect(steps[0].content).toContain('32×32') + expect(steps[0].content).toContain('30×30') + expect(steps[0].content).toContain('896') + expect(steps[0].content).toMatch(/\b3\b/) + expect(steps[0].content).not.toBe(layersGuide(t, language, 'IMAGE-MNIST', layers)[0].content) + }) + + test('los pesos con el formato del idioma, y una capa que no encaja lo dice', async () => { + const t = await translator('es') + const steps = layersGuide(t, 'es', 'IMAGE-MNIST', LAYERS) + // La segunda convolución, 3 × 3 × 16 × 32 + 32 pesos; la densa de 64 recibe 3×3×32 = 288 valores: 288 × 64 + 64 + expect(steps[2].content).toContain('4640 pesos') + expect(steps[6].content).toContain('288 valores') + expect(steps[6].content).toContain('18.496 pesos') + const broken = layersGuide(t, 'es', 'IMAGE-MNIST', [LAYERS[0], { _class: 'dense', units: 10, activation: 'softmax' }]) + expect(broken[1].title).toBe('Capa 2: no encaja') + }) + + test('van justo detrás del paso de las capas', async () => { + const t = await translator('es') + const layerSteps = layersGuide(t, 'es', 'IMAGE-KMNIST', LAYERS) + const targets = trainerGuide(t as never, '3-image-classification', 'IMAGE-KMNIST', { upload: false, datasetTable: false, testSize: 'hp-test-size', stepByStep: false, layerSteps }) + .map(({ target }) => target) + const at = targets.indexOf('[data-guide="layers"]') + expect(targets.slice(at + 1, at + 1 + LAYERS.length)).toEqual(layerSteps.map(({ target }) => target)) + expect(targets[at + 1 + LAYERS.length]).toBe('[data-guide="layers-add"]') + }) +}) diff --git a/tests/pages/modelReviewGuide.test.ts b/tests/pages/modelReviewGuide.test.ts new file mode 100644 index 0000000..692500f --- /dev/null +++ b/tests/pages/modelReviewGuide.test.ts @@ -0,0 +1,144 @@ +import { describe, test, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import path from 'node:path' +import type { GuideStep_t } from '@components/guide/N4LGuide' +import type { GuideTranslate_t } from '@components/guide/buildGuideSteps' +import { TABULAR_REVIEW_GUIDES, tabularReviewGuide } from '@pages/playground/0_TabularClassification/modelReviewGuide' +import { REGRESSION_REVIEW_GUIDES, regressionReviewGuide } from '@pages/playground/1_Regression/modelReviewGuide' +import { OBJECT_DETECTION_REVIEW_GUIDES, objectDetectionReviewGuide } from '@pages/playground/2_ObjectDetection/modelReviewGuide' +import { IMAGE_CLASSIFICATION_REVIEW_GUIDES, imageClassificationReviewGuide } from '@pages/playground/3_ImageClassification/modelReviewGuide' +import { TIME_SERIES_REVIEW_GUIDES, timeSeriesReviewGuide } from '@pages/playground/5_TimeSeries/modelReviewGuide' +import { MAP_TC_CLASSES } from '@pages/playground/0_TabularClassification/models' +import { MAP_IC_CLASSES } from '@pages/playground/3_ImageClassification/models' +import { TASK_MODEL_OPTIONS } from '@/TASK_OPTIONS' +import { TASKS } from '@/TASKS' + +const LANGUAGES = ['es', 'en', 'ja'] +const translations = Object.fromEntries(LANGUAGES.map((language) => [language, + JSON.parse(readFileSync(path.resolve(__dirname, `../../public/locales/${language}/translation.json`), 'utf8'))])) + +const lookup = (language: string, key: string) => + key.split('.').reduce((node, part) => (node as Record | undefined)?.[part], translations[language]) + +/** Como el t de i18next con varias claves: la primera que existe. Apunta las que no tienen ninguna y las usadas */ +function translator(language: string, missing: string[], used: Set): GuideTranslate_t { + return (keys) => { + const list = Array.isArray(keys) ? keys : [keys] + const found = list.find((key) => typeof lookup(language, key) === 'string' && (lookup(language, key) as string).trim() !== '') + if (found === undefined) missing.push(`${language}: ${list.join(' | ')}`) + else used.add(found) + return found === undefined ? list[0] : lookup(language, found) as string + } +} + +/** Todas las claves de textos de una guía (guide..) */ +function keysOf(node: unknown, prefix: string): string[] { + if (typeof node === 'string') return [prefix] + return Object.entries(node as Record).flatMap(([key, value]) => keysOf(value, `${prefix}.${key}`)) +} + +/** Las columnas de entrada de un CSV de regresión (sin la variable objetivo), en su paquete .n4l */ +function csvFeatures(file: string, target: string) { + const header = readFileSync(path.resolve(__dirname, '../../public/n4l/', file), 'utf8').split('\n')[0] + return header.trim().split(',').filter((column) => column !== target) +} + +type Case_t = { task: string, prefix: string, model: string, build: (t: GuideTranslate_t) => GuideStep_t[] | null } + +const REGRESSION_FIELDS: Record = { + AUTO_MPG : csvFeatures('auto-mpg.n4l/data/auto-mpg.csv', 'mpg'), + STUDENT_PERFORMANCE: csvFeatures('student-performance.n4l/data/student-mat-2024.csv', 'G3'), + WINE : csvFeatures('wine-quality.n4l/data/wine-quality-red.csv', 'quality'), + SALARY : csvFeatures('salary.n4l/data/salary.csv', 'Salary'), + HOUSING_PRICES : csvFeatures('boston-housing.n4l/data/boston-housing-2020.csv', 'MEDV'), +} + +async function cases(): Promise { + const tabular = await Promise.all(TABULAR_REVIEW_GUIDES.map(async (model) => { + const ModelClass = await MAP_TC_CLASSES[model]() + const fields = new ModelClass(((key: string) => key) as never, () => {}).FORM.map(({ name }) => name) + // Con Paso a paso activado (/settings): así se comprueban también sus textos + return { task: 'tabular-classification', prefix: 'guide.0-tabular-classification', model, build: (t: GuideTranslate_t) => tabularReviewGuide(t, model, fields, true) } + })) + const regression = REGRESSION_REVIEW_GUIDES.map((model) => ( + { task: 'regression', prefix: 'guide.1-regression', model, build: (t: GuideTranslate_t) => regressionReviewGuide(t, model, REGRESSION_FIELDS[model], true) })) + const detection = OBJECT_DETECTION_REVIEW_GUIDES.map((model) => ( + { task: 'object-detection', prefix: 'guide.2-object-detection', model, build: (t: GuideTranslate_t) => objectDetectionReviewGuide(t, model) })) + const images = await Promise.all(IMAGE_CLASSIFICATION_REVIEW_GUIDES.map(async (model) => { + const ModelClass = await MAP_IC_CLASSES[model]() + // Los de gris se pueden dibujar; los de un conjunto tienen imágenes de test y son LayersModel (con resumen); MobileNet, + // nada de eso + const instance = new ModelClass(((key: string) => key) as never) + const options = { drawable: instance.DRAWABLE, summary: instance.TEST_IMAGES, testImages: instance.TEST_IMAGES } + return { task: 'image-classification', prefix: 'guide.3-image-classification', model, build: (t: GuideTranslate_t) => imageClassificationReviewGuide(t, model, options) } + })) + const series = TIME_SERIES_REVIEW_GUIDES.map((model) => ( + { task: 'time-series', prefix: 'guide.5-time-series', model, build: (t: GuideTranslate_t) => timeSeriesReviewGuide(t, model) })) + return [...tabular, ...regression, ...detection, ...images, ...series] +} + +describe('Guías de las páginas de los modelos', () => { + test('cada paso de cada guía tiene título y texto en todos los idiomas, y no sobra ningún texto', async () => { + for (const { prefix, model, build } of await cases()) { + const missing: string[] = [] + for (const language of LANGUAGES) { + const used = new Set() + const steps = build(translator(language, missing, used))! + expect(steps.length, `${model}`).toBeGreaterThan(5) + expect(steps[0]).toMatchObject({ target: 'body', placement: 'center' }) + expect(steps.at(-1)).toMatchObject({ target: 'body', placement: 'center' }) + // Los textos propios del modelo que ningún paso usa (p. ej. un atributo con otro nombre que el del formulario) + const unused = keysOf(lookup(language, `${prefix}.${model}`) ?? {}, `${prefix}.${model}`).filter((key) => !used.has(key)) + expect(unused, `${language} ${model}`).toEqual([]) + } + expect(missing, model).toEqual([]) + } + }) + + test('el paso de Paso a paso solo está si se ha activado en /settings', () => { + const t: GuideTranslate_t = (keys) => (Array.isArray(keys) ? keys[0] : keys) + const targets = (stepByStep: boolean) => [ + ...tabularReviewGuide(t, 'IRIS', ['sepal_length'], stepByStep)!, + ...regressionReviewGuide(t, 'AUTO_MPG', REGRESSION_FIELDS.AUTO_MPG, stepByStep)!, + ].map(({ target }) => target) + expect(targets(false)).not.toContain('[data-guide="step-by-step"]') + expect(targets(true).filter((target) => target === '[data-guide="step-by-step"]')).toHaveLength(2) + }) + + test('todos los modelos del menú tienen guía', () => { + const guides: Record = { + [TASKS.TABULAR_CLASSIFICATION]: TABULAR_REVIEW_GUIDES, + [TASKS.REGRESSION] : REGRESSION_REVIEW_GUIDES, + [TASKS.OBJECT_DETECTION] : OBJECT_DETECTION_REVIEW_GUIDES, + [TASKS.IMAGE_CLASSIFICATION] : IMAGE_CLASSIFICATION_REVIEW_GUIDES, + [TASKS.TIME_SERIES] : TIME_SERIES_REVIEW_GUIDES, + } + for (const [task, options] of Object.entries(TASK_MODEL_OPTIONS)) { + for (const { value } of options as Array<{ value: string }>) expect(guides[task], `${task} ${value}`).toContain(value) + } + }) + + test('un paso por atributo cuando son pocos y uno para todo el formulario cuando son muchos', () => { + const t: GuideTranslate_t = (keys) => (Array.isArray(keys) ? keys[0] : keys) + const targets = (steps: GuideStep_t[] | null) => steps!.map(({ target }) => target) + expect(targets(tabularReviewGuide(t, 'IRIS', ['sepal_length', 'petal_width']))).toContain('[data-guide="field-petal_width"]') + expect(targets(tabularReviewGuide(t, 'LYMPHOGRAPHY', ['lymphatics']))).toContain('[data-guide="form"]') + expect(targets(regressionReviewGuide(t, 'AUTO_MPG', ['weight']))).toContain('[data-guide="field-weight"]') + expect(targets(regressionReviewGuide(t, 'WINE', ['alcohol']))).toContain('[data-guide="form"]') + // En Rendimiento de estudiantes, justo después del formulario, por qué no están G1 ni G2 + const student = regressionReviewGuide(t, 'STUDENT_PERFORMANCE', ['age'])!.map(({ title }) => title) + expect(student.indexOf('guide.1-regression.STUDENT_PERFORMANCE.grades.title')) + .toBe(student.indexOf('guide.1-regression.STUDENT_PERFORMANCE.form.title') + 1) + // Sin dibujo (MobileNet), sin los pasos del dibujo ni de las imágenes de test + expect(targets(imageClassificationReviewGuide(t, 'IMAGE-MOBILENET', { drawable: false, summary: false, testImages: false }))) + .not.toEqual(expect.arrayContaining(['[data-guide="draw"]', '[data-guide="model-summary"]'])) + expect(targets(imageClassificationReviewGuide(t, 'IMAGE-MNIST', { drawable: true, summary: true, testImages: true }))) + .toEqual(expect.arrayContaining(['[data-guide="draw"]', '[data-guide="test-images"]', '[data-guide="model-summary"]'])) + // Fotos en color (CIFAR-10): imágenes de test, pero sin dibujo + const cifar = targets(imageClassificationReviewGuide(t, 'IMAGE-CIFAR10', { drawable: false, summary: true, testImages: true })) + expect(cifar).toContain('[data-guide="test-images"]') + expect(cifar).not.toContain('[data-guide="draw"]') + expect(tabularReviewGuide(t, 'UPLOAD', [])).toBeNull() + expect(regressionReviewGuide(t, 'BREAST_CANCER', [])).toBeNull() + }) +}) diff --git a/tests/pages/notFoundNetwork.test.ts b/tests/pages/notFoundNetwork.test.ts new file mode 100644 index 0000000..b946d9f --- /dev/null +++ b/tests/pages/notFoundNetwork.test.ts @@ -0,0 +1,54 @@ +import { describe, test, expect } from 'vitest' +import { particles } from '@tsparticles/particles' +import { tsParticles } from '@tsparticles/engine' +import { NETWORK_LAYOUTS, networkOptions } from '@pages/notFound/networkOptions' + +const COLORS = { node: '#0d6efd', hub: '#0dcaf0', link: '#0d6efd' } + +/** Las opciones de las neuronas tal como las recibe tsParticles (las de los plugins no tienen tipo en el motor) */ +type NetworkParticles_t = { + number : { value: number } + opacity: { value: { min: number }, animation: { enable: boolean } } + size : { value: { min: number, max: number }, animation: { enable: boolean } } + move : { enable: boolean } + links : { enable: boolean, opacity: number, frequency: number } +} +const particlesOf = (...args: Parameters) => networkOptions(...args).particles as unknown as NetworkParticles_t + +describe('fondo de la 404 (red neuronal)', () => { + test('el motor es el mismo que trae @tsparticles/particles: con dos copias, sus plugins no llegarían y no se pintaría nada', () => { + expect(tsParticles.version).toBe(particles.version) + }) + + test('menos neuronas cuanto más estrecha es la pantalla, y conexiones más cortas y escasas', () => { + const { desktop, tablet, mobile } = NETWORK_LAYOUTS + expect(desktop.count).toBeGreaterThanOrEqual(40) + expect(desktop.count).toBeLessThanOrEqual(70) + expect(mobile.count).toBeGreaterThanOrEqual(20) + expect(mobile.count).toBeLessThanOrEqual(35) + expect(tablet.count).toBeLessThan(desktop.count) + expect(tablet.count).toBeGreaterThan(mobile.count) + expect(mobile.linkDistance).toBeLessThan(tablet.linkDistance) + expect(mobile.linkFrequency).toBeLessThan(desktop.linkFrequency) + expect(particlesOf(mobile, COLORS, false).number.value).toBe(mobile.count) + }) + + test('neuronas pequeñas, líneas más tenues que ellas y no todas las parejas cercanas conectadas', () => { + const options = particlesOf(NETWORK_LAYOUTS.desktop, COLORS, false) + expect(options.size.value).toEqual({ min: 1.5, max: 3 }) + expect(options.links.enable).toBe(true) + expect(options.links.opacity).toBeLessThan(options.opacity.value.min) + expect(options.links.frequency).toBeLessThan(1) + }) + + test('con movimiento reducido es una imagen fija: ni se mueve ni parpadea', () => { + const moving = particlesOf(NETWORK_LAYOUTS.desktop, COLORS, false) + expect(moving.move.enable).toBe(true) + expect(moving.opacity.animation.enable).toBe(true) + const still = particlesOf(NETWORK_LAYOUTS.desktop, COLORS, true) + expect(still.move.enable).toBe(false) + expect(still.opacity.animation.enable).toBe(false) + expect(still.size.animation.enable).toBe(false) + expect(still.links.enable).toBe(true) + }) +}) diff --git a/tests/pages/smoothing.test.ts b/tests/pages/smoothing.test.ts new file mode 100644 index 0000000..e24963a --- /dev/null +++ b/tests/pages/smoothing.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, test } from 'vitest' + +import { DetectionSmoother, keypointSmoothing, type Smoothing_t } from '@pages/playground/2_ObjectDetection/models/smoothing' + +// Un recuadro de 100 × 100 píxeles con su esquina en (x, y), como los de COCO-SSD +type Box_t = { x: number, y: number, label?: string } +const BOXES: Smoothing_t = { + positions: ({ x, y }) => [x, y, x + 100, y + 100], + update : (box, [x, y]) => ({ ...box, x, y }), +} + +// Ruido de ±4 píxeles, distinto en cada fotograma y siempre el mismo (el hash pseudoaleatorio clásico) +const noise = (i: number) => { + const hash = Math.sin(i * 12.9898 + 78.233) * 43758.5453 + return 8 * (hash - Math.floor(hash) - 0.5) +} +const FRAME_MS = 50 + +/** Una predicción cada 50 ms (20 por segundo, como la página): lo que se dibuja tras cada una */ +function play(smoother: DetectionSmoother, frames: Box_t[][]) { + return frames.map((boxes, i) => { + smoother.update(boxes, i * FRAME_MS) + return smoother.latest() + }) +} + +const spread = (values: number[]) => Math.max(...values) - Math.min(...values) + +describe('DetectionSmoother: las detecciones de la webcam, sin temblar ni parpadear', () => { + test('un objeto quieto con ruido: lo dibujado apenas tiembla', () => { + const frames = Array.from({ length: 60 }, (_, i) => [{ x: 200 + noise(i), y: 100 + noise(i + 7) }]) + const shown = play(new DetectionSmoother(BOXES), frames).slice(20).map(([box]) => box.x) + const raw = frames.slice(20).map(([box]) => box.x) + expect(spread(shown)).toBeLessThan(spread(raw) * 0.4) + }) + + test('un objeto que se mueve deprisa (600 px/s): lo dibujado no se queda atrás', () => { + const frames = Array.from({ length: 20 }, (_, i) => [{ x: 30 * i, y: 100 }]) + const last = play(new DetectionSmoother(BOXES), frames).at(-1)?.[0] + expect(30 * 19 - (last?.x ?? 0)).toBeLessThan(15) + }) + + test('una detección que falta en un fotograma suelto sigue dibujándose', () => { + const box = { x: 200, y: 100 } + const shown = play(new DetectionSmoother(BOXES), [[box], [box], [box], [], [box]]) + expect(shown.map((boxes) => boxes.length)).toEqual([0, 1, 1, 1, 1]) + }) + + test('una que deja de verse desaparece tras un momento (300 ms)', () => { + const box = { x: 200, y: 100 } + const shown = play(new DetectionSmoother(BOXES), [[box], [box], ...Array.from({ length: 8 }, () => [])]) + expect(shown.map((boxes) => boxes.length)).toEqual([0, 1, 1, 1, 1, 1, 1, 1, 0, 0]) + }) + + test('una detección falsa en un solo fotograma no se dibuja', () => { + const box = { x: 200, y: 100 } + const ghost = { x: 500, y: 300 } + const shown = play(new DetectionSmoother(BOXES), [[box], [box], [box, ghost], [box], [box]]) + expect(shown.every((boxes) => boxes.length <= 1)).toBe(true) + }) + + test('dos objetos que cambian de orden en la predicción: cada uno sigue siendo el mismo, en el mismo orden', () => { + const [a, b] = [{ x: 100, y: 100, label: 'a' }, { x: 400, y: 100, label: 'b' }] + const shown = play(new DetectionSmoother(BOXES), [[a, b], [b, a], [a, b], [b, a]]) + for (const boxes of shown.slice(1)) { + expect(boxes.map(({ label }) => label)).toEqual(['a', 'b']) + expect(boxes.map(({ x }) => Math.round(x))).toEqual([100, 400]) + } + }) + + test('con el identificador del modelo (MoveNet), se siguen por él aunque se crucen', () => { + type Pose_t = { id: number, keypoints: Array<{ x: number, y: number }> } + const pose = (id: number, x: number): Pose_t => ({ id, keypoints: [{ x, y: 100 }, { x: x + 50, y: 300 }] }) + const smoother = new DetectionSmoother(keypointSmoothing({ id: (detection) => detection.id })) + // La persona 1 pasa de x = 300 a x = 330 y la 2, de 320 a 290: por la posición se confundirían + smoother.update([pose(1, 300), pose(2, 320)], 0) + smoother.update([pose(1, 300), pose(2, 320)], 50) + smoother.update([pose(2, 290), pose(1, 330)], 100) + const [first, second] = smoother.latest() + expect(first.id).toBe(1) + expect(first.keypoints[0].x).toBeGreaterThan(300) + expect(second.id).toBe(2) + expect(second.keypoints[0].x).toBeLessThan(320) + }) + + test('entre una predicción y la siguiente, lo dibujado se acerca a ella poco a poco en cada fotograma', () => { + const smoother = new DetectionSmoother(BOXES, { minCutoff: 1000 }) + smoother.update([{ x: 0, y: 0 }], 0) + smoother.update([{ x: 0, y: 0 }], 50) + expect(smoother.frame(50)[0].x).toBe(0) + smoother.update([{ x: 100, y: 0 }], 100) + const steps = [116, 133, 150, 300].map((now) => smoother.frame(now)[0].x) + expect(steps[0]).toBeGreaterThan(0) + expect(steps[0]).toBeLessThan(steps[1]) + expect(steps[1]).toBeLessThan(steps[2]) + expect(steps[3]).toBeCloseTo(smoother.latest()[0].x, 0) + }) +}) + +describe('keypointSmoothing: las detecciones con puntos', () => { + type Face_t = { + box : { xMin: number, yMin: number, xMax: number, yMax: number, width: number, height: number } + keypoints: Array<{ x: number, y: number, score?: number, name?: string }> + } + const face = (x: number, score: number): Face_t => ({ + box : { xMin: x, yMin: 50, xMax: x + 100, yMax: 150, width: 100, height: 100 }, + keypoints: [{ x: x + 30, y: 80, score, name: 'rightEye' }, { x: x + 70, y: 80, score, name: 'leftEye' }], + }) + + test('el recuadro y los puntos, con su ancho, su alto y sus nombres', () => { + const smoothing = keypointSmoothing({ box: true }) + expect(smoothing.positions(face(10, 1))).toEqual([10, 50, 110, 150, 40, 80, 80, 80]) + const moved = smoothing.update(face(10, 1), [20, 40, 140, 160, 50, 70, 90, 70], []) + expect(moved.box).toEqual({ xMin: 20, yMin: 40, xMax: 140, yMax: 160, width: 120, height: 120 }) + expect(moved.keypoints).toEqual([{ x: 50, y: 70, score: 1, name: 'rightEye' }, { x: 90, y: 70, score: 1, name: 'leftEye' }]) + }) + + test('con scores, la confianza de los puntos también se suaviza: no salta de golpe', () => { + const smoother = new DetectionSmoother(keypointSmoothing({ scores: true })) + smoother.update([face(10, 0.9)], 0) + smoother.update([face(10, 0.9)], 50) + smoother.update([face(10, 0.1)], 100) + const score = smoother.latest()[0].keypoints[0].score ?? 0 + expect(score).toBeGreaterThan(0.5) + expect(score).toBeLessThan(0.9) + }) +}) diff --git a/tests/pages/timeSeriesGuide.test.ts b/tests/pages/timeSeriesGuide.test.ts new file mode 100644 index 0000000..0a6c5d4 --- /dev/null +++ b/tests/pages/timeSeriesGuide.test.ts @@ -0,0 +1,46 @@ +import { describe, test, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import path from 'node:path' + +import type { GuideTranslate_t } from '@components/guide/buildGuideSteps' +import { timeSeriesTrainerGuide } from '@pages/playground/5_TimeSeries/trainerGuide' +import { TASK_DATASET_OPTIONS } from '@/TASK_OPTIONS' +import { TASKS, UPLOAD } from '@/TASKS' + +const LANGUAGES = ['es', 'en', 'ja'] +const translations = Object.fromEntries(LANGUAGES.map((language) => [language, + JSON.parse(readFileSync(path.resolve(__dirname, `../../public/locales/${language}/translation.json`), 'utf8'))])) + +const lookup = (language: string, key: string) => + key.split('.').reduce((node, part) => (node as Record | undefined)?.[part], translations[language]) + +const keysOf = (node: unknown, prefix: string): string[] => + (typeof node === 'string' ? [prefix] : Object.entries(node as Record).flatMap(([key, value]) => keysOf(value, `${prefix}.${key}`))) + +describe('guía de la página de entrenamiento de las series temporales', () => { + test('cada paso tiene título y explicación en todos los idiomas, y no sobra ningún texto', () => { + const datasets = TASK_DATASET_OPTIONS[TASKS.TIME_SERIES].map(({ value }) => value) + expect(datasets).toContain(UPLOAD) + for (const language of LANGUAGES) { + const missing: string[] = [] + const used = new Set() + const t: GuideTranslate_t = (keys) => { + const list = Array.isArray(keys) ? keys : [keys] + const found = list.find((key) => typeof lookup(language, key) === 'string') + if (found === undefined) missing.push(list.join(' | ')) + else used.add(found) + return found ?? list[0] + } + for (const dataset of datasets) { + const steps = timeSeriesTrainerGuide(t, dataset, dataset === UPLOAD) + expect(steps[0].placement).toBe('center') + expect(steps.at(-1)!.placement).toBe('center') + // Con una serie propia, primero hay que subirla + expect(steps.some(({ target }) => target === '[data-guide="process"]')).toBe(dataset === UPLOAD) + } + expect(missing, language).toEqual([]) + const all = keysOf(lookup(language, 'guide.train.5-time-series'), 'guide.train.5-time-series') + expect(all.filter((key) => !used.has(key)), language).toEqual([]) + } + }) +}) diff --git a/tests/pages/trainerGuide.test.ts b/tests/pages/trainerGuide.test.ts new file mode 100644 index 0000000..ca20d86 --- /dev/null +++ b/tests/pages/trainerGuide.test.ts @@ -0,0 +1,87 @@ +import { describe, test, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import path from 'node:path' +import type { GuideTranslate_t } from '@components/guide/buildGuideSteps' +import { trainerGuide, type TrainerTask_t } from '@components/guide/trainerGuide' +import { TASK_DATASET_OPTIONS } from '@/TASK_OPTIONS' +import { TASKS, UPLOAD } from '@/TASKS' + +const LANGUAGES = ['es', 'en', 'ja'] +const translations = Object.fromEntries(LANGUAGES.map((language) => [language, + JSON.parse(readFileSync(path.resolve(__dirname, `../../public/locales/${language}/translation.json`), 'utf8'))])) + +const lookup = (language: string, key: string) => + key.split('.').reduce((node, part) => (node as Record | undefined)?.[part], translations[language]) + +/** Como el t de i18next con varias claves: la primera que existe. Apunta las que no tienen ninguna y las usadas */ +function translator(language: string, missing: string[], used: Set): GuideTranslate_t { + return (keys) => { + const list = Array.isArray(keys) ? keys : [keys] + const found = list.find((key) => typeof lookup(language, key) === 'string' && (lookup(language, key) as string).trim() !== '') + if (found === undefined) missing.push(`${language}: ${list.join(' | ')}`) + else used.add(found) + return found === undefined ? list[0] : lookup(language, found) as string + } +} + +function keysOf(node: unknown, prefix: string): string[] { + if (typeof node === 'string') return [prefix] + return Object.entries(node as Record).flatMap(([key, value]) => keysOf(value, `${prefix}.${key}`)) +} + +// Cada página de entrenamiento con lo que la diferencia (las mismas opciones que le pasa la página) +const TRAINERS: Array<{ task: TrainerTask_t, datasets: string[], datasetTable: boolean, testSize: 'hp-train-rate' | 'hp-test-size', stepByStep: 'after-train' | 'after-models' | false }> = [ + { task: '0-tabular-classification', datasets: TASK_DATASET_OPTIONS[TASKS.TABULAR_CLASSIFICATION].map(({ value }) => value), datasetTable: true, testSize: 'hp-train-rate', stepByStep: 'after-train' }, + { task: '1-regression', datasets: TASK_DATASET_OPTIONS[TASKS.REGRESSION].map(({ value }) => value), datasetTable: true, testSize: 'hp-train-rate', stepByStep: 'after-models' }, + { task: '3-image-classification', datasets: TASK_DATASET_OPTIONS[TASKS.IMAGE_CLASSIFICATION].map(({ value }) => value), datasetTable: false, testSize: 'hp-test-size', stepByStep: false }, +] + +const CASES = TRAINERS.flatMap((trainer) => trainer.datasets.map((dataset) => ({ ...trainer, dataset }))) + +describe('guías de las páginas de entrenamiento', () => { + test.each(CASES)('$task / $dataset: cada paso tiene título y explicación en todos los idiomas', ({ task, dataset, datasetTable, testSize, stepByStep }) => { + for (const language of LANGUAGES) { + const missing: string[] = [] + const steps = trainerGuide(translator(language, missing, new Set()), task, dataset, { upload: dataset === UPLOAD, datasetTable, testSize, stepByStep }) + expect(missing).toEqual([]) + // Empieza y acaba en medio de la pantalla; en medio, un paso por cada parte de la página + expect(steps[0].placement).toBe('center') + expect(steps.at(-1)!.placement).toBe('center') + expect(steps.length).toBeGreaterThanOrEqual(18) + // La presentación es la de su conjunto de datos, no la genérica + expect(steps[0].content).toBe(lookup(language, `guide.train.${task}.${dataset}.intro.content`)) + } + }) + + test('con datos propios hay que subirlos y prepararlos; con uno de ejemplo, no', () => { + const t: GuideTranslate_t = (keys) => (Array.isArray(keys) ? keys[0] : keys) + const targets = (dataset: string) => trainerGuide(t, '0-tabular-classification', dataset, { upload: dataset === UPLOAD, datasetTable: true, testSize: 'hp-train-rate', stepByStep: 'after-train' }) + .map(({ target }) => target) + expect(targets(UPLOAD)).toContain('[data-guide="process"]') + expect(targets('IRIS')).not.toContain('[data-guide="process"]') + // Paso a paso, solo si está activado en /settings: detrás del botón de entrenar (o de la tabla de modelos) + const withStepByStep = (stepByStep: 'after-train' | 'after-models' | false) => trainerGuide(t, '0-tabular-classification', 'IRIS', { upload: false, datasetTable: true, testSize: 'hp-train-rate', stepByStep }) + .map(({ target }) => target) + expect(withStepByStep(false)).not.toContain('[data-guide="step-by-step"]') + const afterTrain = withStepByStep('after-train') + expect(afterTrain.indexOf('[data-guide="step-by-step"]')).toBe(afterTrain.indexOf('[data-guide="train"]') + 1) + const afterModels = withStepByStep('after-models') + expect(afterModels.indexOf('[data-guide="step-by-step"]')).toBe(afterModels.indexOf('[data-guide="models"]') + 1) + // Cada hiperparámetro, en su paso + expect(targets('IRIS')).toEqual(expect.arrayContaining(['learning-rate', 'number-of-epochs', 'train-rate', 'optimizer', 'loss', 'metrics'] + .map((name) => `[data-guide="hp-${name}"]`))) + }) + + // Los de .common también sirven de respaldo a un conjunto de datos nuevo sin textos propios: esos pueden no usarse hoy. + // Los de las capas (.layer.*) los usa layersGuide y se comprueban en layersGuide.test.ts + test('no sobra ningún texto propio de un conjunto de datos: todos se usan en su guía', () => { + for (const language of LANGUAGES) { + const used = new Set() + for (const { task, dataset, datasetTable, testSize, stepByStep } of CASES) { + trainerGuide(translator(language, [], used), task, dataset, { upload: dataset === UPLOAD, datasetTable, testSize, stepByStep }) + } + const texts = keysOf(lookup(language, 'guide.train'), 'guide.train').map((key) => key.replace(/\.(title|content)$/, '')) + expect([...new Set(texts)].filter((key) => !key.includes('.common.') && !key.includes('.layer.') && !used.has(key + '.title'))).toEqual([]) + } + }) +}) diff --git a/tests/setupTests.ts b/tests/setupTests.ts index 198cd6a..2cdacad 100644 --- a/tests/setupTests.ts +++ b/tests/setupTests.ts @@ -3,8 +3,17 @@ // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom' +import { configure } from '@testing-library/react' import { vi } from 'vitest'; +// Las páginas perezosas (lazy) importan TF.js y tardan en cargar, más con todos los ficheros de tests en paralelo: el +// segundo que esperan por defecto waitFor y findBy se quedaba justo (TestPage tardaba 1045 ms) y fallaban al azar +configure({ asyncUtilTimeout: 5000 }) + +// jsdom no desplaza la página y no tiene scrollIntoView (lo usan los saltos a una sección, como al elegir una tarea en +// la home): uno vacío, que las pruebas pueden espiar +if (typeof Element.prototype.scrollIntoView !== 'function') Element.prototype.scrollIntoView = vi.fn() + vi.mock('react-i18next', async () => { const actual = await vi.importActual('react-i18next'); diff --git a/tests/thirdParty/DataFrame.test.ts b/tests/thirdParty/DataFrame.test.ts index d875bcc..b45ea59 100644 --- a/tests/thirdParty/DataFrame.test.ts +++ b/tests/thirdParty/DataFrame.test.ts @@ -2,16 +2,17 @@ import * as dfd from 'danfojs' describe('DataFrame', () => { test('DataFrame Dates', () => { + // Fechas en hora local (año, mes desde 0, día, horas…), como las lee dt.hours(): así el test da lo mismo en + // cualquier zona horaria. Con new Date('2019-01-02') (solo la fecha) sería medianoche UTC: las 01:00 en Madrid, + // pero las 00:00 en GitHub Actions (UTC). const data = [ - ['Alice', 2, new Date('2029-01-01 01:00:00')], - ['Bob', 5, new Date('2019-01-02')], - ['Charlie', 30, new Date('2020-01-03 01:00:20')], - ['Dennis', 89, new Date('2022-02-04 02:16:00')] + ['Alice', 2, new Date(2029, 0, 1, 1, 0, 0)], + ['Bob', 5, new Date(2019, 0, 2)], + ['Charlie', 30, new Date(2020, 0, 3, 1, 0, 20)], + ['Dennis', 89, new Date(2022, 1, 4, 2, 16, 0)], ] const columns: string[] = ['Name', 'Count', 'Date'] const df = new dfd.DataFrame(data, { columns: columns }) - expect(df['Date'].dt.hours().values).toStrictEqual([1, 1, 1, 2]) - // expect(df['Date'].dt.hours().values).toStrictEqual([1, 0, 1, 2]) - // expect([5,5]).toStrictEqual([6,5]) + expect(df['Date'].dt.hours().values).toStrictEqual([1, 0, 1, 2]) }) }) diff --git a/tsconfig.app.json b/tsconfig.app.json index 984a46b..ac73301 100644 --- a/tsconfig.app.json +++ b/tsconfig.app.json @@ -16,6 +16,7 @@ "@/CONSTANTS_DanfoJS": ["src/CONSTANTS_DanfoJS"], "@/DATA_MODEL": ["src/DATA_MODEL"], "@/TASKS": ["src/TASKS"], + "@/TASK_OPTIONS": ["src/TASK_OPTIONS"], "@/MODEL_KEYS": ["src/MODEL_KEYS"], "@/types/*": ["src/types/*"], diff --git a/tsconfig.e2e.json b/tsconfig.e2e.json new file mode 100644 index 0000000..f9619e2 --- /dev/null +++ b/tsconfig.e2e.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.e2e.tsbuildinfo", + "target": "ES2023", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "module": "ESNext", + "types": ["node"], + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["e2e", "playwright.config.ts"] +} diff --git a/tsconfig.json b/tsconfig.json index 1ffef60..a999c8a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,6 +2,7 @@ "files": [], "references": [ { "path": "./tsconfig.app.json" }, - { "path": "./tsconfig.node.json" } + { "path": "./tsconfig.node.json" }, + { "path": "./tsconfig.e2e.json" } ] } diff --git a/tsconfig.node.json b/tsconfig.node.json index 8a67f62..9a464b9 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -22,5 +22,5 @@ "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true }, - "include": ["vite.config.ts"] + "include": ["vite.config.ts", "vite/**/*.ts"] } diff --git a/vite.config.ts b/vite.config.ts index b9f45fc..bfa5cc9 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,68 +1,169 @@ -/// /// /// -import { defineConfig, loadEnv } from "vite" -import react from "@vitejs/plugin-react" -import path from "path" -import svgrPlugin from "vite-plugin-svgr" +import { defineConfig, loadEnv, type Plugin } from 'vite' +import { configDefaults } from 'vitest/config' +import react from '@vitejs/plugin-react' +import basicSsl from '@vitejs/plugin-basic-ssl' +import fs from 'fs' +import path from 'path' +import svgrPlugin from 'vite-plugin-svgr' + +import { n4lPackages } from './vite/n4lPackages' + +// Ruta real (pnpm enlaza node_modules/@vladmandic/face-api a node_modules/.pnpm/…): así se comparan los importadores +const FACE_API = fs.realpathSync(path.resolve(__dirname, 'node_modules/@vladmandic/face-api')) + +/** + * El código de face-api importa TF.js de ../dist/tfjs.esm, que en el paquete publicado es TF.js entero empaquetado + * (1,2 MB): se cambia por src/tfjs/tf-browser.ts, que reexporta el @tensorflow/tfjs del proyecto (lo mismo que hace + * su build "nobundle"). Igual con ../dist/tfjs.version, que se genera de src/tfjs/tf-version.ts. + */ +function resolveFaceApiTfjs(source: string, importer: string | undefined): string | undefined { + if (importer === undefined || !source.startsWith('.')) return undefined + const target = path.resolve(path.dirname(importer), source).replace(/\.js$/, '') + if (target === path.join(FACE_API, 'dist/tfjs.esm')) return path.join(FACE_API, 'src/tfjs/tf-browser.ts') + if (target === path.join(FACE_API, 'dist/tfjs.version')) return path.join(FACE_API, 'src/tfjs/tf-version.ts') + return undefined +} + +// En la build (Rollup) y con los módulos que Vite sirve uno a uno en desarrollo +const faceApiTfjs: Plugin = { + name : 'n4l:face-api-tfjs', + enforce : 'pre', + resolveId: (source, importer) => resolveFaceApiTfjs(source, importer), +} + +// Lo que danfojs importa al cargarse y casi nunca usa, cambiado solo para él (src/core/dataframe/danfo*.ts): Plotly +// (df.plot) se descarga al dibujar y xlsx (readExcel y toExcel, que la app no usa) no se incluye +const DANFO = fs.realpathSync(path.resolve(__dirname, 'node_modules/danfojs')) +const DANFO_LAZY_DEPS: Record = { + 'plotly.js-dist-min': path.resolve(__dirname, 'src/core/dataframe/danfoPlotly.ts'), + 'xlsx' : path.resolve(__dirname, 'src/core/dataframe/danfoXlsx.ts'), +} + +// Solo en la build: en desarrollo Vite empaqueta danfo con esbuild y no pasa por aquí (lleva los de verdad) +const danfoLazyDeps: Plugin = { + name : 'n4l:danfo-lazy-deps', + enforce : 'pre', + apply : 'build', + resolveId: (source, importer) => (importer?.startsWith(DANFO) ? DANFO_LAZY_DEPS[source] : undefined), +} + +/** + * Librerías que van en un chunk propio. danfojs las importa sin import() (y la app usa también Plotly y mathjs en las + * mismas páginas), así que Rollup las juntaba con danfojs en un solo chunk de 5,3 MB. Por separado se descargan en + * paralelo y siguen en la caché del navegador cuando cambia el código de la app; se siguen cargando solo en las + * páginas que las usan. + */ +const VENDOR_CHUNKS: [name: string, module: RegExp][] = [ + ['plotly', /\/node_modules\/plotly\.js-dist-min\//], + ['mathjs', /\/node_modules\/(mathjs|decimal\.js|complex\.js|fraction\.js|typed-function)\//], + ['xlsx', /\/node_modules\/xlsx\//], +] // https://vite.dev/config/ -export default defineConfig(({ mode }) => { +export default defineConfig(({ mode, command }) => { // `base` (ruta de los assets) sigue a VITE_PATH: // VITE_PATH="" → base "/" (raíz del dominio, p.ej. Netlify) // VITE_PATH="/n4l" → base "/n4l/" (subruta) - const env = loadEnv(mode, process.cwd(), "") - const base = env.VITE_PATH ? `${env.VITE_PATH}/` : "/" + const env = loadEnv(mode, process.cwd(), '') + const base = env.VITE_PATH ? `${env.VITE_PATH}/` : '/' return { plugins: [ + faceApiTfjs, + danfoLazyDeps, + // Los paquetes .n4l de public/n4l/ (modelos, datos y textos de cada conjunto): import 'virtual:n4l-catalog' + n4lPackages(), react(), svgrPlugin({ - svgrOptions: { exportType: "default", ref: true, svgo: false, titleProp: true }, - include : "**/*.svg", + svgrOptions: { exportType: 'default', ref: true, svgo: false, titleProp: true }, + include : '**/*.svg', }), + // `vite --mode https` (pnpm dev:https): un certificado de desarrollo, para que la cámara funcione también desde + // otros dispositivos (por la IP de la red local o de Tailscale; el navegador solo da la cámara con HTTPS) + ...(mode === 'https' ? [basicSsl()] : []), ], optimizeDeps: { include: [ '@tensorflow/tfjs', '@tensorflow/tfjs-core', '@tensorflow/tfjs-converter', + // Se cargan con import() al elegirlos en el menú (src/core/tfBackend.ts): sin esto, en desarrollo Vite los + // descubriría entonces y volvería a empaquetar las dependencias recargando la página + '@tensorflow/tfjs-backend-wasm', + '@tensorflow/tfjs-backend-webgpu', ], + esbuildOptions: { + plugins: [{ + // En desarrollo Vite empaqueta face-api con esbuild, que no pasa los imports relativos por los plugins de + // Vite: sin esto se colaba el TF.js empaquetado de face-api (TF.js dos veces, kernels registrados de nuevo) + name : 'n4l:face-api-tfjs', + setup: (build) => { + build.onResolve({ filter: /dist\/tfjs\.(esm|version)/ }, ({ path: source, importer }) => { + const resolved = resolveFaceApiTfjs(source, importer) + return resolved === undefined ? undefined : { path: resolved } + }) + }, + }], + }, + }, + // Workers de módulo (new Worker(new URL(…, import.meta.url), { type: 'module' })): mismo formato que la app + worker: { + format: 'es' as const, }, resolve: { alias: { - "@" : path.resolve(__dirname, "src"), - "@/App" : path.resolve(__dirname, "src/App"), - "@/CONSTANTS_ACTIONS" : path.resolve(__dirname, "src/CONSTANTS_ACTIONS"), - "@/CONSTANTS_ChartsJs": path.resolve(__dirname, "src/CONSTANTS_ChartsJs"), - "@/CONSTANTS_DanfoJS" : path.resolve(__dirname, "src/CONSTANTS_DanfoJS"), - "@/DATA_MODEL" : path.resolve(__dirname, "src/DATA_MODEL"), - "@/TASKS" : path.resolve(__dirname, "src/TASKS"), - "@/MODEL_KEYS" : path.resolve(__dirname, "src/MODEL_KEYS"), - "@/types" : path.resolve(__dirname, "src/types"), - "@assets" : path.resolve(__dirname, "src/assets"), - "@components" : path.resolve(__dirname, "src/components"), - "@context" : path.resolve(__dirname, "src/context"), - "@core" : path.resolve(__dirname, "src/core"), - "@hooks" : path.resolve(__dirname, "src/hooks"), - "@pages" : path.resolve(__dirname, "src/pages"), - "@shared" : path.resolve(__dirname, "src/shared"), - "@styles" : path.resolve(__dirname, "src/styles"), - "@utils" : path.resolve(__dirname, "src/utils"), + '@' : path.resolve(__dirname, 'src'), + '@/App' : path.resolve(__dirname, 'src/App'), + '@/CONSTANTS_ACTIONS' : path.resolve(__dirname, 'src/CONSTANTS_ACTIONS'), + '@/CONSTANTS_ChartsJs': path.resolve(__dirname, 'src/CONSTANTS_ChartsJs'), + '@/CONSTANTS_DanfoJS' : path.resolve(__dirname, 'src/CONSTANTS_DanfoJS'), + '@/DATA_MODEL' : path.resolve(__dirname, 'src/DATA_MODEL'), + '@/TASKS' : path.resolve(__dirname, 'src/TASKS'), + '@/TASK_OPTIONS' : path.resolve(__dirname, 'src/TASK_OPTIONS'), + '@/MODEL_KEYS' : path.resolve(__dirname, 'src/MODEL_KEYS'), + '@/types' : path.resolve(__dirname, 'src/types'), + '@assets' : path.resolve(__dirname, 'src/assets'), + '@components' : path.resolve(__dirname, 'src/components'), + '@context' : path.resolve(__dirname, 'src/context'), + '@core' : path.resolve(__dirname, 'src/core'), + '@hooks' : path.resolve(__dirname, 'src/hooks'), + '@pages' : path.resolve(__dirname, 'src/pages'), + '@shared' : path.resolve(__dirname, 'src/shared'), + '@styles' : path.resolve(__dirname, 'src/styles'), + '@utils' : path.resolve(__dirname, 'src/utils'), // danfojs publica por defecto un bundle precompilado (lib/bundle.esm.js, ~5,7 MB) que // incluye su propia copia de TensorFlow.js 3. Usamos su código sin empaquetar para que // importe nuestro @tensorflow/tfjs (forzado a 4.x en pnpm-workspace.yaml) y Rollup pueda // repartir plotly, mathjs y xlsx en chunks aparte. - "danfojs" : path.resolve(__dirname, "node_modules/danfojs/dist/danfojs-browser/src/index.js"), + 'danfojs' : path.resolve(__dirname, 'node_modules/danfojs/dist/danfojs-browser/src/index.js'), + // Ese código de danfojs hace require("mathjs"), que daría la build CommonJS entera (lib/cjs) además de la + // ESM que importa la app: en la build se le da también la ESM para que solo haya una copia de mathjs. + // Solo al construir: en los tests danfojs se carga con Node y su require no pasa por aquí. + ...(command === 'build' && { 'mathjs': path.resolve(__dirname, 'node_modules/mathjs/lib/esm/index.js') }), + // face-api se compila desde su código (src/, parcheado en patches/): el build publicado (dist/) no se usa. + // Sus imports de TF.js los redirige el plugin faceApiTfjs (más arriba). + '@vladmandic/face-api': path.resolve(FACE_API, 'src/index.ts'), }, }, test: { globals : true, - environment: "jsdom", - setupFiles : "./tests/setupTests.ts", + environment: 'jsdom', + setupFiles : './tests/setupTests.ts', + // e2e/ son las pruebas de Playwright (pnpm test:e2e), que van en un navegador de verdad + exclude : [...configDefaults.exclude, 'e2e/**'], }, build: { - // Sin manualChunks: Rollup divide el código según las rutas cargadas con lazy(), así - // cada página descarga solo sus librerías (tfjs, danfojs, modelos de visión…). + // Rollup divide el código según las rutas cargadas con lazy(), así cada página descarga solo sus librerías + // (tfjs, danfojs, modelos de visión…). manualChunks solo saca de ahí las de VENDOR_CHUNKS. + rollupOptions: { + output: { + manualChunks : (id: string) => VENDOR_CHUNKS.find(([, module]) => module.test(id))?.[0], + // Sin esto Rollup mete en cada uno también sus dependencias, incluidas las que comparte con el resto de la + // app (los helpers de CommonJS, @babel/runtime, seedrandom…): la página de inicio cargaba entero el de mathjs + onlyExplicitManualChunks: true, + }, + }, // TensorFlow.js y danfojs siguen siendo grandes por sí solos, de ahí el límite alto. chunkSizeWarningLimit: 5000, }, diff --git a/vite/n4lPackages.ts b/vite/n4lPackages.ts new file mode 100644 index 0000000..a1de8bc --- /dev/null +++ b/vite/n4lPackages.ts @@ -0,0 +1,71 @@ +import fs from 'fs' +import path from 'path' +import type { Plugin, ViteDevServer } from 'vite' + +import { N4L_MANIFEST, N4L_PACKAGES_DIR, n4lManifestFiles, type N4LManifest_t } from '../src/core/n4l/format' +import { upgradeManifest } from '../src/core/n4l/migrate' +import { N4LError } from '../src/core/n4l/validate' + +const VIRTUAL_ID = 'virtual:n4l-catalog' +const RESOLVED_ID = '\0' + VIRTUAL_ID + +/** Un paquete del catálogo: su manifiesto (ya migrado y validado) y dónde está, relativo a public/ */ +export type N4LCatalogEntry_t = N4LManifest_t & { path: string } + +/** Los ficheros que nombra el manifiesto tienen que estar en el paquete */ +function missingFiles(dir: string, manifest: N4LManifest_t): string[] { + return n4lManifestFiles(manifest).filter((file) => !fs.existsSync(path.join(dir, file))).map((file) => `falta el fichero ${file}`) +} + +/** Los paquetes de public/n4l/: cada carpeta .n4l/ con su manifest.json. Un paquete no válido para la build */ +export function readN4LCatalog(publicDir: string): N4LCatalogEntry_t[] { + const root = path.join(publicDir, N4L_PACKAGES_DIR) + if (!fs.existsSync(root)) return [] + return fs.readdirSync(root, { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && entry.name.endsWith('.n4l')) + .map(({ name }) => name) + .sort() + .map((name) => { + const dir = path.join(root, name) + const file = path.join(dir, N4L_MANIFEST) + if (!fs.existsSync(file)) throw new N4LError(name, [`falta ${N4L_MANIFEST}`]) + const manifest = upgradeManifest(JSON.parse(fs.readFileSync(file, 'utf-8'))) as N4LManifest_t + const problems = [ + ...(name === `${manifest.id}.n4l` ? [] : [`la carpeta se tiene que llamar ${manifest.id}.n4l`]), + ...missingFiles(dir, manifest), + ] + if (problems.length > 0) throw new N4LError(manifest.id, problems) + return { ...manifest, path: `${N4L_PACKAGES_DIR}/${name}` } + }) +} + +/** + * Reúne los paquetes .n4l de public/n4l/ en un módulo virtual (`import catalog from 'virtual:n4l-catalog'`): para que la + * aplicación los use basta con dejar la carpeta ahí. En desarrollo, al añadir, cambiar o quitar uno, se recarga. + */ +export function n4lPackages(): Plugin { + let publicDir = '' + const isPackageFile = (file: string) => file.startsWith(path.join(publicDir, N4L_PACKAGES_DIR) + path.sep) + return { + name : 'n4l:packages', + configResolved: (config) => { publicDir = config.publicDir }, + resolveId : (id) => (id === VIRTUAL_ID ? RESOLVED_ID : undefined), + load : (id) => { + if (id !== RESOLVED_ID) return undefined + return `export default ${JSON.stringify(readN4LCatalog(publicDir))}` + }, + configureServer: (server: ViteDevServer) => { + const reload = (file: string) => { + if (!isPackageFile(file) || !(file.endsWith(N4L_MANIFEST) || file.endsWith('.n4l'))) return + const module = server.moduleGraph.getModuleById(RESOLVED_ID) + if (module !== undefined) server.moduleGraph.invalidateModule(module) + server.ws.send({ type: 'full-reload' }) + } + server.watcher.add(path.join(publicDir, N4L_PACKAGES_DIR)) + server.watcher.on('add', reload) + server.watcher.on('change', reload) + server.watcher.on('unlink', reload) + server.watcher.on('unlinkDir', reload) + }, + } +}