This article was published as part of the Data Science Blogathon
Introduction
A red neuronalNeural networks are computational models inspired by the functioning of the human brain. They use structures known as artificial neurons to process and learn from data. These networks are fundamental in the field of artificial intelligence, enabling significant advancements in tasks such as image recognition, Natural Language Processing and Time Series Prediction, among others. Their ability to learn complex patterns makes them powerful tools.. artificial es un subcampo de la inteligencia artificial compilado bajo las redes neuronales de deep learningDeep learning, A subdiscipline of artificial intelligence, relies on artificial neural networks to analyze and process large volumes of data. This technique allows machines to learn patterns and perform complex tasks, such as speech recognition and computer vision. Its ability to continuously improve as more data is provided to it makes it a key tool in various industries, from health... que intenta imitar la red de neuronas que hace el cerebro humano, allowing them to understand and respond like a human.
Table of Contents
- Neural network overview
- Introduction to Keras
- Step-by-step implementation of your first Keras model
- Combining all the code
- EndNote
Brief description of the neural network
The neural network consists of a larger set of neurons, called layered units. In simple words, Neural Network is designed to perform a more complex task where Machine Learning algorithms do not find their use and do not achieve the required performance.
Neural networks are used to perform many complex tasks, including image classification, object detection, face identification, the text summary, voice recognition and the list is endless.
How do neural networks learn complex characteristics? A neural network has many layers and each layer performs a specific and complex function the network. The more layers are, more performance is received. That is why the neural network is also called a multilayer perceptron..
Introduction to the Kears Library
Keras is a fast neural network library, Open source and easy to use written in Python that runs on top of Theano or Tensorflow. Tensorflow provides both low-level and high-level APIs; in fact, Keras only provides high-level API.
As a beginner, it is recommended to work first with Keras and then move to TensorFlow. The reason is that using Tensorflow functions as a beginner is a bit complex to understand and interpret, but Keras functionality is simple.
Create your first neural network model with Keras
We will build a simple artificial neural network using Keras step by step which will help you create your own model in the future.
Paso 1) Load data
We are going to use the Pima Indians diabetes data that you can download from here. It is a simple data set provided by the UCI Machine Learning data set, containing a medical record of Indian patients. We have to predict whether the patient has an onset of diabetes within 5 years.
import pandas as pd data = pd.read_csv('diabetes.csv') x = data.drop("Outcome", axis=1) y = data["Outcome"]
It is a binary classification problem where we have to say if your diabetes onset is 1 or not like 0. All columns are numeric, which facilitates the direct creation of a neural network on it. Therefore, we have separated independent and dependent data.
Paso 2) Define the Keras model
The model in Keras is always defined as a sequence of layers. It means we initialize the sequence model and add the layers one after another which runs as the sequence from the list. We practically have to try experimenting with the process of adding and removing layers until we are happy with our architecture..
What you need to take care of is that the first layer has the correct number of input characteristics that is specified using the input_dim parameter. we can specify the number of neurons as the first argument of a layer. para definir la wake functionThe activation function is a key component in neural networks, since it determines the output of a neuron based on its input. Its main purpose is to introduce nonlinearities into the model, allowing you to learn complex patterns in data. There are various activation functions, like the sigmoid, ReLU and tanh, each with particular characteristics that affect the performance of the model in different applications.... utilice el argumento de activación.
In this example, we will define a fully connected network with three layers. To define the fully connected layer, use Keras Dense class.
- The first layer has 12 neuronas y función de activación como resumeThe ReLU activation function (Rectified Linear Unit) It is widely used in neural networks due to its simplicity and effectiveness. Defined as ( f(x) = max(0, x) ), ReLU allows neurons to fire only when the input is positive, which helps mitigate the problem of gradient fading. Its use has been shown to improve performance in various deep learning tasks, making ReLU an option...
- The second hidden layer has 8 neurons and activation function as relu
- Finally, on the Output layerThe "Output layer" is a concept used in the field of information technology and systems design. It refers to the last layer of a software model or architecture that is responsible for presenting the results to the end user. This layer is crucial for the user experience, since it allows direct interaction with the system and the visualization of processed data...., we use 1 unit and activation as sigmoid because it is a binary classification problem.
from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(12, input_dim=8, activation="resume")) model.add(Dense(12, activation="resume")) model.add(Dense(1, activation="sigmoid"))
Recuerde especificar la forma correcta de los datos en la primera capa conocida como input layerThe "input layer" refers to the initial level in a data analysis process or in neural network architectures. Its main function is to receive and process raw information before it is transformed by subsequent layers. In the context of machine learning, Proper configuration of the input layer is crucial to ensure the effectiveness of the model and optimize its performance in specific tasks.....
Paso 3) Compile the Keras model
When we compile the Keras model, use backend numeric libraries like TensorFlow or Theano. Whatever backend you are using, automatically chooses the best way to represent the network on your hardware, as CPU, GPU o TPU.
When we compile the model, debemos especificar algunos parametersThe "parameters" are variables or criteria that are used to define, measure or evaluate a phenomenon or system. In various fields such as statistics, Computer Science and Scientific Research, Parameters are critical to establishing norms and standards that guide data analysis and interpretation. Their proper selection and handling are crucial to obtain accurate and relevant results in any study or project.... adicionales para evaluar mejor el modelo y encontrar el mejor conjunto de ponderaciones para asignar entradas a salidas.
- Loss functionThe loss function is a fundamental tool in machine learning that quantifies the discrepancy between model predictions and actual values. Its goal is to guide the training process by minimizing this difference, thus allowing the model to learn more effectively. There are different types of loss functions, such as mean square error and cross-entropy, each one suitable for different tasks and...: the loss function must be specified to evaluate the set of weights to which the model will be mapped. We will use the cross entropy as a loss function which is actually known as binary cross entropy used for binary classification.
- Optimizer: the second is the optimizer to optimize the loss. We will use adam, which is a popular version of gradient descent and gives the best result on most problems.
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
Paso 4) Start training (fit the model)
After successful compilation of the model, we are ready to fit the data to the model and start training the neural network. In addition to providing data to model, necesitamos definir una cantidad de épocas y un tamaño de lote en el que se produce el trainingTraining is a systematic process designed to improve skills, physical knowledge or abilities. It is applied in various areas, like sport, Education and professional development. An effective training program includes goal planning, regular practice and evaluation of progress. Adaptation to individual needs and motivation are key factors in achieving successful and sustainable results in any discipline.....
- EpochEpoch es una plataforma que ofrece herramientas para la creación y gestión de contenido digital. Su enfoque se centra en facilitar la producción de multimedia, permitiendo a los usuarios colaborar y compartir información de manera eficiente. Con una interfaz intuitiva, Epoch se ha convertido en una opción popular entre profesionales y empresas que buscan optimizar su flujo de trabajo en la era digital. Su versatilidad la hace adecuada para diversas...: single pass through all rows of training dataset
- Batch size: number of samples considered by the model before updating the weights.
model.fit(x,Y, epochs=150, batch_size=10)
An epoch can be made up of more than one batch. These parameters are finally decided after the heat and test method.
Paso 5) Evaluate the model
After training the model, let's know the performance of a neural network. The model is always evaluated in a test set. In this example, For simplicity, we have trained on a complete data set, but while working on any project, basically splits the data and trains the network.
_, accuracy = model.evaluate(x, Y) print("Model accuracy: %.2f"% (accuracy*100))
To evaluate the model, use the evaluation method and pass the input and output to the model and check the performance.
Paso 6) Make predictions
predict the output of new data simply using the prediction method. we have a binary classification problem statement, so the output will be simply 0 O 1.
predictions = model.predict(x) print([round(x[0]) for x in predictions])
Alternatively, you can also use the predict_classes function to directly predict classes.
That is solved, we have easily created a neural network with 3 layers using just a few lines of code with Keras.
Compile all the code together
model = Sequential() #define model model.add(Dense(12, input_dim=8, activation="resume")) model.add(Dense(8, activation="resume")) model.add(Dense(1, activation="sigmoid")) model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]) #compile model model.fit(x,Y, epochs=150, batch_size=10) #training _, accuracy = model.evaluate(x,Y) #testing print("Model accuracy: %.2f"% (accuracy*100)) predictions = model.predict(x) #make predictions #round the prediction rounded = [round(x[0]) for x in predictions]
EndNote
A neural network builds a network of connected layers with multiple neurons in each layer. A measureThe "measure" it is a fundamental concept in various disciplines, which refers to the process of quantifying characteristics or magnitudes of objects, phenomena or situations. In mathematics, Used to determine lengths, Areas and volumes, while in social sciences it can refer to the evaluation of qualitative and quantitative variables. Measurement accuracy is crucial to obtain reliable and valid results in any research or practical application.... que aumentamos el número de capas, the network is capable of learning more complex characteristics.
You have easily created your first neural network model with Keras. I hope it was easy to grasp all the things. If you have any question, please comment. I'll be happy to help you.
If you like the article, check out my other items. Link