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:

1 D铆as
10 Hrs
9 Min
54 Seg

KerasTuner: construyendo el modelo

16/28
Resources

Keras autotuner will allow us to automate the configuration process of our neural network.

When we want to iterate over multiple configurations for our model (testing different layers, neurons, epochs, learning rate and so on) we will not have to do it manually model by model, this tool will allow us to load and run different formulas to compare their performances.

Modificadores del KerasTuner

Implementing the autotuner

The Keras autotuner is not loaded by default in Google Colab, so we must install it via command line.

python !pip install -q -U keras-tuner

To use it we will import it as kerastuner.

python import kerastuner as kt from tensorflow import keras

For this occasion we will create a new model constructor, this will receive as parameters a tuner object that will determine the variations of different hyperparameters.

We will define a general architecture, where we will add a convolution layer, Max Pooling and flattening in a fixed way, then we will determine the first variable of the constructor: The amount of neurons in the following hidden layer, will be initialized in 32 and will increase up to 512 giving jumps of 32 in 32.

The number of neurons in the next layer will be the iterator object. The rest of the network will remain stable.

Finally we will define variations in the learning rate, where we will start the model with 3 possible learning rates: 0.01, 0.001 and 0.0001.

When compiling the model we will define Adam as the optimizer, however, we will call the class directly and give it the iterator object. All other parameters will remain the same.

````python def constructor_models(hp): model = tf.keras.models.Sequential() model.add(tf.keras.layers.Conv2D(75, (3,3), activation = "relu", input_shape = (28,28,1))) model.add(tf.keras.layers.MaxPooling2D((2,2))) model.add(tf.keras.layers.Flatten()))

hp_units = hp.Int("units", min_value = 32, max_value = 512, step = 32) model.add(tf.keras.layers.Dense(units = hp_units, activation = "relu", kernel_regularizer = regularizers.l2(1e-5))) model.add(tf.keras.layers.Dropout(0.2))) model.add(tf.keras.layers.Dense(128, activation = "relu", kernel_regularizer = regularizers.l2(1e-5))) model.add(tf.keras.layers.Dropout(0.2)) model.add(tf.keras.layers.Dense(len(classes), activation = "softmax"))

hp_learning_rate = hp.Choice("learning_rate", values = [1e-2, 1e-3, 1e-4])

model.compile(optimizer = keras.optimizers.Adam(learning_rate=hp_learning_rate), loss = "categorical_crossentropy", metrics = ["accuracy"])

return model ```

This function will be the raw material of the tuner, which will test all the combinatorics to find the most optimal model.

Contribution created by Sebasti谩n Franco G贸mez.

Contributions 5

Questions 1

Sort by:

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

KerasTuner permite la b煤squeda y optimizaci贸n de hiperpar谩metros. KerasTuner viene con algoritmos de optimizaci贸n bayesiana, hiperbanda y b煤squeda aleatoria integrados. El algoritmo de ajuste utiliza la asignaci贸n de recursos adaptativa y la detenci贸n anticipada para converger r谩pidamente en un modelo de alto rendimiento. El algoritmo entrena una gran cantidad de modelos durante algunas epochs y lleva solo la mitad de los modelos con mejor rendimiento a la siguiente ronda.

KerasTuner al rescate:

KerasTuner simplifica el ajuste de hiperpar谩metros al proporcionar una interfaz f谩cil de usar dise帽ada espec铆ficamente para los modelos Keras.


Le permite definir un espacio de b煤squeda para sus hiperpar谩metros, especificando el rango de valores posibles que pueden tomar.


Luego, KerasTuner implementa diferentes algoritmos de b煤squeda para explorar este espacio e identificar la configuraci贸n de hiperpar谩metros que produce el mejor rendimiento en su tarea.


Beneficios de usar KerasTuner:

Rendimiento mejorado del modelo:

  • Al encontrar la configuraci贸n 贸ptima de hiperpar谩metros, KerasTuner puede mejorar significativamente el rendimiento de su modelo en una tarea determinada.

Tiempo de experimentaci贸n reducido

  • Automatiza el proceso de ajuste de hiperpar谩metros, lo que le ahorra tiempo y esfuerzo en comparaci贸n con la experimentaci贸n manual.

Mayor eficiencia

  • Optimiza la capacitaci贸n centr谩ndose en configuraciones con mejor potencial.

En resumen, KerasTuner le permite optimizar el ajuste de hiperpar谩metros para sus modelos Keras, lo que genera modelos con mejor rendimiento y un flujo de trabajo de desarrollo m谩s eficiente.

As铆 estructur茅 los comentarios del codigo del modelo

# definira una funcion que recibe la cantidad de neuronas inicial de la capa de entrada
def constructor_modelos(hp):
  model = tf.keras.models.Sequential() #modelo secuencial

  #capa de entrada
  # aplico convolucion y maxpool
  model.add(tf.keras.layers.Conv2D(75, (3,3), activation= "relu", input_shape = (28, 28, 1))) 
  model.add(tf.keras.layers.MaxPool2D((2,2)))
  #tranformo matriz de imagen a lista
  model.add(tf.keras.layers.Flatten())

  #capas intermedias 1
  #esta capa sera variable
  #para esta capa establecere un rango[32,512] e ire saltando con paso 32
  hp_units = hp.Int("units", min_value = 32, max_value = 512, step = 32) #establezco el rango
  model.add(tf.keras.layers.Dense(units=hp_units,activation = "relu", kernel_regularizer= regularizers.l2(1e-5))) #ese rango le doy a la capa
  model.add(tf.keras.layers.Dropout(0.2)) #como antes le doy ese dropout

  #capa intermedia 2
  #esta capa la hare fija,128 neuronas
  model.add(tf.keras.layers.Dense(128,activation = "relu", kernel_regularizer= regularizers.l2(1e-5)))
  model.add(tf.keras.layers.Dropout(0.2))

  #capa de salida
  model.add(tf.keras.layers.Dense(len(classes), activation = "softmax"))

  #tambien el lerning rate sera variable,entre estas tres opciones:
  hp_learning_rate = hp.Choice('learning_rate', values = [1e-2, 1e-3, 1e-4])
  model.compile(optimizer = keras.optimizers.Adam(learning_rate=hp_learning_rate),loss = "categorical_crossentropy", metrics = ["accuracy"])
  #para el optimizador probara con esas opciones de learning rate

  return model

Tiene errores sint谩cticos pero sem谩nticamente se entiende jeje

a partir de aqu铆 ya me perd铆 o.o