{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "rX8mhOLljYeM" }, "source": [ "##### Copyright 2019 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "cellView": "form", "execution": { "iopub.execute_input": "2020-09-23T00:14:53.762003Z", "iopub.status.busy": "2020-09-23T00:14:53.761361Z", "iopub.status.idle": "2020-09-23T00:14:53.763710Z", "shell.execute_reply": "2020-09-23T00:14:53.763091Z" }, "id": "BZSlp3DAjdYf" }, "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": "3wF5wszaj97Y" }, "source": [ "# Guia inicial de TensorFlow 2.0 para expertos" ] }, { "cell_type": "markdown", "metadata": { "id": "DUNzJc4jTj6G" }, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " Ver en TensorFlow.org\n", " \n", " Ejecutar en Google Colab\n", " \n", " Ver codigo en GitHub\n", " \n", " Descargar notebook\n", "
" ] }, { "cell_type": "markdown", "metadata": { "id": "CJEtYUgQnivP" }, "source": [ "Note: Nuestra comunidad de Tensorflow ha traducido estos documentos. Como las traducciones de la comunidad\n", "son basados en el \"mejor esfuerzo\", no hay ninguna garantia que esta sea un reflejo preciso y actual \n", "de la [Documentacion Oficial en Ingles](https://www.tensorflow.org/?hl=en).\n", "Si tienen sugerencias sobre como mejorar esta traduccion, por favor envian un \"Pull request\"\n", "al siguiente repositorio [tensorflow/docs](https://github.com/tensorflow/docs).\n", "Para ofrecerse como voluntario o hacer revision de las traducciones de la Comunidad\n", "por favor contacten al siguiente grupo [docs@tensorflow.org list](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs)." ] }, { "cell_type": "markdown", "metadata": { "id": "hiH7AC-NTniF" }, "source": [ "Este es un notebook de Google Colaboratory. Los programas de Python se executan directamente en tu navegador —una gran manera de aprender y utilizar TensorFlow. Para poder seguir este tutorial, ejecuta este notebook en Google Colab presionando el boton en la parte superior de esta pagina.\n", "\n", "En Colab, selecciona \"connect to a Python runtime\": En la parte superior derecha de la barra de menus selecciona: CONNECT.\n", "Para ejecutar todas las celdas de este notebook: Selecciona Runtime > Run all." ] }, { "cell_type": "markdown", "metadata": { "id": "eOsVdx6GGHmU" }, "source": [ "Descarga e installa el paquete TensorFlow 2.0 version. \n", "\n", "Importa TensorFlow en tu programa:" ] }, { "cell_type": "markdown", "metadata": { "id": "QS7DDTiZGRTo" }, "source": [ "Import TensorFlow into your program:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "execution": { "iopub.execute_input": "2020-09-23T00:14:53.768488Z", "iopub.status.busy": "2020-09-23T00:14:53.767835Z", "iopub.status.idle": "2020-09-23T00:15:00.138331Z", "shell.execute_reply": "2020-09-23T00:15:00.137576Z" }, "id": "0trJmd6DjqBZ" }, "outputs": [], "source": [ "import tensorflow as tf\n", "\n", "from tensorflow.keras.layers import Dense, Flatten, Conv2D\n", "from tensorflow.keras import Model" ] }, { "cell_type": "markdown", "metadata": { "id": "7NAbSZiaoJ4z" }, "source": [ "Carga y prepara el conjunto de datos [MNIST](http://yann.lecun.com/exdb/mnist/)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "execution": { "iopub.execute_input": "2020-09-23T00:15:00.143927Z", "iopub.status.busy": "2020-09-23T00:15:00.143280Z", "iopub.status.idle": "2020-09-23T00:15:00.625627Z", "shell.execute_reply": "2020-09-23T00:15:00.624843Z" }, "id": "JqFRS6K07jJs" }, "outputs": [], "source": [ "mnist = tf.keras.datasets.mnist\n", "\n", "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n", "x_train, x_test = x_train / 255.0, x_test / 255.0\n", "\n", "# Agrega una dimension de canales\n", "x_train = x_train[..., tf.newaxis]\n", "x_test = x_test[..., tf.newaxis]" ] }, { "cell_type": "markdown", "metadata": { "id": "k1Evqx0S22r_" }, "source": [ "Utiliza `tf.data` to separar por lotes y mezclar el conjunto de datos:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "execution": { "iopub.execute_input": "2020-09-23T00:15:02.359711Z", "iopub.status.busy": "2020-09-23T00:15:02.355523Z", "iopub.status.idle": "2020-09-23T00:15:02.415629Z", "shell.execute_reply": "2020-09-23T00:15:02.416140Z" }, "id": "8Iu_quO024c2" }, "outputs": [], "source": [ "train_ds = tf.data.Dataset.from_tensor_slices(\n", " (x_train, y_train)).shuffle(10000).batch(32)\n", "\n", "test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)" ] }, { "cell_type": "markdown", "metadata": { "id": "BPZ68wASog_I" }, "source": [ "Construye el modelo `tf.keras` utilizando la API de Keras [model subclassing API](https://www.tensorflow.org/guide/keras#model_subclassing):" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "execution": { "iopub.execute_input": "2020-09-23T00:15:02.423036Z", "iopub.status.busy": "2020-09-23T00:15:02.422352Z", "iopub.status.idle": "2020-09-23T00:15:02.750226Z", "shell.execute_reply": "2020-09-23T00:15:02.749471Z" }, "id": "h3IKyzTCDNGo" }, "outputs": [], "source": [ "class MyModel(Model):\n", " def __init__(self):\n", " super(MyModel, self).__init__()\n", " self.conv1 = Conv2D(32, 3, activation='relu')\n", " self.flatten = Flatten()\n", " self.d1 = Dense(128, activation='relu')\n", " self.d2 = Dense(10, activation='softmax')\n", "\n", " def call(self, x):\n", " x = self.conv1(x)\n", " x = self.flatten(x)\n", " x = self.d1(x)\n", " return self.d2(x)\n", "\n", "# Crea una instancia del modelo\n", "model = MyModel()" ] }, { "cell_type": "markdown", "metadata": { "id": "uGih-c2LgbJu" }, "source": [ "Escoge un optimizador y una funcion de perdida para el entrenamiento de tu modelo:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "execution": { "iopub.execute_input": "2020-09-23T00:15:02.754934Z", "iopub.status.busy": "2020-09-23T00:15:02.754238Z", "iopub.status.idle": "2020-09-23T00:15:02.756544Z", "shell.execute_reply": "2020-09-23T00:15:02.755996Z" }, "id": "u48C9WQ774n4" }, "outputs": [], "source": [ "loss_object = tf.keras.losses.SparseCategoricalCrossentropy()\n", "\n", "optimizer = tf.keras.optimizers.Adam()" ] }, { "cell_type": "markdown", "metadata": { "id": "JB6A1vcigsIe" }, "source": [ "Escoge metricas para medir la perdida y exactitud del modelo.\n", "Estas metricas acumulan los valores cada epoch y despues imprimen el resultado total." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "execution": { "iopub.execute_input": "2020-09-23T00:15:02.767317Z", "iopub.status.busy": "2020-09-23T00:15:02.766503Z", "iopub.status.idle": "2020-09-23T00:15:02.792960Z", "shell.execute_reply": "2020-09-23T00:15:02.792317Z" }, "id": "N0MqHFb4F_qn" }, "outputs": [], "source": [ "train_loss = tf.keras.metrics.Mean(name='train_loss')\n", "train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')\n", "\n", "test_loss = tf.keras.metrics.Mean(name='test_loss')\n", "test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')" ] }, { "cell_type": "markdown", "metadata": { "id": "ix4mEL65on-w" }, "source": [ "Utiliza `tf.GradientTape` para entrenar el modelo." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "execution": { "iopub.execute_input": "2020-09-23T00:15:02.798751Z", "iopub.status.busy": "2020-09-23T00:15:02.798104Z", "iopub.status.idle": "2020-09-23T00:15:02.800491Z", "shell.execute_reply": "2020-09-23T00:15:02.799886Z" }, "id": "OZACiVqA8KQV" }, "outputs": [], "source": [ "@tf.function\n", "def train_step(images, labels):\n", " with tf.GradientTape() as tape:\n", " predictions = model(images)\n", " loss = loss_object(labels, predictions)\n", " gradients = tape.gradient(loss, model.trainable_variables)\n", " optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n", "\n", " train_loss(loss)\n", " train_accuracy(labels, predictions)" ] }, { "cell_type": "markdown", "metadata": { "id": "Z8YT7UmFgpjV" }, "source": [ "Prueba el modelo:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "execution": { "iopub.execute_input": "2020-09-23T00:15:02.805291Z", "iopub.status.busy": "2020-09-23T00:15:02.804639Z", "iopub.status.idle": "2020-09-23T00:15:02.806641Z", "shell.execute_reply": "2020-09-23T00:15:02.807066Z" }, "id": "xIKdEzHAJGt7" }, "outputs": [], "source": [ "@tf.function\n", "def test_step(images, labels):\n", " predictions = model(images)\n", " t_loss = loss_object(labels, predictions)\n", "\n", " test_loss(t_loss)\n", " test_accuracy(labels, predictions)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "execution": { "iopub.execute_input": "2020-09-23T00:15:02.813765Z", "iopub.status.busy": "2020-09-23T00:15:02.813108Z", "iopub.status.idle": "2020-09-23T00:15:21.446740Z", "shell.execute_reply": "2020-09-23T00:15:21.446217Z" }, "id": "i-2pkctU_Ci7" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "WARNING:tensorflow:Layer my_model is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2. The layer has dtype float32 because its dtype defaults to floatx.\n", "\n", "If you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this warning is likely only an issue if you are porting a TensorFlow 1.X model to TensorFlow 2.\n", "\n", "To change all layers to have dtype float64 by default, call `tf.keras.backend.set_floatx('float64')`. To change just this layer, pass dtype='float64' to the layer constructor. If you are the author of this layer, you can disable autocasting by passing autocast=False to the base Layer constructor.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Epoch 1, Perdida: 0.13988280296325684, Exactitud: 95.79499816894531, Perdida de prueba: 0.06569191813468933, Exactitud de prueba: 97.81999969482422\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Epoch 2, Perdida: 0.043995000422000885, Exactitud: 98.64833068847656, Perdida de prueba: 0.048938024789094925, Exactitud de prueba: 98.32999420166016\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Epoch 3, Perdida: 0.023024842143058777, Exactitud: 99.2683334350586, Perdida de prueba: 0.055615801364183426, Exactitud de prueba: 98.27999877929688\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Epoch 4, Perdida: 0.01340149249881506, Exactitud: 99.56500244140625, Perdida de prueba: 0.05683732032775879, Exactitud de prueba: 98.45999908447266\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Epoch 5, Perdida: 0.009891842491924763, Exactitud: 99.69666290283203, Perdida de prueba: 0.06292029470205307, Exactitud de prueba: 98.3699951171875\n" ] } ], "source": [ "EPOCHS = 5\n", "\n", "for epoch in range(EPOCHS):\n", " for images, labels in train_ds:\n", " train_step(images, labels)\n", "\n", " for test_images, test_labels in test_ds:\n", " test_step(test_images, test_labels)\n", "\n", " template = 'Epoch {}, Perdida: {}, Exactitud: {}, Perdida de prueba: {}, Exactitud de prueba: {}'\n", " print(template.format(epoch+1,\n", " train_loss.result(),\n", " train_accuracy.result()*100,\n", " test_loss.result(),\n", " test_accuracy.result()*100))\n", "\n", " # Reinicia las metricas para el siguiente epoch.\n", " train_loss.reset_states()\n", " train_accuracy.reset_states()\n", " test_loss.reset_states()\n", " test_accuracy.reset_states()" ] }, { "cell_type": "markdown", "metadata": { "id": "T4JfEh7kvx6m" }, "source": [ "El model de clasificacion de images fue entrenado y alcanzo una exactitud de ~98% en este conjunto de datos. Para aprender mas, lee los [tutoriales de TensorFlow](https://www.tensorflow.org/tutorials)." ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "advanced.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.9" } }, "nbformat": 4, "nbformat_minor": 0 }