1 of 127

CS307

Machine Learning

Lecture 24

Neural Networks

Krishnendu Ghosh

Department of Computer Science & Engineering

Indian Institute of Information Technology Dharwad

2 of 127

Neural Networks

Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.

​

​

2

3 of 127

Neural Networks

Neural networks are capable of learning and identifying patterns directly from data without predefined rules. These networks are built from several key components:

  • Neurons: The basic units that receive inputs, each neuron is governed by a threshold and an activation function.
  • Connections: Links between neurons that carry information, regulated by weights and biases.
  • Weights and Biases: These parameters determine the strength and influence of connections.
  • Propagation Functions: Mechanisms that help process and transfer data across layers of neurons.
  • Learning Rule: The method that adjusts weights and biases over time to improve accuracy.

3

4 of 127

Neural Networks

Learning in neural networks follows a structured, three-stage process:

  • Input Computation: Data is fed into the network.
  • Output Generation: Based on the current parameters, the network generates an output.
  • Iterative Refinement: The network refines its output by adjusting weights and biases, gradually improving its performance on diverse tasks.

4

5 of 127

Neural Networks

5

6 of 127

Neural Networks

Importance of Neural Networks

Neural networks are pivotal in identifying complex patterns, solving intricate challenges, and adapting to dynamic environments. Their ability to learn from vast amounts of data is transformative, impacting technologies like natural language processing, self-driving vehicles, and automated decision-making.

Neural networks streamline processes, increase efficiency, and support decision-making across various industries. As a backbone of artificial intelligence, they continue to drive innovation, shaping the future of technology.

6

7 of 127

Neural Networks

Layers in Neural Network Architecture

  • Input Layer: This is where the network receives its input data. Each input neuron in the layer corresponds to a feature in the input data.
  • Hidden Layers: These layers perform most of the computational heavy lifting. A neural network can have one or multiple hidden layers. Each layer consists of units (neurons) that transform the inputs into something that the output layer can use.
  • Output Layer: The final layer produces the output of the model. The format of these outputs varies depending on the specific task (e.g., classification, regression).

7

8 of 127

Neural Networks

Forward Propagation

When data is input into the network, it passes through the network in the forward direction, from the input layer through the hidden layers to the output layer. This process is known as forward propagation. Here’s what happens during this phase:

​

  • Linear Transformation
  • Activation

8

9 of 127

Neural Networks

Backpropagation

After forward propagation, the network evaluates its performance using a loss function, which measures the difference between the actual output and the predicted output. The goal of training is to minimize this loss. This is where backpropagation comes into play:

  • Loss Calculation
  • Gradient Calculation
  • Weight Update

9

10 of 127

Neural Networks

Types of Neural Networks

  • Feed Forward Networks
  • Single Layer Perceptron
  • Multi Layer Perceptron (MLP)
  • Convolutional Neural Network (CNN)
  • Recurrent Neural Network (RNN)
  • Long Short-Term Memory (LSTM)

10

11 of 127

Neural Networks

Advantages of Neural Networks

  • Adaptability: Neural networks are useful for activities where the link between inputs and outputs is complex or not well defined because they can adapt to new situations and learn from data.
  • Pattern Recognition: Their proficiency in pattern recognition renders them efficacious in tasks like as audio and image identification, natural language processing, and other intricate data patterns.
  • Parallel Processing: Because neural networks are capable of parallel processing by nature, they can process numerous jobs at once, which speeds up and improves the efficiency of computations.
  • Non-Linearity: Neural networks are able to model and comprehend complicated relationships in data by virtue of the non-linear activation functions found in neurons, which overcome the drawbacks of linear models.

11

12 of 127

Neural Networks

Disadvantages of Neural Networks

  • Computational Intensity: Large neural network training can be a laborious and computationally demanding process that demands a lot of computing power.
  • Black box Nature: As “black box” models, neural networks pose a problem in important applications since it is difficult to understand how they make decisions.
  • Overfitting: Overfitting is a phenomenon in which neural networks commit training material to memory rather than identifying patterns in the data. Although regularization approaches help to alleviate this, the problem still exists.
  • Need for Large datasets: For efficient training, neural networks frequently need sizable, labeled datasets; otherwise, their performance may suffer from incomplete or skewed data.

12

13 of 127

Units in Neural Networks

14 of 127

This is in your brain

14

By BruceBlaus - Own work, CC BY 3.0, https://commons.wikimedia.org/w/index.php?curid=28761830

15 of 127

Neural Network Unit: This is not in your brain

15

Weights

Input layer

Weighted sum

Non-linear transform

Output value

bias

16 of 127

Neural unit

Take weighted sum of inputs, plus a bias

​

​

​

Instead of just using z, we'll apply a nonlinear activation function f:

17 of 127

Non-Linear Activation Functions

17

Sigmoid

We're already seen the sigmoid for logistic regression:

18 of 127

Final function the unit is computing

19 of 127

Final unit again

19

Weights

Input layer

Weighted sum

Non-linear activation function

Output value

bias

20 of 127

An example

Suppose a unit has:

w = [0.2,0.3,0.9]

b = 0.5

What happens with input x:

x = [0.5,0.6,0.1]

​

​

21 of 127

An example

Suppose a unit has:

w = [0.2,0.3,0.9]

b = 0.5

What happens with the following input x?

x = [0.5,0.6,0.1]

​

​

22 of 127

An example

Suppose a unit has:

w = [0.2,0.3,0.9]

b = 0.5

What happens with input x:

x = [0.5,0.6,0.1]

​

​

23 of 127

An example

Suppose a unit has:

w = [0.2,0.3,0.9]

b = 0.5

What happens with input x:

x = [0.5,0.6,0.1]

​

​

24 of 127

Non-Linear Activation Functions besides sigmoid

24

tanh

ReLU

Rectified Linear Unit

Most Common:

25 of 127

The XOR problem

26 of 127

The XOR problem

Can neural units compute simple functions of input?

Minsky and Papert (1969)

27 of 127

Perceptrons

A very simple neural unit

  • Binary output (0 or 1)
  • No non-linear activation function

​

28 of 127

Easy to build AND or OR with perceptrons

AND

OR

29 of 127

Easy to build AND or OR with perceptrons

AND

OR

30 of 127

Easy to build AND or OR with perceptrons

AND

OR

31 of 127

Not possible to capture XOR with perceptrons

Pause the lecture and try for yourself!

32 of 127

Why? Perceptrons are linear classifiers

Perceptron equation given x1 and x2, is the equation of a line

w1x1 + w2x2 + b = 0

​

(in standard linear format: x2 = (−w1/w2)x1 + (−b/w2) )

This line acts as a decision boundary

  • 0 if input is on one side of the line
  • 1 if on the other side of the line

​

​

33 of 127

Decision boundaries

XOR is not a linearly separable function!

34 of 127

Solution to the XOR problem

XOR can't be calculated by a single perceptron

XOR can be calculated by a layered network of units.

​

ReLU

ReLU

35 of 127

Solution to the XOR problem

XOR can't be calculated by a single perceptron

XOR can be calculated by a layered network of units.

​

36 of 127

The hidden representation h

(With learning: hidden layers will learn to form useful representations)

37 of 127

Feedforward Neural Networks

38 of 127

Feedforward Neural Networks

Can also be called multi-layer perceptrons (or MLPs) for historical reasons

​

39 of 127

Binary Logistic Regression as a 1-layer Network

39

w

xn

x1

 

+1

w1

wn

b

(y is a scalar)

σ

Output layer

(σ node)

Input layer

vector x

(we don't count the input layer in counting layers!)

(vector)

(scalar)

40 of 127

Multinomial Logistic Regression as a 1-layer Network

40

W

xn

x1

Fully connected single layer network

W is a matrix

 

+1

y is a vector

y1

yn

b is a vector

b

s

s

s

Output layer

(softmax nodes)

Input layer

scalars

41 of 127

Reminder: softmax: a generalization of sigmoid

​

For a vector z of dimensionality k, the softmax is:

​

​

​

​

Example:

42 of 127

Two-Layer Network with scalar output

U

W

xn

x1

+1

y is a scalar

b

hidden units

(σ node)

​

Input layer

(vector)

Output layer

(σ node)

Could be ReLU

Or tanh

 

 

43 of 127

Two-Layer Network with scalar output

U

W

xn

x1

+1

b

hidden units

(σ node)

​

Input layer

(vector)

Output layer

(σ node)

i

j

Wji

vector

y is a scalar

 

 

44 of 127

Two-Layer Network with scalar output

U

W

xn

x1

+1

b

hidden units

(σ node)

​

Input layer

(vector)

Output layer

(σ node)

Could be ReLU

Or tanh

y is a scalar

 

 

45 of 127

Two-Layer Network with softmax output

U

W

xn

x1

+1

b

hidden units

(σ node)

​

Input layer

(vector)

Output layer

(σ node)

Could be ReLU

Or tanh

y is a vector

 

 

46 of 127

Multi-layer Notation

W[1]

xn

x1

+1

b[1]

i

j

W[2]

b[2]

 

 

 

 

 

 

sigmoid or softmax

ReLU

47 of 127

Multi Layer Notation

47

48 of 127

Replacing the bias unit

Let's switch to a notation without the bias unit

Just a notational change

  1. Add a dummy node a0=1 to each layer
  2. Its weight w0 will be the bias
  3. So input layer a[0]0=1,
    • And a[1]0=1 , a[2]0=1,…

49 of 127

Replacing the bias unit

Instead of: We'll do this:

x= x1, x2, …, xn0

x= x0, x1, x2, …, xn0

50 of 127

Replacing the bias unit

Instead of: We'll do this:

51 of 127

Applying feedforward networks to NLP tasks

52 of 127

Use cases for feedforward networks

Let's consider 2 (simplified) sample tasks:

    • Text classification
    • Language modeling

​

State of the art systems use more powerful neural architectures, but simple models are useful to consider!

53 of 127

Classification: Sentiment Analysis

We could do exactly what we did with logistic regression

Input layer are binary features as before

Output layer is 0 or 1

U

W

xn

x1

σ

54 of 127

Sentiment Features

55 of 127

55

56 of 127

Classifying sentiment for input x

56

Suppose w =

b = 0.1

57 of 127

Classifying sentiment for input x

57

58 of 127

Feedforward nets for simple classification

Just adding a hidden layer to logistic regression

  • allows the network to use non-linear interactions between features
  • which may (or may not) improve performance.

58

U

W

xn

x1

f1

f2

fn

58

W

xn

x1

f1

f2

fn

Logistic

Regression

2-layer

feedforward

network

σ

σ

59 of 127

Even better: representation learning

The real power of deep learning comes from the ability to learn features from the data

Instead of using hand-built human-engineered features for classification

Use learned representations like embeddings!

U

W

xn

x1

e1

e2

en

σ

60 of 127

Neural Net Classification with embeddings as input features!

61 of 127

Issue: texts come in different sizes

This assumes a fixed size length (3)!

Kind of unrealistic.

Some simple solutions (more sophisticated solutions later)

  1. Make the input the length of the longest review
    • If shorter then pad with zero embeddings
    • Truncate if you get longer reviews at test time
  2. Create a single "sentence embedding" (the same dimensionality as a word) to represent all the words
    • Take the mean of all the word embeddings
    • Take the element-wise max of all the word embeddings
      • For each dimension, pick the max value from all words

62 of 127

Reminder: Multiclass Outputs

What if you have more than two output classes?

    • Add more output units (one for each class)
    • And use a “softmax layer”

U

W

xn

x1

63 of 127

Neural Language Models (LMs)

Language Modeling:

Calculating the probability of the next word in a sequence given some history.

  • We've seen N-gram based LMs
  • But neural network LMs far outperform n-gram language models

State-of-the-art neural LMs are based on more powerful neural network technology like Transformers

But simple feedforward LMs can do almost as well!

​

64 of 127

Simple feedforward Neural Language Models

Task: predict next word wt

given prior words wt-1, wt-2, wt-3, …

Problem: Now we’re dealing with sequences of arbitrary length.

Solution: Sliding windows (of fixed length)

65 of 127

Neural Language Model

66 of 127

Why Neural LMs work better than N-gram LMs

Training data:

We've seen: I have to make sure that the cat gets fed.

Never seen: dog gets fed

Test data:

I forgot to make sure that the dog gets ___

N-gram LM can't predict "fed"!

Neural LM can use similarity of "cat" and "dog" embeddings to generalize and predict “fed” after dog

​

​

​

​

​

​

67 of 127

Training Neural Nets: Overview

68 of 127

Intuition: training a 2-layer Network

U

W

xn

x1

 

 

Training instance

 

Forward pass

Backward pass

69 of 127

Intuition: Training a 2-layer network

 

70 of 127

Reminder: Loss Function for binary logistic regression

A measure for how far off the current answer is to the right answer

Cross entropy loss for logistic regression:

​

​

71 of 127

Reminder: gradient descent for weight updates

 

72 of 127

Let's see if this works for our sentiment example

​

True value is y=1. How well is our model doing?

​

​

​

Pretty well! What's the loss?

73 of 127

Let's see if this works for our sentiment example

Suppose true value instead was y=0.

​

​

What's the loss?

74 of 127

Let's see if this works for our sentiment example

The loss when model was right (if true y=1)

​

​

​

Is lower than the loss when model was wrong (if true y=0):

​

​

​

Sure enough, loss was bigger when model was wrong!

75 of 127

Where did that derivative come from?

Using the chain rule! f (x) = u(v(x))

Intuition (see the text for details)

Derivative of the Loss

Derivative of the Activation

Derivative of the weighted sum

 

76 of 127

How can I find that gradient for every weight in the network?

These derivatives on the prior slide only give the updates for one weight layer: the last one!

What about deeper networks?

  • Lots of layers, different activation functions?

Solution in the next lecture:

  • Even more use of the chain rule!!
  • Computation graphs and backward differentiation!

77 of 127

Stochastic Gradient Descent

78 of 127

Our goal: minimize the loss

 

79 of 127

Intuition of gradient descent

How do I get to the bottom of this river canyon?

​

x

Look around me 360∘

Find the direction of steepest slope down

Go that way

80 of 127

Our goal: minimize the loss

For logistic regression, loss function is convex

  • A convex function has just one minimum
  • Gradient descent starting from any point is guaranteed to find the minimum
    • (Loss for neural networks is non-convex)

​

​

​

81 of 127

Let's first visualize for a single scalar w

Q: Given current w, should we make it bigger or smaller?

A: Move w in the reverse direction from the slope of the function

82 of 127

Let's first visualize for a single scalar w

Q: Given current w, should we make it bigger or smaller?

A: Move w in the reverse direction from the slope of the function

So we'll move positive

83 of 127

Let's first visualize for a single scalar w

Q: Given current w, should we make it bigger or smaller?

A: Move w in the reverse direction from the slope of the function

So we'll move positive

84 of 127

Gradients

The gradient of a function of many variables is a vector pointing in the direction of the greatest increase in a function.

​

Gradient Descent: Find the gradient of the loss function at the current point and move in the opposite direction.

85 of 127

How much do we move in that direction ?

 

86 of 127

Now let's consider N dimensions

We want to know where in the N-dimensional space (of the N parameters that make up θ ) we should move.

The gradient is just such a vector; it expresses the directional components of the sharpest slope along each of the N dimensions.

​

​

87 of 127

Imagine 2 dimensions, w and b

Visualizing the gradient vector at the red point

It has two dimensions shown in the x-y plane

​

88 of 127

Real gradients

Are much longer; lots and lots of weights

For each dimension wi the gradient component i tells us the slope with respect to that variable.

    • “How much would a small change in wi influence the total loss function L?”
    • We express the slope as a partial derivative ∂ of the loss ∂wi

The gradient is then defined as a vector of these partials.

​

​

​

89 of 127

The gradient

 

The final equation for updating θ based on the gradient is thus

90 of 127

What are these partial derivatives for logistic regression?

The loss function

The elegant derivative of this function (see textbook 5.8 for derivation)

91 of 127

92 of 127

Hyperparameters

The learning rate η is a hyperparameter

    • too high: the learner will take big steps and overshoot
    • too low: the learner will take too long

Hyperparameters:

  • Briefly, a special kind of parameter for an ML model
  • Instead of being learned by algorithm from supervision (like regular parameters), they are chosen by algorithm designer.

93 of 127

Stochastic Gradient Descent: An example and more details

94 of 127

Working through an example

One step of gradient descent

A mini-sentiment example, where the true y=1 (positive)

Two features:

x1  = 3 (count of positive lexicon words)

x2  = 2 (count of negative lexicon words)

Assume 3 parameters (2 weights and 1 bias) in Θ0 are zero:

w1 = w2 = b = 0

η = 0.1

​

​

​

95 of 127

Example of gradient descent

Update step for update θ is:

​

​

where

​

Gradient vector has 3 dimensions:

w1 = w2 = b = 0;

x1  = 3; x2  = 2

​

96 of 127

Example of gradient descent

Update step for update θ is:

​

​

where

​

Gradient vector has 3 dimensions:

w1 = w2 = b = 0;

x1  = 3; x2  = 2

​

97 of 127

Example of gradient descent

Update step for update θ is:

​

​

where

​

Gradient vector has 3 dimensions:

w1 = w2 = b = 0;

x1  = 3; x2  = 2

​

98 of 127

Example of gradient descent

Update step for update θ is:

​

​

where

​

Gradient vector has 3 dimensions:

w1 = w2 = b = 0;

x1  = 3; x2  = 2

​

99 of 127

Example of gradient descent

Update step for update θ is:

​

​

where

​

Gradient vector has 3 dimensions:

w1 = w2 = b = 0;

x1  = 3; x2  = 2

​

100 of 127

Example of gradient descent

η = 0.1;

Now that we have a gradient, we compute the new parameter vector θ1 by moving θ0 in the opposite direction from the gradient:

101 of 127

Example of gradient descent

η = 0.1;

Now that we have a gradient, we compute the new parameter vector θ1 by moving θ0 in the opposite direction from the gradient:

102 of 127

Example of gradient descent

η = 0.1;

Now that we have a gradient, we compute the new parameter vector θ1 by moving θ0 in the opposite direction from the gradient:

103 of 127

Example of gradient descent

η = 0.1;

Now that we have a gradient, we compute the new parameter vector θ1 by moving θ0 in the opposite direction from the gradient:

Note that enough negative examples would eventually make w2 negative

104 of 127

Mini-batch training

Stochastic gradient descent chooses a single random example at a time.

That can result in choppy movements

More common to compute gradient over batches of training instances.

Batch training: entire dataset

Mini-batch training: m examples (512, or 1024)

​

105 of 127

Computation Graphs and Backward Differentiation

106 of 127

Why Computation Graphs

For training, we need the derivative of the loss with respect to each weight in every layer of the network

  • But the loss is computed only at the very end of the network!

Solution: error backpropagation (Rumelhart, Hinton, Williams, 1986)

  • Backprop is a special case of backward differentiation
  • Which relies on computation graphs.

107 of 127

Computation Graphs

A computation graph represents the process of computing a mathematical expression

​

​

​

108 of 127

Example:

Computations:

109 of 127

Example:

109

Computations:

110 of 127

Backwards differentiation in computation graphs

The importance of the computation graph comes from the backward pass

This is used to compute the derivatives that we’ll need for the weight update.

111 of 127

Example

111

 

We want:

112 of 127

The chain rule

Computing the derivative of a composite function:

​

f (x) = u(v(x))

​

​

f (x) = u(v(w(x)))

​

​

113 of 127

Example

113

114 of 127

Example

114

115 of 127

Example

115

116 of 127

Example

116

117 of 127

Backward differentiation on a two layer network

117

σ

W[2]

W[1]

y

x2

x1

Sigmoid activation

ReLU activation

1

1

b[1]

b[2]

118 of 127

Backward differentiation on a two layer network

118

119 of 127

Backward differentiation on a 2-layer network

120 of 127

 

 

 

 

 

 

 

 

121 of 127

Summary

For training, we need the derivative of the loss with respect to weights in early layers of the network

  • But loss is computed only at the very end of the network!

Solution: backward differentiation

Given a computation graph and the derivatives of all the functions in it we can automatically compute the derivative of the loss with respect to these early weights.

​

121

122 of 127

Extra: Pooling

There are various ways to represent an input for classification. One simple baseline is to apply some sort of pooling function to the embeddings of all the words in the input. For example, for a text with n input words w1, ..., wn, we can turn the n embeddings e(w1), ..., e(wn), each of dimension d, into a single embedding by just summing the embeddings, or by taking their mean:

​

122

123 of 127

Extra: Pooling

There are other options, like taking element-wise max.

x = mean(e(w1), e(w2), . . . , e(wn))

h = σ (Wx + b)

z = Uh

ŷ = softmax(z)

​

123

124 of 127

Extra: Pretraining

Here are the final equations for computing the output class distribution for an entire test set:

H = σ (XWT | + b)

Z = HUT

Ŷ = softmax(Z)

The idea of using word2vec or GloVe embeddings as our input representation and more generally the idea of relying on another algorithm to have already learned an embedding representation for our input words is called pretraining.

124

125 of 127

Extra: One-hot Vector

A vector with one value equal to 1 and the rest 0, is called a one-hot vector.

125

126 of 127

Extra: Dropout

Various forms of regularization are used to prevent overfitting.

One of the most important is dropout: randomly dropping some units and their connections from the network during training.

At each iteration of training, we repeatedly choose a probability p and for each unit we replace its output with zero with probability p.

​

126

127 of 127

Thank You

127