1. Trang chủ
  2. » Công Nghệ Thông Tin

Applied deep learning

425 112 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Cấu trúc

  • Table of Contents

  • About the Author

  • About the Technical Reviewer

  • Acknowledgments

  • Introduction

  • Chapter 1: Computational Graphs and TensorFlow

    • How to Set Up Your Python Environment

      • Creating an Environment

      • Installing TensorFlow

      • Jupyter Notebooks

    • Basic Introduction to TensorFlow

      • Computational Graphs

      • Tensors

      • Creating and Running a Computational Graph

      • Computational Graph with tf.constant

      • Computational Graph with tf.Variable

      • Computational Graph with tf.placeholder

      • Differences Between run and eval

      • Dependencies Between Nodes

      • Tips on How to Create and Close a Session

  • Chapter 2: Single Neuron

    • The Structure of a Neuron

      • Matrix Notation

      • Python Implementation Tip: Loops and NumPy

      • Activation Functions

        • Identity Function

        • Sigmoid Function

        • Tanh (Hyperbolic Tangent Activation) Function

        • ReLU (Rectified Linear Unit) Activation Function

        • Leaky ReLU

        • Swish Activation Function

        • Other Activation Functions

      • Cost Function and Gradient Descent: The Quirks of the Learning Rate

      • Learning Rate in a Practical Example

      • Example of Linear Regression in tensorflow

        • Dataset for Our Linear Regression Model

        • Neuron and Cost Function for Linear Regression

        • Satisficing and Optimizing a Metric

    • Example of Logistic Regression

      • Cost Function

      • Activation Function

      • The Dataset

      • tensorflow Implementation

    • References

  • Chapter 3: Feedforward Neural Networks

    • Network Architecture

      • Output of Neurons

      • Summary of Matrix Dimensions

      • Example: Equations for a Network with Three Layers

      • Hyperparameters in Fully Connected Networks

    • sof tmax Function for Multiclass Classification

    • A Brief Digression: Overfitting

      • A Practical Example of Overfitting

      • Basic Error Analysis

    • The Zalando Dataset

    • Building a Model with tensorflow

      • Network Architecture

      • Modifying Labels for the softmax Function—One-Hot Encoding

      • The tensor flow Model

    • Gradient Descent Variations

      • Batch Gradient Descent

      • Stochastic Gradient Descent

      • Mini-Batch Gradient Descent

      • Comparison of the Variations

    • Examples of Wrong Predictions

    • Weight Initialization

    • Adding Many Layers Efficiently

    • Advantages of Additional Hidden Layers

    • Comparing Different Networks

    • Tips for Choosing the Right Network

  • Chapter 4: Training Neural Networks

    • Dynamic Learning Rate Decay

      • Iterations or Epochs?

      • Staircase Decay

      • Step Decay

      • Inverse Time Decay

      • Exponential Decay

      • Natural Exponential Decay

      • tensorflow Implementation

      • Applying the Methods to the Zalando Dataset

    • Common Optimizers

      • Exponentially Weighted Averages

      • Momentum

      • RMSProp

      • Adam

      • Which Optimizer Should I Use?

    • Example of Self-Developed Optimizer

  • Chapter 5: Regularization

    • Complex Networks and Overfitting

    • What Is Regularization?

      • About Network Complexity

    • ℓp Norm

    • ℓ2 Regularization

      • Theory of ℓ2 Regularization

      • tensorflow Implementation

    • ℓ1 Regularization

      • Theory of ℓ1 Regularization and tensorflow Implementation

      • Are Weights Really Going to Zero?

    • Dropout

    • Early Stopping

    • Additional Methods

  • Chapter 6: Metric Analysis

    • Human-Level Performance and Bayes Error

    • A Short Story About Human-Level Performance

    • Human-Level Performance on MNIST

    • Bias

    • Metric Analysis Diagram

    • Training Set Overfitting

    • Test Set

    • How to Split Your Dataset

    • Unbalanced Class Distribution: What Can Happen

    • Precision, Recall, and F1 Metrics

    • Datasets with Different Distributions

    • K-Fold Cross-Validation

    • Manual Metric Analysis: An Example

  • Chapter 7: Hyperparameter Tuning

    • Black-Box Optimization

    • Notes on Black-Box Functions

    • The Problem of Hyperparameter Tuning

    • Sample Black-Box Problem

    • Grid Search

    • Random Search

    • Coarse-to-Fine Optimization

    • Bayesian Optimization

      • Nadaraya-Watson Regression

      • Gaussian Process

      • Stationary Process

      • Prediction with Gaussian Processes

      • Acquisition Function

      • Upper Confidence Bound (UCB)

      • Example

    • Sampling on a Logarithmic Scale

    • Hyperparameter Tuning with the Zalando Dataset

    • A Quick Note on the Radial Basis Function

  • Chapter 8: Convolutional and Recurrent Neural Networks

    • Kernels and Filters

    • Convolution

    • Examples of Convolution

    • Pooling

      • Padding

    • Building Blocks of a CNN

      • Convolutional Layers

      • Pooling Layers

      • Stacking Layers Together

      • Example of a CNN

    • Introduction to RNNs

      • Notation

      • Basic Idea of RNNs

      • Why the Name Recurrent?

      • Learning to Count

  • Chapter 9: A Research Project

    • The Problem Description

    • The Mathematical Model

    • Regression Problem

    • Dataset Preparation

    • Model Training

  • Chapter 10: Logistic Regression from Scratch

    • Mathematics Behind Logistic Regression

    • Python Implementation

    • Test of the Model

      • Dataset Preparation

      • Running the Test

    • Conclusion

  • Index

Nội dung

Applied Deep Learning A Case-Based Approach to Understanding Deep Neural Networks — Umberto Michelucci www.allitebooks.com Applied Deep Learning A Case-Based Approach to Understanding Deep Neural Networks Umberto Michelucci www.allitebooks.com Applied Deep Learning: A Case-Based Approach to Understanding Deep Neural Networks Umberto Michelucci toelt.ai, Dübendorf, Switzerland ISBN-13 (pbk): 978-1-4842-3789-2 https://doi.org/10.1007/978-1-4842-3790-8 ISBN-13 (electronic): 978-1-4842-3790-8 Library of Congress Control Number: 2018955206 Copyright © 2018 by Umberto Michelucci This work is subject to copyright All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed Trademarked names, logos, and images may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image, we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights While the advice and information in this book are believed to be true and accurate at the date of publication, neither the author nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made The publisher makes no warranty, express or implied, with respect to the material contained herein Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Celestin Suresh John Development Editor: Matthew Moodie Coordinating Editor: Aditee Mirashi Cover designed by eStudioCalamar Cover image designed by Freepik (www.freepik.com) Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders ny@springersbm.com, or visit www.springeronline.com Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science+Business Media Finance Inc (SSBM Finance Inc) SSBM Finance Inc is a Delaware corporation For information on translations, please e-mail rights@apress.com, or visit www.apress.com/ rights-permissions Apress titles may be purchased in bulk for academic, corporate, or promotional use eBook versions and licenses are also available for most titles For more information, reference our Print and eBook Bulk Sales web page at www.apress.com/bulk-sales Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the book’s product page, located at www.apress.com/9781484237892 For more detailed information, please visit www.apress.com/source-code Printed on acid-free paper www.allitebooks.com I dedicate this book to my daughter, Caterina, and my wife, Francesca Thank you for the inspiration, the motivation, and the happiness you bring to my life every day Without you, this would not have been possible www.allitebooks.com Table of Contents About the Author����������������������������������������������������������������������������������������������������� xi About the Technical Reviewer������������������������������������������������������������������������������� xiii Acknowledgments���������������������������������������������������������������������������������������������������xv Introduction�����������������������������������������������������������������������������������������������������������xvii Chapter 1: Computational Graphs and TensorFlow��������������������������������������������������� How to Set Up Your Python Environment�������������������������������������������������������������������������������������� Creating an Environment��������������������������������������������������������������������������������������������������������� Installing TensorFlow��������������������������������������������������������������������������������������������������������������� Jupyter Notebooks���������������������������������������������������������������������������������������������������������������� 11 Basic Introduction to TensorFlow������������������������������������������������������������������������������������������������ 14 Computational Graphs����������������������������������������������������������������������������������������������������������� 14 Tensors���������������������������������������������������������������������������������������������������������������������������������� 17 Creating and Running a Computational Graph���������������������������������������������������������������������� 19 Computational Graph with tf.constant����������������������������������������������������������������������������������� 19 Computational Graph with tf.Variable������������������������������������������������������������������������������������ 20 Computational Graph with tf.placeholder������������������������������������������������������������������������������ 22 Differences Between run and eval���������������������������������������������������������������������������������������� 25 Dependencies Between Nodes���������������������������������������������������������������������������������������������� 26 Tips on How to Create and Close a Session�������������������������������������������������������������������������� 27 Chapter 2: Single Neuron���������������������������������������������������������������������������������������� 31 The Structure of a Neuron����������������������������������������������������������������������������������������������������������� 31 Matrix Notation���������������������������������������������������������������������������������������������������������������������� 35 Python Implementation Tip: Loops and NumPy��������������������������������������������������������������������� 36 Activation Functions�������������������������������������������������������������������������������������������������������������� 38 v www.allitebooks.com Table of Contents Cost Function and Gradient Descent: The Quirks of the Learning Rate��������������������������������� 47 Learning Rate in a Practical Example������������������������������������������������������������������������������������ 50 Example of Linear Regression in tensorflow������������������������������������������������������������������������� 57 Example of Logistic Regression�������������������������������������������������������������������������������������������������� 70 Cost Function������������������������������������������������������������������������������������������������������������������������� 70 Activation Function���������������������������������������������������������������������������������������������������������������� 71 The Dataset��������������������������������������������������������������������������������������������������������������������������� 71 tensorflow Implementation��������������������������������������������������������������������������������������������������� 75 References���������������������������������������������������������������������������������������������������������������������������������� 80 Chapter 3: Feedforward Neural Networks�������������������������������������������������������������� 83 Network Architecture������������������������������������������������������������������������������������������������������������������ 84 Output of Neurons����������������������������������������������������������������������������������������������������������������� 87 Summary of Matrix Dimensions�������������������������������������������������������������������������������������������� 88 Example: Equations for a Network with Three Layers����������������������������������������������������������� 88 Hyperparameters in Fully Connected Networks�������������������������������������������������������������������� 90 softmax Function for Multiclass Classification��������������������������������������������������������������������������� 90 A Brief Digression: Overfitting����������������������������������������������������������������������������������������������������� 91 A Practical Example of Overfitting����������������������������������������������������������������������������������������� 92 Basic Error Analysis��������������������������������������������������������������������������������������������������������������� 99 The Zalando Dataset����������������������������������������������������������������������������������������������������������������� 100 Building a Model with tensorflow��������������������������������������������������������������������������������������������� 105 Network Architecture����������������������������������������������������������������������������������������������������������� 106 Modifying Labels for the softmax Function—One-Hot Encoding���������������������������������������� 108 The tensorflow Model���������������������������������������������������������������������������������������������������������� 110 Gradient Descent Variations������������������������������������������������������������������������������������������������������ 114 Batch Gradient Descent������������������������������������������������������������������������������������������������������� 114 Stochastic Gradient Descent����������������������������������������������������������������������������������������������� 116 Mini-Batch Gradient Descent���������������������������������������������������������������������������������������������� 117 Comparison of the Variations����������������������������������������������������������������������������������������������� 119 Examples of Wrong Predictions������������������������������������������������������������������������������������������������ 123 Weight Initialization������������������������������������������������������������������������������������������������������������������� 125 vi Table of Contents Adding Many Layers Efficiently������������������������������������������������������������������������������������������������� 127 Advantages of Additional Hidden Layers����������������������������������������������������������������������������������� 130 Comparing Different Networks������������������������������������������������������������������������������������������������� 131 Tips for Choosing the Right Network���������������������������������������������������������������������������������������� 135 Chapter 4: Training Neural Networks������������������������������������������������������������������� 137 Dynamic Learning Rate Decay�������������������������������������������������������������������������������������������������� 137 Iterations or Epochs?����������������������������������������������������������������������������������������������������������� 139 Staircase Decay������������������������������������������������������������������������������������������������������������������� 140 Step Decay�������������������������������������������������������������������������������������������������������������������������� 142 Inverse Time Decay������������������������������������������������������������������������������������������������������������� 145 Exponential Decay��������������������������������������������������������������������������������������������������������������� 148 Natural Exponential Decay�������������������������������������������������������������������������������������������������� 150 tensorflow Implementation������������������������������������������������������������������������������������������������� 158 Applying the Methods to the Zalando Dataset��������������������������������������������������������������������� 162 Common Optimizers������������������������������������������������������������������������������������������������������������������ 163 Exponentially Weighted Averages���������������������������������������������������������������������������������������� 163 Momentum�������������������������������������������������������������������������������������������������������������������������� 167 RMSProp������������������������������������������������������������������������������������������������������������������������������ 172 Adam����������������������������������������������������������������������������������������������������������������������������������� 175 Which Optimizer Should I Use?������������������������������������������������������������������������������������������� 177 Example of Self-Developed Optimizer�������������������������������������������������������������������������������������� 179 Chapter 5: Regularization������������������������������������������������������������������������������������� 185 Complex Networks and Overfitting������������������������������������������������������������������������������������������� 185 What Is Regularization?������������������������������������������������������������������������������������������������������������ 190 About Network Complexity�������������������������������������������������������������������������������������������������� 191 ℓp Norm������������������������������������������������������������������������������������������������������������������������������������� 192 ℓ2 Regularization����������������������������������������������������������������������������������������������������������������������� 192 Theory of ℓ2 Regularization������������������������������������������������������������������������������������������������������� 192 tensorflow Implementation������������������������������������������������������������������������������������������������� 194 ℓ1 Regularization����������������������������������������������������������������������������������������������������������������������� 205 vii Table of Contents Theory of ℓ1 Regularization and tensorflow Implementation���������������������������������������������������� 206 Are Weights Really Going to Zero?�������������������������������������������������������������������������������������� 208 Dropout������������������������������������������������������������������������������������������������������������������������������������� 211 Early Stopping��������������������������������������������������������������������������������������������������������������������������� 215 Additional Methods������������������������������������������������������������������������������������������������������������������� 216 Chapter 6: Metric Analysis����������������������������������������������������������������������������������� 217 Human-Level Performance and Bayes Error����������������������������������������������������������������������������� 218 A Short Story About Human-Level Performance����������������������������������������������������������������������� 221 Human-Level Performance on MNIST��������������������������������������������������������������������������������������� 223 Bias������������������������������������������������������������������������������������������������������������������������������������������� 223 Metric Analysis Diagram����������������������������������������������������������������������������������������������������������� 225 Training Set Overfitting������������������������������������������������������������������������������������������������������������� 225 Test Set������������������������������������������������������������������������������������������������������������������������������������� 228 How to Split Your Dataset���������������������������������������������������������������������������������������������������������� 230 Unbalanced Class Distribution: What Can Happen�������������������������������������������������������������������� 234 Precision, Recall, and F1 Metrics���������������������������������������������������������������������������������������������� 239 Datasets with Different Distributions���������������������������������������������������������������������������������������� 245 K-Fold Cross-Validation������������������������������������������������������������������������������������������������������������ 253 Manual Metric Analysis: An Example���������������������������������������������������������������������������������������� 263 Chapter 7: Hyperparameter Tuning����������������������������������������������������������������������� 271 Black-Box Optimization������������������������������������������������������������������������������������������������������������� 271 Notes on Black-Box Functions�������������������������������������������������������������������������������������������������� 273 The Problem of Hyperparameter Tuning����������������������������������������������������������������������������������� 274 Sample Black-Box Problem������������������������������������������������������������������������������������������������������ 275 Grid Search������������������������������������������������������������������������������������������������������������������������������� 277 Random Search������������������������������������������������������������������������������������������������������������������������� 282 Coarse-to-Fine Optimization����������������������������������������������������������������������������������������������������� 285 Bayesian Optimization�������������������������������������������������������������������������������������������������������������� 289 Nadaraya-Watson Regression��������������������������������������������������������������������������������������������� 290 Gaussian Process���������������������������������������������������������������������������������������������������������������� 291 viii Table of Contents Stationary Process�������������������������������������������������������������������������������������������������������������� 292 Prediction with Gaussian Processes����������������������������������������������������������������������������������� 292 Acquisition Function������������������������������������������������������������������������������������������������������������ 298 Upper Confidence Bound (UCB)������������������������������������������������������������������������������������������� 299 Example������������������������������������������������������������������������������������������������������������������������������� 300 Sampling on a Logarithmic Scale��������������������������������������������������������������������������������������������� 310 Hyperparameter Tuning with the Zalando Dataset�������������������������������������������������������������������� 312 A Quick Note on the Radial Basis Function������������������������������������������������������������������������������� 321 Chapter 8: Convolutional and Recurrent Neural Networks����������������������������������� 323 Kernels and Filters�������������������������������������������������������������������������������������������������������������������� 323 Convolution������������������������������������������������������������������������������������������������������������������������������� 325 Examples of Convolution����������������������������������������������������������������������������������������������������������� 334 Pooling�������������������������������������������������������������������������������������������������������������������������������������� 342 Padding������������������������������������������������������������������������������������������������������������������������������� 345 Building Blocks of a CNN���������������������������������������������������������������������������������������������������������� 346 Convolutional Layers����������������������������������������������������������������������������������������������������������� 347 Pooling Layers��������������������������������������������������������������������������������������������������������������������� 349 Stacking Layers Together���������������������������������������������������������������������������������������������������� 349 Example of a CNN���������������������������������������������������������������������������������������������������������������� 350 Introduction to RNNs����������������������������������������������������������������������������������������������������������������� 355 Notation������������������������������������������������������������������������������������������������������������������������������� 357 Basic Idea of RNNs�������������������������������������������������������������������������������������������������������������� 358 Why the Name Recurrent ?�������������������������������������������������������������������������������������������������� 359 Learning to Count���������������������������������������������������������������������������������������������������������������� 359 Chapter 9: A Research Project������������������������������������������������������������������������������ 365 The Problem Description����������������������������������������������������������������������������������������������������������� 365 The Mathematical Model���������������������������������������������������������������������������������������������������������� 369 Regression Problem������������������������������������������������������������������������������������������������������������������ 369 Dataset Preparation������������������������������������������������������������������������������������������������������������������ 375 Model Training��������������������������������������������������������������������������������������������������������������������������� 384 ix Table of Contents Chapter 10: Logistic Regression from Scratch����������������������������������������������������� 391 Mathematics Behind Logistic Regression��������������������������������������������������������������������������������� 392 Python Implementation������������������������������������������������������������������������������������������������������������� 395 Test of the Model���������������������������������������������������������������������������������������������������������������������� 398 Dataset Preparation������������������������������������������������������������������������������������������������������������� 398 Running the Test������������������������������������������������������������������������������������������������������������������ 400 Conclusion�������������������������������������������������������������������������������������������������������������������������������� 401 Index��������������������������������������������������������������������������������������������������������������������� 403 x Chapter 10 Logistic Regression from Scratch These equations can be written in matrix form (where ∇w indicates the gradient with respect to w) as Ñw J ( w , b ) = X Yˆ - Y m ( ) ( ) T and for b, ¶J ( w, b ) ¶b = m ˆ å Yi - Yi m i =1 Finally, the equation we need to implement for the gradient descent algorithm is w[n +1] = w[n ] - g X Yˆ - Y m ( ) b[n +1] = b[n ] - g m ˆ å Yi - Yi m i =1 ( ) T and for b, At this point, you should already have gained a completely new appreciation of TensorFlow The library does all this for you in the background, and, more important, all automatically Remember: We are dealing here with just one neuron You can easily see how complicated it can get when you want to calculate the same equations for networks with many layers and neurons, or for something as a convolutional or recurrent neural network We now have all the mathematics we need to implement logistic regression completely from scratch Let’s move on to some Python Python Implementation Let’s start importing the necessary libraries import numpy as np %matplotlib inline import matplotlib.pyplot as plt Note that we don’t import TensorFlow We will not need it here Let’s write a function for the sigmoid activation function sigmoid(z) 395 Chapter 10 Logistic Regression from Scratch def sigmoid(z):     s = 1.0 / (1.0 + np.exp(-z))     return s We will also require a function to initialize the weights In this basic case, we can simply initialize everything with zeros Logistic regression will work anyway def initialize(dim):     w = np.zeros((dim,1))     b =     return w,b Then we must implement the following equations, which we have calculated in the previous section: Ñw J ( w , b ) = X Yˆ - Y m ( ) ( ) T and ¶J ( w, b ) ¶b = m ˆ å Yi - Yi m i =1 def derivatives_calculation(w, b, X, Y):     m = X.shape[1]     z = np.dot(w.T,X)+b     y_ = sigmoid(z)     cost = -1.0/m*np.sum(Y*np.log(y_)+(1.0-Y)*np.log(1.0-y_))     dw = 1.0/m*np.dot(X, (y_-Y).T)     db = 1.0/m*np.sum(y_-Y)     derivatives = {"dw": dw, "db":db}     return derivatives, cost Now we need the function that will update the weights def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):     costs = [] for i in range(num_iterations):         derivatives, cost = derivatives_calculation(w, b, X, Y) 396 Chapter 10 Logistic Regression from Scratch         dw = derivatives ["dw"]         db = derivatives ["db"]         w = w - learning_rate*dw         b = b - learning_rate*db         if i % 100 == 0:             costs.append(cost)         if print_cost and i % 100 == 0:             print ("Cost (iteration %i) = %f" %(i, cost))     derivatives = {"dw": dw, "db": db}     params = {"w": w, "b": b}     return params, derivatives, costs The next function, predict(), creates a matrix of dimensions (1, m) that contains the predictions of the model given the inputs w and b def predict (w, b, X):     m = X.shape[1]     Y_prediction = np.zeros((1,m))     w = w.reshape(X.shape[0],1)     A = sigmoid (np.dot(w.T, X)+b)     for i in range(A.shape[1]):         if (A[:,i] > 0.5):             Y_prediction[:, i] =         elif (A[:,i]

Ngày đăng: 12/04/2019, 00:24