100% found this document useful (2 votes)
46 views

Download Complete (Ebook) Deep Learning with JavaScript: Neural networks in TensorFlow.js by Shanqing Cai, Stan Bileschi, Eric Nielsen ISBN 9781617296178, 1617296171 PDF for All Chapters

The document provides information about various eBooks available for download, including titles related to deep learning, mathematics, and history. It highlights the eBook 'Deep Learning with JavaScript: Neural Networks in TensorFlow.js' and includes links for purchasing and downloading multiple eBooks. Additionally, it outlines the content structure of the deep learning book, covering topics such as model building, data handling, and advanced deep learning techniques.

Uploaded by

juranhaffad9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
46 views

Download Complete (Ebook) Deep Learning with JavaScript: Neural networks in TensorFlow.js by Shanqing Cai, Stan Bileschi, Eric Nielsen ISBN 9781617296178, 1617296171 PDF for All Chapters

The document provides information about various eBooks available for download, including titles related to deep learning, mathematics, and history. It highlights the eBook 'Deep Learning with JavaScript: Neural Networks in TensorFlow.js' and includes links for purchasing and downloading multiple eBooks. Additionally, it outlines the content structure of the deep learning book, covering topics such as model building, data handling, and advanced deep learning techniques.

Uploaded by

juranhaffad9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Download the Full Ebook and Access More Features - ebooknice.

com

(Ebook) Deep Learning with JavaScript: Neural


networks in TensorFlow.js by Shanqing Cai, Stan
Bileschi, Eric Nielsen ISBN 9781617296178,
1617296171
https://ebooknice.com/product/deep-learning-with-javascript-
neural-networks-in-tensorflow-js-10792450

OR CLICK HERE

DOWLOAD EBOOK

Download more ebook instantly today at https://ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Deep Learning with JavaScript: Neural networks in TensorFlow.js by Shanqing


Cai; Stanley Bileschi; Eric D. Nielsen ISBN 9781617296178, 1617296171

https://ebooknice.com/product/deep-learning-with-javascript-neural-networks-in-
tensorflow-js-27166480

ebooknice.com

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason; Viles, James ISBN
9781459699816, 9781743365571, 9781925268492, 1459699815, 1743365578, 1925268497

https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena Alfredsson, Hans Heikne, Sanna
Bodemyr ISBN 9789127456600, 9127456609

https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com

(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT II Success) by Peterson's
ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-math-1c-and-2c-2002-peterson-s-sat-
ii-success-1722018

ebooknice.com
(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master the SAT Subject Test: Math
Levels 1 & 2) by Arco ISBN 9780768923049, 0768923042

https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-arco-master-
the-sat-subject-test-math-levels-1-2-2326094

ebooknice.com

(Ebook) Deep Learning with Keras: Implementing Deep Learning Models and Neural
Networks with the power of Python by Antonio Gulli, Sujit Pal ISBN 9781787128422,
1787128423

https://ebooknice.com/product/deep-learning-with-keras-implementing-deep-
learning-models-and-neural-networks-with-the-power-of-python-7360028

ebooknice.com

(Ebook) Cambridge IGCSE and O Level History Workbook 2C - Depth Study: the United
States, 1919-41 2nd Edition by Benjamin Harrison ISBN 9781398375147, 9781398375048,
1398375144, 1398375047

https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044

ebooknice.com

(Ebook) MATLAB Deep Learning: With Machine Learning, Neural Networks and Artificial
Intelligence by Phil Kim ISBN 9781484228449, 9781484228456, 1484228448, 1484228456

https://ebooknice.com/product/matlab-deep-learning-with-machine-learning-neural-
networks-and-artificial-intelligence-5880894

ebooknice.com

(Ebook) Learning TensorFlow.js: Powerful Machine Learning in JavaScript by Gant


Laborde ISBN 9781492090793, 1492090794

https://ebooknice.com/product/learning-tensorflow-js-powerful-machine-learning-
in-javascript-50785622

ebooknice.com
Neural networks in TensorFlow.js

Shanqing Cai
Stanley Bileschi
Eric D. Nielsen
François Chollet
Foreword by
Nikhil Thorat and Daniel Smilkov

MANNING
Working with data

Ingest data Clean data Augment data


Data Sect. 6.1, 6.2, 6.3 Sect. 6.4 Sect. 6.5

Visualize data
Sect. 7.1

Model building 1: Choosing key layer types based on your data

Input data type Recommended layer API Reference

Numerical data Dense Chapters 2 and 3


(without sequential order)

Images or data that can be represented 2D convolution and pooling Chapters 4 and 5
as images (e.g., audio, game board)

Sequential data, including text • RNN (LSTM, GRU) • Sect. 9.1.2


• Embedding • Sect. 9.2.3
• 1D convolution • Sect. 9.2.4
• Attentional • Sect. 9.3

Model building 2: Choosing last-layer activation, loss, and metric functions

Task type Last-layer


(What are you predicting?) activation Loss function Metric(s) Reference

Regression Linear meanSquaredError (Same as loss) Chapter 2


(predicting a real number) meanAbsoluteError Sect. 9.1

Binary classification Sigmoid binaryCrossentropy Accuracy, precision, Sect. 3.1, 3.2, 9.2
(making a binary decision) recall, sensitivity, TPR,
FPR, ROC, AUC
Multi-class classification Softmax categoricalCrossentropy Accuracy, confusion Sect. 3.3, 9.3
(deciding among multiple matrix
classes)
A mix of the above (for example, (Multiple) Custom loss function (multiple) Sect. 5.2
numbers plus classes)

Advanced and miscellaneous task types Reference

Transfer learning Chapter 5


(applying a pretrained model to new data)

Generative learning Chapter 10


(generating new examples based on training data)

Reinforcement learning Chapter 11


(training an agent to interact with the environment)

Continues inside back cover


Deep Learning with JavaScript
Deep Learning
with JavaScript
NEURAL NETWORKS IN TENSORFLOW.JS

SHANQING CAI
STANLEY BILESCHI
ERIC D. NIELSEN
WITH FRANÇOIS CHOLLET

FOREWORD BY NIKHIL THORAT


DANIEL SMILKOV

MANNING
SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: orders@manning.com

© 2020 by Manning Publications Co. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in


any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.

Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.

Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books
are printed on paper that is at least 15 percent recycled and processed without the use of
elemental chlorine.

Manning Publications Co. Development editor: Jenny Stout


20 Baldwin Road Technical development editor: Marc-Phillipe Huget
PO Box 761 Review editor: Ivan Martinovič
Shelter Island, NY 11964 Project editor: Lori Weidert
Copy editor: Rebecca Deuel-Gallegos
Proofreader: Jason Everett
Technical proofreader: Karsten Strøbæck
Typesetter: Dottie Marsico
Cover designer: Marija Tudor

ISBN 9781617296178
Printed in the United States of America
brief contents
PART 1 MOTIVATION AND BASIC CONCEPTS . .................................1
1 ■ Deep learning and JavaScript 3

PART 2 A GENTLE INTRODUCTION TO TENSORFLOW.JS . ............. 35


2 ■ Getting started: Simple linear regression in TensorFlow.js 37
3 ■ Adding nonlinearity: Beyond weighted sums 79
4 ■ Recognizing images and sounds using convnets 117
5 ■ Transfer learning: Reusing pretrained neural networks 152

PART 3 ADVANCED DEEP LEARNING WITH TENSORFLOW.JS. ....... 199


6 ■ Working with data 201
7 ■ Visualizing data and models 246
8 ■ Underfitting, overfitting, and the universal workflow
of machine learning 273
9 ■ Deep learning for sequences and text 292
10 ■ Generative deep learning 334
11 ■ Basics of deep reinforcement learning 371

PART 4 SUMMARY AND CLOSING WORDS . .................................. 415


12 ■ Testing, optimizing, and deploying models 417
13 ■ Summary, conclusions, and beyond 453

v
contents
foreword xiii
preface xv
acknowledgments xvii
about this book xix
about the authors xxii
about the cover illustration xxiii

PART 1 MOTIVATION AND BASIC CONCEPTS ....................1

1 Deep learning and JavaScript


1.1
3
Artificial intelligence, machine learning, neural networks,
and deep learning 6
Artificial intelligence 6 Machine learning: How it differs from

traditional programming 7 Neural networks and deep


learning 12 Why deep learning? Why now? 16


1.2 Why combine JavaScript and machine learning? 18


Deep learning with Node.js 24 ■
The JavaScript ecosystem 25
1.3 Why TensorFlow.js? 27
A brief history of TensorFlow, Keras, and TensorFlow.js 27 Why ■

TensorFlow.js: A brief comparison with similar libraries 31 How ■

is TensorFlow.js being used by the world? 31 What this book will


and will not teach you about TensorFlow.js 32

vii
viii CONTENTS

PART 2 A GENTLE INTRODUCTION TO


TENSORFLOW.JS ..............................................35

2 Getting started: Simple linear regression in TensorFlow.js


2.1 Example 1: Predicting the duration of a download using
37

TensorFlow.js 38
Project overview: Duration prediction 38 A note on code listings

and console interactions 39 Creating and formatting the


data 40 Defining a simple model 43 Fitting the model


■ ■

to the training data 46 Using our trained model to make


predictions 48 Summary of our first example 49


2.2 Inside Model.fit(): Dissecting gradient descent


from example 1 50
The intuitions behind gradient-descent optimization 50
Backpropagation: Inside gradient descent 56
2.3 Linear regression with multiple input features 59
The Boston Housing Prices dataset 60 Getting and running the

Boston-housing project from GitHub 61 Accessing the Boston-


housing data 63 Precisely defining the Boston-housing


problem 65 A slight diversion into data normalization 66


Linear regression on the Boston-housing data 70


2.4 How to interpret your model 74
Extracting meaning from learned weights 74 Extracting internal ■

weights from the model 75 Caveats on interpretability 77


3 Adding nonlinearity: Beyond weighted sums


3.1 Nonlinearity: What it is and what it is good for 80
79

Building the intuition for nonlinearity in neural networks 82


Hyperparameters and hyperparameter optimization 89
3.2 Nonlinearity at output: Models for classification 92
What is binary classification? 92 Measuring the quality of

binary classifiers: Precision, recall, accuracy, and ROC curves 96


The ROC curve: Showing trade-offs in binary classification 99
Binary cross entropy: The loss function for binary classification 103
3.3 Multiclass classification 106
One-hot encoding of categorical data 107 Softmax ■

activation 109 Categorical cross entropy: The loss function


for multiclass classification 111 Confusion matrix: Fine-grained


analysis of multiclass classification 113


Visit https://ebooknice.com to
discover a wide range of
eBooks across various genres.
Enjoy exclusive deals and
discounts to enhance your
reading experience. Start your
digital reading journey today!
CONTENTS ix

4 Recognizing images and sounds using convnets 117


4.1 From vectors to tensors: Representing images 118
The MNIST dataset 119
4.2 Your first convnet 120
conv2d layer 122 maxPooling2d layer 126 Repeating
■ ■

motifs of convolution and pooling 127 Flatten and dense


layers 128 Training the convnet 130 Using a convnet to


■ ■

make predictions 134


4.3 Beyond browsers: Training models faster using
Node.js 137
Dependencies and imports for using tfjs-node 137 Saving the

model from Node.js and loading it in the browser 142


4.4 Spoken-word recognition: Applying convnets on
audio data 144
Spectrograms: Representing sounds as images 145

5 Transfer learning: Reusing pretrained neural networks 152


5.1 Introduction to transfer learning: Reusing pretrained
models 153
Transfer learning based on compatible output shapes: Freezing
layers 155 Transfer learning on incompatible output shapes:

Creating a new model using outputs from the base model 161
Getting the most out of transfer learning through fine-tuning: An
audio example 174
5.2 Object detection through transfer learning on a
convnet 185
A simple object-detection problem based on synthesized scenes 186
Deep dive into simple object detection 187

PART 3 ADVANCED DEEP LEARNING WITH


TENSORFLOW.JS . ...........................................199

6 Working with data 201


6.1 Using tf.data to manage data 202
The tf.data.Dataset object 203 Creating a tf.data.Dataset 203

Accessing the data in your dataset 209 Manipulating tfjs-data


datasets 210
6.2 Training models with model.fitDataset 214
x CONTENTS

6.3 Common patterns for accessing data 220


Working with CSV format data 220 Accessing video data using

tf.data.webcam() 225 Accessing audio data using


tf.data.microphone() 228
6.4 Your data is likely flawed: Dealing with problems
in your data 230
Theory of data 231 ■
Detecting and cleaning problems with
data 235
6.5 Data augmentation 242

7 Visualizing data and models 246


7.1 Data visualization 247
Visualizing data using tfjs-vis 247 ■
An integrative case study:
Visualizing weather data with tfjs-vis 255
7.2 Visualizing models after training 260
Visualizing the internal activations of a convnet 262
Visualizing what convolutional layers are sensitive to: Maximally
activating images 265 Visual interpretation of a convnet’s

classification result 269

8 Underfitting, overfitting, and the universal workflow


of machine learning 273
8.1 Formulation of the temperature-prediction problem 274
8.2 Underfitting, overfitting, and countermeasures 278
Underfitting 278 Overfitting 280 Reducing overfitting
■ ■

with weight regularization and visualizing it working 282


8.3 The universal workflow of machine learning 287

9 Deep learning for sequences and text 292


9.1 Second attempt at weather prediction:
Introducing RNNs 294
Why dense layers fail to model sequential order 294 ■
How RNNs
model sequential order 296
9.2 Building deep-learning models for text 305
How text is represented in machine learning: One-hot and multi-hot
encoding 306 First attempt at the sentiment-analysis

problem 308 A more efficient representation of text: Word


embeddings 310 1D convnets 312



CONTENTS xi

9.3 Sequence-to-sequence tasks with attention


mechanism 321
Formulation of the sequence-to-sequence task 321 The encoder-

decoder architecture and the attention mechanism 324 Deep dive ■

into the attention-based encoder-decoder model 327

10 Generative deep learning 334


10.1 Generating text with LSTM 335
Next-character predictor: A simple way to generate text 335
The LSTM-text-generation example 337 Temperature:■

Adjustable randomness in the generated text 342


10.2 Variational autoencoders: Finding an efficient and
structured vector representation of images 345
Classical autoencoder and VAE: Basic ideas 345 A detailed ■

example of VAE: The Fashion-MNIST example 349


10.3 Image generation with GANs 356
The basic idea behind GANs 357 The building blocks of

ACGAN 360 Diving deeper into the training of ACGAN 363


Seeing the MNIST ACGAN training and generation 366

11 Basics of deep reinforcement learning 371


11.1 The formulation of reinforcement-learning
problems 373
11.2 Policy networks and policy gradients: The cart-pole
example 376
Cart-pole as a reinforcement-learning problem 376 Policy ■

network 378 Training the policy network: The REINFORCE


algorithm 381
11.3 Value networks and Q-learning: The snake game
example 389
Snake as a reinforcement-learning problem 389 Markov decision

process and Q-values 392 Deep Q-network 396 Training


■ ■

the deep Q-network 399

PART 4 SUMMARY AND CLOSING WORDS .....................415

12 Testing, optimizing, and deploying models


12.1 Testing TensorFlow.js models 418
417

Traditional unit testing 419 Testing with golden values



422
Considerations around continuous training 424
xii CONTENTS

12.2 Model optimization 425


Model-size optimization through post-training weight
quantization 426 Inference-speed optimization using

GraphModel conversion 434


12.3 Deploying TensorFlow.js models on various platforms
and environments 439
Additional considerations when deploying to the web 439
Deployment to cloud serving 440 Deploying to a browser

extension, like Chrome Extension 441 Deploying TensorFlow.js


models in JavaScript-based mobile applications 443 Deploying


TensorFlow.js models in JavaScript-based cross-platform desktop


applications 445 Deploying TensorFlow.js models on WeChat

and other JavaScript-based mobile app plugin systems 447


Deploying TensorFlow.js models on single-board computers 448
Summary of deployments 450

13 Summary, conclusions, and beyond 453


13.1 Key concepts in review 454
Various approaches to AI 454 What makes deep learning stand

out among the subfields of machine learning 455 How to think


about deep learning at a high level 455 Key enabling


technologies of deep learning 456 Applications and


opportunities unlocked by deep learning in JavaScript 457


13.2 Quick overview of the deep-learning workflow
and algorithms in TensorFlow.js 458
The universal workflow of supervised deep learning 458
Reviewing model and layer types in TensorFlow.js: A quick
reference 460 Using pretrained models from TensorFlow.js

465
The space of possibilities 468 Limitations of deep learning

470
13.3 Trends in deep learning 473
13.4 Pointers for further exploration 474
Practice real-world machine-learning problems on Kaggle 474
Read about the latest developments on arXiv 475 Explore the

TensorFlow.js Ecosystem 475

appendix A Installing tfjs-node-gpu and its dependencies 477


appendix B A quick tutorial of tensors and operations in TensorFlow.js 482
glossary 507
index 519
foreword
When we started TensorFlow.js (TF.js), formerly called deeplearn.js, machine learning
(ML) was done mostly in Python. As both JavaScript developers and ML practitioners
on the Google Brain team, we quickly realized that there was an opportunity to bridge
the two worlds. Today, TF.js has empowered a new set of developers from the extensive
JavaScript community to build and deploy ML models and enabled new classes of on-
device computation.
TF.js would not exist in its form today without Shanqing, Stan, and Eric. Their con-
tributions to TensorFlow Python, including the TensorFlow Debugger, eager execu-
tion, and build and test infrastructure, uniquely positioned them to tie the Python
and JavaScript worlds together. Early on in the development, their team realized the
need for a library on top of deeplearn.js that would provide high-level building blocks
to develop ML models. Shanqing, Stan, and Eric, among others, built TF.js Layers,
allowing conversion of Keras models to JavaScript, which dramatically increased the
wealth of available models in the TF.js ecosystem. When TF.js Layers was ready, we
released TF.js to the world.
To investigate the motivations, hurdles, and desires of software developers, Carrie
Cai and Philip Guo deployed a survey to the TF.js website. This book is in direct
response to the study’s summary: “Our analysis found that developers’ desires for ML
frameworks extended beyond simply wanting help with APIs: more fundamentally,
they desired guidance on understanding and applying the conceptual underpinnings
of ML itself.”1
Deep Learning with JavaScript contains a mix of deep learning theory as well as real-
world examples in JavaScript with TF.js. It is a great resource for JavaScript developers

1
C. Cai and P. Guo, (2019) “Software Developers Learning Machine Learning: Motivations, Hurdles, and
Desires,” IEEE Symposium on Visual Languages and Human-Centric Computing, 2019.

xiii
xiv FOREWORD

with no ML experience or formal math background, as well as ML practitioners who


would like to extend their work into the JavaScript ecosystem. This book follows the
template of Deep Learning with Python, one of the most popular applied-ML texts, writ-
ten by the Keras creator, François Chollet. Expanding on Chollet’s work, Deep Learning
with JavaScript does an amazing job building on the unique things that JavaScript has
to offer: interactivity, portability, and on-device computation. It covers core ML con-
cepts, but does not shy away from state-of-the-art ML topics, such as text translation,
generative models, and reinforcement learning. It even gives pragmatic advice on
deploying ML models into real-world applications written by practitioners who have
extensive experience deploying ML to the real world. The examples in this book are
backed by interactive demos that demonstrate the unique advantages of the JavaScript
ecosystem. All the code is open-sourced, so you can interact with it and fork it online.
This book should serve as the authoritative source for readers who want to learn
ML and use JavaScript as their main language. Sitting at the forefront of ML and
JavaScript, we hope you find the concepts in this book useful and the journey in Java-
Script ML a fruitful and exciting one.
—NIKHIL THORAT AND DANIEL SMILKOV,
inventors of deeplearn.js
and technical leads of TensorFlow.js
preface
The most significant event in the recent history of technology is perhaps the explo-
sion in the power of neural networks since 2012. This was when the growth in labeled
datasets, increases in computation power, and innovations in algorithms came
together and reached a critical mass. Since then, deep neural networks have made
previously unachievable tasks achievable and boosted the accuracies in other tasks,
pushing them beyond academic research and into practical applications in domains
such as speech recognition, image labeling, generative models, and recommendation
systems, just to name a few.
It was against this backdrop that our team at Google Brain started developing
TensorFlow.js. When the project started, many regarded “deep learning in JavaScript”
as a novelty, perhaps a gimmick, fun for certain use cases, but not to be pursued with
seriousness. While Python already had several well-established and powerful frame-
works for deep learning, the JavaScript machine-learning landscape remained splin-
tered and incomplete. Of the handful of JavaScript libraries available back then, most
only supported deploying models pretrained in other languages (usually in Python).
For the few that supported building and training models from scratch, the scope of
supported model types was limited. Considering JavaScript’s popular status and its
ubiquity that straddles client and server sides, this was a strange situation.
TensorFlow.js is the first full-fledged industry-quality library for doing neural net-
works in JavaScript. The range of capabilities it provides spans multiple dimensions.
First, it supports a wide range of neural-networks layers, suitable for various data types
ranging from numeric to text, from audio to images. Second, it provides APIs for load-
ing pretrained models for inference, fine-tuning pretrained models, and building and
training models from scratch. Third, it provides both a high-level, Keras-like API for
practitioners who opt to use well-established layer types, and a low-level, TensorFlow-
like API for those who wish to implement more novel algorithms. Finally, it is designed

xv
xvi PREFACE

to be runnable in a wide selection of environments and hardware types, including the


web browser, server side (Node.js), mobile (e.g., React Native and WeChat), and desk-
top (electron). Adding to the multidimensional capability of TensorFlow.js is its status
as a first-class integrated part of the larger TensorFlow/Keras ecosystem, specifically its
API consistency and two-way model-format compatibility with the Python libraries.
The book you have in your hands will guide your grand tour through this multi-
dimensional space of capabilities. We’ve chosen a path that primarily cuts through the
first dimension (modeling tasks), enriched by excursions along the remaining dimen-
sions. We start from the relatively simpler task of predicting numbers from numbers
(regression) to the more complex ones such as predicting classes from images and
sequences, ending our trip on the fascinating topics of using neural networks to gen-
erate new images and training agents to make decisions (reinforcement learning).
We wrote the book not just as a recipe for how to write code in TensorFlow.js, but
as an introductory course in the foundations of machine learning in the native lan-
guage of JavaScript and web developers. The field of deep learning is a fast-evolving
one. It is our belief that a firm understanding of machine learning is possible without
formal mathematical treatment, and this understanding will enable you to keep your-
self up-to-date in future evolution of the techniques.
With this book you’ve made the first step in becoming a member of the growing
community of JavaScript machine-learning practitioners, who’ve already brought
about many impactful applications at the intersection between JavaScript and deep
learning. It is our sincere hope that this book will kindle your own creativity and inge-
nuity in this space.
SHANQING CAI, STAN BILESCHI, AND ERIC NIELSEN
September 2019
Cambridge, MA
acknowledgments
This book owes Deep Learning with Python by François Chollet for its overall structure.
Despite the fact that the code was rewritten in a different language and much new
content was added for the JavaScript ecosystem and to reflect new developments in
the field, neither this book nor the entire high-level API of TensorFlow.js would have
been a reality without pioneer work on Keras led by François.
Our journey to the completion of this book and all the related code was made
pleasant and fulfilling thanks to the incredible support from our colleagues on Goo-
gle’s TensorFlow.js Team. The seminal and foundational work by Daniel Smilkov and
Nikhil Thorat on the low-level WebGL kernels and backpropagation forms a rock-
solid foundation for model building and training. The work by Nick Kreeger on the
Node.js binding to TensorFlow’s C library is the main reason why we can run neural
networks in the browser and Node.js with the same code. The TensorFlow.js data API
by David Soergel and Kangyi Zhang makes chapter 6 of the book possible, while chap-
ter 7 was enabled by the visualization work by Yannick Assogba. The performance
optimization techniques described in chapter 11 wouldn’t be possible without Ping
Yu’s work on op-level interface with TensorFlow. The speed of our examples wouldn’t
be nearly as fast as it is today without the focused performance optimization work by
Ann Yuan. The leadership of Sarah Sirajuddin, Sandeep Gupta, and Brijesh Krishnas-
wami is critical to the overall long-term success of the TensorFlow.js project.
We would have fallen off the track without the support and encouragement of
D. Sculley, who carefully reviewed all the chapters of the book. We’re also immensely
grateful for all the encouragement we received from Fernanda Viegas, Martin Watten-
berg, Hal Abelson, and many other colleagues of ours at Google. Our writing and
content were greatly improved as a result of the detailed review by François Chollet,

xvii
xviii ACKNOWLEDGMENTS

Nikhil Thorat, Daniel Smilkov, Jamie Smith, Brian K. Lee, and Augustus Odena, as
well as by in-depth discussion with Suharsh Sivakumar.
One of the unique pleasures of working on a project such as TensorFlow.js is the
opportunity to work alongside and interact with the worldwide open-source software
community. TensorFlow.js was fortunate to have a group of talented and driven con-
tributors including Manraj Singh, Kai Sasaki, Josh Gartman, Sasha Illarionov, David
Sanders, syt123450@, and many many others, whose tireless work on the library
expanded its capability and improved its quality. Manraj Singh also contributed the
phishing-detection example used in chapter 3 of the book.
We are grateful to our editorial team at Manning Publications. The dedicated and
tireless work by Brian Sawyer, Jennifer Stout, Rebecca Rinehart, and Mehmed Pasic,
and many others made it possible for we authors to focus on writing the content.
Marc-Philip Huget provided extensive and incisive technical review throughout the
development process. Special thanks go to our reviewers, Alain Lompo, Andreas Refs-
gaard, Buu Nguyen, David DiMaria, Edin Kapic, Edwin Kwok, Eoghan O’Donnell,
Evan Wallace, George thomas, Giuliano Bertoti, Jason Hales, Marcio Nicolau, Michael
Wall, Paulo Nuin, Pietro Maffi, Polina Keselman, Prabhuti Prakash, Ryan Burrows,
Satej Sahu, Suresh Rangarajulu, Ursin Stauss, and Vaijanath Rao, whose suggestions
helped make this a better book.
We thank our MEAP readers for catching and pointing out quite a few typographi-
cal and technical errors.
Finally, none of this would be possible without the tremendous understanding and
sacrifice on the part of our families. Shanqing Cai would like to express the deepest
gratitude to his wife, Wei, as well as his parents and parents-in-law for their help and
support during this book’s year-long writing process. Stan Bileschi would like to thank
his mother and father, as well as his step-mother and step-father, for providing a foun-
dation and direction to build a successful career in science and engineering. He
would also like to thank his wife, Constance, for her love and support. Eric Nielsen
would like to say to his friends and family, thank you.
Visit https://ebooknice.com to
discover a wide range of
eBooks across various genres.
Enjoy exclusive deals and
discounts to enhance your
reading experience. Start your
digital reading journey today!
about this book
Who should read this book
This book is written for programmers who have a working knowledge of JavaScript,
from prior experience with either web frontend development or Node.js-based back-
end development, and wish to venture into the world of deep learning. It aims to sat-
isfy the learning needs of the following two subgroups of readers:
 JavaScript programmers who aspire to go from little-to-no experience with
machine learning or its mathematical background, to a decent knowledge of
how deep learning works and a practical understanding of the deep-learning
workflow that is sufficient for solving common data-science problems such as
classification and regression
 Web or Node.js developers who are tasked with deploying pre-trained models in
their web app or backend stack as new features
For the first group of readers, this book develops the basic concepts of machine learn-
ing and deep learning in a ground-up fashion, using JavaScript code examples that
are fun and ready for fiddling and hacking. We use diagrams, pseudo-code, and con-
crete examples in lieu of formal mathematics to help you form an intuitive, yet firm,
grasp of the foundations of how deep learning works.
For the second group of readers, we cover the key steps of converting existing
models (e.g., from Python training libraries) into a web- and/or Node-compatible for-
mat suitable for deployment in the frontend or the Node stack. We emphasize practi-
cal aspects such as optimizing model size and performance, as well as considerations
for various deployment environments ranging from a server to browser extensions
and mobile apps.

xix
xx ABOUT THIS BOOK

This book provides in-depth coverage of the TensorFlow.js API for ingesting and
formatting data, for building and loading models, and for running inference, evalua-
tion, and training for all readers.
Finally, technically minded people who don’t code regularly in JavaScript or any
other language will also find this book useful as an introductory text for both basic
and advanced neural networks.

How this book is organized: A roadmap


This book is organized into four parts. The first part, consisting of chapter 1 only,
introduces you to the landscape of artificial intelligence, machine learning, and deep
learning, and why it makes sense to practice deep learning in JavaScript.
The second part forms a gentle introduction to the most foundational and
frequently encountered concepts in deep learning. In particular:
 Chapters 2 and 3 are your gentle on-ramp to machine learning. Chapter 2
works through a simple problem of predicting a single number from another
number by fitting a straight line (linear regression) and uses it to illustrate how
backpropagation (the engine of deep learning) works. Chapter 3 builds on
chapter 2 by introducing nonlinearity, multi-layered networks, and classification
tasks. From this chapter you will gain an understanding of what nonlinearity is,
how it works, and why it gives deep neural networks their expressive power.
 Chapter 4 deals with image data and the neural-network architecture dedicated
to solving image-related machine-learning problems: convolutional networks
(convnets). We will also show you why convolution is a generic method that has
uses beyond images by using audio inputs as an example.
 Chapter 5 continues the focus on convnets and image-like inputs, but shifts into
the topic of transfer learning: how to train new models based on existing ones,
instead of starting from scratch.
Part 3 of the book systematically covers more advanced topics in deep learning for
users who wish to build an understanding of more cutting-edge techniques, with a
focus on specific challenging areas of ML systems, and the TensorFlow.js tools to work
with them:
 Chapter 6 discusses techniques for dealing with data in the context of deep
learning.
 Chapter 7 shows the techniques for visualizing data and the models that process
them, an important and indispensable step for any deep-learning workflow.
 Chapter 8 focuses on the important topics of underfitting and overfitting in
deep learning, and techniques for analyzing and mitigating them. Through this
discussion, we condense what we’ve learned in this book so far into a recipe
referred to as “the universal workflow of machine learning.” This chapter pre-
pares you for the advanced neural-network architectures and problems in chap-
ters 9–11.
ABOUT THIS BOOK xxi

 Chapter 9 is dedicated to deep neural networks that process sequential data


and text inputs.
 Chapters 10 and 11 cover the advanced deep-learning areas of generative mod-
els (including generative adversarial networks) and reinforcement learning,
respectively.
In the fourth and final part of the book, we cover techniques for testing, optimizing
and deploying models trained or converted with TensorFlow.js (chapter 12) and wrap
up the whole book by recapitulating the most important concepts and workflows
(chapter 13).
Each chapter finishes with exercises to help you gauge your level of understanding
and hone your deep-learning skills in TensorFlow.js in a hands-on fashion.

About the code


This book contains many examples of source code both in numbered listings and in
line with normal text. In both cases, source code is formatted in a fixed-width font
like this to separate it from ordinary text. Sometimes code is also in bold to high-
light code that has changed from previous steps in the chapter, such as when a new
feature adds to an existing line of code.
In many cases, the original source code has been reformatted; we’ve added line
breaks and reworked indentation to accommodate the available page space in the
book. In rare cases, even this was not enough, and listings include line-continuation
markers (➥). Additionally, comments in the source code have often been removed
from the listings when the code is described in the text. Code annotations accom-
pany many of the listings, highlighting important concepts. The code for the exam-
ples in this book is available for download from GitHub at https:/ /github.com/
tensorflow/tfjs-examples.

liveBook discussion forum


Purchase of Deep Learning with JavaScript includes free access to a private web forum
run by Manning Publications where you can make comments about the book, ask
technical questions, and receive help from the author and from other users. To
access the forum, go to https://livebook.manning.com/#!/book/deep-learning-with-
javascript/discussion. You can also learn more about Manning’s forums and the rules
of conduct at https://livebook.manning.com/#!/discussion.
Manning’s commitment to our readers is to provide a venue where a meaningful
dialogue between individual readers and between readers and the author can take
place. It is not a commitment to any specific amount of participation on the part of
the author, whose contribution to the forum remains voluntary (and unpaid). We sug-
gest you try asking the authors some challenging questions lest their interest stray!
The forum and the archives of previous discussions will be accessible from the pub-
lisher’s website as long as the book is in print.
about the authors
SHANQING CAI, STANLEY BILESCHI, AND ERIC NIELSEN are software engineers on the
Google Brain team. They were the primary developers of the high-level API of Tensor-
Flow.js, including the examples, the documentation, and the related tooling. They
have applied TensorFlow.js-based deep learning to real-world problems such as alter-
native communication for people with disabilities. They each have advanced degrees
from MIT.

xxii
about the cover illustration
The figure on the cover of Deep Learning with JavaScript is captioned “Finne Katschin,”
or a girl from the Katschin tribe. The illustration is taken from a collection of dress
costumes from various countries by Jacques Grasset de Saint-Sauveur (1757-1810),
titled Costumes de Différents Pays, published in France in 1797. Each illustration is finely
drawn and colored by hand. The rich variety of Grasset de Saint-Sauveur’s collection
reminds us vividly of how culturally apart the world’s towns and regions were just 200
years ago. Isolated from each other, people spoke different dialects and languages. In
the streets or in the countryside, it was easy to identify where they lived and what their
trade or station in life was just by their dress.
The way we dress has changed since then and the diversity by region, so rich at the
time, has faded away. It is now hard to tell apart the inhabitants of different conti-
nents, let alone different towns, regions, or countries. Perhaps we have traded cultural
diversity for a more varied personal life—certainly for a more varied and fast-paced
technological life.
At a time when it is hard to tell one computer book from another, Manning cele-
brates the inventiveness and initiative of the computer business with book covers
based on the rich diversity of regional life of two centuries ago, brought back to life by
Grasset de Saint-Sauveur’s pictures.

xxiii
Part 1
Motivation
and basic concepts

P art 1 consists of a single chapter that orients you to the basic concepts that
will form the backdrop for the rest of the book. These include artificial intelli-
gence, machine learning, and deep learning and the relations between them.
Chapter 1 also addresses the value and potential of practicing deep learning in
JavaScript.
Deep learning
and JavaScript

This chapter covers


 What deep learning is and how it is related to artificial
intelligence (AI) and machine learning
 What makes deep learning stand out among various
machine-learning techniques, and the factors that led to the
current “deep-learning revolution”
 The reasons for doing deep learning in JavaScript using
TensorFlow.js
 The overall organization of this book

All the buzz around artificial intelligence (AI) is happening for a good reason: the
deep-learning revolution, as it is sometimes called, has indeed happened. Deep-
learning revolution refers to the rapid progress made in the speed and techniques of
deep neural networks that started around 2012 and is still ongoing. Since then,
deep neural networks have been applied to an increasingly wide range of prob-
lems, enabling machines to solve previously unsolvable problems in some cases and
dramatically improving solution accuracy in others (see table 1.1 for examples). To
experts in AI, many of these breakthroughs in neural networks were stunning.

3
Other documents randomly have
different content
“3rd. That there was no system of regular education for the
merchant service of Great Britain, but that, in foreign countries, this
matter was much attended to.
“4th. That the sort of education which a British subject receives,
when training for the higher grades of the merchant sea service,
does not suffice to qualify him to represent with advantage to the
merchant by whom he may be employed that merchant’s interest;
and that he may often neglect those interests and the merchant not
be aware of the fact.”
“What was wanted,” Mr. Murray continued, “was not merely a study
of navigation and seamanship, but a thorough knowledge of ship’s
husbandry, and a thorough knowledge of stowage of cargo, of
exchanges, and other commercial information which would qualify a
master to act, if necessary, as the representative of his employer in
the character of merchant; the commander of a ship being in law
considered the representative of the owners of the property on
board. It was further urged that a merchant had no means of
accurately ascertaining the character and capability of shipmasters
or of seamen, and really depended for the safety of his property
upon his insurances.”
For these reasons, with a view to maintain the
and suggestions supremacy of Great Britain in commercial
for remedies navigation and enterprise, Mr. Murray proposed to
establish “a Board or Department of Commercial
Marine,” at the same time pointing out that the want of such a
department was greatly felt in the preparation of any new law, and
still more so in the subsequent process of acting upon it. Nine
departments, he explained, were concerned in the Merchant Sea
Service Laws; and there was no central board to point out to each
department how each could best act for the success of the whole;
each department being left to look merely to those interests
committed to its charge, and to its own convenience. The Board of
Trade was indicated as the department to which the community
would naturally look with regard to everything relating to commerce,
whether at sea or on shore.
Previously to the issue of Mr. Murray’s
Board of Trade ‘Memorandum,’ that Board had, on the 17th May,
Commission,
1847,[21] announced the intention of Government
May 17, 1847.
to issue a commission without delay to examine
into certain matters relating to the commercial
Its results. marine. This inquiry confirmed in all material
respects the information previously received by Mr.
Murray. Indeed, three only out of seventy-five reports from consuls
stated that the condition of British shipping had improved rather
than declined; and, in these cases, it was shown that, from the
nature of the trade in which the vessels were engaged—the fruit
trade of Greece, and from the perishable character of their cargoes—
the greatest care had to be taken in selecting the best ships.
There can be no doubt that, as early as 1843, when Mr. Murray
issued his circular letter to the consuls, and more especially in 1847,
when Lord Palmerston ordered further inquiry to be made by means
of this commission, Government saw the time was approaching
when great changes would be demanded, not merely with regard to
the Navigation Act, but likewise in the laws affecting our ships and
seamen; and that it would, ere long, be essential for our own
interests to follow the example set us by foreigners in the education
of our seamen, as well as in the application of public tests to prove
the competency of the masters and officers of British merchant
vessels.
Strong objections were, however, raised by the
Shipowners shipowners against any Government interference,
condemned for on the ground that it would be partial, and
the character of
consequently so far unjust, these objections being
their ships and
officers. naturally strengthened by the manner in which Mr.
Murray had set about the enquiry of 1843. It was,
nevertheless, but too evident that, however much British shipowners
might deprecate the assistance or interference of Government, a
large proportion of their ships were commanded and navigated in a
manner reflecting discredit on our national intelligence, and injurious
to the interests of Great Britain; that the persons placed in command
of them were too frequently unfit for their duties; and that, while
many of them were so habitually addicted to drunkenness as to be
altogether incompetent for their position, not a few of them were
almost without education.[22]
Nor in too many instances were the ships much better than their
masters; and hence foreign vessels were frequently chartered in
preference to British, not because, as ships, they were superior in
quality, but on account of the greater care foreign shipmasters
bestowed on the stowage and transport of their cargoes, and from
the fact that being generally educated, sober, intelligent, and
capable of commanding respect and maintaining discipline, the
seamen themselves were consequently more orderly.
For these and numerous other reasons,
Views of Government naturally asked whether it was
Government. justifiable that the lives of thousands of persons
should be constantly jeopardised, because
shipowners had the power of placing incompetent persons in charge
of their vessels; and whether it was proper for the State to allow its
seafaring population to be left in ignorance and disorder, and
exposed to the evil example of illiterate and intemperate masters.
Many thoughtful men out of doors also began to enquire if it was
right that these men, by sheltering themselves under the Navigation
Laws, should be thus allowed to encourage the growth and
employment of foreign in preference to British shipping, to the injury
of the national interests.
Even had it not become apparent that the time
Necessity of a had arrived for great changes in the commercial
competent policy of England, the condition of our seamen and
Marine
the state altogether of our merchant service
Department.
required the exclusive attention of some such
public department as Mr. Murray had recommended. But such
matters, however important, being subsidiary to the question of the
Navigation Laws and their effect upon maritime commerce, were left
in abeyance till these had been fully considered.

FOOTNOTES:
[16] See papers relating to the Commercial Marine of Great Britain, 1846, p. 235.
[17] The “Winding-up Act, 1851,” enacted that compulsory contributions should
cease from that date; that those who had paid up till then, should have the option
of continuing these payments, but those seamen who had not contributed before
1851 should not be admitted. Thus the fund was practically “abolished,” and is
now only in operation for the purpose, as the Act names, of “winding-up.” This
well-intended Institution had become hopelessly insolvent through the grossest
mismanagement. Its administration was vested in different irresponsible bodies at
the different ports, and while the Legislature compelled contributions, it took no
security for the just appropriation of these funds, and no security for solvency!
The Winding-up Act of 1851 transferred its affairs to the Board of Trade for the
purpose of paying all existing pensions, and to allow the then existing contributors
to continue their annual payment should they wish to do so. It has cost the
country upwards of 1,000,000l., and will probably cost 500,000l. more before all
claims have been satisfied. The pensions granted by the Board of Trade until now
(1875) have been 7528l. to masters and seamen, and 14,972l. to widows and
children.
[18]
The “Belvidere,” known as the “Royal Alfred Aged Seaman’s
The “Belvidere,” Institution,” was established, soon after the abolition of the
or “Royal Alfred “Merchant Seaman’s Fund,” mainly through the exertions of
Aged Seaman’s the late Mr. William Phillipps, Mr. George Marshall, and other
Institution.” philanthropic shipowners. The laudable object of this
excellent institution is to provide for the “relief of aged and
worn out merchant seamen of the United Kingdom.” It was started by a grant of
5000l. from the Shipwrecked Mariners’ Society, and is now maintained entirely by
legacies, donations, and annual subscriptions from charitable persons. These
amounted, in 1874, to somewhere about 7600l., though, out of this sum, the
annual subscriptions were only 1600l. Its inmates were then 105 decayed seamen,
whose ages ranged from 63 to 85. There were, besides, in that year 110 persons
receiving from its funds 12l. per annum in out-door pensions. The inmates are
provided with comfortable cabins, clothed, a good mess, and have every comfort,
with pleasant grounds for exercise, overlooking the River Thames. All their
physical and spiritual wants are well supplied; and, so far as its limited funds
permit, it has proved of great service, being well and economically managed.
When its claims on the public—I might say on the country—become better known,
its means of doing good will thus, I hope, be largely extended. Indeed, the Board
of Trade having now in hand upwards of 200,000l., arising from the unclaimed
wages and effects of deceased merchant seamen, from the surplus fees of the
mercantile marine, and other similar sources, the question suggests itself if a
portion of these surplus funds could not be appropriated to the benevolent
purposes of the Royal Alfred Aged Seaman’s Institution?
[19] In 1859, when a member of the Royal Commission on manning the Royal
Navy, I proposed to my colleagues the establishment of a merchant seamen’s
fund, under Government supervision, as a means of raising a large portion of the
reserves of seamen we were then considering. Though my views on this and other
points were not adopted, they were published by order of the House of Commons,
and accompanied the report; and as the question is still one of much public
importance and still requires solution, I furnish extracts from these “remarks”:—
“‘Experience has shown,’ says Mr. H. R. Williams, of the
Mr. Williams, Board of Trade, in his sensible paper on the subject, ‘that any
observations by, attempt to establish a merchant seamen’s fund upon the
on the principle of voluntary payments would not be supported by a
advantage of large body of seamen. The working of the Seamen’s Fund
general Winding-up Act has proved that seamen generally, whatever
Seaman’s Fund. advantages may be offered to them, will not voluntarily
contribute to a fund. However great may be the objections,
therefore, to compulsory payments, there is no probability that a fund can be
established with any chance of success upon any other principle.’
“I admit that there is something repugnant to the feelings of the sailor, and, in
fact, to all Englishmen, in the word ‘compulsory,’ when applied to the management
of his own affairs; but, in general practice, that which would be termed
compulsion, if sanctioned and regulated by the Legislature, is already a voluntary
act cheerfully undertaken by large masses of the people. There is scarcely a
handicraft trade in the kingdom the members of which have not formed
themselves into a society, the object of which is, by means of periodical
subscriptions, to secure a pension or payment in sickness or old age. Both
individually and nationally, every such institution is in the highest degree
commendable. If, therefore, these benefit societies deserve encouragement and
support, when formed for artisans and others whose occupations are on shore,
they merit encouragement and support still more when their object is to relieve
those whose occupation is at sea. Seamen have no means of forming such
associations, as they are scattered over the whole world, having no organization,
no central power, and no machinery to put such a system into operation. Whatever
incentives they may have to combine together for such a purpose, they have not
the means of carrying into effect their wishes. This appears to be generally
conceded; and we have arrived at the conclusion that it is the duty of Government
to step forward to aid those who, from their peculiar calling, are incapable of
acting themselves.
“Commander Brown, the Registrar, Mr. Baker and Mr. Williams, of the Board of
Trade, together with Captain Pierce, of the Liverpool Sailors’ Home, all concur in
the opinion that the time has arrived when a new seamen’s fund should be
established on sound principles under Government supervision, and upon such a
basis as shall offer to the seaman a strong and powerful inducement to preserve
that test which secures to him substantial maintenance in old age, or when
prematurely worn out. The whole of the machinery necessary to effect this object
is now established at the shipping offices, and in the existing departments of the
Board of Trade, and already in operation upon 12,000 masters and seamen who
have contributed to the fund under the Winding-up Act of 1851.
“... I am of opinion that such an institution would be highly popular, even with the
shipping interest. I say this, with the knowledge that a seaman may calculate his
wages at only 2l. 9s. instead of 2l. 10s. per month; and with the possibility, that
the difference of 1s. per month may fall upon the shipowner, to which class I
belong. But if the incidence of this extra shilling should, in point of fact, fall
absolutely upon the shipowners, they would be gainers thereby, as it is of the
highest importance to them that the seaman should have some substantial tie to
bind him to this country. At present no such tie exists. The British-born seamen
become citizens of the world, and find themselves quite as much at home in the
United States as in their native country. The higher rate of wages paid in the
American ships presents a temptation to them to enter that service in preference
to that of England. Now if some special inducement were offered to them to
remain at home, it would operate to diminish the number of British seamen in the
service of foreign states. The sailor would thus have also ‘his stake in the public
hedge.’ At present, the exceptional use of savings banks furnishes almost the only
link, for the beneficial use of money-order offices, however great their advantages,
is rather a ready facility given than a permanent benefit enjoyed.
“With those views, I should propose to make a seamen’s fund the basis of raising
the remaining 18,000 men for a reserve. I think that the fund should be a general
one, to which both seamen in the Royal Navy and in the mercantile marine should
be called upon to subscribe. I think it would be desirable to break through the line
of demarcation which has so long existed between the two services, and this
would be one step towards effecting that object. I would give seamen of all
classes a common interest in this one great fund, which might be designated as
National.
“I am aware that objections will be raised to any compulsory fund. I would much
prefer to have it a voluntary one; but knowing the character of the seamen as I
do, I am thoroughly convinced that any fund established even under the auspices
and with the guarantee of the Government, on the voluntary principle, would be a
failure.
“... So far as the nation was concerned, the salutary effects of such a fund would
operate in three different ways: it would prevent the seamen from being objects of
charity or claimants upon the poor rates during their old age; it would be a
permanent tie to bind them to their native country, founded upon a common bond
of self-interest; while it would form the groundwork of a system whereby the
reserve of 18,000, still wanting, might be raised.”
[20] Papers relating to Commercial Marine of Great Britain.
[21] See Sir John Shaw Lefevre’s letter, page 144, part ii., Parl. Papers relating to
Mercantile Marine.
[22] In my own time, I remember a shipowner saying to me that he never would
have a “scholar” in command of any of his vessels, because education taught him
how to make up false accounts and the art of cheating; while another whom I
knew, only retained one “educated” master in his service, because he was
flattered by being invariably addressed by him as “Mr. Joseph Perkins, Esquire.”
CHAPTER III.
High estimate abroad of English Navigation Laws—Change necessary,
owing to the Independence of America—Other nations at first
Protectionist—Mr. Pitt’s proposals with reference to trade with
America—Mr. Pitt resigns, and a temporary Act ensues—Shipowners
and loyalists in America successfully resist his scheme—Congress the
first to retaliate—Restrictions injurious, alike, to England and her
Colonies—Commercial treaties with America between 1794 and 1817
—Acts of 1822 and 1823, and further irritation in America—Order in
Council, July 1826—Conciliatory steps of the Americans in 1830—
Foreigners look with suspicion on any change in the Navigation Laws
—Reciprocity treaties of 1824-6—Value of treaties in early times, but
inadequate for the regulation of commercial intercourse, and liable to
unfair diplomacy—Reciprocity treaties only, partially, of value, and do
not check the anomalies of Protection—Committee of 1844-5
promoted by the Shipowners, who seek protection against Colonial
shipping—Reciprocity must lead to free navigation—New class of
Statesmen, well supported by the People—Exertions of Lord John
Russell, who leads the way against Protection—Richard Cobden and
the Anti-Corn-Law League—John Bright—Effect of the Irish famine,
1845-6—Sir Robert Peel carries the Repeal of the Corn Laws, and
resigns.

In proceeding to consider the great alterations in the ancient


commercial system of England which have ultimately led to the
entire abrogation of the Navigation Laws, it is advisable to trace their
remarkable history under several distinct heads, premising, however,
that, previously to 1844, their complete repeal had probably not
suggested itself to any of the statesmen who, at various periods,
had held the chief power in England.
For nearly two centuries an opinion had prevailed
High estimate in England, as well as in all foreign countries
abroad of carrying on maritime commerce, that the English
English
Navigation Laws, created originally to check, if not
to annihilate, the maritime power of Holland, had
Navigation been the means of raising Great Britain to her
Laws. unquestioned superiority on the ocean. But this
opinion is best answered by the fact that, long
after the creation of these laws, the Dutch still remained more
powerful at sea than any other nation;[23] while, on the other hand,
the shipping of England, under a different policy, has become much
more prosperous than it ever was at any period during which the
laws of Cromwell were enforced.
Other nations, however, could not fail to see that
Change English shipowners upheld these laws with much
necessary, tenacity; hence when, on the cessation of the wars
of Napoleon, they had more time to devote their
attention to individual pursuits, they asked themselves two
questions: (1st) if protective laws had been beneficial to English
ships, why should they not follow the example of that country and
enact for themselves similar laws? and (2nd) if England persisted in
excluding their ships from her ports, why should they not treat her
vessels in the same manner? In other words, they were already
prepared to act on the principle of retaliation, and adopt the course
pursued by the United States of America in 1817, when Congress
passed a law, the counterpart, if not the copy, of that in the English
Statute-book, which was adopted with the declared intention of
retaliating on Great Britain.
In the case of the American States, so long as they
owing to the were dependencies of the British Crown, their
Independence ships could trade with all British dependencies on
of America.
the same footing as our own; but, when they
became independent, their ships, like those of any other foreign
Power, were excluded from every port where our laws prohibited the
entry of such vessels. Previously they could freely trade with the
British possessions in America and with the West Indies, with which
they had hitherto carried on a profitable intercourse, supplying them
with lumber for their houses, staves for their casks, corn, fish, and
other provisions, together with horses and cattle for their
plantations, besides affording our people there a sure market for
their surplus produce of coffee, sugar, and rum.
Up to this period the practice of foreign nations
Other nations at had not very materially complicated our navigation
first system. If Great Britain, on her part, persisted in
Protectionist.
refusing to receive, for instance, the produce of
the Spanish and Portuguese colonies in any but
Mr. Pitt’s British ships, Spain and Portugal, on their side,
proposals with declined to send their goods to England in any
reference to
ships but their own. So that our law in such cases,
trade with
America. rigorous as it was, did nothing but determine how
a trade, in which we had never had a share, must
be carried on, should we be permitted to enter it.
Mr. Pitt resigns,
and a temporary
But the case of the United States was attended
Act ensues. with much greater difficulty. Here was an extensive
and flourishing maritime commerce, averaging
nearly 3,500,000l. yearly, which had hitherto been open to English
and American vessels, indifferently, but which was now, by the
operation of our Navigation Laws, confined entirely to the former.[24]
It was then that the strength and elasticity of our exclusive system
were first severely tested. Mr. Pitt foresaw this serious difficulty so
early as 1783 when Chancellor of the Exchequer, and the necessity
of immediately introducing a temporary measure to regulate the
commercial intercourse with the now independent States of North
America. The Bill then actually introduced by Mr. Pitt proposed to
allow American vessels to import into our colonies any articles
whatever of the growth, produce, or manufacture of the United
States, and to export any articles from our colonies to the United
States. But, unfortunately, while this wise measure was under the
consideration of the House of Commons, the ministry to which Mr.
Pitt belonged resigned, and their successors, to save themselves the
trouble of passing a Bill of this prudent and necessary character,
passed a temporary Act, afterwards renewed from time to time,
vesting in the Crown alone the power of regulating the trade with
America.
As might have been anticipated, considerable
The shipowners discussion immediately arose with regard to the
and loyalists in manner in which this power of the Crown should
America
be exercised. The West Indians, on the one hand,
successfully
resist Mr. Pitt’s represented the ruinous position in which they
scheme. would be placed if they were forbidden to trade
with the United States: while, on the other, the
loyalists of the remaining North American Colonies pleaded that they
were quite able to supply the people of the West Indies with all they
required, and prayed that the monopoly the war had given them
should not be abrogated. These views were maintained by the
shipowners of Great Britain, on the plea that, if American vessels
were allowed to export West Indian produce, they would convey it to
foreign countries as well as to the United States, thus securing a
materially improved position as carriers by sea; and, after this case
had been fully argued before the Board of Trade, the shipowners
and the loyalists unfortunately won the day.
Exasperated by such conduct, three of the
Congress the American States made a requisition to Congress to
first to retaliate. prohibit all commercial intercourse with the British
colonies;[25] and, before Congress met in 1789, no
less than nine of these States had demanded retaliatory measures
on British commerce and navigation. The result was that two Acts of
Congress were immediately passed: one imposing a tonnage duty of
six cents on all American built and American owned vessels, of thirty
cents on vessels built in the United States but owned by foreigners,
and of forty cents on foreign vessels; while the other imposed a
tariff of duties in the ordinary form, and provided for the remission
of 10 per cent. of such duties in case the goods were imported in
American ships. The Americans thus paid us off in our own coin, and
continued this retaliatory system till 1817, when they passed the
Navigation Act to which I have just referred, in all respects
analogous to our own. Nor, indeed, can there be any question but
that they were fully justified in these retaliatory measures. If one
nation insists on excluding the vessels of other nations from their
trade, they must naturally expect that the legislators of the
countries, whose vessels are thus excluded, will take similar steps,
even to the injury of their own people; in fact, this is just what
England did when she prohibited her people from obtaining from
other countries, at the lowest cost, the produce or manufactures
essential for their existence.
But besides this, these restrictive measures on the
These part of Great Britain, had in more than one
restrictions instance, proved, in many other respects, most
injurious, alike,
injurious to her own people, while inflicting the
to England and
her Colonies. greatest hardships and most lamentable sufferings
on her own West Indian colonies. Thus, between
1780 and 1787 no less than 15,000 slaves perished from starvation,
having been unable to obtain the requisite supplies of food from the
North American colonies at a period, when the home-grown portion
of their sustenance had been destroyed by several hurricanes. Yet,
notwithstanding this terrible calamity, the British Parliament
persevered in the system it adopted, and ultimately passed an Act
(28 Geo. III., cap. 6) whereby no goods could be imported into the
West Indies from the United States, even in British ships, except
about thirty enumerated articles, the produce of these States.
Indeed, the Act went so far as to prohibit the importation of even
these articles from any of the foreign West Indian Islands, except in
cases of public emergency, when the governors of individual colonies
were allowed to relax this prohibition. Similar laws were also passed
to prohibit the importation of goods into our North American
colonies from the United States, except for similar reasons.
The injurious consequences of such policy,
Commercial especially in the provocation it gave to the
treaties with Americans, led to the conclusion, in 1794, of the
America
treaty to which I have already incidentally
between 1794
and 1817. referred[26] (though, strange to say, even this was
disapproved of by many persons in England),
whereby American vessels, not exceeding seventy tons burden, were
allowed admission into the British West Indies with such articles of
United States produce as were not generally prohibited, and, at the
same time, permitted to export therefrom to the United States any
produce of the West Indies legally exportable thereto in British
vessels. Curiously enough, the following proviso was appended to
this clause:—“That this liberty only extends to a direct intercourse
between the British West Indies and the ports of the United States,
and the United States engage to prohibit the carriage of molasses,
sugar, coffee, cocoa, or cotton in American vessels, either from his
Majesty’s dominions or from the United States to any other part of
the world.” The treaty also provided for placing the trade between
Great Britain and the United States on a permanent footing, it
having till then been regulated by Orders in Council. This treaty,
which gave even greater dissatisfaction in the United States than in
England, was not ratified by Congress till 1796; nor was the Act for
giving effect to it in Great Britain passed till the following year.
This Act, however, made no provision for the admission of American
vessels generally into our colonies. It simply provided that American
ships were at liberty to import into Great Britain such produce of
their own States as was admissible in British vessels; it moreover
imposed a tonnage duty on the ships, and a discriminating duty on
the goods imported by them, in order to countervail any duties
levied on goods imported into the United States by British ships. The
provisions of the treaty as to opening the trade of the West Indies
appear to have fallen to the ground. An additional article to the
treaty of 1794 stipulated that the article containing those provisions
shall be suspended; while a later treaty (1806) contained a recital
that the two high contracting parties had been unable to arrange the
terms on which the commerce between the United States and the
West Indies was to be carried on. In fact, they came to no definite
arrangements till the United States passed their retaliatory Acts in
1817 and 1820, and, even then, it took more than ten years to settle
the differences between them on almost any one question. Indeed,
the only alterations of any importance made between 1806 and the
passing of the American Navigation Act, in 1817, were the opening
of the trade between the United States and our North American
colonies, in 1807, and the conclusion of a treaty in 1815 abolishing
the differential duties levied by the two countries on the ships of
each other in respect of direct voyages between them.[27]
In 1808, and more fully in 1810, similar privileges were granted to
the Portuguese dominions in South America; and, in 1822, these
were extended to all countries in America, being, or having been,
under the dominion of Spain. When the Customs Laws were first
consolidated in 1825, the exceptions became the rule, and
importations from Asia and Africa were placed on a similar footing to
those from America. Thus our original rule as to importations from
Asia and Africa, as well as from America, was broken down.
Though the Act of 1822 allowed a considerable
Acts of 1822 number of articles to be imported into the free
and 1823, and ports of the West Indies from any foreign country
further irritation
in America in ships of such country, it contained a
in America.
clause reserving to the King the power of
prohibiting such intercourse with any foreign country not treating
British shipping with equal favour. The President of the United
States, having been previously empowered by Congress to open the
ports of that country to British vessels on the same terms as were
required from United States vessels when coming from any British
port in the West Indies, passed on the 21st March, 1823, an Act to
regulate “the commercial intercourse between the United States and
certain British ports.” By this Act the ports of the United States
became open to British vessels coming from the free ports of the
British North American and West Indian possessions, while power
was given to the President to remove the differential duties levied on
goods so imported, on receiving information that similar privileges
had been conceded in such British colonial ports to the vessels of the
United States. The Act, however, required all goods so imported to
be the produce of the colony whence they came and to have been
imported thence direct. It further enacted that such British ships
might take back produce of the United States, provided they gave
bonds to land it directly at the port for which they cleared out. As
the provisions of this Act were, however, to depend on the
continuance of those enacted by the British Legislature in 1822 (3rd
Geo. IV., cap. 44), and, as the vessels of the United States were not
placed on precisely the same footing in the ports of the West Indies
as British ships, this power of the President was never exercised,
and a British Order in Council in opposition to it was subsequently
issued on the 21st July, 1823. Here again arose another war of
tariffs, for this Order levied countervailing duties on vessels of the
United States and their cargoes in the ports of the British North
American and West Indian possessions from the ports in the United
States to the extent of 4s. 3d. per ton, as well as a discriminating
duty of 10 per cent. on imported articles.
In 1825, when the consolidation of the Customs
Order in Laws was under consideration, as well as the
Council, July, extension of treaties with other countries,
1826.
negotiations were again renewed with the United
States, but they were not successful, and another Order in Council
was issued on the 27th July, 1826, reciting that the conditions laid
down by the Possessions Act, 6 Geo. IV., cap. 114, had not been
fulfilled, that is to say, that the United States had not reciprocated
the privileges Great Britain had granted to American ships, and that,
therefore, the privileges possessed by American vessels of importing
the produce of their country into British possessions abroad, and of
exporting the produce of those possessions to any foreign country
whatever, would cease on certain dates fixed in the following year.
As might have been anticipated, the President issued, on the 17th
March, 1827, a proclamation prohibiting the trade and intercourse
with the British possessions authorised by the Act of Congress of 1st
March, 1823.
Happily, however, these retaliatory measures did
Conciliatory not remain long in force; and, after various
steps of the negotiations, it was enacted by the American
Americans,
Congress on the 29th May, 1830, that, whenever
1830.
the President should have evidence that Great
Britain would open the ports of her colonial possessions in the West
Indies, South America, and the Bermudas, for a limited or indefinite
time to United States ships, at the same rate of impost and tonnage
and with the same cargoes as British vessels, and that they would
be allowed to export from such British possessions to any country
whatever any article which could be exported in British vessels,
leaving any other intercourse with Great Britain in other respects as
it then was, he might grant similar privileges to British vessels
coming from the said possessions to the United States. This
conciliatory measure was followed on October 5th, 1830, by a
proclamation from the President, extending the provisions of the Act
to the British colonies therein specified, and which had been opened
to American vessels. Finally, a British Order in Council of the 5th
November of that year, repealing the various Orders passed between
1823 and 1827, was issued, authorising vessels of the United States
to import into British possessions abroad any produce of the United
States from those States, and to export goods from the British
possessions abroad to any foreign countries whatever.
Subsequently to the failure of Mr. Pitt’s measure
Foreigners look respecting the trade of the United States, no great
with suspicion effort was made for many years to modify
on any change
grievances with other nations, which every one felt
in the
Navigation were caused by the Navigation Laws. Protection
Laws. had become so thoroughly engrafted on the whole
policy of the nation, that the question of the repeal
of these laws could only be approached by degrees, the country
being so impressed with their necessity, that any attempt during the
first quarter of this century to sweep them away would have proved
a signal failure. Indeed, at the close of the French war, when
modifications were offered, conditionally, to other countries, it is not
surprising that such foreign nations as believed the prosperity of
England to be due to her protective system were not satisfied of the
honesty of her intentions: most of them, in fact, looked with
suspicion on proposals which, in the dawn of sound commercial
knowledge, were not unnaturally thought by them inimical to the
interests of England. Foreign nations were slow to recognise that the
comparative freedom of her constitution, her vast mineral resources,
the skill and energy of her people, the security of property, and the
equality of taxation, could secure for England either her commercial
or her manufacturing superiority; and, still less, could they
comprehend how much such causes as these had to do with her
maritime supremacy. They were equally unable to discover to how
great an extent the prosperity of these interests and of shipping
were mutually dependent on each other, ships being really the
adjuncts only of commerce, as without it there would be no reason
for their existence.
But after much discussion reciprocity treaties were
Reciprocity concluded by Mr. Canning and Mr. Huskisson with
Treaties of several Continental Powers, the object of these
1824-6.
statesmen being to hold out the right hand of
fellowship to other nations, and to surrender in exchange for some
concession on their part the more stringent conditions of our
Navigation Laws. The earliest of these treaties was with Prussia, on
the 2nd April, 1824: on the 16th June, we made another with
Denmark; on the 29th September, 1825, with the Hanseatic
Republics of Lubeck, Bremen, and Hamburg; on the 16th January,
1826, with France, and on the 26th December, of the same year,
with Mexico. Various other treaties followed; opening, on certain
terms of reciprocity, the ports of Great Britain to the ships of the
nations with whom they were made; but reserving to her own ships,
as a rule and with jealous care, her colonial ports.
During the Middle Ages, when foreigners were too
Value of treaties frequently subjected to unjust treatment, treaties
in early times, were, no doubt, necessary for their protection. For
instance, at one time, all foreigners residing in
England were held liable for the debts and even for the crimes of
each other. Shipwrecks, though attended with less of the barbarity of
earlier times, were regarded in most countries as fortunate
opportunities for plunder; while tolls and local charges of the most
arbitrary description were levied on aliens by states, princes,
corporations, and the lords of manors. There were also many other
matters scarcely less oppressive and unjust which could only be
redressed by negotiations.
Under such circumstances it was necessary for
but inadequate commercial States to secure, by treaties, that
for the protection and security for the person and property
regulation of
of their subjects abroad against the injustice they
commercial
intercourse, and were liable to, and which they could not obtain
liable to unfair from the laws of the countries where they might
diplomacy. happen to be. Treaties were also required for the
regulation of neutral commerce during war, and for
defining clearly what goods could not be carried by neutrals for the
belligerents. For all such purposes treaties were, of course,
essential; but, when they came to be used, with the further object of
teaching different nations how to conduct their own business, a
practice arose which, however useful at the time in assisting a
change of system, could not long endure. Regulations as to the
duties chargeable on certain articles, or for the privileges of certain
ships, according as they were built by, or belonged to, particular
countries, inducing constant misrepresentation and tending to create
grave differences between nations, were soon found to be neither
the best nor the wisest means for producing economic or friendly
commerce. Moreover, the whole system of treaties so constructed
was attended with a mode of bargaining, in which the clever
diplomatist might frequently gain unfair advantages for the people
he represented. Such a course of action was so obviously undignified
in the conduct of national affairs, that all merchants of high standing
in different countries at length protested against it. Statesmen, also,
began to discover that, as a rule, it was better for commerce to flow
on with no interference from treaties or other legislation—that, as a
matter of fact, it prospers best unaided; and, further, that such a
state of things, while unsatisfactory so far as the intercourse
between nations is concerned, was also discreditable, alike to the
nations entertaining such propositions, and to the ministers or
officers by whom they were proposed.
As the whole of the treaties, with their numerous protocols and
appendices, their labyrinths of “clever clauses” and mysterious
paragraphs, have been published,[28] and can be examined by those
of my readers who are interested in such diplomatic intricacies, it is
only necessary to give here the general purport of them, as I shall
have occasion to notice, hereafter, in reviewing the progress of
merchant shipping, those more directly affecting that interest; but,
that my readers may understand more clearly the nature of these
treaties, I furnish the text of that with France.[29] It gives the
general conditions embodied in such documents, and the extent of
the concessions England was prepared to make with those countries
which were willing to reciprocate with her.
The results of these “Reciprocity Treaties,”
Reciprocity however, as shown in the note,[30] were, for the
treaties only,
partially, of
time, satisfactory to both countries, in so far as
value, they materially tended to increase intercourse,
while they, certainly, proved advantageous, in the
long run, to the shipowners of England. But they were full of
inconsistencies, and, as the trade between nations increased, it
became simply impossible to carry them out satisfactorily.
Nor was it, indeed, likely that people of different nations, who had
been thus far “educated” to the advantages derivable from free
intercourse, would continue to endure the absurd clauses of treaties
prohibiting them from using corn, cotton, sugar, and numerous other
necessaries of life, piled in heaps as these often were in their stores
and warehouses, merely because they had been imported in other
ships than those of Great Britain, or of the countries where they had
been produced.
The fact was, that while these treaties did create a
and do not sort of uniformity before unknown, and so far
check the increased the facilities of intercourse, they did not
anomalies of
obviate the most glaring hardships and
Protection.
inconveniences of the previous system of
protection. An American vessel, for instance, might bring American
cotton to England direct; but if this cotton had been landed at any
foreign port, neither the ships of that country nor of any other could
have conveyed it thence to our shores; while the corn of Russia, if
landed in Prussia, or in the ports of any other nation, was prohibited
in England, however great might be the demand for it at the time.
Nevertheless, when it was first proposed in 1821 to allow British
ships to import non-prohibited articles from any part of the world,
the proposal was, for the time, effectually resisted by our
shipowners, on the plea that the cheaply built and navigated vessels
of other countries would carry the produce of America and Asia into
continental ports, and leave to British ships only the small profit to
be derived from its conveyance across the English Channel!
But though it was abundantly clear that great
Committee of changes were necessary beyond the treaties which
1844-5 had been effected (an enlightened class of
promoted by
merchants and manufacturers having now arisen
the Shipowners,
who seek who required that they should be entirely
protection unfettered in the conduct of their own affairs, and
against Colonial that they should be at liberty to import and export
shipping. whence, whither, and how they pleased) it was no
easy thing to induce Government even to consider
the advisability of taking a further step in advance and repealing
laws so long in force. No important changes were, therefore,
contemplated until 1844, when a Committee of the House of
Commons was appointed to inquire into the working of those
treaties and the condition of the commercial marine of the country:
indeed, the appointment of even this Committee appears to have
originated from complaints preferred by our shipowners, as one of
the duties imposed upon it was the consideration of the best mode
of encouraging and extending the employment of British shipping.
Curiously enough, the chief complaint of the shipowners, in this
instance, was against the privileges granted to colonial-built ships,
the owners of which were, of course, on the same footing as those
of vessels built in the United Kingdom. It was alleged that the latter,
as costing a great deal more, were unable to compete successfully
with the less costly ships of North America, and, therefore,
legislative protection was sought, on the ground that the competition
of these ships had materially lowered the rates of freight.
The Committee of 1844 was appointed at the instance of Mr. Lyall, a
shipowner, and one of the Members for London; and, although it sat
during the whole Session, it reported that, from unforeseen
circumstances, it had been prevented from going fully into the
matter, and requested re-appointment in the following Session,
which was acceded to. But, as about this time, after a long period of
depression, prosperity returned to the shipping interest, employment
for ships having become better, while, in many important trades, the
rates of freight had advanced, the inquiry by the Committee, under
such auspicious circumstances, was allowed to drop. It was,
however, plain enough from the temper of Parliament, that no
recurrence would be permitted to anti-colonial protective measures.
The General Shipowners’ Society[31] attributed this
Reciprocity must prosperity to the guano trade, which had recently
lead to free
navigation.
arisen on the coast of Africa; but other and far
more influential causes had been at work. The
treaties of reciprocity had, with all their imperfections, no doubt,
tended materially to increase our intercourse with foreign nations,
while the admission of their ships to our own ports, strange as it
may appear, had greatly increased the employment for our own.
Though our shipowners resolutely denied that these measures had
anything whatever to do with the increased prosperity, more
enlightened men had arrived at entirely different conclusions, and
were convinced that the policy of reciprocity, however unsatisfactory
in many respects, was not merely a step in the right direction, but
was the best, and perhaps then the only, mode of breaking down,
bit by bit, the huge fabric of protection, the growth of more than two
centuries: indeed, it was clear that the “Great Maritime Charter of
England,” as the Act of Cromwell had been somewhat ostentatiously
denominated, could only be destroyed by degrees. This vast tree, if
it may be so described, had taken too deep root in the soil of
England to be overthrown at one blow; and the Reciprocity Treaties
undoubtedly served as wedges for its destruction.
In the meantime, Sir Robert Peel had made great changes in the
Tariff. Commencing with the coarser sorts of manufactures, he had
relinquished all duties on the importation of wool, linen, and cotton,
and had reduced the duties on the finer qualities of the same goods
from twenty to ten per cent., and on manufactured silks from thirty
to fifteen per cent., making equally important reductions in the
duties imposed on various other articles.
But a new class of men had now arisen to extend
New Class of the principles of Free-trade, and to force home the
Statesmen, well wedges of unfettered commerce with heavier
supported by
blows than Canning, Huskisson, or even Peel, had
the People
outside. ever done. The people, led in this instance by men
from among themselves, of the industrial classes;
and, guided by the voice of Wisdom, were now trumpet-tongued
proclaiming their rights and demanding justice, on conditions which,
however large, were yet so unanswerable, that, before long, the
proudest of our aristocracy and the most exalted of our statesmen
paid their homage to the “unadorned eloquence” resounding
throughout the land.
Though Lord John Russell, an honest adherent
Exertions of from his youth to the enlightened policy of Charles
Lord John James Fox, followed in their footsteps, and
Russell,
struggled onwards amid innumerable difficulties, it
was impossible for him to force his way, almost alone against the
class to which he belonged, and through the rank grass and tangled
brushwood which surrounded this huge old tree. Indeed, almost
every member of the ancient aristocracy except himself was opposed
to the course he had resolved to pursue; and although the
Parliamentary Reform Bill of 1832 carried on his motion, and, in a
great measure, by his early and unwearied exertions, had returned
to the House of Commons many men ready to render him every
assistance, the power of that House was still insufficient to effect, to
anything like the extent he had in view, the laudable and, indeed,
noble object of his ambition, a thoroughly unfettered commerce. On
the people, however, he could fully rely: they were now inquiring
more earnestly than they had ever done how it was that the food
necessary for their existence was so heavily taxed, and why they
were not allowed to buy that food where they pleased, and to import
it on the most economical terms. If their knowledge of geography, as
they were sometimes sneeringly told, extended no further than what
they had learned from the Sacred writings, that grand old historical
record taught them, that Egypt produced grain at less cost and in far
greater abundance, than England; so great, indeed, that its
granaries had once supplied the wants of Rome and of the Ancient
World. When, therefore, they learned that that grain could not be
had, because a comparatively small number of men—landowners
and shipowners—who, from their wealth, exercising great influence
in Parliament, were of opinion that the importation of food from
other and cheaper countries meant ruin to them, the people, in
mass, unequivocally desired to know, in a more detailed and more
satisfactory manner than they had hitherto been told, “the reasons
Why.” The question they had now asked, through their leaders, was
one which demanded an answer. First promulgated in the workshops
of Lancashire, it spread in all directions. It was whispered in
Belgravia; loudly proclaimed by the toiling millions; talked about by
the cottagers in every valley and by the shepherds on every hillside;
till, at length, it was adopted, in the most earnest manner, by the
middle classes, the bone and sinew of Great Britain.
With such overwhelming aid, Lord Russell and his
who leads the exploring party were enabled to penetrate the
way against dense forest of protection, and reach the roots of
Protection.
the huge and rank old tree, which not merely
overshadowed the rich soil of their native land, but spread its
branches over their seaports, so as to prevent the importation from
other lands of articles necessary for their existence. They saw that,
under its shadow, no herbs grew except such as, from their position,
were favoured by a ray of the hazy sunlight of protection; healthy
shrubs, luxuriant in their nature, withered and decayed wherever its
branches extended.
The chief of the new class of politicians, who had
Richard Cobden arisen was no common man: he was one whose
and the Anti- clear judgment, while it embraced existing wants,
Corn-Law
penetrated far into the future. Richard Cobden, the
League
son of a Sussex yeoman, and, practically, one of
themselves, who had been trained to commerce,[32] saw perhaps
more clearly than any one else the pernicious effects of all protective
laws. Supported by an overwhelming array of facts, he arranged
them in a manner so clear, and made them known in so pleasing and
homely a style of eloquence, as to command attention and carry
conviction to every man who was open to reason. In a word, he was
the first to thoroughly convince the people of Great Britain that they
had a right to be allowed to purchase the necessaries of life
wherever they could obtain them, and to dispose of their
manufactures wherever they could sell them, on the most
advantageous terms.
In directing the attention of the masses to this all-
John Bright. important question he sought the aid of men who
had sprung from the people and had been trained
to commerce; and he found many able and truly earnest colleagues,
but none more so than John Bright, a man of greater, though
perhaps not more convincing eloquence than his own, who like
himself had no object in view, as the whole experience of his life has
proved, than the good of his country. While Cobden and Bright
proclaimed, with overwhelming force, the policy of Charles James
Fox, which Huskisson and Canning had first practically put in
operation, and which Lord John Russell was now zealously pursuing
in Parliament,[33] an Association, under their leadership, was being
formed out of doors destined to give the fullest freedom to
commerce. The first object of the Anti-Corn-Law League was to
lower the price of bread, which with every deficient harvest
approached a famine price, and thus enable the working classes of
every grade to compete with greater prospects of success and to the
best advantage, in the production of those articles most in demand
in their own and other countries, and, at the same time, to secure
them more steady employment and a higher rate of wages. With this
object, its members set themselves heartily to work, proclaiming
their views at public meetings in almost every city and town in Great
Britain, and, in the course of their labours, making many converts to
their policy among the higher classes, among whom Charles Villiers
ought to take high rank, for he was unwearied in his exertions on
behalf of the people. Nor did they lack some associates among even
the shipowners of England, who, seeing that the free importation of
corn from other countries would afford greatly increased
employment for their ships, readily joined the league. It is certain,
however, that many of this class did not at the time perceive that,
though the immediate object of the association was to cut down the
chief branch of the huge old tree of protection, other branches, such
as those interfering with free navigation, must likewise be pulled
down as the supplement to free importation of corn: probably they
did not reflect that, should the Free-traders abolish the protection
then afforded to the proprietors of land, a protective system for the
maritime interest alone could no longer be maintained.
But an event happened which, although in itself a
Effect of the grievous national misfortune, brought about, at an
Irish famine, earlier period than might otherwise have been the
1845-6.
case, the abolition of the Corn Laws, as well as the
suspension, for a time, of the Navigation Laws. This calamity was
the failure of the potato crop in Ireland in 1845 by “a pestilence so
minute that it eluded the power of the finest microscope, so
mysterious that it defied the researches of the most searching
philosophy, but strong enough to overturn governments, general
enough to alter established commerce, powerful enough to cause
the migration of nations.”[34]
The whole crop of potatoes in Ireland having been destroyed, the
price of grain rose at one bound from 45s. 9d. to 60s. the quarter,
and Cabinet Councils assembled in November to consider the
propriety of throwing open the ports of the United Kingdom. As the
Cabinet was divided on the subject, Sir Robert Peel, impressed with
the dangers of the approaching crisis, resigned office, and Lord John
Russell, whose celebrated letter on that occasion must long be
remembered, was called upon to form a new Administration; but
personal jealousy among the Whigs[35]—a jealousy which lasted
many years—prevented the formation of a ministry by the opposition
party. Nor was Lord Stanley, who had been a member of Sir Robert
Peel’s Cabinet, more successful in a similar attempt: hence, with the
exception of his Lordship, the members of that Cabinet resumed
their former places.
On the 4th December, 1845, it was intimated through the ‘Times’
newspaper, which had for some months previously avoided the
question of total repeal, that Sir Robert Peel would propose the
entire abolition of the Corn Laws. The Queen’s speech, as well as the
speech of Sir Robert Peel on the Address, more distinctly announced
the policy of the reconstructed Administration, and, having called
attention to the measures of commercial reform already adopted,
which had tended so materially to the greatness of this country and
the welfare and happiness of its inhabitants,[36] he called on the
agriculturists to submit to some sacrifice on their part, proposing a
sliding-scale of duties on corn until February 1849, with the
condition, however, that wheat and other cereal produce should,
after that date, be imported from foreign countries at a duty of 1s. a
quarter.
It is not the province of this work to describe the
Sir Robert Peel struggles of parties during this momentous period,
carries the and it is therefore sufficient to state that the
Repeal of the
Corn Laws, and
measures of Sir Robert Peel, supported as they
resigns. were out of doors by the vigorous action of the
Anti-Corn-Law League, and in Parliament by the
Liberal party, were carried by large majorities through the Commons
and were, ultimately, passed by the Lords. But, meantime the Irish
Arms Bill had furnished the Opposition with a temporary accession of
members to defeat that measure, and consequently with the means
of overthrowing Sir Robert’s Administration, so that the night of his
triumph on the great question of the repeal of the Corn Laws was a
witness also of his downfall; and, in the records of the debates of
that ever-memorable evening, may be read the words now so
familiar to our ears:—“It may be,” he remarked, in his concluding
speech, “that I shall be sometimes remembered with good-will in
those places which are the abodes of men whose lot it is to labour
and earn their daily bread by the sweat of their brow; in such places,
perhaps, my name may be remembered with expressions of good-
will, when those who inhabit them recruit their exhausted strength
with abundant and untaxed food, the sweeter because no longer
leavened with the spirit of injustice.”

FOOTNOTES:
[23] In a little book, ‘Political Arithmetic,’ by Sir William Petty, written about 1675,
and published in 1691, the author of it remarks, “The extent of the shipping of
Europe being about two millions of tons, I suppose the English have five hundred
thousand—the Dutch nine hundred thousand, the French an hundred thousand,
the Hamburgers and the subjects of Dantzic two hundred and fifty, and Spain,
Portugal, Italy, &c., two hundred and fifty thousand!” the value of which the author
reckoned “at 8l. per tun” (ton).
[24] See a review of the ‘History of the Navigation Laws of England from the
Earliest Times,’ by a Barrister, a most able exposition, from the pen (I understand)
of Sir Stafford H. Northcote, Bart., now (1875) Chancellor of the Exchequer,
published by Ridgway, London, 1849.
[25] McPherson’s ‘Annals of Commerce,’ vol. iv. p. 26.
[26] See ante, vol. ii. p. 354.
[27] See Mr. Huskisson’s Speech on Colonial Policy, March 21, 1825.
[28] Hertslet’s Treaties.
[29] Appendix, No. I., p. 563.
[30] In 1814 there were entered inwards 1,290,248 tons of British shipping, and
599,287 tons of foreign shipping.
In 1824 there were entered inwards 1,797,320 tons of British shipping, and
759,441 tons of foreign shipping.
In 1846 there were entered inwards 4,294,733 tons of British shipping, and
1,806,282 tons of foreign shipping.
The clearances at the respective dates were about the same in amount and
proportion.
[31] See these Reports of 16th July, 1845.
[32] I first became intimate with Cobden in 1852, and our friendship continued
unbroken until his untimely death in 1865. He was the most agreeable companion,
and the most convincing reasoner I ever met. Though his name has long been a
household word, yet as his life has not been written (I hope it may soon be given
to the world), many of my readers may not be aware of his career as a man of
business. He was often my companion for days together where I now pen these
notes, and, though I possess many pleasing reminiscences in connexion with his
most useful life and numerous letters from him, for he had the pen of a ready
writer, I prefer leaving these to be dealt with by his biographer, when his executors
consider that the time has arrived to publish his life. But I think I ought not to
withhold from my readers the account he gave me of his commercial career, more
especially as an erroneous impression prevails in public that, though great as a
statesman, he was unsuccessful as a man of business. This letter referred to the
question of Limited Liability which we had frequently discussed. It is written in his
happiest style; and if I could to advantage (but I cannot), I would not alter a
single word. “It is singular,” he remarks in another letter of his now before me,
approving of some comments I had made, “how much better we all write when we
are expressing ourselves with unrestrained freedom to a friend, than when we are
polishing off our sentences for the great public. I find it always in my own case,
and the reason is simply that we are more natural, and therefore kindle a warmer
sympathy in the breast of the reader. It is this which makes the private memoirs
and correspondence of great men much more interesting than their public
performances.” For these reasons, I venture to give to the public the letter he
writes about himself and his business career unaltered, except where I have
omitted the names of two noble Lords still living.
“Midhurst, 24th March, 1856.
“My dear Lindsay,
“I can see no flaw in your indictment, and do not think there is a
shade of difference in our views upon partnership matters. But I
would rather talk than write to you on the subject. It has always
appeared to me that the fundamental fallacy which overrules all the
objections to limited liability is the fear that capitalists will not be able
to take care of their money without a little help from Parliament. I
think they may be safely trusted. You and I agree also in the practical
view of the question—that legislators and theorists overrate the
extent to which the actual possession of capital affords a guarantee to
the creditor. It is the character, experience, and connexions of the
man wanting credit, his knowledge of his business, and opportunities
of making it available in the struggle of life, that weigh with the
shrewd capitalists far more than the actual command of a few
thousands more or less of money in hand. I began business in
partnership with two other young men, and we only mustered a
thousand pounds amongst us, and more than half of it was borrowed.
We all got on the ‘Peveril of the Peak’ coach, and went from London
to Manchester in the, at that day, marvellously short space of twenty
hours. We were literally so ignorant of Manchester houses that we
called for a directory at the hotel, and turned to the list of ‘calico
printers,’ theirs being the business with which we were acquainted,
and they being the people from whom we felt confident we could
obtain credit. And why? Because we knew we should be able to
satisfy them that we had advantages from our large connexions, our
knowledge of the best branch of the business in London, and our
superior taste in design, which would insure success. We introduced
ourselves to Fort Brothers and Co., a rich house, and told our tale,
honestly concealing nothing. In less than two years from 1830 we
owed them forty thousand pounds for goods which they had sent to
us in Watling Street, upon no other security than our characters and
knowledge of our business. I frequently talked with them in later
times upon the great confidence they showed in men who avowed
that they were not possessed of 200l. each. Their answer was that
they would always prefer to trust young men with connexions and
with a knowledge of their trade, if they knew them to possess
character and ability, to those who started with capital without these
advantages, and that they had acted on this principle successfully in
all parts of the world. We did not disappoint them or ourselves. In
1834-1835 our stock takings showed a net balance of 20,000l. a year
profit. Then I began to write pamphlets and to talk politics, and from
that moment I ceased to make money, and in 1846, when the League
finished its labours, my children must have been beggars, had not my
neighbours, who knew my circumstances, originated the subscription
which restored me independence. I took the money without shame,
because I had earned it. If money had been my sole object in life I
should have been a more successful man by sticking to my calicoes,
for my partners have grown richer than I by doing so, and young men
taken into the concern since I left have made fortunes. I may add that
the original formation of the partnership, and the whole scheme of
the business, sprung exclusively from myself. But what has this to do
with your bill? I never detect myself falling into a twaddle about
things personal and past without suspecting that I am growing old
and garrulous. I doubt the policy of your presenting a bill to the
House. Your strength lies in your principle—perfect freedom—which
you can argue with more force when not compelled to enter upon
details. If you have any suggestions as to the clauses of the Bill,
would it not be better to do as you did with the Shipping Bill by giving
the Board of Trade the benefit of your hints? It may be necessary to
concede something for the sake of carrying any measure, but I doubt
whether any concession, beyond a registration, which may be shown
to be a convenience to all parties, will not be unsoundness. If it be
necessary to tamper with sound principles for the sake of pleasing the
Lords, let the proposal come from their party. I suspect we shall be
weaker in both Houses in dealing with the question of private
partnership upon free-trade principles than with that of Joint Stock
Associations. Upon the latter question, people of the —— and ——
school of political economy, whose principles are, if pushed home, a
little socialistic, took a great interest, because they have an amiable
faith in the power of association amongst the working classes. But I
doubt whether they will throw much zeal into the question of private
partnership. By the way, don’t put the question in the House in the
form of a problem A. B. C. D. &c. It does in a written argument, and
even then demands a severe attention; but I find that that mode of
stating the case in the House does not succeed.
“I shall be happy to renew the discussion when we meet, and remain
very sincerely yours,
“Rd. Cobden.”
[33] Though not within the province of this work, it should be remembered that
Fox stoutly opposed Pitt’s great Free-trade Treaty with France, in 1756, and that
Lord John Russell did not come out as a thorough and earnest Free-trader until
1840-41.
[34] Alison’s ‘History of Europe,’ vol. vii. p. 168.
[35] This difference reached its climax in 1845, when Lord Grey wished to exclude
Lord Palmerston from the Foreign Office, and Lord Russell insisted on his being
nominated for that department.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like