class: center, middle, inverse, title-slide .title[ # Deep Learning ] .subtitle[ ## Machine Learning in Economics ] .author[ ### Hüseyin Taştan ] .institute[ ### Yildiz Technical University ] --- <style type="text/css"> .remark-slide-content { font-size: 25px; padding: 1em 4em 1em 4em; } .my-large-font { font-size: 40px; } .my-small-font { font-size: 20px; } .my-medium-font { font-size: 25px; } </style> # Lecture Outline - [Artificial Neural Networks (ANN)](#ysa) - [History of ANNs](#history) - [ANN architecture](#struct) - [A simple example](#ex1) - [Multilayer ANNs](#multi) - [Training ANNs](#training) - [Convolutional Neural Networks](#cnn) - [Recurrent Neural Networks](#rnn) --- name: ysa # Artificial Neural Networks (ANNs)  - Artificial neural networks are nonlinear and highly flexible models inspired by the structure and function of nerve cells (neurons) in the brain. - Biological neural networks consist of neurons that communicate by transmitting electrical signals, which together produce complex outputs. - Each neuron integrates incoming signals, and if their combined strength exceeds a certain threshold, it "fires," sending an electrical impulse to connected neurons. - This network of interconnected neurons enables complex information processing, learning, and decision-making in the brain. ??? To help make this clearer, consider what happens when you touch something hot. The sensory neurons in your skin detect the high temperature and send electrical signals through the neural network in your body. These signals are processed by neurons in your spinal cord and brain. If the combined input is strong enough, motor neurons fire impulses that tell your muscles to quickly pull your hand away. This rapid, automatic response shows how neurons work together by passing signals, integrating them, and triggering an action when needed. Artificial neural networks mimic this process by aggregating inputs and passing outputs through connected nodes --- name: ysa # Artificial Neural Networks (ANNs)  - **ANNs perform transformation of multiple inputs:** They process numerous input variables through layers of neurons, each weighted by parameters learned during training to capture complex patterns. - **Handling multiple output variables:** ANNs can simultaneously predict several outputs, enabling multitask learning and more sophisticated modeling scenarios. - **Applicable to regression and classification problems:** They adapt to both continuous output prediction (regression) and categorical output classification by adjusting output layers and training objectives. ??? ANNs perform transformation of multiple inputs: An artificial neural network (ANN) takes in many input variables simultaneously and processes them using layers of interconnected nodes (neurons). Each input is assigned a weight (an unknown parameter), which the network learns during training to model complex relationships in data. Handling multiple output variables: Unlike some simple models that predict a single outcome, ANNs can be designed to predict several outputs simultaneously. This makes them suitable for multitask learning or problems where multiple related predictions arise from the same inputs. Applicable to regression and classification problems: ANNs are highly flexible and can be adapted for various types of tasks. For regression problems, they can predict continuous values (e.g., house prices). For classification, they can categorize inputs into discrete classes (e.g., spam vs. non-spam emails) by using different output layer activation functions and loss functions. --- name: history # History of ANNs and Deep Learning - **1940s - 1950s** - The concept of artificial neural networks was first introduced, inspired by the biological neural networks in the brain. - **1960s - 1970s** - Significant advancements were made in the field of ANNs, particularly in the development of perceptrons by Frank Rosenblatt. - However, the limitations of perceptrons in solving nonlinear problems led to a decline in interest in ANNs. --- # History of ANNs and Deep Learning - **1980s - 1990s** - The backpropagation algorithm was rediscovered and popularized, allowing for efficient training of multi-layer perceptrons. - Despite these advancements, ANNs faced challenges in handling complex tasks and were overshadowed by other machine learning approaches like boosting trees. - **2000s - 2010s** - A renaissance of ANNs began with breakthroughs in deep learning. Introduction of Convolutional Neural Networks (CNNs) by Yann LeCun and others revolutionized image recognition tasks. - Recurrent Neural Networks (RNNs) gained popularity for sequential data processing, leading to advancements in speech recognition and natural language processing. --- # History of ANNs and Deep Learning - **2012 - Present** - The ImageNet Large Scale Visual Recognition Challenge (ILSVRC) in 2012 marked a significant milestone with the victory of AlexNet <https://en.wikipedia.org/wiki/ImageNet#ImageNet_Challenge> - Since then, deep learning has become the dominant approach in various fields, achieving remarkable success in tasks such as object detection, machine translation, and autonomous driving. - Advances in hardware (such as GPUs) and software (deep learning frameworks like TensorFlow and PyTorch) have further accelerated the progress of deep learning. --- name: struct # ANN structure .pull-left[  - The structure of artificial neural networks (ANNs) can be visually represented using a network graph. (image source: James et al. ISLR, 2nd ed., p.405) ] -- .pull-right[ - Typically, an ANN comprises three primary layers: the input layer, hidden layers, and output layer. - The input layer receives input data, which is then processed through the hidden layers before producing output through the output layer. - This network architecture allows ANNs to effectively learn and make predictions across various tasks, including regression and classification. ] --- # Key Components of an Artificial Neural Network (ANN) - ANN can be multilayer or single layer. - Components of an ANN - Inputs: `\(x_1, x_2,\ldots,x_p\)` - Weights (unknown parameters): `\(w_1,w_2,\ldots,w_p\)`, and `\(w_0\)` (intercept or bias) - Summation function: `\(\sum_{j=1}^{p} w_{j} x_{j}+w_{0}\)` - Activation function: `\(g(\cdot)\)` - A simple ANN (perceptron) can be written as: `$$y=g\left( \sum_{j=1}^{p} w_{j} x_{j}+w_{0} \right)$$` --- # 🔧 Key Components of a One-Hidden-Layer ANN Let the number of hidden units be `\(K\)`. The model has two layers: 1. **Hidden layer (nonlinear transformation of inputs)** For each hidden unit `\(k = 1, \ldots, K\)`: `$$A_k = h_k(X) = g\left(w_{k0} + \sum_{j=1}^{p} w_{kj} X_j \right)$$` where - `\(g(\cdot)\)`: activation function (e.g., ReLU, sigmoid) - `\(w_{kj}\)`: weights from input `\(j\)` to hidden unit `\(k\)` - `\(w_{k0}\)`: bias term for unit `\(k\)` --- # 🧾 Output Layer The output is a **linear function** of the hidden units: `$$f(X) = \beta_0 + \sum_{k=1}^{K} \beta_k A_k$$` - The activations `\(A_k\)` act like transformed features - Coefficients `\(\beta_0, \ldots, \beta_K\)` are estimated from the data along with weights `\(w_{kj}\)` - The network transforms the inputs using nonlinear activation functions, followed by a linear combination in the output layer. - Tuning parameters: --- # Activation function  *Figure: Examples of common activation functions* ([Source](https://en.wikipedia.org/wiki/Activation_function)) Two popular choices: **Sigmoid**: outputs values between 0 and 1, useful for probability-like outputs. **Rectified Linear Unit (ReLU)**: outputs zero for negative inputs and linear for positive --- # Sigmoid activation function .pull-left[  - Sigmoid activation function: `$$\sigma(v) = \frac{1}{1+e^{-v}}$$` ] -- .pull-right[ - The graph shows the plot of `\(\sigma(v)\)` - It also includes `\(\sigma(sv)\)` with two values: `\(s=0.5\)` (blue), and `\(s=10\)` (purple) (source: Elements of Statistical Learning, p.394) - `\(s\)` is known as the scale parameter. Larger `\(s\)` implies hard activation at `\(v=0\)`. - When `\(\sigma=1\)` we have an identity function and the model becomes linear. - ANN can be considered as a generalization of the linear regression and classification problems. ] --- # ReLU activation function .pull-left[  - Rectified Linear Unit (ReLU) activation function: `$$g(z)=(z)_{+}= \begin{cases}0 & \text { if } z<0\\z & \text { otherwise }\end{cases}$$` ] -- .pull-right[ - For negative values of `\(z\)`, activation function is 0. - Otherwise it equals `\(z\)`. - ReLU can be more efficiently stored than sigmoid function - Popular for faster training and mitigating vanishing gradients problem (this means gradients (first derivatives) don’t shrink too much during backpropagation, allowing effective learning in deep layers). - For more details, see ISLR2, p. 405. ] ??? The vanishing gradient problem occurs when gradients become very small as they are propagated backward through layers, making it hard for the network to learn weights in early layers. ReLU helps prevent this by having a gradient of 1 for positive inputs, keeping the learning signal strong. --- name: ex1 # Linear Regression as a Simple ANN `$$\hat{y} = -3.01408(-2.46247 - 0.76578x_1+1.49965x_2-1.29388x_3) + 2.17061$$` `$$\hat{y}\approx 9.593+2.308x_1-4.52x_2+3.90x_3$$` .pull-left[  ] -- .pull-right[ - 3 inputs, single layer with single neuron (cell), activation: `\(h(z)=z\)` (identity) - Notice that this a linear regression. OLS solution gives:  - An ANN can capture unknown interactions among inputs without explicitly specifying them. ] --- # Example .pull-left[  ] -- .pull-right[ - One input layer, One hidden layer with 3 neurons (cells), and one output layer - Intercepts ("bias" terms), shown in blue, act as adjustable constants added to neurons' inputs. - This ANN can learn complex interactions among inputs without explicitly specifying them. ] --- # MNIST handwritten-digit problem .pull-left[  Problem: classify handwritten digits into correct digits `\(0,1,\ldots,9\)` (image source: James et al. ISLR, 2nd ed., p.407) ] -- .pull-right[ - Handwritten digits are save as `\(28\times 28\)` grayscale images. - There are 60000 images in the training set, and 10000 images in the test set. - Features: 784 pixel grayscale values - Labels: digits `\(0,1,\ldots,9\)` - Human error rate: 0.2% (20 in 10K) - Machine error rates: best rates below 0.5% ] --- name: multi # Multilayer ANNs .pull-left[  - There are 2 hidden layers (shown here as `\(L_1\)` and `\(L_2\)`) and multiple outputs. (image source: James et al. ISLR, 2nd ed., p.409) ] -- .pull-right[ - This example is suitable for handwritten digit recognition (MNIST problem). - The input layer has 784 units, the two hidden layers `\(K_1=256\)`, and `\(K_2=128\)` units (cells), respectively. Output layer has 10 units (digits `\(0,1,\ldots,9\)`). - This ANN has 235146 parameters (weights) including intercepts (biases). ] --- name: training # Training ANNs - For regression problems, the objective function is the sum of squared residuals: `$$R(\theta)=\sum_{k=1}^{K} \sum_{i=1}^{N}\left(y_{i k}-f_{k}\left(x_{i}\right)\right)^{2}$$` - For classification problems, the objective function is either squared error or cross-entropy (deviance): `$$R(\theta)=-\sum_{i=1}^{N} \sum_{k=1}^{K} y_{i k} \log f_{k}\left(x_{i}\right)$$` `\(\theta\)`: unknown weights, `\(y_{i k}\)`: observed outcome, `\(f_{k}\)`: prediction for output `\(k\)`, `\(K\)` is the number of outputs, `\(N\)` is the number of observations. --- # Training ANNs - The minimum `\(R(\theta)\)` can be found by the gradient descent algorithm. - In this context, this algorithm is also known as the **backpropagation** algorithm. - Backpropagation enables the network to learn by computing how the prediction error changes with respect to each weight and updating these weights to reduce the error over many iterations. - The gradient (vector of first derivatives) is efficiently computed using the chain rule. - To avoid overfitting, the gradient is multiplied by a small positive parameter to control the learning rate. - For more technical details of training ANNs in practice, see pp. 395-397, Hastie, Tibshirani, Friedman (2017), Elements of Statistical Learning, 2nd ed. Springer. --- # Gradient Descent  (image source: James et al. ISLR, 2nd ed., p.435) --- name: cnn # Convolutional Neural Networks (CNNs) - CNNs can be particularly useful for classifying images. For example, CIFAR100 database contains `\(32\times 32\)` color images with 100 classes (labels). - The CNN builds up an image in a hierarchical fashion. - This hierarchical construction is achieved using convolution and pooling layers. - The filter is itself an image, and represents a small shape, edge etc. We slide it around the input image, scoring for matches. - If the subimage of the input image is similar to the filter, the score is high, otherwise low. - The filters are learned during training. (for an example and more details see James et al., ISLR, 2nd ed., p.414) --- name: rnn # Recurrent Neural Networks (RNNs)  - RNNs are particularly useful for sequential data, such as time series, recorded speech, music, or a sequence of words in a document. - RNNs build models that take into account this sequential nature of the data, and build a memory of the past. (image source: James et al. ISLR, 2nd ed., p.422) --- # Recurrent Neural Networks (RNNs) - In RNNs the feature set is a sequence of vectors `\(X=\{X_1,X_2,\ldots,X_L\}\)`. The output `\(Y\)` can be vector as well, for example the same document in a different language. - There is single target variable `\(Y\)` in this example. - RNN processes inputs `\(\{X_1,X_2,\ldots,X_L\}\)` sequentially. Each `\(X_l\)` feeds into the hidden layer with current activation vector `\(A_l\)`. - `\(A_l\)` receives `\(X_l\)` as well as `\(A_{l-1}\)` as input and produces an output `\(O_l\)`. - `\(W\)`, `\(U\)`, and `\(B\)` are the weights. - Recurrent = the same weights used at each step in the sequence. - For the mathematical details see the textbook pp. 423-4 --- # LSTM - Long Term and Short Term Memory (LSTM) is a variation on RNNs. - For economic and financial time series data, current value may depend on both current shocks and past shocks. - LSTM RNNs maintain activations from both current values (short term) and values from distance past (long term). Thus LSTM RNNs overcome the problem of early signals being washed out by the time they LSTM RNN get propagated through the chain to the final activation vector (ISLR2, p.426) - This can be particularly useful for forecasting in finance and economics where time series data can be highly persistent (autocorrelated). (see the NYSE example on p. 427) --- # NYSE example on p. 427 .pull-left[  (image source: James et al. ISLR, 2nd ed., p.427) ] .pull-right[ - This figure shows log trading volume, Dow Jones daily returns, and log volatility (absolute value of daily range) - Objective: predict log trading volume using daily returns and log volatility. - Data: time series with significant autocorrelation — past values are strongly related to current values - RNN approach: incorporate lagged values of variables as sequential inputs to model temporal dependencies - RNN advantage: captures complex patterns and nonlinear dynamics over time that traditional models may miss ] --- # Text/Document classification - Text data includes customer reviews, feedback, economic reports, news articles, and social media posts that can be useful sources of economic information. - Typically **unstructured**: represented as sequences or collections of words, lacking fixed numerical form. - Traditional Approach: **Bag-of-Words (BoW)** — convert text to word frequency vectors ignoring word order. - Limitations of BoW: loses context and word sequencing important for meaning. - Sentiment Analysis with BoW: - Assign sentiment scores to words (positive, negative, neutral). - Aggregate word scores to infer overall sentiment of a document or review. - Can be useful for measuring consumer confidence or market mood from text data. --- # Deep Learning for Text/Document Data - Deep learning uses word embeddings (Word2Vec, GloVe) to capture semantic meaning in dense vector form. - Methods such as RNNs, LSTMs, and Transformers (e.g., BERT) capture word order and context. - These methods significantly improve tasks like sentiment analysis, topic modeling, and document classification. - Applications in economics: - Analyzing financial news and reports for market sentiment. - Extracting features from textual data for forecasting economic indicators. - Detecting patterns in policy documents or social media related to economic trends. --- # Example: Using RNNs for Sentiment Analysis - Problem: Classify movie reviews as positive or negative based on the text. - Data: Each review is paired with a known sentiment label (positive or negative) — this is supervised learning. - Input: A sequence of words from the review (e.g., "The movie was fantastic and exciting"). - How RNN works: - Reads one word at a time, updating its “memory” of the context. - Captures how earlier words affect the meaning of later words (e.g., "not bad" vs "bad"). - Training: The model adjusts its internal parameters to minimize errors between its predictions and the known sentiment labels. - Output: A prediction of sentiment (positive or negative) once the whole review is processed. - Why better: Unlike simple Bag-of-Words, RNN understands word order and context, leading to more accurate sentiment classification. --- # Limitations of RNNs in Text Analysis - Struggle to remember information far back in the text: - They have difficulty using words or ideas from much earlier in a sentence or paragraph. - Process words one at a time: - This makes training slow because they cannot handle many words all at once (making parallel processing difficult). - Can only consider a limited amount of context: - Even advanced versions still have trouble fully understanding very long texts. - Need lots of labeled examples to learn well: - Getting enough quality data can be expensive or difficult. - Challenges with complex language - Difficulty understanding sarcasm, subtle meanings, or ambiguous sentences - **Why this matters:** These challenges inspired the development of **transformers**, which process many words at once, better handle long-range context, and serve as the foundation for today’s powerful **Large Language Models (LLMs)** that greatly improve language understanding and generation.