Mostrando entradas con la etiqueta algoritmo. Mostrar todas las entradas
Mostrando entradas con la etiqueta algoritmo. Mostrar todas las entradas

martes, 13 de marzo de 2018

Random memory adaptation model inspired by the paper: "Memory-based parameter adaptation (MbPA)"


Os dejo a continuación el contenido de un trabajo de investigation sobre machine learning que he realizado en mi escaso tiempo libre: https://github.com/Zeta36/random-memory-adaptation
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Introduction.

I present in this repository a (very simple) random memory adaptation model (RMA) inspired by the Google DeepMind paper:
"Memory-based parameter adaptation (MbPA)" (https://arxiv.org/pdf/1802.10542.pdf)
In the paper, point 4.1. CONTINUAL LEARNING: SEQUENTIAL DISTRIBUTIONAL SHIFT (inside experiments and results), they study the improvements their model suppose in relation to the catastrophic forgetting problem.
They explored the effects of their model (MbPA) on continual learning, i.e. when dealing with the problem of sequentially learning multiple tasks without the ability to revisit a task. For this purposed they use the permuted MNIST setup (Goodfellow et al., 2013).
In page 6 they mention about that once a task is catastrophically forgotten, they found that only a few gradient steps on carefully selected data from memory are sufficient to recover performance.
That point got my attention and I wondered if the same improvement could be reached in an easier (and faster) way using a different approach.

Random memory adaptation model (RMA).

I played around with this idea and created a new model based in a random allocation access (instead of using as they did for MbPA a memory architecture similar to the Differentiable Neural Dictionary (DND) used in Neural Episodic Control (NEC) (Pritzel et al., 2017). The random memory I used has an asymptotic cost of insertion of O(1) and it retrieves pairs of {k,v} also in order O(1). This is much better than what a sorted tree (DND) can do.
The way the RMA works is very straightforward:
  1. We have a memory M = {(hi, vi)}. Keys {hi} are given by the embedding network (in the example of this repository the embedding function is the identity). More details in https://arxiv.org/pdf/1802.10542.pdf
  2. In each step i of the training process we append the current training batch {xi, yi} to the end of the memory M, if and only if m steps lapsed since the last inserting. I.e., we add only a tiny and random fraction of the whole training dataset into the memory M.
  3. In the training process, the backpropagation will be realized over an augmented batch composed by the current training batch i {xi, yi} plus a totally random tiny batch retrieved from the memory M.
  4. We repeat this continue learning process for the n tasks in the same model and without further modification.
That's all.

Results.

The development and use of the RMA is much easier than in the MPbA case, and also the performance of the algorithm is even better that in the DeepMind results. The RMA is able to keep the past knowledge almost perfectly and with a minimal impact in the training time. Moreover, the RMA model does not need access to the test dataset like it's the case in the MPbA.
The only two hyper-parameters we have to chose are the memory size and how much training data we are going to store in the memory.
In the case of the permuted MNIST setup for example it's enough to have sufficient memory allocation to store some examples of all the tasks in order to remember how to solve all of them. In fact, the task n only is forgotten once that all their past "memories" have been overwritten due to a memory no big enough (in relation to the number of tasks).
This is the DeepMind MbPA results in the permuted MNIST (Solving 20 tasks):
These are the results of a RMA with a memory of size 15.000 and where we memorize only 10 batches of the 10.000 used in each task, we can see we still got a great continuity learning ratio in test time.
Solving 10 tasks:
Solving 20 tasks:
Finally, these are the results of the same RMA with a memory of size 15.000, 10 batches of each 10.000 but resolving 40 tasks.
We can see that as long as there is memory for keeping some examples of every task the continual learning rate is very stable against the test dataset...and at the end we are just using a two layers MLP for all the job!! The augmented random memory really seems to do a great work against the catastrophic forgetting.

Future work.

I'd like to check this same model in other tasks and also use a different embedding function (network) different of the identity one used here. Also, there are a lot of possibilities to improve these results. An easy way would be just to keep an independent memory (Mi) for every different task in a similar way Neural Episodic Control(NEC) does for each action in the action space (Ma). Then we would retrieve a random equal proportion from every memory in any backpropagation step.
It'd be interesting too apply this method to some complex supervised task and look for some kind of improvement.

Conclusions.

There is no doubt that the use of some kind of external memory like the one used in MbPA or the used in Neural Episodic Control (NEC) (Pritzel et al., 2017) is going to be a fundamental part of any model able to solve the main shortcomings of neural networks such as catastrophic forgetting, fast, stable acquisition of new knowledge, learning with an imbalanced class labels, and fast learning during evaluation. I showed here that maybe an easy way to solve some of these problems resides just in the use of a random and fast external memory that stores "memories" of past events seen during the training process. It may be possible that we don't need to weighted over the whole memory, and that we don't need neither to use a sorted tree with a kernel able to return the nearest examples.

viernes, 29 de diciembre de 2017

Creando un detector de setas para el móvil (utilizando el framework de machine learning KerasJS)


About

I explain how to export weights from a Keras model and import those weights in Keras.js, a JavaScript framework for running pre-trained neural networks in the browser. I show you later how to include the final result into a Phonegap Cordova mobile application.

Introduction

We are going to create a mushroom detector application for our mobiles. For this task we need to use a machine learning approximation, and as a good approximation we'll use the KerasJS framework.

First Step: Build an image recognition system for several mushroom families.

  • We need to begin training a Keras model in Python. For this purpose we'll use a transfer learning/fine tuning process over a pre-trained InceptionV3 model. The pipeline will be:
  1. Transfer learning: take a ConvNet that has been pre-trained on ImageNet, remove the last fully-connected layer, then treat the rest of the ConvNet as a feature extractor for the new dataset. Once you extract the features for all images, train a classifier for the new dataset.
  2. Fine-tuning: replace and retrain the classifier on top of the ConvNet, and also fine-tune the weights of the pre-trained network via backpropagation.
  • But first we need the database for the customizable mushroom categories. We have to find a big labeled database with thousands of images of each mushroom family we want to detect. This is not an easy issue, so we can trick a bit by searching and downloading Google Images/Image Links:
We can use this Python script in order to download images from Google base in a set if query strings:
google-images-download.py
This script will download 200 images for each of the specified mushroom families:
search_keyword = [
            'Paxinus involutus',
            'sarcosphaera',
            'Inonatus tamaricis',
   ...
   ...
   ];
After this process end we'll have a folder with 200 images named with the mushroom family. We have to cut this folders and move them to a new 'train_dir' folder. We need also create a 'val_dir' folder. In 'val_dir' folder we will have a copy of all downloaded mushroom family folders but just with some images for the validation process (this images cannot be anymore in the 'train_dir' folder).
Now we can start the fine tuning process using the Python Keras script:
fine-tune.py.py
This script will train the mushroom detection model and finally will create as output some weights files we'll use in the next step:
model_mushrooms.json
model_mushrooms_metadata.json
model_mushrooms_weights.buf
We can use the script: predict.py to check the accuracy of the training process.

Second Step: Running the Neural Network in the Browser

We will now create a tiny JavaScript application that loads the previously saved model and weights. Create frontent code and distribution folders:
mkdir -p frontend/dist
You’ll want to copy the extracted model data files into the frontend/dist directory:
cp model_mushrooms.json frontend/dist/
cp model_mushrooms_metadata.json frontend/dist/
cp model_mushrooms_weights.buf frontend/dist/
The Webpack Setup:
We will write the code in ES6 and prepare it for the browser using the webpack JavaScript code and asset bundler. So, install webpack and the webpack development server via npm by running
npm install webpack -g
npm install webpack-dev-server -g
You will also want to start a node project and install the required packages
npm init
npm install --save keras-js url-loader
  • The HTML:
I will use a very basic HTML file placed directly in the 'frontend/dist/index.html' distribution directory, which is generally not a good idea but works for this demonstration.
  • The JavaScript:
The actual model loading code will live inside 'frontend/entry.js'
  • With the sources in place, compile the bundle with:
cd frontend
webpack
To view the app, run:
webpack-dev-server
and open the indicated address (likely http://localhost:8080) in a web browser.
  • Testing the web:
Just type in the file input the name of an image file located in the folder 'frontend/dist/' and click the 'Predict' button. After some seconds you will have as output the prediction of the model with the top 3 confidence probabilities.


Third Step: Running the Neural Network in a Phonegap Cordova application.

  • This step is so simple as creating a new Phonegap project, and copying the former folders into the 'www' folder. Then we can just use a controller to redirect to a page containing our 'frontend/dist/index.html'.






lunes, 17 de julio de 2017

Utilizando el modelo de red neuronal de traducción de Google (GNMT)...¡para jugar al ajedrez!

Hace unos días, y para mi gran sorpresa, Google nos hizo el enorme regalo de hacer público el código fuente de su motor de traducción de lenguaje natural más moderno (GNMT): https://github.com/tensorflow/nmt

Así que decidí rápidamente hacer uso de esta maravilla, junto con las mejoras con la que la versión 1.2 de TensorFlow viene cargada, para programar las modificaciones necesarias para poder enfocar este modelo de Google a la traducción...¡de jugadas en el juego del ajedrez! Es decir; que el modelo (con modificaciones mínimas), en lugar de aprender a traducir por ejemplo de español a inglés, es también capaz de inferir movimientos de ajedrez válidos (usando la notación algebraica) dado un estado cualquiera de tablero.

El resultado final lo podéis ver (y usar) en el siguiente repositorio de mi cuenta personal en GitHub: https://github.com/Zeta36/Using-Google-Neural-Machine-Translation-for-chess-movements-inference-TensorFlow-.

Pero lo realmente importante de todo es sin duda el hecho de comprender la potencia que tiene el modelo de Google para poder ser generalizado a cualquier tarea de mapeo que pueda ser tratada y representada de manera adecuada y de modo que podamos generar pares de entrada (source-target) para el entrenamiento supervisado. En este sentido se puede decir que el mismo modelo neuronal que es capaz de traducir entre idiomas, es también capaz de aprender a inferir como realizar tareas que en principio parecen poco relacionadas con  la propia traducción de textos. 

Esto me hace pensar que con este hecho se está demostrando algo significativo pero ya a un nivel neuronal (humano). Es posible que resultados como el que se demuestran con este tipo de generalizaciones de aprendizaje (y memorización) bajo una misma estructura de red neuronal artificial, sean una pista del modo en que nuestro propio cerebro podría igualmente ser capaz de reutilizar una misma zona cerebral para realizar muy diversas tareas de procesamiento. En este sentido no es descabellado a la luz de lo observado que por ejemplo partes de nuestro cerebro que se utilicen para entender y traducir lenguaje natural, sea utilizado además para otras tareas de inferencias totalmente distintas de las lingüísticas (como aprender a jugar al ajedrez, o incluso comprender ciertas ideas matemáticas). Os dejo a continuación con un poco de más información técnica sobre el proyecto que he realizado:

Using (Google) Neural Machine Translation for chess movements inference

Somedays ago a free version of the source code of the GNMT (Google Neural Machine Translation) was release in: https://github.com/tensorflow/nmt by Thang Luong, Eugene Brevdo, Rui Zhao
 

Introduction

Sequence-to-sequence (seq2seq) models (Sutskever et al., 2014Cho et al., 2014) have enjoyed great success in a variety of tasks such as machine translation, speech recognition, and text summarization.
I've used the release of this seq2seq to show the power of the model. Using a vocabulary with just de numbers and letters (the symbols) used for the chess algebraic notation, I was able to train a model to infer the movement a human would do given a table state.
The supervised learning uses then source-target pairs of the form:
Source: rnq1kb1r/pp11ppp1/11p11n11/1111111p/11111111/11111NPb/PPPP1P1P/RNBQR1KB b
Target: Bg4
The source is the state of the board, and the target the movement a human would do in this situation.
In this way the source vocabulary was:
w
/
1
p
r
n
b
q
k
P
R
N
B
Q
K
and the target vocabulary:
p
r
n
b
q
k
P
R
N
B
Q
K
x
+
O
-
1
2
3
4
5
6
7
8
a
c
d
e
f
g
h
=

Results

Using a NMT + GNMT attention (2 layers) the model was able to reach a good result with:
eval dev: perplexity 2.83 eval test: perplexity 3.07 global training step 72100 lr 0.868126 step-time 0.51s wps 9.57K ppl 2.76 bleu 20.64
This means that, given a board state whatever, the model can predict in a seq2seq way a valid (and usually human) chess movement.

miércoles, 12 de julio de 2017

La magnífica mejora en el sistema de traducción de Google (que ha pasado casi desapercibida)

"Alrededor de dos mil quinientos años atrás, un comerciante mesopotámico reunió arcilla, madera y juncos y cambió la humanidad para siempre. Con el tiempo, su ábaco permitiría a los comerciantes hacer un seguimiento de los bienes y reconciliar sus finanzas, permitiendo que la economía florezca.

Pero ese momento de inspiración también ilumina otra asombrosa habilidad humana: nuestra capacidad de recombinar conceptos existentes e imaginar algo completamente nuevo. El inventor desconocido habría tenido que pensar en el problema que querían resolver, el artefacto que podían construir y las materias primas que podían reunir para crearlo. La arcilla se podría moldear en una tableta, un palillo se podría utilizar para rasguñar las columnas y los juncos pueden actuar como contadores. Cada componente era familiar y distinto, pero juntos en esta nueva forma, formaron algo revolucionario.

Esta idea de "composicionalidad" está en el centro de las capacidades humanas como la creatividad, la imaginación y la comunicación basada en el lenguaje. Equipado con sólo un pequeño número de bloques de construcción conceptuales familiares, somos capaces de crear un gran número de nuevos sobre la marcha. Hacemos esto naturalmente colocando conceptos en jerarquías que van de específico a más general y luego recombinando diferentes partes de la jerarquía de maneras novedosas.

Pero lo que viene tan naturalmente a nosotros, sigue siendo un reto en la investigación de la IA.

En nuestro nuevo artículo , proponemos un nuevo enfoque teórico para abordar este problema. También se demuestra un nuevo componente de red neural denominado Symbol-Concept Association Network (SCAN), que puede, por primera vez, aprender una jerarquía de conceptos visuales conectados de manera que imita la visión humana y la adquisición de palabras, permitiéndole imaginar conceptos novedosos guiado por instrucciones de lenguaje.

Nuestro enfoque difiere de los trabajos previos en esta área, ya que está totalmente basado en los datos sensoriales y aprende de muy pocos pares de "imagen-palabra". Mientras que otros enfoques de aprendizaje profundo requieren miles de ejemplos de imágenes para aprender un concepto, SCAN aprende tanto las primitivas visuales como las abstracciones conceptuales principalmente de observaciones sin supervisión y con tan sólo cinco pares de una imagen y una etiqueta por concepto. Una vez entrenado, SCAN puede generar una lista diversa de conceptos que corresponden a una imagen en particular, e imaginar diversos ejemplos visuales que corresponden a un concepto particular, incluso si nunca ha experimentado el concepto antes.

Esta capacidad de aprender nuevos conceptos mediante la recombinación de los existentes a través de instrucciones simbólicas ha dado a los seres humanos capacidades asombrosas, lo que nos permite razonar sobre conceptos abstractos como el universo, el humanismo o - como fue el caso en Mesopotamia - economía. Mientras que nuestros algoritmos tienen un largo camino por recorrer antes de que puedan hacer tales saltos conceptuales, este trabajo demuestra un primer paso hacia tener algoritmos que pueden aprender de una manera en gran medida sin supervisión, y pensar en abstracciones conceptuales como las utilizadas por los seres humanos."

Este texto que acabo de pegar arriba es la asombrosa conclusión de un nuevo trabajo de Google DeepMind (publicado hoy). Se trata de una traducción parcial del siguiente artículo del blog oficial de la propia compañía de Google: https://deepmind.com/blog/imagine-creating-new-visual-concepts-recombining-familiar-ones/

Pero lo más destacado de todo esto no es quizás el trabajo comentado en sí mismo, sino el hecho de que el texto mostrado antes ha sido totalmente traducido de manera autónoma por el actual motor de IA de Google. No he necesitado hacer ni una sola modificación o corrección al texto devuelto, y si acaso lo que yo quizás pondría sería un "la" delante de donde dice "sobre conceptos abstractos como el universo, el humanismo o - como fue el caso en Mesopotamia - LA economía".

En fin, es evidente que rápidamente nos acostumbramos a lo bueno, y que pocos recuerdan ya las críticas hacia la traducción automática que hacíamos del traductor de Google hace apenas un año y pico. Pues bien, desde entonces Google ha mejorado MUCHO el sistema de traducción gracias a una innovación tecnológica que han denominado Neural Machine Translation:
https://research.googleblog.com/2016/09/a-neural-network-for-machine.html
https://research.googleblog.com/2016/11/zero-shot-translation-with-googles.html


El sistema aún no es perfecto (y su implantación tristemente casi ha pasado desapercibida en los medios de comunicación), pero si uno se fija y compara el tipo de traducciones automáticas de las que disponíamos hace apenas 5 años con las que tenemos hoy día, se puede ver claramente una mejora literalmente exponencial. Muy (muy) probablemente Google logrará una traducción con capacidades sobrehumanas en los próximos 5 años, amén de un sistema de reconocimiento de voz igualmente mejor que el del hombre medio. Vale unir a esto la síntesis autónoma de voz "end-to-end" de trabajos como los de WaveNet o Tacotron para poderse asegurar que en no más de un lustro dispondremos de aparatos (igual un simple móvil Android) capaces de oír (y transcribir el contenido de) una voz, detectar el lenguaje, traducir lo escuchado a otra lengua arbitraria, y dictar con una voz sintética indiferenciable de una humana dicho texto ya traducido. Esto de hecho ya hay dispositivos que "pueden" hacerlo, pero la cuestión es que en poco tiempo existirán proyectos capaces de realizar esta tarea siempre MEJOR (y más rápido) que cualquier persona.

Los traductores humanos serán posiblemente el primer gremio (mucho antes incluso que los taxistas y demás transportistas) en perder TODO su trabajo a manos de la automatización.

Un saludo, compañeros.

viernes, 25 de noviembre de 2016

Creatividad neuronal artificial

"A ninguno de nosotros le gusta el pensamiento de que lo que hacemos depende de procesos que no conocemos; preferimos atribuir nuestras elecciones a la voluntad, el libre albedrío, el autocontrol…Quizás sería más honesto decir: “Mi decisión fue determinada por fuerzas internas que desconozco“ 
(Marvin Minsky)

Hace apenas unas semanas, apareció la siguiente noticia en el blog de investigaciones de Google: https://research.googleblog.com/2016/11/zero-shot-translation-with-googles.html. En este artículo se habla en concreto sobre estos dos papers publicado por esta compañía recientemente: https://arxiv.org/abs/1609.08144 y https://arxiv.org/abs/1611.04558, y lo que se relata en ellos es realmente impresionante. Un nuevo hito en esta carrera a la que estamos asistiendo en la busca de una inteligencia artificial general.

Estos dos trabajos hablan detalladamente sobre el desarrollo que ha logrado Google en cuanto a la mejora de su sistema de traducción entre diferentes idiomas.  En concreto, el segundo paper se titula "Google's Multilingual Neural Machine Translation System: Enabling Zero-Shot Translation" y trata precisamente del descubrimiento teórico (aún en estudio) que los científicos de Google han detectado cuando "cacharreaban" con el modelo que lograron hace un par de meses y que describen en el primer paper que os he enlazado.

Este descubrimiento (el "Zero-Shot Translation") no es ni más ni menos que el hecho de que muy posiblemente la red neuronal que han usado para el aprendizaje automático (end-to-end) de idiomas, es capaz de generalizar por si mismo el modo en que funciona el lenguaje humano de manera general y abstracta; siendo por tanto capaz de traducir entre pares de idiomas para los que dicha red neuronal no fue entrenada.


Por ejemplo, los chicos de Google entrenaron("enseñaron") a la red neuronal con frases (original, traducción) entre algunos pares de idiomas, por ejemplo: Inglés->Español, Inglés->Italiano, Inglés->Alemán, e Inglés->Portugués. Pues bien, la red neuronal que han desarrollado fue capaz luego de inferir traducciones para pares de idiomas ¡para cuya traducción no había sido entrenado! Por ejemplo, sin haber visto nunca (como "input") ni una sola frase de traducciones entre Español->Portugués, el sistema fue capaz de "intuir" traducciones bastante decentes entre estos dos idiomas mediante una "creatividad" o abstracción que los chicos de Google han denominado por su cuenta "interlingua" (el nombre es arbitrario, pero viene a ser un modo de llamar a esta capacidad de abstracción que han descubierto).

Para que lo entendáis mejor:  es como si vosotros aprendéis con el español como lengua nativa inglés y también chino, ¡y luego os piden que traduzcáis de chino a inglés o de inglés a chino sin pasar por el español! Con mucho esfuerzo, es cierto que nuestra mente sería capaz de inferir y generalizar este proceso de traducción entre lenguas independientemente aprendidas, pero una red neuronal artificial nunca había sido capaz de mostrar semejante capacidad "humana" de abstracción (y muchos incluso defendían que no era posible tal cosa...estaban equivocados :P).

Por cierto que los chicos de Google dicen: "Visual interpretation of the results shows that these models learn a form of interlingua representation for the multilingual model between all involved language pairs.", y el ejemplo que nos muestran es la siguiente imagen donde se puede ver claramente una representación visual de la red neuronal artificial que yo no sé a vosotros, pero a mí me recuerda enormemente al modo en que se ve funcionar a nuestro cerebro cuando se escanea mediante diversas técnicas: todo parece un barullo incomprensible, pero al final se obtiene el resultado. Pues en este caso lo mismo pero con redes artificiales. La equivalencia salta a la vista (al menos esa es mi opinión).



Realmente es un hito importante en IA, y acaba de ocurrir hace apenas unas semanas ;). Además, supone una prueba añadida a la tesis que vengo defendiendo en este blog desde sus inicios: todas nuestras tan vanagloriadas habilidades "humanas" se reducen siempre en último término a procesamientos eléctricos por entre las redes neuronales de nuestro cerebro.

Un saludo.

jueves, 3 de noviembre de 2016

Red neuronal enfocada en el aprendizaje supervisado del ajedrez

Enfocado en el reciente trabajo teórico de Google DeepMind (AlphaGo), he desarrollado e implementado una versión en TensorFlow de dicha arquitectura, pero realizando modificaciones para enfocar el diseño en el juego del ajedrez en lugar del Go (el paper original es: https://storage.googleapis.com/deepmind-media/alphago/AlphaGoNaturePaper.pdf).

El modelo ideado originalmente por DeepMind fue divulgado con detalle en este artículo: https://deepmind.com/research/alphago/, y mi implementation del mismo (con las modificaciones necesarias para enfocarlo todo en el juego del ajedrez), se encuentra en el siguiente repositorio de mi cuenta personal en GitHub: https://github.com/Zeta36/Policy-chess. Se trata como podéis ver, de un desarrollo Python usando el framework de Google, TensorFlow.

Os dejo a continuación toda la información técnica sobre mi trabajo, aunque siento no tener tiempo para traducirlo y simplemente copiaré a continuación la introducción que hice del mismo en inglés (prometo más adelante escribir una entrada dedicada a divulgar de manera más sencilla el potencial de esta red neuronal, y el indicio que puede contener sobre el modo en que nuestro propio cerebro biológico realiza ciertas tareas relacionadas con la generalización de conceptos, en este caso; aprender a clasificar con cierta habilidad y de manera "intuitiva" cual es una buena jugada de ajedrez de una mala):

A Policy Network in Tensorflow to classify chess moves

This work is inspired in the SL policy network used by Google DeepMind in the program AlphaGo (https://storage.googleapis.com/deepmind-media/alphago/AlphaGoNaturePaper.pdf).
The network models the probability for every legal chess move given a chess board based only in the raw state of the game. In this sense, the input s to the policy network is a simple representation of the board state using a tensor (batc_sizex8x8x8) with information of the chess board piece state, the number of the movement in the game, the current player, etc.
The SL policy network Pσ(a|s) alternates between convolutional layers with weights σ, and rectifier nonlinearities. A final softmax layer outputs a probability distribution over all legal moves a (labels).
The policy network is trained on randomly sampled state-action pairs (s, a), using stochastic gradient ascent to maximize the likelihood of the human move a selected in state.

Preparing the Data sets

We train the 3-layer policy network using any set of chess games stored as PGN files. To prepare the training and the validation data set, we just need to download many PGN file (more data means more accuracy after the training) and put them in the datasets folder (there is in the repository some pgn examples to use).
After that, we run in the console:
python pgn-to-txt.py
In this way, the PGN files will be reformated in the proper way, and chuncked in a tuple of (board state, human move). We the pgn-to-txt.py script finish, go into the datasets folder and copy almost all the "*.txt" files generated into a new folders called "data_train", and some text files into another folder called "data_validation".
Finally, you have to run
python pgn-to-label.py
And we will get the labels for the SL. This labels will be generated and saved in a labels.txt file inside the "labels" folder.

Training

Training is a easy step. Just run:
python train.py
You can adjust before if you wish some hyperparameters inside this python script.

Playing

Once the model is trained (and the loss has converged), you can play a chess game against the SL policy network. Just type:
python play.py
The machine moves will be generate by the policy network, and the human moves in the game will be asked to you to be type in the keyboard. In order to move, you have to know the san Algebraic notation(https://en.wikipedia.org/wiki/Algebraic_notation_(chess)).
The game board is printed in ASCII, but you can use any online chess board configuration (like this http://www.apronus.com/chess/wbeditor.php) to mimic the movements so you can see clearly the game.

Requirements

TensorFlow needs to be installed before running the training script. TensorFlow 0.10 and the current master version are supported.
In addition, python-chess must be installed for reading and writing PGN files, and for the play.py script to work.

Results

After some thousands of training steps, the model is able to generalize and play a reasonable chess game based only in the prediction of the human movements in the training process.

lunes, 3 de octubre de 2016

Implementación en TensorFlow de la red neuronal generativa (WaveNet) enfocada en la generación de texto

Enfocado en el reciente trabajo teórico de Google DeepMind (WaveNet), he desarrollado e implementado una versión en TensorFlow de dicha arquitectura, pero realizando modificaciones para enfocar el diseño en la generación automática de textos (el paper original es: https://arxiv.org/pdf/1609.03499.pdf).

El modelo ideado originalmente por DeepMind fue divulgado con detalle en este artículo: https://deepmind.com/blog/wavenet-generative-model-raw-audio/, y mi implementación del mismo (con las modificaciones necesarias para enfocarlo todo en la generación de texto), se encuentra en el siguiente repositorio de mi cuenta personal en GitHub: https://github.com/Zeta36/tensorflow-tex-wavenet. Se trata como podéis ver, de un desarrollo Python usando el framework de Google, TensorFlow.

Os dejo a continuación toda la información técnica sobre mi trabajo, aunque siento no tener tiempo para traducirlo y simplemente copiaré a continuación la introducción que hice del mismo en inglés (prometo más adelante escribir una entrada dedicada a divulgar de manera más sencilla el potencial de esta red neuronal, y el indicio que puede contener sobre el modo en que nuestro propio cerebro biológico realiza ciertas tareas relacionadas con la memorización):

A TensorFlow implementation of DeepMind's WaveNet paper for text generation.


This is a TensorFlow implementation of the WaveNet generative neural network architecture for text generation.

Previous Work

Originally, the WaveNet neural network architecture directly generates a raw audio waveform, showing excellent results in text-to-speech and general audio generation (see the DeepMind blog post and paper for details).
This network models the conditional probability to generate the next sample in the audio waveform, given all previous samples and possibly additional parameters.
After an audio preprocessing step, the input waveform is quantized to a fixed integer range. The integer amplitudes are then one-hot encoded to produce a tensor of shape (num_samples, num_channels).
A convolutional layer that only accesses the current and previous inputs then reduces the channel dimension.
The core of the network is constructed as a stack of causal dilated layers, each of which is a dilated convolution (convolution with holes), which only accesses the current and past audio samples.
The outputs of all layers are combined and extended back to the original number of channels by a series of dense postprocessing layers, followed by a softmax function to transform the outputs into a categorical distribution.
The loss function is the cross-entropy between the output for each timestep and the input at the next timestep.
In this repository, the network implementation can be found in wavenet.py.

New approach


This work is based in one implementation of the original WaveNet model (Wavenet), but applying some modifications.
In summary: we are going to use the WaveNet model as a text generator. We'll use raw text data (characters), instead of raw audio files, and once the network is trained, we'll use the conditional probability found to generate samples (characters) into an self-generating process.

Only printable ASCII characters (Dec. 0 up to 255) is supported right now.

Results


Pretty interesting results are reached!! Feeding the network with enough text and training, the model is able to memorize the probability of the characters disposition (in a lenguage), and generate later even a very similar text!!

For example, using the Penn Tree Bank (PTB) dataset, and only after 15000 steps of training (with low set of parameters setting) this was the self-generated output (the final loss was around 1.1):

"Prediction is: 300-servenns on the divide mushin attore and operations losers nis called him for investment it was with as pursicularly federal and sotheby d. reported firsts truckhe of the guarantees as paining at the available ransions i 'm new york for basicane as a facerement of its a set to the u.s. spected on install death about in the little there have a $ N million or N N bilot in closing is of a trading a congress of society or N cents for policy half feeling the does n't people of general and the crafted ended yesterday still also arjas trading an effectors that a can singaes about N bound who that mestituty was below for which unrecontimer 's have day simple d. frisons already earnings on the annual says had minority four-$ N sance for an advised in reclution by from $ N million morris selpiculations the not year break government these up why thief east down for his hobses weakness as equiped also plan amr. him loss appealle they operation after and the monthly spendings soa $ N million from cansident third-quarter loan was N pressure of new and the intended up he header because in luly of tept. N million crowd up lowers were to passed N while provision according to and canada said the 1980s defense reporters who west scheduled is a volume at broke also and national leader than N years on the sharing N million pro-m was our american piconmentalist profited himses but the measures from N in N N of social only announcistoner corp. say to average u.j. dey said he crew is vice phick-bar creating the drives will shares of customer with welm reporters involved in the continues after power good operationed retain medhay as the end consumer whitecs of the national inc. closed N million advanc"

This is really wonderful!! We can see that the original WaveNet model has a great capacity to learn and save long codified text information inside its nodes (and not only audio or image information). This "text generator" WaveNet was able to learn how to write English words and phrases just by predicting characters one by one, and sometimes was able even to learn what word to use based on context.

This output is far to be perfect, but It was trained in a only CPU machine (without GPU) using a low set of parameters configuration in just two hours!! I hope somebody with a better computer can explore the potential of this implementation.

If you want to check this results, you just have to type this in a command line terminal (this will use the trained model checkout I uploaded to the respository):
python generate.py --text_out_path=output.txt --samples 2000 
./logdir/train/2016-10-02T10-45-10/model.ckpt-14999

Requirements


TensorFlow needs to be installed before running the training script. TensorFlow 0.10 and the current master version are supported.

Training the network


You can use any text (.txt) file.

In order to train the network, execute
python train.py --data_dir=data

to train the network, where data is a directory containing .txt files. The script will recursively collect all .txt files in the directory.
You can see documentation on each of the training settings by running
python train.py --help

You can find the configuration of the model parameters in wavenet_params.json. These need to stay the same between training and generation.

Generating text


You can use the generate.py script to generate audio using a previously trained model.

Run
python generate.py --samples 16000 model.ckpt-1000
where model.ckpt-1000 needs to be a previously saved model. You can find these in the logdir. The --samples parameter specifies how many characters samples you would like to generate.
The generated waveform can be stored as a .txt file by using the --text_out_path parameter:
python generate.py --text_out_path=mytext.txt --samples 1500 model.ckpt-1000
Passing --save_every in addition to --text_out_path will save the in-progress wav file every n samples.

python generate.py --text_out_path=mytext.txt --save_every 2000 --samples 1500 model.ckpt-1000

Fast generation is enabled by default. It uses the implementation from the Fast Wavenet repository. You can follow the link for an explanation of how it works. This reduces the time needed to generate samples to a few minutes.

To disable fast generation:
python generate.py --samples 1500 model.ckpt-1000 --fast_generation=false

Missing features

Currently, there is no conditioning on extra information.