martes, 20 de noviembre de 2018

TensorFlow and deep learning, without a PhD

https://codelabs.developers.google.com/codelabs/cloud-tensorflow-mnist/#0

TensorFlow and deep learning, without a PhD

 

1. Overview


In this codelab, you will learn how to build and train a neural network that recognises handwritten digits. Along the way, as you enhance your neural network to achieve 99% accuracy, you will also discover the tools of the trade that deep learning professionals use to train their models efficiently.
This codelab uses the MNIST dataset, a collection of 60,000 labeled digits that has kept generations of PhDs busy for almost two decades. You will solve the problem with less than 100 lines of Python / TensorFlow code.

What you'll learn

  • What is a neural network and how to train it
  • How to build a basic 1-layer neural network using TensorFlow
  • How to add more layers
  • Training tips and tricks: overfitting, dropout, learning rate decay...
  • How to troubleshoot deep neural networks
  • How to build convolutional networks

What you'll need

  • Python 2 or 3 (Python 3 recommended)
  • TensorFlow
  • Matplotlib (Python visualisation library)
Installation instructions are given in the next step of the lab.

 

Adding layers in Tensor Flow - Trabajando varias capas en Tensor Flow

Adding layers in Tensor Flow - Trabajando varias capas en Tensor Flow
https://codelabs.developers.google.com/codelabs/cloud-tensorflow-mnist/#6


7. Lab: adding layers


To improve the recognition accuracy we will add more layers to the neural network. The neurons in the second layer, instead of computing weighted sums of pixels will compute weighted sums of neuron outputs from the previous layer. Here is for example a 5-layer fully connected neural network:

We keep softmax as the activation function on the last layer because that is what works best for classification. On intermediate layers however we will use the the most classical activation function: the sigmoid:

To add a layer, you need an additional weights matrix and an additional bias vector for the intermediate layer:
W1 = tf.Variable(tf.truncated_normal([28*28, 200] ,stddev=0.1))
B1 = tf.Variable(tf.zeros([200]))

W2 = tf.Variable(tf.truncated_normal([200, 10], stddev=0.1))
B2 = tf.Variable(tf.zeros([10]))
The shape of the weights matrix for a layer is [N, M] where N is the number of inputs and M of outputs for the layer. In the code above, we use 200 neurons in the intermediate layer and still 10 neurons in the last layer.
And now change your 1-layer model into a 2-layer model:
XX = tf.reshape(X, [-1, 28*28])

Y1 = tf.nn.sigmoid(tf.matmul(XX, W1) + B1)
Y  = tf.nn.softmax(tf.matmul(Y1, W2) + B2)
That's it. You should now be able to push your network above 97% accuracy with 2 intermediate layer with for example 200 and 100 neurons.

Red neuronal con varias capas en TEnsor Flow - Simple MNIST Autoencoder in TensorFlow


Red neuronal con varias capas en TEnsor Flow - Simple MNIST Autoencoder in TensorFlow
https://gertjanvandenburg.com/blog/autoencoder/



Simple MNIST Autoencoder in TensorFlow

GitHub: AutoEncoder.

Recently I’ve been playing around a bit with TensorFlow. Even though my past research hasn’t used a lot of deep learning, it’s a valuable tool to know how to use. To get to know the basics, I’m trying to implement a few simple models myself. The benefit of implementing it yourself is of course that it's much easier to play with the code and extend it. In this post, I will present my TensorFlow implementation of Andrej Karpathy’s MNIST Autoencoder, originally written in ConvNetJS.
An autoencoder is a neural network that consists of two parts: an encoder and a decoder. The encoder network encodes the original data to a (typically) low-dimensional representation, whereas the decoder network converts this representation back to the original feature space. The idea is that the low-dimensional representation forms a non-linear dimensionality reduction of the original data. Here’s a graphical illustration of the network structure:
Illustration of the network structure of the autoencoder. In reality the size of the layers is larger than shown here: the blue layers have 50 nodes in the actual network and the input and output layers have 784 nodes. Illustration of the network structure of the autoencoder. In reality the size of the layers is larger than shown here: the blue layers have 50 nodes in the actual network and the input and output layers have 784 nodes.
Okay, let’s get to the code. As mentioned, I’ll be reconstructing Andrej Karpathy’s structure, which consists of 2 fully connected layers with 50 neurons, then a layer with just 2 neurons, and then again 2 layers with 50 neurons before a final read-out layer. Since we’ll use a lot of fully connected layers we’ll make some quick utility functions to make our life easier. First, for the weight matrix we use: The functions for the weights and biases are taken from the TensorFlow MNIST tutorial.
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)
and for the biases:
def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)
For the fully connected layer, we’ll make use of the fact that the MNIST data is monochrome, so we don’t have to care about the color channels. This means that we can define our fully connected layers simply as follows:
def fc_layer(prev, input_size, output_size):
    W = weight_variable([input_size, output_size])
    b = bias_variable([output_size])
    return tf.matmul(prev, W) + b
With these utilities in place, we’re ready to build our model. Recall that the MNIST images are 28 x 28 = 784 pixels. Here we consider the input to the model to be a single vector of length 784. The model can then be captured through the following function:
def autoencoder(x):
    l1 = tf.nn.tanh(fc_layer(x, 28*28, 50))
    l2 = tf.nn.tanh(fc_layer(l1, 50, 50))
    l3 = fc_layer(l2, 50, 2)
    l4 = tf.nn.tanh(fc_layer(l3, 2, 50))
    l5 = tf.nn.tanh(fc_layer(l4, 50, 50))
    out = fc_layer(l5, 50, 28*28)
    loss = tf.reduce_mean(tf.squared_difference(x, out))
    return loss, out, l3
This function clearly shows the symmetry in the model through the parameters to the fc_layer function. In the end, we compute the mean squared error between the input and the output image and use that as the loss function.
Before turning to the code for training the model, I’ll present some code for using a TensorBoard with this model. I wanted to be able to visualize the input, output, and latent layers in the model for a batch of input images. To do this nicely, I used the form_image_grid function from the Magenta package, with the following helper function:
def layer_grid_summary(name, var, image_dims):
    prod = np.prod(image_dims)
    grid = form_image_grid(tf.reshape(var, [BATCH_SIZE, prod], [GRID_ROWS,
        GRID_COLS], image_dims, 1))
    return tf.summary.image(name, grid)
This creates a nice tiled image of GRID_ROWS x GRID_COLS as a single tensor, which we can use in a Summary. For the sake of presentation, we can wrap the TensorBoard related stuff in a function:
def create_summaries(loss, x, latent, output):
    writer = tf.summary.FileWriter("./logs")
    tf.summary.scalar("Loss", loss)
    layer_grid_summary("Input", x, [28, 28])
    layer_grid_summary("Encoder", latent, [2, 1])
    layer_grid_summary("Output", output, [28, 28])
    return writer, tf.summary.merge_all()
By combining all summary statements in a single operation using tf.summary.merge_all(), we can use some simple code to create all summaries simultaneously. Finally, we have the following function to pull everything together and run the training:
def main():
    # load the data
    mnist = input_data.read_data_sets("./MNIST_data")
    # initialize inputs
    x = tf.placeholder(tf.float32, shape=[None, 28*28])
    # build the model
    loss, output, latent = autoencoder(x)
    # initialize optimizer
    train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)
    # initialize summaries
    writer, summary_op = create_summaries(loss, x, latent, output)

    # run the training loop
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for i in range(10000):
            batch = mnist.train.next_batch(BATCH_SIZE)
            feed = {x : batch[0]}
            if i % 500 == 0:
                summary, train_loss = sess.run([summary_op, loss],
                    feed_dict=feed)
                print("Step: %d. Loss: %g" % (i, train_loss))

                writer.add_summary(summary, i)
                writer.flush()

            train_step.run(feed_dict=feed)
That’s the full code for the MNIST autoencoder. There’s plenty of things to play with here, such as the network architecture, activation functions, the minimizer, training steps, etc. Below I’ll take a brief look at some of the results.
We can compare the input images to the autoencoder with the output images to see how accurate the encoding/decoding becomes during training. Remember, in the architecture above we only have 2 latent neurons, so in a way we’re trying to encode the images with 28 x 28 = 784 bytes of information down to 2 bytes of information. This is not entirely true because the latent neurons are not clipped to the range [0, 255]. It would be more accurate to say that the autoencoder is a nonlinear feature transformation that maps a 784 dimensional space down to a 2 dimensional space.
Here is an animation that shows the evolution over time of some input images and the corresponding output images of the network.
Animation of the input and output layer of the network over time.
As you can see, there’s a bit of a grey offset in the images. This is because the last layer of the network doesn’t clip the pixel values to the range [0, 255]. I found that adding a ReLU over the read-out layer can help remove this offset: I'm sure there are other ways to get rid of this offset too. For instance, you could apply a softmax over the last layer and multiply with 255.
out = tf.nn.relu(fc_layer(l5, 50, 28*28))
With this modification, the animation looks as follows:
Animation of the input and output layer of the network with a ReLU over the read-out layer.
From this figure it is evident that the network actually converges pretty quickly and then spends quite some time tweaking the few incorrect outcomes. Notice that the encoding/decoding of the images removes a lot of nuance from the images: for instance the 2 1 pair on the second row has a lot of detail on the left that does not appear on the right.
To look at how the latent space maps images from different digits, we can feed some test set images through the network and record the values of the latent neurons. Here is a scatter plot of this latent space for the first 1000 images from the test set:
Plot of the latent space for the first 1000 digits of the test dataset. Plot of the latent space for the first 1000 digits of the test dataset.
It can be seen that the latent space for the digit 1 is quite well defined, as well as that for 0 and 6. However, the mappings strongly overlap for the digits 4 and 9 as well as for 3 and 8. Note that this mapping is not necessarily a clustering of the data points: there is nothing in the network structure that requires the images of the same digit to lie in the same area of the latent space. For an exploration of clustering the MNIST dataset, see Chris Olah's blog. The only requirement is that the encoding is such that the decoder network can reconstruct the input image accurately.
Finally, we can take a point in the latent space and see the image that the decoder network constructs from it. Below is an animation where we walk around a circle in the latent space and show the corresponding output image. This animation shows how digits are transformed into their neighboring digits in the latent space.
Animation of a path through the latent space and the corresponding output images. Note that the mapping here is slightly different than in the previous figure, because this is generated from a different run.
That’s it! The full code can be found on GitHub. I hope you learned something from this post, I know I did!

Simulador de Redes Neuroanles con Tensor Flow


https://playground.tensorflow.org/#activation=relu&batchSize=10&dataset=xor&regDataset=reg-plane&learningRate=0.03&regularizationRate=0&noise=0&networkShape=4&seed=0.45356&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=true&ySquared=true&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false








Clasificador de Perros con Tensor Flow


https://medium.com/datos-y-ciencia/construye-tu-primer-clasificador-de-deep-learning-con-tensorflow-ejemplo-de-razas-de-perros-ed218bb4df89


Construye tu primer clasificador de Deep Learning con TensorFlow: Ejemplo de razas de perros

Las redes neuronales contorneadas (como la que se muestra arriba) son herramientas poderosas para la clasificación de imágenes
En este artículo, presentaré varias técnicas para que dé los primeros pasos hacia el desarrollo de un algoritmo que podría usarse para un problema clásico de clasificación de imágenes : detectar la raza de un perro a partir de una imagen.
Al final de este artículo, habremos desarrollado un código que aceptará cualquier imagen proporcionada por el usuario como entrada y devolverá una estimación de la raza del perro. Además, si se detecta un ser humano, el algoritmo proporcionará una estimación de la raza de perro que más se asemeja.
NB: Este proyecto se completó como parte de Udacity ‘s Machine Learning Nanodegree ( GitHub repo ).

1. ¿Qué son las redes neuronales convolucionales?

Las redes neuronales convolucionales (también denominadas CNN o ConvNet) son una clase de redes neuronales profundas que se han adoptado ampliamente en varias aplicaciones de visión artificial e imágenes visuales.
Un famoso caso de aplicación CNN fue detallado en este trabajo de investigación por un equipo de investigación de Stanford en el que demostraron la clasificación de las lesiones cutáneas usando una sola CNN. La Red Neural fue entrenada a partir de imágenes utilizando solo píxeles y etiquetas de enfermedades como entradas.
Las redes neuronales convolucionales constan de múltiples capas diseñadas para requerir un preprocesamiento relativamente pequeño en comparación con otros algoritmos de clasificación de imágenes.
Aprenden usando filtros y aplicándolos a las imágenes. El algoritmo toma un cuadrado pequeño (o ‘ventana’) y comienza a aplicarlo sobre la imagen. Cada filtro permite que la CNN identifique ciertos patrones en la imagen. La CNN busca partes de la imagen donde un filtro coincida con el contenido de la imagen.
Un ejemplo de CNN Layer Architecture for Image Classification (fuente: https://bit.ly/2vwlegO )
Las primeras capas de la red pueden detectar características simples como líneas, círculos, bordes. En cada capa, la red puede combinar estos hallazgos y aprender continuamente conceptos más complejos a medida que profundizamos en las capas de la red neuronal.

1.1 ¿Qué tipos de capas hay?

La arquitectura general de una CNN consiste en una capa de entrada, capa(s) oculta(s) y una capa de salida. Son varios tipos de capas, por ejemplo, Convolucional, Activación, Pooling, Dropout, Dense y capa SoftMax.
Las redes neuronales constan de una capa de entrada, capas ocultas y una capa de salida (fuente: https://bit.ly/2Hxhjaw )
La capa convolucional (o capa Conv) es el núcleo de lo que hace una red neuronal convolucional. La capa Conv consiste en un conjunto de filtros. Cada filtro se puede considerar como un cuadrado pequeño (con un ancho y una altura fijos) que se extiende a través de la profundidad total del volumen de entrada.
Durante cada pasada, el filtro ‘se desplaza’ en el ancho y la altura del volumen de entrada. Este proceso da como resultado un mapa de activación bidimensional que proporciona las respuestas de ese filtro en cada posición espacial.
Para evitar un ajuste excesivo, las capas de agrupación se utilizan para aplicar la reducción de muestreo no lineal en los mapas de activación. En otras palabras, agrupar capas es agresivo al descartar información, pero puede ser útil si se usa de forma adecuada. Una capa Pooling a menudo seguiría una o dos Capas Conv en la arquitectura CNN.
Las capas de agrupamiento se utilizan para aplicar la reducción de muestreo no lineal en los mapas de activación (fuente: https://bit.ly/2Hxhjaw )
Las capas de deserción también se utilizan para reducir el exceso de ajuste, ignoran aleatoriamente ciertas funciones de activación, mientras que las capas densas son capas completamente conectadas y, a menudo, se encuentran al final de la red neuronal.

1.2 ¿Qué son las funciones de activación?

La salida de las capas y de la red neuronal se procesa utilizando una función de activación, que es un nodo que se agrega a las capas de ocultación y a la capa de salida.
A menudo encontrará que la función de activación de ReLu se usa en capas ocultas, mientras que la capa final generalmente consiste en una función de activación de SoftMax. La idea es que al apilar capas de funciones lineales y no lineales, podemos detectar una amplia gama de patrones y predecir con precisión una etiqueta para una imagen determinada.
SoftMax a menudo se encuentra en la capa final que actúa básicamente como un normalizador y produce un vector discreto de distribución de probabilidad, que es genial para nosotros, ya que la salida de la CNN que queremos es una probabilidad de que una imagen se corresponda con una clase en particular.
Las funciones de activación más comunes incluyen las funciones de activación ReLU y Sigmoid
Cuando se trata de la evaluación del modelo y la evaluación del rendimiento, se elige una función de pérdida. En las CNN para la clasificación de imágenes, a menudo se elige la entropía cruzada categorial (en pocas palabras: corresponde a -log(error)). Existen varios métodos para minimizar el error usando Gradient Descent: en este artículo, confiaremos en “ rmsprop “, que es un método de tasa de aprendizaje adaptativo, como un optimizador con precisión como una métrica.

2. Configuración de los bloques de construcción del algoritmo

Para construir nuestro algoritmo, utilizaremos TensorFlow , Keras (API de redes neuronales que se ejecuta sobre TensorFlow) y OpenCV (biblioteca de visión por computadora).
Los conjuntos de datos de capacitación y prueba también estuvieron disponibles cuando se completó este proyecto (ver Repo de GitHub ).

2.1 Detectando si la imagen contiene un rostro humano

Para detectar si la imagen suministrada es una cara humana, usaremos uno de los algoritmos de detección de rostros de OpenCV . Antes de utilizar cualquiera de los detectores faciales, es un procedimiento estándar convertir las imágenes a escala de grises. A continuación, la detectMultiScalefunción ejecuta el clasificador almacenado en face_cascadey toma la imagen en escala de grises como parámetro.

2.2 Detectando si la imagen contiene un perro

Para detectar si la imagen suministrada contiene una cara de perro, usaremos un modelo ResNet -50 preentrenado utilizando el conjunto de datos de ImageNet que puede clasificar un objeto de una de las 1000 categorías . Dada una imagen, este modelo ResNet-50 preentrenado arroja una predicción para el objeto que está contenido en la imagen.
Cuando se usa TensorFlow como backend, las CNN de Keras requieren una matriz 4D como entrada. La path_to_tensorfunción siguiente toma una ruta de archivo con valores de cadena a una imagen en color como entrada, la redimensiona a una imagen cuadrada de 224x224 píxeles y devuelve una matriz 4D (denominada "tensor") adecuada para suministrar a una Keras CNN.
Además, todos los modelos pre-entrenados tienen el paso de normalización adicional que debe restar el píxel medio de cada píxel en cada imagen. Esto se implementa en la función importada preprocess_input.
Como se muestra en el código anterior, para la predicción final obtenemos un número entero correspondiente a la clase de objeto predicha del modelo tomando el argmax del vector de probabilidad pronosticado, que podemos identificar con una categoría de objeto mediante el uso del diccionario deetiquetas ImageNet .

3. Construye tu clasificador CNN usando Transfer Learning

Ahora que tenemos funciones para detectar humanos y perros en imágenes, necesitamos una manera de predecir la raza a partir de las imágenes. En esta sección, crearemos una CNN que clasifique las razas de perros.
Para reducir el tiempo de entrenamiento sin sacrificar la precisión, entrenaremos una CNN usando Transfer Learning , que es un método que nos permite usar Redes que han sido pre-entrenadas en un gran conjunto de datos. Al mantener las primeras capas y solo entrenar las capas recién agregadas, podemos aprovechar el conocimiento adquirido por el algoritmo pre-entrenado y usarlo para nuestra aplicación.
Keras incluye varios modelos de aprendizaje profundo preentrenamiento que se pueden utilizar para la predicción, la extracción de características y el ajuste fino.

3.1 Arquitectura del modelo

Como se mencionó anteriormente, la salida del modelo ResNet-50 va a ser nuestra capa de entrada, llamada características de cuello de botella . En el siguiente bloque de código, extraemos las características del cuello de botella correspondientes a los conjuntos de tren, prueba y validación ejecutando lo siguiente.
Configuraremos nuestra arquitectura de modelo de modo que la última salida convolucional de ResNet-50 se alimente como entrada a nuestro modelo. Solo agregamos una capa Global Pooling común y una capa Fully Connected , donde esta última contiene un nodo para cada categoría de perro y tiene una función de activación de Softmax .
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= global_average_pooling2d_3 ( (None, 2048) 0 _________________________________________________________________ dense_3 (Dense) (None, 133) 272517 ================================================================= Total params: 272,517 Trainable params: 272,517 Non-trainable params: 0 _________________________________________________________________
Como podemos ver en el resultado del código anterior, ¡terminamos con una red neuronal con 272.517 parámetros!

3.2 Compila y prueba el modelo

Ahora, podemos usar la CNN para probar qué tan bien identifica la raza dentro de nuestro conjunto de datos de prueba de imágenes de perros. Para afinar el modelo, pasamos por 20 iteraciones (o “ épocas “) en las que se ajustan los hiperparámetros del modelo para reducir la función de pérdida ( entropía cruzada categorial ) que se optimiza utilizando la proposición RMS.
Test accuracy: 80.0239%
Provisto de un conjunto de prueba, el algoritmo obtuvo una precisión de prueba del 80% . ¡No está mal!

3.3 Predecir razas de perro con el modelo

Ahora que tenemos el algoritmo, vamos a escribir una función que tome una ruta de imagen como entrada y devuelva la raza de perro que predice nuestro modelo.

4. Probando nuestro clasificador CNN

Ahora, podemos escribir una función que acepta aceptar una ruta de archivo a una imagen y primero determina si la imagen contiene un ser humano, un perro o ninguno.
Si se detecta un perro en la imagen, devuelve la raza predicha. Si se detecta un ser humano en la imagen, devuelve la raza de perro que se asemeja. Si nose detecta ninguno en la imagen, proporcione un resultado que indique un error.
¡Estamos listos para tomar el algoritmo para dar un giro! Probemos el algoritmo en algunas imágenes de muestra:
¡Estas predicciones me parecen acertadas!
En una nota final, observé que el algoritmo es propenso a errores a menos que sea una toma clara de frente con muy poco ruido / información adicional sobre la imagen. Por lo tanto, necesitamos hacer que el algoritmo sea más robusto al ruido. El aumento de imagen puede ser útil para resolver esto, que es un tema que trataré en un artículo futuro.

Referencias para tensor Flow


25 Open Datasets for Deep Learning Every Data Scientist Must Work With
https://www.analyticsvidhya.com/blog/2018/03/comprehensive-collection-deep-learning-datasets/

Build a Handwritten Text Recognition System using TensorFlow
https://towardsdatascience.com/build-a-handwritten-text-recognition-system-using-tensorflow-2326a3487cd5

Recognizing Handwritten Digits with a Convolutional Neural Network
https://js.tensorflow.org/tutorials/mnist.html

Tensor Board
https://aimatters.wordpress.com/2016/01/16/solving-xor-with-a-neural-network-in-tensorflow/

xor
https://gist.github.com/pannous/2b8e2e05cf05a630b132
https://martin-thoma.com/tf-xor-tutorial/


Regresion con redes neuronales
https://nbortolotti.blogspot.com/2017/04/regresion-lineal-simple-en-tensorflow.html

Ejemplos de Regresion
altura de los niños basada en su edad (Regresion)
http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=MachineLearning&doc=exercises/ex2/ex2.html

Libro de Tensor Flow
https://torres.ai/research-teaching/tensorflow/libro-hello-world-en-tensorflow/

Como hacer un notebook (tiro parabolico) en Jupyter
https://relopezbriega.github.io/blog/2016/01/10/ecuaciones-diferenciales-con-python/