1. Home
  2. Explore
  3. Computer Science
  4. Artificial Neural Networks

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Artificial Neural Networks

Artificial Neural Networks and Their Applications

Artificial intelligence, machine learning, and deep learning

Artificial intelligence (AI) is the broad field of creating computer systems that perform tasks associated with intelligent behavior, such as recognizing images, understanding language, making predictions, or choosing actions. The term was coined by John McCarthy in 1956 at the Dartmouth conference.

AI systems can excel at some tasks while struggling with others. A computer can calculate a square root quickly, for example, but navigating a home and handling an unfamiliar object requires perception, adaptation, and knowledge of the physical world. This contrast helps distinguish narrow task performance from the broader flexibility of human intelligence.

AI has developed alongside improvements in computing power, hardware, and the availability of data. A notable milestone occurred in 1997, when IBM’s Deep Blue defeated world chess champion Garry Kasparov. AI is also used in many everyday services:

  • Search engines rank results based on a query and other available information.

  • Streaming services recommend content based on viewing patterns.

  • Social networks identify people in photographs using learned visual patterns.

  • Businesses use predictive systems in areas such as retail, finance, travel, and e-commerce.

Machine learning is a branch of AI in which systems learn patterns from data, often using statistical methods, rather than relying only on explicitly written rules. Deep learning is a branch of machine learning that uses neural networks with multiple layers to learn increasingly complex representations from data.

Artificial neural networks are one family of machine-learning models. They are inspired by biological nervous systems, but their operations are mathematical rather than literal copies of how brains work.


Biological neurons as an analogy

A biological neural network contains interconnected neurons that receive and transmit signals. A simplified neuron has several parts:

  • Dendrites receive signals from other neurons.

  • The cell body processes incoming signals.

  • The axon carries a signal away from the neuron.

  • Synapses connect neurons and influence how signals pass between them.

An artificial neural network borrows some of this vocabulary and the general idea of interconnected units. The analogy is useful for understanding signal flow, but artificial neurons are much simpler mathematical units.

In a simplified biological account, a neuron may transmit a signal when its activity reaches a threshold. Artificial networks also use activation functions to transform their inputs. However, an artificial activation function is a mathematical operation; it is not a biological firing mechanism.


Structure of an artificial neural network

An artificial neural network (ANN) is a system of connected computational units, often called neurons or nodes. A common feed-forward network contains:

  1. An input layer, which receives the data’s features.

  2. One or more hidden layers, which transform information.

  3. An output layer, which produces predictions.

For example, a flower-classification model might receive four measurements in its input layer and produce three output scores, one for each possible species.

Weighted inputs, bias, and activation

Each connection has a weight. A weight controls how strongly a particular input contributes to a neuron’s calculation. A larger positive weight increases the input’s influence; a negative weight can reduce or reverse it.

For a neuron with inputs x1,x2,…,xnx_1, x_2, \ldots, x_nx1​,x2​,…,xn​, weights w1,w2,…,wnw_1, w_2, \ldots, w_nw1​,w2​,…,wn​, and bias bbb, the weighted sum is:

z=∑i=1nwixi+bz = \sum_{i=1}^{n} w_i x_i + bz=∑i=1n​wi​xi​+b

The neuron then applies an activation function fff:

a=f(z)a = f(z)a=f(z)

The resulting value aaa is passed to neurons in the next layer. The bias lets the neuron adjust its output independently of whether the input values are zero. It plays a role similar to an intercept in a regression model.

A common activation function is the sigmoid function:

σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}σ(z)=1+e−z1​

It maps values to the interval from 000 to 111. Other activation functions are also widely used; the appropriate choice depends on the network architecture and task.

A network layer applies these calculations to multiple neurons. The weights and biases determine the transformations learned by the network. The hidden layers can learn combinations of input features that are useful for predicting the output, although their internal representations may not be straightforward to interpret.


How a neural network learns

A network starts with weights and biases that are usually initialized to small, often random, values. It learns by comparing its predictions with the desired outputs and adjusting those parameters to reduce prediction error.

Forward pass

During a forward pass, input data moves from the input layer through the hidden layers to the output layer. Each neuron calculates a weighted sum, adds its bias, and applies an activation function.

Loss or error calculation

A loss function measures the difference between the network’s predictions and the correct answers. For one simple example, the sum of squared errors is:

SSE=∑j=1m(yj−y^j)2\text{SSE} = \sum_{j=1}^{m} (y_j - \hat{y}_j)^2SSE=∑j=1m​(yj​−y^​j​)2

Here, yjy_jyj​ is the desired output and y^j\hat{y}_jy^​j​ is the predicted output for example jjj. Squaring the differences makes the contributions nonnegative and penalizes larger errors more heavily. Other loss functions may be more suitable for particular tasks, such as classification.

Backpropagation

Backpropagation is the method used to calculate how changes in network parameters would affect the loss. It works backward from the output layer through the network, applying the chain rule to compute gradients for the weights and biases.

The gradients indicate how the loss changes as each parameter changes. An optimization method uses them to update the parameters. A simplified gradient-descent update is:

w←w−α∂L∂ww \leftarrow w - \alpha \frac{\partial L}{\partial w}w←w−α∂w∂L​

In this expression, www is a weight, LLL is the loss, and α\alphaα is the learning rate. Biases are updated in a similar way.

  • A learning rate that is too large may cause updates to overshoot useful parameter values or prevent stable learning.

  • A learning rate that is too small may make learning very slow.

  • The learning rate is a control on the size of updates; it is not itself a measure of model accuracy.

The forward pass, loss calculation, gradient calculation, and parameter update are repeated during training. Backpropagation does not mean that an activation function fires again; it refers to calculating how prediction error should influence earlier layers’ parameters.


Training cycles and stopping criteria

Training generally involves repeated passes over the training data. An epoch is commonly defined as one complete pass through the training set. Depending on the implementation, parameter updates may occur after individual examples, small batches, or a full dataset.

Training needs a stopping rule so that it does not continue indefinitely. Common stopping conditions include:

  • Reaching a chosen error or gradient threshold.

  • Reaching a maximum number of training steps or epochs.

  • Stopping when performance on validation data no longer improves.

In the R package neuralnet, the threshold setting is associated with the size of the partial derivatives of the error function used as a stopping criterion. It is not a threshold that decides whether an individual neuron activates. A setting such as stepmax limits the maximum number of training steps.

A maximum number of steps is a safeguard, not a guarantee that the model has learned well. Conversely, reaching a stopping threshold does not by itself prove that a model will perform accurately on new data.


Choosing the network structure

The number of hidden layers and neurons affects a network’s capacity to learn patterns. More units can allow more complex functions to be represented, but they can also increase training time and the risk of fitting the training data too closely.

A rough rule sometimes used as a starting point is to choose hidden-layer sizes by repeatedly taking square roots of the number of input features. This is only a heuristic, not a general design rule or an optimal method. Architecture should be selected and assessed using the specific task, the amount of data, and validation results.

For example, a network with two hidden layers containing three and two neurons can be represented conceptually as hidden-layer sizes [3,2][3, 2][3,2]. In R, some neural-network functions accept these sizes as a vector, such as hidden = c(3, 2).


Example: classifying Iris flowers

The Iris dataset contains 150 flower examples, with four measurements for each flower and three possible species. The goal is to use the measurements to predict the species.

Preparing the data

A neural network generally needs numeric inputs and numeric target values.

  • The four measurement variables are numeric inputs.

  • The categorical species label can be represented with one-hot encoding: three target columns are created, one for each species. A row has a value of 111 in the column for its species and 000 in the other two.

  • Input features may need scaling so that variables with larger numerical ranges do not dominate simply because of their units.

  • The data is divided into training and test sets. The training set is used to fit the network; the test set is reserved to evaluate predictions on examples not used for fitting.

Scaling parameters should be estimated from the training data and then applied to the test data. Using the test data to determine scaling parameters can allow information from the test set to leak into training.

A typical R workflow using neuralnet follows this general pattern:

library(neuralnet)

model <- neuralnet(
  target_1 + target_2 + target_3 ~ feature_1 + feature_2 + feature_3 + feature_4,
  data = training_data,
  hidden = 2,
  threshold = 0.1,
  stepmax = 2000,
  linear.output = FALSE
)

The names in this example stand for the three one-hot target columns and four input features. For classification, linear.output = FALSE requests non-linear output behavior. Exact preprocessing and model settings depend on the data and implementation.

Interpreting and evaluating predictions

For each test flower, a model can produce a score for each species. The predicted class is typically the class with the largest score. These scores should not automatically be treated as well-calibrated probabilities unless the model and evaluation support that interpretation.

A confusion matrix compares predicted classes with actual classes. It shows which classes were correctly identified and which were confused with others. In one described example, 47 of 50 test flowers were classified correctly, corresponding to 94% accuracy. That figure describes a particular run and split; it is not a guaranteed result for every training run.

Different random initial weights or data splits can produce different outcomes. A model should therefore be judged on held-out data, and repeated validation can provide a more reliable picture of its performance.


Exploratory data analysis and feature preparation

Before building a neural network, the data needs to be examined and prepared. Exploratory data analysis (EDA) helps identify data-quality problems, understand feature distributions, and decide which variables and transformations are appropriate.

Inspecting continuous variables

Histograms and box plots can reveal a variable’s range, shape, skew, and possible outliers. Comparing distributions across outcome groups can help show whether a feature is associated with the target.

For example, an age distribution can be summarized using its minimum, maximum, median, and a plot. A density or distribution plot separated by attrition status can show whether employees who leave differ in age from those who stay. Such differences are useful for identifying possible predictive relationships, but they do not establish that age causes attrition.

A highly skewed variable may require transformation. For example, a logarithmic transformation can make a right-skewed income distribution more manageable:

xtransformed=log⁡(x)x_{\text{transformed}} = \log(x)xtransformed​=log(x)

The transformed feature can then be considered in place of the original, if appropriate. Transformations should be chosen based on the variable’s values and the modeling goal; they are not automatically beneficial in every case.

Inspecting categorical variables

Categorical features, such as department or business-travel frequency, can be summarized with counts and cross-tabulations against the outcome. Comparing the proportion of each outcome category across feature levels can reveal whether a category may be informative.

For numerical modeling, categorical features usually need a numeric encoding, such as one-hot encoding. A category with no meaningful order should not automatically be converted to arbitrary numeric codes, because a model could treat those codes as having meaningful distances.

Checking data quality and redundant features

The analysis should also check for:

  • Missing values, which may need to be removed, imputed, or otherwise handled.

  • Outliers, which should be investigated to determine whether they are genuine observations or data errors.

  • Constant or near-constant variables, which provide little or no useful variation.

  • Identifiers, such as employee IDs, which identify records but generally do not describe an outcome-relevant property.

  • Redundant variables, where one feature is a total or direct calculation from others.

  • Correlated features, which can complicate interpretation and sometimes affect model behavior.

For instance, if a dataset contains each month’s salary and a total salary that is calculated from those monthly values, including every monthly value alongside the total may add redundancy. An employee-count field that has the same value for every row does not distinguish employees and is not a useful predictor.

Example: analyzing employee attrition

The described employee-attrition example contains approximately 2,940 records and about 35 variables, with roughly 474 employees marked as having left. These figures correspond to an attrition rate of approximately 16%. The exact counts depend on the version and processing of the dataset.

Several patterns were considered:

  • Age: Employees who left appeared more concentrated in younger age groups in the exploratory plots.

  • Distance from home: Greater distance appeared associated with more attrition in the observed data.

  • Overtime: Employees working overtime appeared more likely to have left.

  • Monthly income and salary hike: These variables had skewed distributions and required attention to their scales and shapes before modeling.

  • Business travel, daily rate, department, and education categories: Their usefulness should be judged by comparing outcome rates across their levels rather than assuming that the feature matters.

These are exploratory associations, not causal conclusions. A variable may appear useful on its own but contribute little once other features are considered, or its apparent relationship may reflect another factor.

Why careful feature preparation matters for neural networks

Some models, including random forests, can provide measures of feature importance or perform splits that favor useful variables. Such behavior does not eliminate the need for data preparation or guarantee that irrelevant features will be ignored.

A neural network learns from the variables it receives. If irrelevant, redundant, poorly encoded, or badly scaled features are included, they can make learning less effective or make the model harder to evaluate. Careful EDA helps identify these issues before fitting the network.

If the outcome is imbalanced—as in an example where attrition is much less common than non-attrition—accuracy alone can be misleading. A model that mostly predicts the majority class may achieve a high accuracy while performing poorly on the less common class. Confusion matrices and class-specific measures such as recall and precision help reveal this problem.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent