Cómo utilizar TensorFlow 2.0 con Python

1

Redes neuronales con TensorFlow

2

Introducción a TensorFlow 2.0

Manejo y preprocesamiento de datos para redes neuronales

3

Uso de data pipelines

4

Cómo cargar bases de datos JSON

5

Cargar bases de datos CSV y BASE 64

6

Preprocesamiento y limpieza de datos

7

Keras datasets

8

Datasets generators

9

Aprende a buscar bases de datos para deep learning

10

Cómo distribuir los datos

11

Crear la red neural, definir capas, compilar, entrenar, evaluar y predicciones

Optimización de precisión de modelos

12

Métodos de regularización: overfitting y underfitting

13

Recomendaciones prácticas para ajustar un modelo

14

Métricas para medir la eficiencia de un modelo: callback

15

Monitoreo del entrenamiento en tiempo real: early stopping y patience

16

KerasTuner: construyendo el modelo

17

KerasTuner: buscando la mejor configuración para tu modelo

Almacenamiento y carga de modelos

18

Almacenamiento y carga de modelos: pesos y arquitectura

19

Criterios para almacenar los modelos

Fundamentos de aprendizaje por transferencia

20

Introducción al aprendizaje por transferencia

21

Cuándo utilizar aprendizaje por transferencia

22

Carga de sistemas pre-entrenados en Keras

23

API funcional de Keras

24

Uso sistemas pre-entrenados de TensorFlow Hub

Resultados de entrenamiento

25

Introducción a variables relevantes del TensorBoard

26

Análisis y publicación de resultados del entrenamiento

27

Introducción al despliegue de modelos en producción

28

Siguientes pasos con deep learning

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
10 Hrs
12 Min
37 Seg

Keras datasets

7/28
Resources

Keras offers a series of default datasets with which to feed models, these databases are ideal for testing the performance of different machine learning algorithms because their data is quite clean and ready to be digested.

In the official Keras documentation you can find the available datasets, for this occasion we will work with CIFAR100, a dataset of 60,000 images of 100 different classes related to world objects such as vehicles, animals and others.

You can read the basic structure and a quickstart of use in the documentation, if you want more detail, you can go to the official page of the dataset where you will have access to more specific information.

Downloading and manipulating Keras datasets

We will import the modules to work, where the protagonist will be TensorFlow.

{code-block} python import tensorflow as tf import numpy as np %matplotlib inline import matplotlib.pyplot as plt

To extract the dataset, we will make use of the Keras dataset module (which is included in TensorFlow).

{code-block} python from tensorflow.keras.datasets import cifar100

We will load the dataset with the load_data function and it will be stored in 2 tuples related to the training data (which will be 50,000) and the test data (the remaining 10,000).

{code-block} python (x_train, y_train), (x_test, y_test) = cifar100.load_data(label_mode = "fine")

If we check the dimensions of the training set, we will get in x a set of 50,000 32x32 images in 3 RGB channels, while the labels will be an array of 50,000 elements from 0 to 99.

````{code-block} python print(x_train.shape) print(y_train.shape)

(50000, 32, 32, 3) (50000, 1) ```

We can access any element of the dataset and plot it with matplotlib, where the label will be 78, but what does this value mean?

{code-block} python num_image = 40 plt.imshow(x_train[num_image]) print(y_train[num_image]) 78

Generally the labels are stored in different sessions, i.e., externally there is a dictionary "translation" of these values to their real counterpart. To obtain this translation, we will download it from an external repository.

{code-block} bash !wget --no-check-certificate https://storage.googleapis.com/platzi-tf2/cifar100_labels.json -O /tmp/cifar100_labels.json

We will deserialize the JSON to make it compatible with Python dictionaries.

{code-block} python import json with open("/tmp/cifar100_labels.json") as fine_labels: cifa100r_labels = json.load(fine_labels)

Now we can understand what the numeric tags refer to.

{code-block} python num_label = 78 plt.imshow(x_train[num_label]) print(cifar100_labels[y_train[num_label][0]]) Forest

With this we have loaded a functional dataset to be processed and digested by your models.

Contribution created by Sebastián Franco Gómez.

Contributions 21

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

!wget --no-check-certificate https://storage.googleapis.com/platzi-tf2/cifar100_labels.json \
    -O /tmp/cifar100_labels.json

Para el reto de la semana cargué el dataset de Fashion MNIST:

Creo que es una bota jajajaja

Hay un error en uno de los print. La corrección es la siguiente:

print(cifar100_labels[y_train[num_label][0]])

Utilice el Dataset fashion_mnist e hice la consulta al elemento 52

aparte me cree una variable de llaves, de acuerdo a la informacion del dataset de Keras

Pero no se si sea correcto hacer esto

import tensorflow as tf
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import fashion_mnist

(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
fashion_mnist_labels = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

num_image = 52
plt.imshow(x_train[num_image])
print(fashion_mnist_labels[y_train[num_image]])

Si están en un entorno como VSCode y el comando wget no se los reconoce, pueden internar de la siguiente forma con curl

!curl -k -o  cifar100_labels.json https://storage.googleapis.com/platzi-tf2/cifar100_labels.json
```js plt.imshow(x_train[0]) # Changed 'srt' to 'str' to convert the integer to a string. title_string = "This is the number {}".format(y_train[0]) plt.title(title_string) # Added title to the plot plt.show() ```![](https://static.platzi.com/media/user_upload/image-5f252f92-5dd8-48c4-941d-7b8ad1537912.jpg)
Interesante tarea: ![](https://static.platzi.com/media/user_upload/image-b6917380-3432-4463-9cd5-217d25af90c1.jpg)Y este fue el resultado: ![](https://static.platzi.com/media/user_upload/image-db325629-af55-4c5d-972c-1b4229c3c88b.jpg)

Conjuntos de datos de Keras: una poderosa herramienta para el aprendizaje profundo
Keras, un popular marco de aprendizaje profundo creado sobre TensorFlow, proporciona una manera conveniente de acceder y utilizar varios conjuntos de datos para entrenar y evaluar sus modelos. Estos conjuntos de datos están preprocesados ​​y listos para usarse con el mínimo esfuerzo, lo que le permite ahorrar tiempo y recursos valiosos.

Conjuntos de datos integrados:


  • Keras ofrece un puñado de conjuntos de datos integrados, también conocidos como conjuntos de datos de juguete, que son pequeños y adecuados para principiantes o experimentación rápida. Estos conjuntos de datos se utilizan normalmente para tareas como clasificación o regresión de imágenes. Algunos ejemplos populares incluyen:

MNIST

  • Este conjunto de datos clásico consta de dígitos escritos a mano (0-9) en varios tamaños y orientaciones. Es un excelente punto de partida para los problemas de clasificación de imágenes.

CIFAR-10

  • Conjunto de datos de pequeñas imágenes en color que pertenecen a 10 clases diferentes (p. ej., aviones, automóviles, perros). Es un poco más complejo que MNIST y se utiliza a menudo para la clasificación de imágenes con redes neuronales convolucionales (CNN).

CIFAR-100

  • Una versión extendida de CIFAR-10 con 100 clases de objetos, que proporciona una tarea de clasificación más desafiante.

Boston Housing

  • Conjunto de datos que contiene información sobre casas en Boston, Massachusetts. Se utiliza habitualmente para tareas de regresión, como predecir los precios de la vivienda.
Hola!! En mi caso usando Fashión MNIST obtuve esta imagen: ![](https://static.platzi.com/media/user_upload/image-df9ee0b4-5ef6-43c7-9518-0d44a0d30c5e.jpg)

Utilice la base de datos de fashion_mnist y obtuve un bolso

from tensorflow.keras.datasets import fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
num_image = 99
plt.imshow(x_train[num_image])
print(y_train[num_image])
print(labels[y_train[num_image]])

Pueden ocupar la función squeeze para quitarle una dimensión a y_train. Ya que y_train[40] devuelve un [40] y queremos solo el numero para luego buscarlo en el json

print(y_train[40].squeeze(0)) -> devuelve 40 en vez de [40]
print(cifar100_labels[y_train[40].squeeze(0)]) -> ocupamos ese indice dentro del json

MNIST digits classification 😃

La importancia de cargar %matplotlib inline para contar con todos los beneficios de Matplot en Colab antes de cargar la librería %matplotlib inline import matplotlib.pyplot as plt

Mas facil :

import pandas as pd
jso=pd.read_json("https://storage.googleapis.com/platzi-tf2/cifar100_labels.json")
jso[0][78]

#desacargamos la subclase.
(x_train,y_train),(x_text,y_test) = tf.keras.datasets.
cifar100.load_data(label_mode=“fine”)

from tensorflow.keras.datasets import fashion_mnist
 (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
plt.imshow(x_train[10])

Si estan de forma local y no pueden por alguna razon hacer wget o curl, también puede ejecutar este codigo de python

import urllib.request
url = 'https://storage.googleapis.com/platzi-tf2/cifar100_labels.json'
filename = 'cifar100_labels.json'
urllib.request.urlretrieve(url, filename) 

Por si a alguien no le sale la importacion de keras, la siguiente puede ser una alternativa:

from tensorflow import keras

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar100.load_data()

Trabaje con el dataset de MNIST

from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
assert x_train.shape == (60000, 28, 28)
assert x_test.shape == (10000, 28, 28)
assert y_train.shape == (60000,)
assert y_test.shape == (10000,)
num_image = 55
plt.imshow(x_train[num_image])
print(y_train[num_image])
num_image = 36
plt.imshow(x_train[num_image])
print(y_train[num_image])

Tambien cargué el dataset fashion_mnist
![](