Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ES] Translations #729

Merged
merged 9 commits into from Jan 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
390 changes: 390 additions & 0 deletions site/es-419/addons/tutorials/average_optimizers_callback.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,390 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "Tce3stUlHN0L"
},
"source": [
"##### Copyright 2020 The TensorFlow Authors."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"id": "tuOe1ymfHZPu"
},
"outputs": [],
"source": [
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MfBg1C5NB3X0"
},
"source": [
"# Promedio de modelos\n",
"\n",
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
" <td><a target=\"_blank\" href=\"https://www.tensorflow.org/addons/tutorials/average_optimizers_callback\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\">Ver en TensorFlow.org</a></td>\n",
" <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/es-419/addons/tutorials/average_optimizers_callback.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\">Ejecutar en Google Colab</a></td>\n",
" <td> <a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/es-419/addons/tutorials/average_optimizers_callback.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\">Ver código fuente en GitHub</a>\n",
"</td>\n",
" <td> <a href=\"https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/es-419/addons/tutorials/average_optimizers_callback.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\">Descargar el bloc de notas</a>\n",
"</td>\n",
"</table>\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xHxb-dlhMIzW"
},
"source": [
"## Descripción general\n",
"\n",
"En este bloc de notas de muestra cómo usar el Moving Average Optimizer (optimizador de promedio móvil) junto con el Model Average Checkpoint (punto de verificación del promedio de modelos) del paquete de complementos de TensorFlow.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "o2UNySlpXkbl"
},
"source": [
"## Promedio móvil\n",
"\n",
"> La ventaja del promedio móvil es que son menos propensos a cambios incontrolables de pérdidas o a una representación irregular de datos en el último lote. Da una idea más fluida y general del entrenamiento del modelo hasta cierto punto.\n",
"\n",
"## Promedio estocástico\n",
"\n",
"> El Stochastic Weight Averaging (promedio de peso estocástico, SWA) converge en óptimos más amplios. Al hacerlo, se asemeja a un conjunto geométrico. El SWA es un método simple para mejorar el rendimiento del modelo cuando se usa como contenedor de otros optimizadores y promedia los resultados de diferentes puntos de la trayectoria del optimizador interno.\n",
"\n",
"## Punto de verificación promedio del modelo\n",
"\n",
"> `callbacks.ModelCheckpoint` no da la opción de guardar pesos promedio móviles a la mitad del entrenamiento, por esa razón los Model Average Optimizers (optimizadores de promedio del modelo) solicitaron una retrollamada personalizada. Mediante el uso del parámetro `update_weights`, `ModelAverageCheckpoint` le permite:\n",
"\n",
"1. Asignar los pesos de promedio móvil al modelo y guardarlos.\n",
"2. Mantener los pesos antiguos no promediados, pero que el modelo guardado use los pesos promedio."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MUXex9ctTuDB"
},
"source": [
"## Preparación"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "sXEOqj5cIgyW"
},
"outputs": [],
"source": [
"!pip install -U tensorflow-addons"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IqR2PQG4ZaZ0"
},
"outputs": [],
"source": [
"import tensorflow as tf\n",
"import tensorflow_addons as tfa"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4hnJ2rDpI38-"
},
"outputs": [],
"source": [
"import numpy as np\n",
"import os"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Iox_HZNNYLEB"
},
"source": [
"## Construir el modelo "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KtylpxOmceaC"
},
"outputs": [],
"source": [
"def create_model(opt):\n",
" model = tf.keras.models.Sequential([\n",
" tf.keras.layers.Flatten(), \n",
" tf.keras.layers.Dense(64, activation='relu'),\n",
" tf.keras.layers.Dense(64, activation='relu'),\n",
" tf.keras.layers.Dense(10, activation='softmax')\n",
" ])\n",
"\n",
" model.compile(optimizer=opt,\n",
" loss='sparse_categorical_crossentropy',\n",
" metrics=['accuracy'])\n",
"\n",
" return model"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pwdM2pl3RSPb"
},
"source": [
"## Preparar el conjunto de datos"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "mMOeXVmbdilM"
},
"outputs": [],
"source": [
"#Cargar grupo de datos de Fashion MNIST \n",
"train, test = tf.keras.datasets.fashion_mnist.load_data()\n",
"\n",
"images, labels = train\n",
"images = images/255.0\n",
"labels = labels.astype(np.int32)\n",
"\n",
"fmnist_train_ds = tf.data.Dataset.from_tensor_slices((images, labels))\n",
"fmnist_train_ds = fmnist_train_ds.shuffle(5000).batch(32)\n",
"\n",
"test_images, test_labels = test"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "iEbhI_eajpJe"
},
"source": [
"Aquí comparamos tres optimizadores:\n",
"\n",
"- SGD (Stochastic gradient descent [descenso de gradiente estocástico]) sin contenedor\n",
"- SGD con promedio móvil\n",
"- SGD con promedio de peso estocástico\n",
"\n",
"Y a continueación puede observar cómo se desempeñan con el mismo modelo."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_Q76K1fNk7Va"
},
"outputs": [],
"source": [
"#Optimizadores\n",
"sgd = tf.keras.optimizers.SGD(0.01)\n",
"moving_avg_sgd = tfa.optimizers.MovingAverage(sgd)\n",
"stocastic_avg_sgd = tfa.optimizers.SWA(sgd)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nXlMX4p9qHwg"
},
"source": [
"Tanto el optimizador `MovingAverage` como el `StochasticAverage` usan `ModelAverageCheckpoint`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "SnvZjt34qEHY"
},
"outputs": [],
"source": [
"#Callback \n",
"checkpoint_path = \"./training/cp-{epoch:04d}.ckpt\"\n",
"checkpoint_dir = os.path.dirname(checkpoint_path)\n",
"\n",
"cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_dir,\n",
" save_weights_only=True,\n",
" verbose=1)\n",
"avg_callback = tfa.callbacks.AverageModelCheckpoint(filepath=checkpoint_dir, \n",
" update_weights=True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "uabQmjMtRtzs"
},
"source": [
"## Entrenar el modelo\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SPmifETHmPix"
},
"source": [
"### Optimizador Vanilla SGD "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Xy8W4LYppadJ"
},
"outputs": [],
"source": [
"#Generar modelo\n",
"model = create_model(sgd)\n",
"\n",
"#Entrenar la red\n",
"model.fit(fmnist_train_ds, epochs=5, callbacks=[cp_callback])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "uU2iQ6HAZ6-E"
},
"outputs": [],
"source": [
"#Evalute results\n",
"model.load_weights(checkpoint_dir)\n",
"loss, accuracy = model.evaluate(test_images, test_labels, batch_size=32, verbose=2)\n",
"print(\"Loss :\", loss)\n",
"print(\"Accuracy :\", accuracy)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lAvhD4unmc6W"
},
"source": [
"### SGD de promedio móvil"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "--NIjBp-mhVb"
},
"outputs": [],
"source": [
"#Build Model\n",
"model = create_model(moving_avg_sgd)\n",
"\n",
"#Train the network\n",
"model.fit(fmnist_train_ds, epochs=5, callbacks=[avg_callback])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "zRAym9EBmnW9"
},
"outputs": [],
"source": [
"#Evalute results\n",
"model.load_weights(checkpoint_dir)\n",
"loss, accuracy = model.evaluate(test_images, test_labels, batch_size=32, verbose=2)\n",
"print(\"Loss :\", loss)\n",
"print(\"Accuracy :\", accuracy)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "K98lbU07m_Bk"
},
"source": [
"### SGD de promedio de peso estocástico "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Ia7ALKefnXWQ"
},
"outputs": [],
"source": [
"#Generar modelo\n",
"model = create_model(stocastic_avg_sgd)\n",
"\n",
"#Entrenar la red\n",
"model.fit(fmnist_train_ds, epochs=5, callbacks=[avg_callback])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "EOT2E9NBoeHI"
},
"outputs": [],
"source": [
"#Evalute results\n",
"model.load_weights(checkpoint_dir)\n",
"loss, accuracy = model.evaluate(test_images, test_labels, batch_size=32, verbose=2)\n",
"print(\"Loss :\", loss)\n",
"print(\"Accuracy :\", accuracy)"
]
}
],
"metadata": {
"colab": {
"collapsed_sections": [
"Tce3stUlHN0L"
],
"name": "average_optimizers_callback.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Loading
Loading