Neural Networks Intro
Neural Networks
Biological Inspiration and Artificial Neurons
Neural networks are a popular set of techniques within machine learning, inspired by the structure of the human brain. The brain consists of billions of neurons connected to each other, communicating via electrical signals. Neurons receive input signals, process them, and when a certain threshold is reached, they become activated and propagate signals to other neurons.
An artificial neural network (ANN) is a mathematical model for learning inspired by these biological neural networks. Instead of biological neurons, artificial neural networks use units (also called artificial neurons) represented as nodes in a graph. These units are connected by edges that represent weights — numerical values that determine the strength of the connection.
The fundamental idea is to model a mathematical function that maps inputs to outputs. A simple example: given inputs x1 and x2 (e.g., weather variables), the network predicts whether it will rain (binary output). The hypothesis function h(x1,x2) is a linear combination of the inputs plus a bias term:
Here, w1 and w2 are weights multiplied by the inputs, and w0 is the bias (or an extra weight with a dummy input of 1). The goal of training is to find the optimal values of these weights.
Activation Functions
The output of the linear combination is passed through an activation function to produce a final output. Several common activation functions exist:
Step function: Outputs 1 if the weighted sum is at least 0, otherwise 0. This is used for binary classification.
Logistic sigmoid function: An S-shaped curve that outputs a value between 0 and 1, interpretable as a probability. Useful for probabilities and gradient-based learning.
Rectified Linear Unit (ReLU): Outputs the input if positive, otherwise 0. Defined as g(z)=max(0,z). Very popular in deep networks due to computational efficiency and mitigation of vanishing gradient.
Thus, the complete hypothesis becomes:
where g is the activation function.
Simple Neural Network for OR Function
A neural network with two inputs and one output can represent the OR function. By setting weights to 1 and bias to -1, and using the step activation function:
Input (0,0): weighted sum = 0⋅1+0⋅1−1=−1, step(-1) = 0.
Input (1,0): weighted sum = 1⋅1+0⋅1−1=0, step(0) = 1.
Input (1,1): weighted sum = 1⋅1+1⋅1−1=1, step(1) = 1.
The network correctly computes x1∨x2.
Simple Neural Network for AND Function
For the AND function, weights are 1 and bias is -2:
Input (1,1): weighted sum = 1+1−2=0, step(0) = 1.
Input (1,0): weighted sum = 1+0−2=−1, step(-1) = 0.
This demonstrates that simple logical functions can be learned by adjusting weights and bias.
Training Neural Networks with Gradient Descent
For more complex problems (e.g., predicting rain from humidity and pressure), manually setting weights is impossible. The computer must learn the weights that minimize the loss — a measure of how poorly the hypothesis function performs on the training data.
Gradient descent is an algorithm for minimizing loss by iteratively updating weights in the direction of steepest descent of the loss function (the negative gradient). The high-level process:
Start with random weights for all connections.
Repeat until convergence:
Calculate the gradient of the loss function with respect to each weight, based on all training data points. The gradient indicates the direction of greatest increase in loss; we move opposite to it.
Update the weights by taking a small step in the direction of the negative gradient. The step size (learning rate) is a hyperparameter.
While effective, computing the gradient using all data points is computationally expensive, especially for large datasets.
Variants of Gradient Descent
Stochastic gradient descent (SGD): Instead of using all data points, randomly select one data point at a time to compute the gradient and update weights. This is faster per iteration but produces a noisier estimate of the gradient.
Mini-batch gradient descent: A middle ground that splits the dataset into small batches (e.g., 32 or 64 samples) and computes the gradient on each batch. This balances computational efficiency and accuracy of gradient estimation.
Multi-Class Classification and Multiple Outputs
Many problems require more than binary classification. For example, weather might be categorized as rainy, sunny, cloudy, or snowy. A neural network can have multiple output units, each representing the probability of one class. The structure is fully connected: each input unit connects to every output unit via separate weights.
Training a network with multiple outputs can be viewed as training several independent single-output networks simultaneously, each with their own set of weights. The outputs can be converted into a probability distribution using the softmax activation function, which ensures the sum of all outputs equals 1.
Applications Beyond Classification
Neural networks can also be applied to reinforcement learning: the input could represent the current state of the environment, and the outputs could represent the value or desirability of each possible action. The agent selects the action with the highest output.
Limitations of Single Perceptron
A single unit performing binary classification (a perceptron) can only learn linearly separable decision boundaries. If the data points cannot be separated by a straight line (e.g., blue points inside a circle, red points outside), a single perceptron fails. Real-world data is often not linearly separable, necessitating more complex architectures.
Multilayer Neural Networks and Backpropagation
To overcome linear separability, researchers introduced multilayer neural networks, which contain one or more hidden layers between the input and output layers. Each hidden layer consists of multiple units that learn different decision boundaries. By combining these boundaries, the network can model complex, non-linear functions.
For example, with two inputs and one hidden layer with two neurons, the network can learn two lines and combine them to create a more complex separation (e.g., a rectangular region).
Training with Backpropagation
The challenge is that the training data only provides inputs and correct outputs, not the desired values for hidden units (hence "hidden"). Backpropagation solves this by propagating the error backward through the network:
Start with random weights.
Repeat:
Forward pass: Compute the output for the current input.
Calculate error at the output layer.
Backpropagate the error: For each layer, starting from the output and moving backward, estimate the contribution of each hidden unit to the output error, based on the weights.
Update weights using gradient descent.
This algorithm makes training deep networks feasible and is the cornerstone of modern neural network learning.
Deep Neural Networks and Dropout
A deep neural network has multiple hidden layers. Each layer can learn increasingly abstract features. However, as complexity increases, there is a risk of overfitting — memorizing the training data rather than generalizing to new data.
Dropout is a regularization technique to combat overfitting. During training, randomly selected units (along with their connections) are temporarily removed from the network. This prevents the network from becoming overly reliant on specific units, promoting robustness. The dropout rate (e.g., 50%) is a hyperparameter.
Computer Vision: Convolution and Pooling
Computer vision involves computational methods for analyzing and understanding images. Images are grids of pixels, each with numerical values (e.g., 0 for black, 255 for white, or RGB triplets for color). A naive approach would flatten the image into a long vector of pixel values and feed it into a standard neural network. This suffers from:
Large number of inputs — a small 28×28 image yields 784 inputs, and a color image with thousands of pixels is even larger.
Loss of spatial structure — pixels are treated independently, ignoring local patterns.
Image Convolution
Image convolution applies a filter (also called a kernel) to an image to extract useful features like edges, curves, or textures. The kernel is a small matrix (e.g., 3×3) that slides across the image. At each position, the kernel values are multiplied element-wise with the corresponding pixel values, and the results are summed to produce a single output pixel in a new feature map.
Example kernel for edge detection (often called the Laplacian):
[[ 0, -1, 0],
[-1, 8, -1],
[ 0, -1, 0]]When a pixel and its neighbors have similar values, the output is near 0.
When the central pixel is very different from its surroundings (e.g., on an edge), the output is high.
Applying this filter to an image extracts boundaries between objects. Many different filters can be learned by the network to detect various features.
Pooling
Pooling reduces the spatial dimensions of an image or feature map, which decreases the number of parameters and provides translation invariance. The most common type is max-pooling, which partitions the input into non-overlapping regions (e.g., 2×2) and outputs the maximum value in each region. Another option is average-pooling, which outputs the average.
Pooling makes the network less sensitive to small shifts or distortions in the input.
Convolutional Neural Networks (CNNs)
A convolutional neural network (CNN) combines convolution, pooling, and traditional neural network layers to process images effectively. The typical architecture:
Input layer: An image (e.g., 28×28 grayscale).
Convolution layer: Applies multiple learnable filters (kernels) to produce several feature maps. The network learns optimal filter values during training.
Pooling layer: Reduces the size of each feature map (e.g., 2×2 max pooling).
Additional convolution and pooling layers (optional): To extract higher-level features. Often, a second convolution+pooling block is used.
Flattening: Converts the 2D feature maps into a 1D vector.
Fully connected hidden layers: Standard dense layers with activation functions.
Dropout layer (optional): To prevent overfitting.
Output layer: Typically uses softmax activation for classification into multiple classes.
CNNs are particularly powerful for tasks like handwriting recognition. The MNIST dataset (28×28 grayscale digits) is a classic benchmark. A CNN trained on MNIST can achieve over 99% accuracy on test data.
Example code structure (using TensorFlow/Keras):
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
tf.keras.layers.MaxPooling2D((2,2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(10, activation='softmax')
])The network learns both the weights of fully connected layers and the filter values in the convolution layers through backpropagation.
Recurrent Neural Networks (RNNs)
Traditional feed-forward neural networks have fixed-size inputs and outputs, and information flows only in one direction (from input to output). They cannot handle sequential data effectively because they lack memory of previous inputs.
Recurrent neural networks (RNNs) address this by allowing connections that feed output from the network back into itself as input for future steps. This creates a form of state or memory, enabling the network to process sequences of arbitrary length.
One-to-Many Architecture
In one-to-many RNNs, a single input (e.g., an image) generates a sequence of outputs (e.g., a caption). The process:
The image is fed into the network, which outputs the first word (or token).
That output is fed back into the same network (along with some context from the image) to generate the second word.
This repeats until the caption is complete.
This is how systems like Microsoft's CaptionBot can describe an image with a sentence.
Many-to-One Architecture
Many-to-one RNNs take a sequence as input and produce a single output. Examples:
Sentiment analysis: Given a sequence of words (a review), classify it as positive or negative.
Video classification: Process frames of a video sequentially and output a category.
The network receives inputs one step at a time, and after all inputs have been processed, the final hidden state is used for the output.
Many-to-Many Architecture
Many-to-many RNNs take a sequence as input and produce a sequence as output. A classic example is machine translation (e.g., English to French). The approach often uses an encoder-decoder structure:
Encoder: Reads the entire input sequence (e.g., English sentence) and encodes it into a fixed-length context vector (or a sequence of hidden states).
Decoder: Generates the output sequence (e.g., French sentence) one word at a time, using the encoded context and previously generated words as input.
A popular variant is the Long Short-Term Memory (LSTM) network, which is designed to capture long-range dependencies in sequences and mitigate the vanishing gradient problem.
Summary and Next Steps
Neural networks are versatile tools for modeling complex functions from data. Key types include:
Feed-forward neural networks: Basic architecture for classification and regression.
Convolutional neural networks (CNNs): Designed for grid-like data (especially images), using convolution and pooling to extract spatial features.
Recurrent neural networks (RNNs): Suited for sequential data, with memory enabled by feedback loops. Variants include LSTMs.
Adversarial networks: Two networks compete (e.g., generator vs. discriminator) to generate new data.
These techniques have broad applications, from handwriting recognition and image captioning to machine translation. The next step is to explore how AI processes natural language — understanding, analyzing, and generating human language using these and other methods.

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