Introduction to the simplest neural network and its step-by-step implementation

Once I stumbled upon a book called “Create your own neural network” , the author of which is Tariq Rashid and after reading I was satisfied, unlike many other manuals on neural networks, which are undoubtedly good in their own way, everything in this book was presented in simple language with a sufficient number of examples and advice.

For the same book, I want to go step by step, namely in the practical part - writing the code of a simple neural network .

This article is for those who want to do neural networks and machine learning, but so far hardly understand this amazing field of science. The simplest skeleton will be described below. neural network code, so that many understand the simplest principle of construction and interaction of all that consists of this neural network.

image

Theories on machine learning and neural networks in Habré are enough. But if it is necessary for someone, I will leave some links at the end of the article. And now, let's start writing the code directly, and we will write in python, it will be better if you use jupyter-notebook when writing code

Step 1. Initialize the network


First, of course, we need to initialize all the active components of our network.

#импортируем numpy — это библиотека языка Python, добавляющая поддержку больших многомерных массивов и матрицimport numpy
# импортируем scipy.special , -scipy содержит модули для оптимизации, интегрирования, специальных функций, обработки изображений и  многих других задач, нам же здесь нужна наша функция активации, имя которой -Сигмоидаimport scipy.special
#Вероятно, нам понадобится визуализировать наши данныеimport matplotlib.pyplot 
# Определяем наш класс нейронной сетиclassneuralNetwork:# Инициализация нашей  нейронной сетиdef__init__(self, inputnodes, hiddennodes, outputnodes, learningrate):#В параметрах мы записываем обязательный self, входные данные,  данные  скрытого слоя, выходные данные ,скорость обучения соответственно)# устанавливаем количество узлов для входного , скрытого слоя, выходного слоя
        self.inodes = inputnodes
        self.hnodes = hiddennodes
        self.onodes = outputnodes
        # Тут обозначены веса матрицы, wih -  вес между входным и скрытым слоем , а  так же  who- вес между скрытым и выходным  слоем
        self.wih = numpy.random.rand(self.hnodes, self.inodes))
        self.who = numpy.random.rand(self.onodes, self.hnodes))
        # Скорость обучения -это наш гиперпараметр, то есть, параметр , который мы подбираем ручками, и в зависимости от того, как нам это удобно нам, и , конечно же, нейронной сети
        self.lr = learningrate
        # Наша Сигмоида- функция активации
        self.activation_function = lambda x: scipy.special.expit(x)

A little bit about how a node looks like in a neural network.


image

The picture shows the most that there is a knot, only it is usually presented in the form of a circle, and not a rectangle. As we see, inside a rectangle (well, or a circle) - this is all abstract, there are 2 functions:

the 1st function is engaged in receiving all the input, taking into account the weights, data, and sometimes even taking into account the displacement neuron (a special neuron, which it simply allows the graphs to move, rather than mix up into one ugly heap, that's all) The

2nd Function takes as a parameter the same value that the first function summarized, and this second function is called the activation function. In our case, Sigmoid. We

continue :

Part 2. Neural Network Training


deftrain(self, inputs_list, targets_list):# Конвертируем наш список в двумерный массив
        inputs = numpy.array(inputs_list, ndmin=2).T # поступающие на вход данные input
        targets = numpy.array(targets_list, ndmin=2).T #целевые значения targets# Подсчет сигнала в скрытом слое
        hidden_inputs = numpy.dot(self.wih, inputs)
        # Подсчет сигналов, выходящих из скрытого слоя к выходному слою. Тут в нашем узле, куда поступали все данные в переменную hidden_inputs (1я функция), эта переменная подается  как параметр в Сигмоиду - функцию активации (2я функция)
        hidden_outputs = self.activation_function(hidden_inputs)
        # Подсчет сигналов в конечном(выходном) слое
        final_inputs = numpy.dot(self.who, hidden_outputs)
        # Подсчет  сигналов, подающихся в функцию активации
        final_outputs = self.activation_function(final_inputs)
        # Значение ошибки (Ожидание - Реальность)
        output_errors = targets - final_outputs
        # Ошибка скрытого слоя становится ошибкой ,которую мы получили для <b>ошибки выходного слоя</b>, но уже <b>распределенные по весам между скрытым и выходным слоями</b>(иначе говоря с учетом умножения соответствующих весов) 
        hidden_errors = numpy.dot(self.who.T, output_errors) 
        # Обновление весов между скрытым слоем и выходным (Явление того, что люди зовут ошибкой обратного распространения)
        self.who += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)), numpy.transpose(hidden_outputs))
        # Обновление весов между скрытым слоем и входным(Та же ошибка ошибка обратного распространения в действии)
        self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), numpy.transpose(inputs))
        pass

And here we are approaching the end

Part 3. Neuron network survey


#Создаем функцию , которая будет принимать входные данныеdefquery(self, inputs_list):# Конвертируем поданный список входных данных в двумерный массив
        inputs = numpy.array(inputs_list, ndmin=2).T
        # Подсчет сигналов в скрытом слое
        hidden_inputs = numpy.dot(self.wih, inputs)
        # Подсчет сигналов, поданных в функцию активации
        hidden_outputs = self.activation_function(hidden_inputs)
        #Подсчет сигналов в конечном выходном слое
        final_inputs = numpy.dot(self.who, hidden_outputs)
        #Подсчет сигналов в конечном выходном слое, переданных в функцию активации
        final_outputs = self.activation_function(final_inputs)
        return final_outputs

We finish business


#Подаем конкретное значение для входного , скрытого ,выходного слоев соответственно(указываем количество <b>нод</b>- узлов в ряду входного, скрытого, выходного соответственно
input_nodes = 3
hidden_nodes = 3
output_nodes = 3# Возьмем коэффициент обучения - скорость обучения равной, например... 0.3!
learning_rate = 0.3# Создаем нейронную сеть(n это объект класса neuralNetwork , при его создании запустится конструктор __init__  , и дальше все будет включаться по цепочке
n = neuralNetwork(input_nodes,hidden_nodes,output_nodes, learning_rate)

PS


Above was presented the simplest model of a neural network capable of computing. But no particular application was shown.

If you wish, you can continue this code by adding the MNIST handwriting recognition feature . To do this, you can completely figure out (or just have some fun) having this jupyter file , my task was to show the code and, if possible, chew for what . Links to the theory, as promised, attach at the end, well, and you will also find Github and the book of Tariq Rashid, I'll leave them too

1. Github
2. The book "Create your neural network"
3. The theory of machine learning 1
4. Theory on machine learning 2
5. Machine Learning Theory 3
6. Machine Learning Theory 4

You can also familiarize yourself with this course.

Also popular now: