
En este artículo, exploraremos las redes neuronales convolucionales (CNN) y, en un nivel alto, veremos cómo se inspiran en la estructura del cerebro. Si desea leer más sobre el cerebro específicamente, hay más recursos al final del artículo para ayudarlo más.
El cerebro
Analizamos constantemente el mundo que nos rodea. Sin un esfuerzo consciente, hacemos predicciones sobre todo lo que vemos y actuamos sobre ellas. Cuando vemos algo, etiquetamos cada objeto en función de lo que hemos aprendido en el pasado. Para ilustrar esto, mire esta imagen por un momento.

Probablemente pensaste algo como "es un niño feliz parado en una silla". O tal vez pensaste que parece que está gritando, a punto de atacar este pastel frente a él.

Esto es lo que hacemos inconscientemente todo el día. Vemos, etiquetamos, hacemos predicciones y reconocemos patrones. Pero cómo hacemos eso? ¿Cómo es que podemos interpretar todo lo que vemos?
La naturaleza tardó más de 500 millones de años en crear un sistema para hacer esto. La colaboración entre los ojos y el cerebro, llamada vía visual primaria, es la razón por la que podemos dar sentido al mundo que nos rodea.

Si bien la visión comienza en los ojos, la interpretación real de lo que vemos ocurre en el cerebro, en la corteza visual primaria .
Cuando ve un objeto, los receptores de luz en sus ojos envían señales a través del nervio óptico a la corteza visual primaria, donde se procesa la entrada. La corteza visual primaria da sentido a lo que ve el ojo.
Todo esto nos parece muy natural. Apenas pensamos en lo especial que es que seamos capaces de reconocer todos los objetos y personas que vemos en nuestras vidas. La estructura jerárquica profundamente compleja de las neuronas y las conexiones en el cerebro juega un papel importante en este proceso de recordar y etiquetar objetos.
Piense en cómo aprendimos qué es, por ejemplo, un paraguas. O un pato, una lámpara, una vela o un libro. Al principio, nuestros padres o familiares nos decían el nombre de los objetos en nuestro entorno directo. Aprendimos de los ejemplos que se nos dieron. Poco a poco, comenzamos a reconocer ciertas cosas cada vez más a menudo en nuestro entorno. Se volvieron tan comunes que la próxima vez que los viéramos, sabríamos instantáneamente cuál era el nombre de este objeto. Se convirtieron en parte de nuestro modelo en el mundo.
Redes neuronales convolucionales
De manera similar a como un niño aprende a reconocer objetos, necesitamos mostrarle a un algoritmo millones de imágenes antes de que pueda generalizar la entrada y hacer predicciones para imágenes que nunca antes había visto.
Las computadoras 'ven' de una manera diferente a la nuestra. Su mundo consta solo de números. Cada imagen se puede representar como matrices bidimensionales de números, conocidas como píxeles.
Pero el hecho de que perciban las imágenes de una manera diferente no significa que no podamos entrenarlos para reconocer patrones, como lo hacemos nosotros. Solo tenemos que pensar en qué es una imagen de otra manera.

Para enseñarle a un algoritmo cómo reconocer objetos en imágenes, utilizamos un tipo específico de red neuronal artificial: una red neuronal convolucional (CNN). Su nombre proviene de una de las operaciones más importantes de la red: la convolución.
Las redes neuronales convolucionales están inspiradas en el cerebro. La investigación realizada en las décadas de 1950 y 1960 por DH Hubel y TN Wiesel sobre el cerebro de los mamíferos sugirió un nuevo modelo de cómo los mamíferos perciben el mundo visualmente. Demostraron que las cortezas visuales de los gatos y los monos incluyen neuronas que responden exclusivamente a las neuronas en su entorno directo.
En su artículo, describieron dos tipos básicos de células neuronales visuales en el cerebro, cada una de las cuales actúa de manera diferente: células simples ( células S ) y células complejas ( células C ).
Las celdas simples se activan, por ejemplo, cuando identifican formas básicas como líneas en un área fija y un ángulo específico. Las células complejas tienen campos receptivos más grandes y su salida no es sensible a la posición específica en el campo.
Las células complejas continúan respondiendo a un cierto estímulo, a pesar de que cambia su posición absoluta en la retina. Complejo se refiere a más flexible, en este caso.
En la visión, un campo receptivo de una sola neurona sensorial es la región específica de la retina en la que algo afectará la activación de esa neurona (es decir, activará la neurona). Cada célula de neurona sensorial tiene campos receptivos similares, y sus campos se superponen.

Además, el concepto de jerarquía juega un papel importante en el cerebro. La información se almacena en secuencias de patrones, en orden secuencial. La neocorteza , que es la capa más externa del cerebro, almacena información jerárquicamente. Se almacena en columnas corticales o agrupaciones de neuronas organizadas uniformemente en el neocórtex.
En 1980, un investigador llamado Fukushima propuso un modelo de red neuronal jerárquica. Lo llamó neocognitrón . Este modelo se inspiró en los conceptos de las celdas simples y complejas. El neocognitrón pudo reconocer patrones aprendiendo sobre las formas de los objetos.
Más tarde, en 1998, Bengio, Le Cun, Bottou y Haffner introdujeron las redes neuronales convolucionales en un artículo. Su primera red neuronal convolucional se llamó LeNet-5 y fue capaz de clasificar dígitos a partir de números escritos a mano.
Para conocer la historia completa de las redes neuronales convolucionales, puede ir aquí.
Arquitectura
En el resto de este artículo, lo guiaré a través de la arquitectura de una CNN y también le mostraré la implementación de Python.
Las redes neuronales convolucionales tienen una arquitectura diferente a las redes neuronales normales. Las redes neuronales regulares transforman una entrada pasándola por una serie de capas ocultas. Cada capa está formada por un conjunto de neuronas , donde cada capa está completamente conectada a todas las neuronas de la capa anterior. Finalmente, hay una última capa completamente conectada, la capa de salida, que representa las predicciones.
Las redes neuronales convolucionales son un poco diferentes. En primer lugar, las capas se organizan en 3 dimensiones : ancho, alto y profundidad. Además, las neuronas de una capa no se conectan a todas las neuronas de la siguiente, sino solo a una pequeña región de la misma. Por último, el resultado final se reducirá a un solo vector de puntuaciones de probabilidad, organizado a lo largo de la dimensión de profundidad.

Las CNN tienen dos componentes:
- The Hidden layers/Feature extraction part
In this part, the network will perform a series of convolutions and pooling operations during which the features are detected. If you had a picture of a zebra, this is the part where the network would recognise its stripes, two ears, and four legs.
- The Classification part
Here, the fully connected layers will serve as a classifier on top of these extracted features. They will assign a probability for the object on the image being what the algorithm predicts it is.
# before we start building we import the libraries
import numpy as np
from keras.layers import Conv2D, Activation, MaxPool2D, Flatten, Densefrom keras.models import Sequential

Feature extraction
Convolution is one of the main building blocks of a CNN. The term convolution refers to the mathematical combination of two functions to produce a third function. It merges two sets of information.
In the case of a CNN, the convolution is performed on the input data with the use of a filter or kernel (these terms are used interchangeably)to then produce a feature map.
We execute a convolution by sliding the filter over the input. At every location, a matrix multiplication is performed and sums the result onto the feature map.
In the animation below, you can see the convolution operation. You can see the filter (the green square) is sliding over our input (the blue square) and the sum of the convolution goes into the feature map (the red square).
The area of our filter is also called the receptive field, named after the neuron cells! The size of this filter is 3x3.

For the sake of explaining, I have shown you the operation in 2D, but in reality convolutions are performed in 3D. Each image is namely represented as a 3D matrix with a dimension for width, height, and depth. Depth is a dimension because of the colours channels used in an image (RGB).

We perfom numerous convolutions on our input, where each operation uses a different filter. This results in different feature maps. In the end, we take all of these feature maps and put them together as the final output of the convolution layer.
Just like any other Neural Network, we use an activation function to make our output non-linear. In the case of a Convolutional Neural Network, the output of the convolution will be passed through the activation function. This could be the ReLU activation function.
Stride is the size of the step the convolution filter moves each time. A stride size is usually 1, meaning the filter slides pixel by pixel. By increasing the stride size, your filter is sliding over the input with a larger interval and thus has less overlap between the cells.
The animation below shows stride size 1 in action.

Because the size of the feature map is always smaller than the input, we have to do something to prevent our feature map from shrinking. This is where we use padding.
A layer of zero-value pixels is added to surround the input with zeros, so that our feature map will not shrink. In addition to keeping the spatial size constant after performing convolution, padding also improves performance and makes sure the kernel and stride size will fit in the input.
After a convolution layer, it is common to add a pooling layer in between CNN layers. The function of pooling is to continuously reduce the dimensionality to reduce the number of parameters and computation in the network. This shortens the training time and controls overfitting.
The most frequent type of pooling is max pooling,which takes the maximum value in each window. These window sizes need to be specified beforehand. This decreases the feature map size while at the same time keeping the significant information.

Thus when using a CNN, the four important hyperparameters we have to decide on are:
- the kernel size
- the filter count (that is, how many filters do we want to use)
- stride (how big are the steps of the filter)
- padding
# Images fed into this model are 512 x 512 pixels with 3 channels
img_shape = (28,28,1)
# Set up the model
model = Sequential()
# Add convolutional layer with 3, 3 by 3 filters and a stride size of 1# Set padding so that input size equals output size
model.add(Conv2D(6,2,input_shape=img_shape))
# Add relu activation to the layer
model.add(Activation('relu'))
#Pooling
model.add(MaxPool2D(2))
A nice way of visualizing a convolution layer is shown below. Try to look at it for a bit and really understand what is happening.

Classification
After the convolution and pooling layers, our classification part consists of a few fully connected layers. However, these fully connected layers can only accept 1 Dimensional data. To convert our 3D data to 1D, we use the function flatten
in Python. This essentially arranges our 3D volume into a 1D vector.
The last layers of a Convolutional NN are fully connected layers. Neurons in a fully connected layer have full connections to all the activations in the previous layer. This part is in principle the same as a regular Neural Network.
#Fully connected layers
# Use Flatten to convert 3D data to 1Dmodel.add(Flatten())
# Add dense layer with 10 neuronsmodel.add(Dense(10))
# we use the softmax activation function for our last layermodel.add(Activation('softmax'))
# give an overview of our model
model.summary
_________________________________________________________________Layer (type) Output Shape Param # =================================================================conv2d_1 (Conv2D) (None, 27, 27, 6) 30 _________________________________________________________________activation_1 (Activation) (None, 27, 27, 6) 0 _________________________________________________________________max_pooling2d_1 (MaxPooling2 (None, 13, 13, 6) 0 _________________________________________________________________flatten_1 (Flatten) (None, 1014) 0 _________________________________________________________________dense_1 (Dense) (None, 10) 10150 _________________________________________________________________activation_2 (Activation) (None, 10) 0 =================================================================Total params: 10,180Trainable params: 10,180Non-trainable params: 0__________________________________________________________________
Training
Training a CNN works in the same way as a regular neural network, using backpropagration or gradient descent. However, here this is a bit more mathematically complex because of the convolution operations.
If you would like to read more about how regular neural nets work, you can read my previous article.
"""Before the training process, we have to put together a learning process in a particular form. It consists of 3 elements: an optimiser, a loss function and a metric."""
model.compile(loss='sparse_categorical_crossentropy', optimizer = 'adam', metrics=['acc'])
# dataset with handwritten digits to train the model onfrom keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = np.expand_dims(x_train,-1)
x_test = np.expand_dims(x_test,-1)
# Train the model, iterating on the data in batches of 32 samples# for 10 epochs
model.fit(x_train, y_train, batch_size=32, epochs=10, validation_data=(x_test,y_test)
# Training...
Train on 60000 samples, validate on 10000 samplesEpoch 1/1060000/60000 [==============================] - 10s 175us/step - loss: 4.0330 - acc: 0.7424 - val_loss: 3.5352 - val_acc: 0.7746Epoch 2/1060000/60000 [==============================] - 10s 169us/step - loss: 3.5208 - acc: 0.7746 - val_loss: 3.4403 - val_acc: 0.7794Epoch 3/1060000/60000 [==============================] - 11s 176us/step - loss: 2.4443 - acc: 0.8372 - val_loss: 1.9846 - val_acc: 0.8645Epoch 4/1060000/60000 [==============================] - 10s 173us/step - loss: 1.8943 - acc: 0.8691 - val_loss: 1.8478 - val_acc: 0.8713Epoch 5/1060000/60000 [==============================] - 10s 174us/step - loss: 1.7726 - acc: 0.8735 - val_loss: 1.7595 - val_acc: 0.8718Epoch 6/1060000/60000 [==============================] - 10s 174us/step - loss: 1.6943 - acc: 0.8765 - val_loss: 1.7150 - val_acc: 0.8745Epoch 7/1060000/60000 [==============================] - 10s 173us/step - loss: 1.6765 - acc: 0.8777 - val_loss: 1.7268 - val_acc: 0.8688Epoch 8/1060000/60000 [==============================] - 10s 173us/step - loss: 1.6676 - acc: 0.8799 - val_loss: 1.7110 - val_acc: 0.8749Epoch 9/1060000/60000 [==============================] - 10s 172us/step - loss: 1.4759 - acc: 0.8888 - val_loss: 0.1346 - val_acc: 0.9597Epoch 10/1060000/60000 [==============================] - 11s 177us/step - loss: 0.1026 - acc: 0.9681 - val_loss: 0.1144 - val_acc: 0.9693
Summary
In summary, CNNs are especially useful for image classification and recognition. They have two main parts: a feature extraction part and a classification part.
The main special technique in CNNs is convolution, where a filter slides over the input and merges the input value + the filter value on the feature map. In the end, our goal is to feed new images to our CNN so it can give a probability for the object it thinks it sees or describe an image with text.

You can find the entire code here.
More brain related recommendations?
- Read this really cool article on the brain and more.
- I also recommend this book on intelligence and the brain.
- “How to Create a Mind” by Ray Kurzweil.