100% found this document useful (2 votes)
97 views68 pages

AI and Machine Learning for Coders A Programmer s Guide to Artificial Intelligence 1st Edition Laurence Moroney instant download

The document provides information about the book 'AI and Machine Learning for Coders' by Laurence Moroney, which serves as a practical guide for programmers to learn about artificial intelligence and machine learning using TensorFlow. It includes praise from various professionals highlighting its effectiveness in teaching ML concepts through coding examples rather than theoretical math. Additionally, it lists other related resources and books available for download on the same platform.

Uploaded by

joyalpruttbm
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)
97 views68 pages

AI and Machine Learning for Coders A Programmer s Guide to Artificial Intelligence 1st Edition Laurence Moroney instant download

The document provides information about the book 'AI and Machine Learning for Coders' by Laurence Moroney, which serves as a practical guide for programmers to learn about artificial intelligence and machine learning using TensorFlow. It includes praise from various professionals highlighting its effectiveness in teaching ML concepts through coding examples rather than theoretical math. Additionally, it lists other related resources and books available for download on the same platform.

Uploaded by

joyalpruttbm
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/ 68

AI and Machine Learning for Coders A Programmer

s Guide to Artificial Intelligence 1st Edition


Laurence Moroney download

https://textbookfull.com/product/ai-and-machine-learning-for-
coders-a-programmer-s-guide-to-artificial-intelligence-1st-
edition-laurence-moroney/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Artificial Intelligence and Machine Learning for


Business: A No-Nonsense Guide to Data Driven
Technologies Steven Finlay

https://textbookfull.com/product/artificial-intelligence-and-
machine-learning-for-business-a-no-nonsense-guide-to-data-driven-
technologies-steven-finlay/

Artificial Intelligence and Machine Learning for


Business for Non-Engineers 1st Edition Stephan S. Jones
(Editor)

https://textbookfull.com/product/artificial-intelligence-and-
machine-learning-for-business-for-non-engineers-1st-edition-
stephan-s-jones-editor/

Cracking the Code: Introduction to Machine Learning for


Novices: Building a Foundation for Artificial
Intelligence 1st Edition Sarah Parker

https://textbookfull.com/product/cracking-the-code-introduction-
to-machine-learning-for-novices-building-a-foundation-for-
artificial-intelligence-1st-edition-sarah-parker/

Agriculture 5.0: Artificial Intelligence, IoT and


Machine Learning 1st Edition Latief Ahmad

https://textbookfull.com/product/agriculture-5-0-artificial-
intelligence-iot-and-machine-learning-1st-edition-latief-ahmad/
Artificial Intelligence With an Introduction to Machine
Learning 2nd Edition Richard E. Neapolitan

https://textbookfull.com/product/artificial-intelligence-with-an-
introduction-to-machine-learning-2nd-edition-richard-e-
neapolitan/

MATLAB Deep Learning: With Machine Learning, Neural


Networks and Artificial Intelligence 1st Edition Phil
Kim

https://textbookfull.com/product/matlab-deep-learning-with-
machine-learning-neural-networks-and-artificial-intelligence-1st-
edition-phil-kim/

Artificial Intelligence for Business: What You Need to


Know about Machine Learning and Neural Networks Doug
Rose

https://textbookfull.com/product/artificial-intelligence-for-
business-what-you-need-to-know-about-machine-learning-and-neural-
networks-doug-rose/

Oracle Business Intelligence with Machine Learning :


Artificial Intelligence Techniques in OBIEE for
Actionable BI 1st Edition Rosendo Abellera

https://textbookfull.com/product/oracle-business-intelligence-
with-machine-learning-artificial-intelligence-techniques-in-
obiee-for-actionable-bi-1st-edition-rosendo-abellera/

The Definitive Guide to Firebase: Build Android Apps on


Google's Mobile Platform 1st Edition Laurence Moroney
(Auth.)

https://textbookfull.com/product/the-definitive-guide-to-
firebase-build-android-apps-on-googles-mobile-platform-1st-
edition-laurence-moroney-auth/
Praise for AI and Machine Learning for Coders

“Machine learning should be in the toolbox of every great engineer in this coming decade.
For people looking to get started, AI and Machine Learning for Coders by Laurence
Moroney is the much-needed practical starting point to dive deep into
deep learning, computer vision, and NLP.”
—Dominic Monn, Machine Learning at Doist

“The book is a great introduction to understand and practice machine learning and
artificial intelligence models by using TensorFlow. It covers various deep learning models,
and their practical applications, as well as how to utilize TensorFlow framework to
develop and deploy ML/AI applications across platforms. I recommend it
for anyone who is interested in ML and AI practice.”
—Jialin Huang PhD, Data and Applied Scientist at Microsoft

“Laurence’s book helped me refresh TensorFlow framework and Coursera Specialization,


and motivated me to take the certification provided by Google. If you have time and
you are willing to embark to an ML journey, this book is a
starting point from the practice side.”
—Laura Uzcátegui, Software Engineer

“This book is a must-read for developers who would like to get into AI/ML.
You will learn a variety of examples by coding instead of math equations.”
—Margaret Maynard-Reid, ML Google Developer Expert

“A practical handbook to have on your desk for implementing deep learning models.”
—Pin-Yu Chen, Research Staff Member at IBM Research AI
“A fun book to read and practice coding for AI and machine learning projects. Intuitive
wording and graphs to explain the nonintuitive concepts and algorithms. Cool coding
examples to teach you key building blocks for AI and ML. In the end, you can code
AI projects for your PC program, Android, iOS and Browser!”
—Su Fu, CEO of Alchemist
AI and Machine Learning
for Coders
A Programmer’s Guide to Artificial Intelligence

Laurence Moroney

Beijing Boston Farnham Sebastopol Tokyo


AI and Machine Learning for Coders
by Laurence Moroney
Copyright © 2021 Laurence Moroney. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional
sales department: 800-998-9938 or [email protected].

Acquisitions Editor: Rebecca Novack Indexer: Judith McConville


Development Editor: Angela Rufino Interior Designer: David Futato
Production Editor: Katherine Tozer Cover Designer: Karen Montgomery
Copyeditor: Rachel Head Illustrator: O’Reilly Media, Inc.
Proofreader: Piper Editorial, LLC

October 2020: First Edition

Revision History for the First Edition


2020-10-01: First Release

See http://oreilly.com/catalog/errata.csp?isbn=9781492078197 for release details.

The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. AI and Machine Learning for Coders,
the cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
The views expressed in this work are those of the author, and do not represent the publisher’s views.
While the publisher and the author have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the author disclaim all responsibility
for errors or omissions, including without limitation responsibility for damages resulting from the use of
or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.

978-1-492-07819-7
[LSI]
Table of Contents

Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv

Part I. Building Models


1. Introduction to TensorFlow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
What Is Machine Learning? 1
Limitations of Traditional Programming 3
From Programming to Learning 5
What Is TensorFlow? 7
Using TensorFlow 8
Installing TensorFlow in Python 9
Using TensorFlow in PyCharm 9
Using TensorFlow in Google Colab 12
Getting Started with Machine Learning 13
Seeing What the Network Learned 18
Summary 19

2. Introduction to Computer Vision. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21


Recognizing Clothing Items 21
The Data: Fashion MNIST 22
Neurons for Vision 23
Designing the Neural Network 25
The Complete Code 26
Training the Neural Network 29

v
Exploring the Model Output 29
Training for Longer—Discovering Overfitting 30
Stopping Training 30
Summary 32

3. Going Beyond the Basics: Detecting Features in Images. . . . . . . . . . . . . . . . . . . . . . . . . 33


Convolutions 34
Pooling 35
Implementing Convolutional Neural Networks 37
Exploring the Convolutional Network 39
Building a CNN to Distinguish Between Horses and Humans 42
The Horses or Humans Dataset 42
The Keras ImageDataGenerator 43
CNN Architecture for Horses or Humans 45
Adding Validation to the Horses or Humans Dataset 47
Testing Horse or Human Images 49
Image Augmentation 52
Transfer Learning 55
Multiclass Classification 59
Dropout Regularization 63
Summary 65

4. Using Public Datasets with TensorFlow Datasets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67


Getting Started with TFDS 68
Using TFDS with Keras Models 70
Loading Specific Versions 73
Using Mapping Functions for Augmentation 73
Using TensorFlow Addons 74
Using Custom Splits 74
Understanding TFRecord 76
The ETL Process for Managing Data in TensorFlow 78
Optimizing the Load Phase 80
Parallelizing ETL to Improve Training Performance 81
Summary 83

5. Introduction to Natural Language Processing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85


Encoding Language into Numbers 85
Getting Started with Tokenization 86
Turning Sentences into Sequences 87
Removing Stopwords and Cleaning Text 91
Working with Real Data Sources 93

vi | Table of Contents
Getting Text from TensorFlow Datasets 93
Getting Text from CSV Files 97
Getting Text from JSON Files 99
Summary 101

6. Making Sentiment Programmable Using Embeddings. . . . . . . . . . . . . . . . . . . . . . . . . 103


Establishing Meaning from Words 103
A Simple Example: Positives and Negatives 104
Going a Little Deeper: Vectors 105
Embeddings in TensorFlow 106
Building a Sarcasm Detector Using Embeddings 106
Reducing Overfitting in Language Models 109
Using the Model to Classify a Sentence 119
Visualizing the Embeddings 120
Using Pretrained Embeddings from TensorFlow Hub 123
Summary 125

7. Recurrent Neural Networks for Natural Language Processing. . . . . . . . . . . . . . . . . . . 127


The Basis of Recurrence 127
Extending Recurrence for Language 130
Creating a Text Classifier with RNNs 132
Stacking LSTMs 134
Using Pretrained Embeddings with RNNs 139
Summary 146

8. Using TensorFlow to Create Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147


Turning Sequences into Input Sequences 148
Creating the Model 152
Generating Text 154
Predicting the Next Word 154
Compounding Predictions to Generate Text 155
Extending the Dataset 156
Changing the Model Architecture 157
Improving the Data 158
Character-Based Encoding 161
Summary 162

9. Understanding Sequence and Time Series Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163


Common Attributes of Time Series 165
Trend 165
Seasonality 165

Table of Contents | vii


Autocorrelation 166
Noise 166
Techniques for Predicting Time Series 167
Naive Prediction to Create a Baseline 167
Measuring Prediction Accuracy 170
Less Naive: Using Moving Average for Prediction 170
Improving the Moving Average Analysis 171
Summary 172

10. Creating ML Models to Predict Sequences. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173


Creating a Windowed Dataset 174
Creating a Windowed Version of the Time Series Dataset 176
Creating and Training a DNN to Fit the Sequence Data 178
Evaluating the Results of the DNN 179
Exploring the Overall Prediction 181
Tuning the Learning Rate 183
Exploring Hyperparameter Tuning with Keras Tuner 185
Summary 189

11. Using Convolutional and Recurrent Methods for Sequence Models. . . . . . . . . . . . . . 191
Convolutions for Sequence Data 191
Coding Convolutions 192
Experimenting with the Conv1D Hyperparameters 195
Using NASA Weather Data 198
Reading GISS Data in Python 199
Using RNNs for Sequence Modeling 200
Exploring a Larger Dataset 203
Using Other Recurrent Methods 205
Using Dropout 206
Using Bidirectional RNNs 209
Summary 211

Part II. Using Models


12. An Introduction to TensorFlow Lite. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
What Is TensorFlow Lite? 215
Walkthrough: Creating and Converting a Model to TensorFlow Lite 217
Step 1. Save the Model 218
Step 2. Convert and Save the Model 219
Step 3. Load the TFLite Model and Allocate Tensors 219

viii | Table of Contents


Step 4. Perform the Prediction 220
Walkthrough: Transfer Learning an Image Classifier and Converting to
TensorFlow Lite 222
Step 1. Build and Save the Model 222
Step 2. Convert the Model to TensorFlow Lite 223
Step 3. Optimize the Model 225
Summary 227

13. Using TensorFlow Lite in Android Apps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229


What Is Android Studio? 229
Creating Your First TensorFlow Lite Android App 230
Step 1. Create a New Android Project 230
Step 2. Edit Your Layout File 232
Step 3. Add the TensorFlow Lite Dependencies 234
Step 4. Add Your TensorFlow Lite Model 236
Step 5. Write the Activity Code to Use TensorFlow Lite for Inference 236
Moving Beyond “Hello World”—Processing Images 239
TensorFlow Lite Sample Apps 242
Summary 244

14. Using TensorFlow Lite in iOS Apps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245


Creating Your First TensorFlow Lite App with Xcode 245
Step 1. Create a Basic iOS App 245
Step 2. Add TensorFlow Lite to Your Project 247
Step 3. Create the User Interface 248
Step 4. Add and Initialize the Model Inference Class 250
Step 5. Perform the Inference 253
Step 6. Add the Model to Your App 254
Step 7. Add the UI Logic 256
Moving Beyond “Hello World”—Processing Images 258
TensorFlow Lite Sample Apps 261
Summary 261

15. An Introduction to TensorFlow.js. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263


What Is TensorFlow.js? 263
Installing and Using the Brackets IDE 265
Building Your First TensorFlow.js Model 266
Creating an Iris Classifier 270
Summary 274

Table of Contents | ix
16. Coding Techniques for Computer Vision in TensorFlow.js. . . . . . . . . . . . . . . . . . . . . . . 275
JavaScript Considerations for TensorFlow Developers 276
Building a CNN in JavaScript 277
Using Callbacks for Visualization 279
Training with the MNIST Dataset 282
Running Inference on Images in TensorFlow.js 288
Summary 288

17. Reusing and Converting Python Models to JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . 291


Converting Python-Based Models to JavaScript 291
Using the Converted Models 293
Using Preconverted JavaScript Models 295
Using the Toxicity Text Classifier 295
Using MobileNet for Image Classification in the Browser 298
Using PoseNet 301
Summary 304

18. Transfer Learning in JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305


Transfer Learning from MobileNet 306
Step 1. Download MobileNet and Identify the Layers to Use 306
Step 2. Create Your Own Model Architecture with the Outputs from
MobileNet as Its Input 308
Step 3. Gather and Format the Data 310
Step 4. Train the Model 316
Step 5. Run Inference with the Model 317
Transfer Learning from TensorFlow Hub 319
Using Models from TensorFlow.org 322
Summary 324

19. Deployment with TensorFlow Serving. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327


What Is TensorFlow Serving? 327
Installing TensorFlow Serving 330
Installing Using Docker 330
Installing Directly on Linux 331
Building and Serving a Model 332
Exploring Server Configuration 335
Summary 338

20. AI Ethics, Fairness, and Privacy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339


Fairness in Programming 340
Fairness in Machine Learning 343

x | Table of Contents
Tools for Fairness 345
The What-If Tool 345
Facets 346
Federated Learning 349
Step 1. Identify Available Devices for Training 349
Step 2. Identify Suitable Available Devices for Training 350
Step 3. Deploy a Trainable Model to Your Training Set 350
Step 4. Return the Results of the Training to the Server 351
Step 5. Deploy the New Master Model to the Clients 351
Secure Aggregation with Federated Learning 352
Federated Learning with TensorFlow Federated 353
Google’s AI Principles 354
Summary 355

Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357

Table of Contents | xi
Foreword

Dear Reader,
AI is poised to transform every industry, but almost every AI application needs to be
customized for its particular use. A system for reading medical records is different
from one for finding defects in a factory, which is different from a product recom‐
mendation engine. For AI to reach its full potential, engineers need tools that can
help them adapt the amazing capabilities available to the millions of concrete prob‐
lems we wish to solve.
When I led the Google Brain team, we started to build the C++ precursor to
TensorFlow called DistBelief. We were excited about the potential of harnessing thou‐
sands of CPUs to train a neural network (for instance, using 16,000 CPUs to train a
cat detector on unlabeled YouTube videos). How far deep learning has come since
then! What was once cutting-edge can now be done for around $3,000 of cloud com‐
puting credits, and Google routinely trains neural networks using TPUs and GPUs at
a scale that was unimaginable just years ago.
TensorFlow, too, has come a long way. It is far more usable than what we had in the
early days, and has rich features ranging from modeling, to using pretrained models,
to deploying on low-compute edge devices. It is today empowering hundreds of thou‐
sands of developers to build their own deep learning models.
Laurence Moroney, as Google’s lead AI Advocate, has been a major force in building
TensorFlow into one of the world’s leading AI frameworks. I was privileged to sup‐
port his teaching TensorFlow with deeplearning.ai and Coursera. These courses have
reached over 80,000 learners and received numerous glowing reviews.
One unexpected aspect of friendship with Laurence is that he is also a free source of
Irish poetry. He once Slacked me:

xiii
Andrew sang a sad old song
fainted through miss milliner
invitation hoops
fainted fainted
[...]
He had trained an LSTM on lyrics of traditional Irish songs and it generated these
lines. If AI opens the door to fun like that, how could anyone not want to get
involved? You can (i) work on exciting projects that move humanity forward, (ii)
advance your career, and (iii) get free Irish poetry.
I wish you the best in your journey learning TensorFlow. With Laurence as a teacher,
great adventures await you.
Keep learning,

— Andrew Ng
Founder, deeplearning.ai

xiv | Foreword
Preface

Welcome to AI and Machine Learning for Coders, a book that I’ve been wanting to
write for many years but that has only really become possible due to recent advances
in machine learning (ML) and, in particular, TensorFlow. The goal of this book is to
prepare you, as a coder, for many of the scenarios that you can address with machine
learning, with the aim of equipping you to be an ML and AI developer without need‐
ing a PhD! I hope that you’ll find it useful, and that it will empower you with the con‐
fidence to get started on this wonderful and rewarding journey.

Who Should Read This Book


If you’re interested in AI and ML, and you want to get up and running quickly with
building models that learn from data, this book is for you. If you’re interested in get‐
ting started with common AI and ML concepts—computer vision, natural language
processing, sequence modeling, and more—and want to see how neural networks can
be trained to solve problems in these spaces, I think you’ll enjoy this book. And if you
have models that you’ve trained and want to get them into the hands of users on
mobile, in the browser, or via the cloud, then this book is also for you!
Most of all, if you’ve been put off entering this valuable area of computer science
because of perceived difficulty, in particular believing that you’ll need to dust off your
old calculus books, then fear not: this book takes a code-first approach that shows
you just how easy it is to get started in the world of machine learning and artificial
intelligence using Python and TensorFlow.

Why I Wrote This Book


I first got seriously involved with artificial intelligence in the spring of 1992. A freshly
minted physics graduate living in London in the midst of a terrible recession, I had
been unemployed for six months. The British government started a program to train
20 people in AI technology, and put out a call for applicants. I was the first

xv
participant selected. Three months later, the program failed miserably, because while
there was plenty of theoretical work that could be done with AI, there was no easy way
to do it practically. One could write simple inference in a language called Prolog, and
perform list processing in a language called Lisp, but there was no clear path to
deploying them in industry. The famous “AI winter” followed.
Then, in 2016, while I was working at Google on a product called Firebase, the com‐
pany offered machine learning training to all engineers. I sat in a room with a num‐
ber of other people and listened to lectures about calculus and gradient descent. I
couldn’t quite match this to a practical implementation of ML, and I was suddenly
transported back to 1992. I brought feedback about this, and about how we should
educate people in ML, to the TensorFlow team—and they hired me in 2017. With the
release of TensorFlow 2.0 in 2018, and in particular the emphasis on high-level APIs
that made it easy for developers to get started, I realized the need was there for a book
that took advantage of this, and widened access to ML so that it wasn’t just for mathe‐
maticians or PhDs anymore.
I believe that more people using this technology and deploying it to end users will
lead to an explosion in AI and ML that will prevent another AI winter, and change
the world very much for the better. I’m already seeing the impact of this, from the
work done by Google on diabetic retinopathy, through Penn State University and
PlantVillage building an ML model for mobile that helps farmers diagnose cassava
disease, Médecins Sans Frontières using TensorFlow models to help diagnose antibi‐
otic resistance, and much, much more!

Navigating This Book


The book is written in two main parts. Part I (Chapters 1–11) talks about how to use
TensorFlow to build machine learning models for a variety of scenarios. It takes you
from first principles—building a model with a neural network containing only one
neuron—through computer vision, natural language processing, and sequence mod‐
eling. Part II (Chapters 12–20) then walks you through scenarios for putting your
models in people’s hands on Android and iOS, in browsers with JavaScript, and serv‐
ing via the cloud. Most chapters are standalone, so you can drop in and learn some‐
thing new, or, of course, you could just read the book cover to cover.

Technology You Need to Understand


The goal of the first half of the book is to help you learn how to use TensorFlow to
build models with a variety of architectures. The only real prerequisite to this is
understanding Python, and in particular Python notation for data and array process‐
ing. You might also want to explore Numpy, a Python library for numeric
calculations. If you have no familiarity with these, they are quite easy to learn, and

xvi | Preface
you can probably pick up what you need as you go along (although some of the array
notation might be a bit hard to grasp).
For the second half of the book, I generally will not teach the languages that are
shown, but instead show how TensorFlow models can be used in them. So, for exam‐
ple, in the Android chapter (Chapter 13) you’ll explore building apps in Kotlin with
Android studio, and in the iOS chapter (Chapter 14) you’ll explore building apps in
Swift with Xcode. I won’t be teaching the syntax of these languages, so if you aren’t
familiar with them, you may need a primer—Learning Swift by Jonathan Manning,
Paris Buttfield-Addison, and Tim Nugent (O’Reilly) is a great choice.

Online Resources
A variety of online resources are used by, and supported in, this book. At the very
least I would recommend that you keep an eye on TensorFlow and its associated You‐
Tube channel for any updates and breaking changes to technologies discussed in the
book.
The code for this book is available at https://github.com/lmoroney/tfbook, and I will
keep it up to date there as the platform evolves.

Conventions Used in This Book


The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program ele‐
ments such as variable or function names, data types, environment variables,
statements, and keywords.
Constant width bold
Used for emphasis in code snippets.

This element signifies a note.

Preface | xvii
Using Code Examples
This book is here to help you get your job done. In general, if example code is offered
with this book, you may use it in your programs and documentation. You do not
need to contact us for permission unless you’re reproducing a significant portion of
the code. For example, writing a program that uses several chunks of code from this
book does not require permission. Selling or distributing examples from O’Reilly
books does require permission. Answering a question by citing this book and quoting
example code does not require permission. Incorporating a significant amount of
example code from this book into your product’s documentation does require
permission.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: “AI and Machine Learning for Coders,
by Laurence Moroney. Copyright 2021 Laurence Moroney, 978-1-492-07819-7.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at [email protected].

O’Reilly Online Learning


For more than 40 years, O’Reilly Media has provided technol‐
ogy and business training, knowledge, and insight to help
companies succeed.

Our unique network of experts and innovators share their knowledge and expertise
through books, articles, and our online learning platform. O’Reilly’s online learning
platform gives you on-demand access to live training courses, in-depth learning
paths, interactive coding environments, and a vast collection of text and video from
O’Reilly and 200+ other publishers. For more information, visit http://oreilly.com.

How to Contact Us
Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.


1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

xviii | Preface
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at https://oreil.ly/ai-ml.
Email [email protected] to comment or ask technical questions about this
book.
For news and information about our books and courses, visit http://oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments
I’d like to thank lots of people who have helped in the creation of this book.
Jeff Dean, who gave me the opportunity to be part of the TensorFlow team, beginning
the second phase of my AI journey. There’s also the rest of the team, and while there
are too many to name, I’d like to call out Sarah Sirajuddin, Megan Kacholia, Martin
Wicke, and Francois Chollet for their amazing leadership and engineering!
The developer relations team for TensorFlow, led by Kemal El Moujahid, Magnus
Hyttsten, and Wolff Dobson, who create the platform for people to learn AI and ML
with TensorFlow.
Andrew Ng, who, as well as writing the Foreword for this book, also believed in my
approach to teaching TensorFlow, and with whom I created three specializations at
Coursera, teaching hundreds of thousands of people how to succeed with machine
learning and AI. Andrew also leads a team at deeplearning.ai who were terrific at
helping me be a better machine learner, including Ortal Arel, Eddy Shu, and Ryan
Keenan.
The team at O’Reilly that made this book possible: Rebecca Novack and Angela
Rufino, without whose hard work I never would have gotten it done!
The amazing tech review team: Jialin Huang, Laura Uzcátegui, Lucy Wong, Margaret
Maynard-Reid, Su Fu, Darren Richardson, Dominic Monn, and Pin-Yu.
And of course, most important of all (even more than Jeff and Andrew ;) ) is my fam‐
ily, who make the most important stuff meaningful: my wife Rebecca Moroney, my
daughter Claudia Moroney, and my son Christopher Moroney. Thanks to you all for
making life more amazing than I ever thought it could be.

Preface | xix
PART I
Building Models
CHAPTER 1
Introduction to TensorFlow

When it comes to creating artificial intelligence (AI), machine learning (ML) and
deep learning are a great place to begin. When getting started, however, it’s easy to get
overwhelmed by the options and all the new terminology. This book aims to demys‐
tify things for programmers, taking you through writing code to implement concepts
of machine learning and deep learning; and building models that behave more as a
human does, with scenarios like computer vision, natural language processing (NLP),
and more. Thus, they become a form of synthesized, or artificial, intelligence.
But when we refer to machine learning, what in fact is this phenomenon? Let’s take a
quick look at that, and consider it from a programmer’s perspective before we go any
further. After that, this chapter will show you how to install the tools of the trade,
from TensorFlow itself to environments where you can code and debug your Tensor‐
Flow models.

What Is Machine Learning?


Before we get into the ins and outs of ML, let’s consider how it evolved from tradi‐
tional programming. We’ll start by examining what traditional programming is, then
consider cases where it is limited. Then we’ll see how ML evolved to handle those
cases, and as a result has opened up new opportunities to implement new scenarios,
unlocking many of the concepts of artificial intelligence.
Traditional programming involves us writing rules, expressed in a programming lan‐
guage, that act on data and give us answers. This applies just about everywhere that
something can be programmed with code.
For example, consider a game like the popular Breakout. Code determines the move‐
ment of the ball, the score, and the various conditions for winning or losing the game.
Think about the scenario where the ball bounces off a brick, like in Figure 1-1.

1
Figure 1-1. Code in a Breakout game

Here, the motion of the ball can be determined by its dx and dy properties. When it
hits a brick, the brick is removed, and the velocity of the ball increases and changes
direction. The code acts on data about the game situation.
Alternatively, consider a financial services scenario. You have data about a company’s
stock, such as its current price and current earnings. You can calculate a valuable ratio
called the P/E (for price divided by earnings) with code like that in Figure 1-2.

Figure 1-2. Code in a financial services scenario

Your code reads the price, reads the earnings, and returns a value that is the former
divided by the latter.

2 | Chapter 1: Introduction to TensorFlow


If I were to try to sum up traditional programming like this into a single diagram, it
might look like Figure 1-3.

Figure 1-3. High-level view of traditional programming

As you can see, you have rules expressed in a programming language. These rules act
on data, and the result is answers.

Limitations of Traditional Programming


The model from Figure 1-3 has been the backbone of development since its incep‐
tion. But it has an inherent limitation: namely, that only scenarios that can be imple‐
mented are ones for which you can derive rules. What about other scenarios? Usually,
they are infeasible to develop because the code is too complex. It’s just not possible to
write code to handle them.
Consider, for example, activity detection. Fitness monitors that can detect our activity
are a recent innovation, not just because of the availability of cheap and small hard‐
ware, but also because the algorithms to handle detection weren’t previously feasible.
Let’s explore why.
Figure 1-4 shows a naive activity detection algorithm for walking. It can consider the
person’s speed. If it’s less than a particular value, we can determine that they are prob‐
ably walking.

Figure 1-4. Algorithm for activity detection

Limitations of Traditional Programming | 3


Given that our data is speed, we could extend this to detect if they are running
(Figure 1-5).

Figure 1-5. Extending the algorithm for running

As you can see, going by the speed, we might say if it is less than a particular value
(say, 4 mph) the person is walking, and otherwise they are running. It still sort of
works.
Now suppose we want to extend this to another popular fitness activity, biking. The
algorithm could look like Figure 1-6.

Figure 1-6. Extending the algorithm for biking

I know it’s naive in that it just detects speed—some people run faster than others, and
you might run downhill faster than you cycle uphill, for example. But on the whole, it
still works. However, what happens if we want to implement another scenario, such as
golfing (Figure 1-7)?

4 | Chapter 1: Introduction to TensorFlow


Figure 1-7. How do we write a golfing algorithm?

We’re now stuck. How do we determine that someone is golfing using this methodol‐
ogy? The person might walk for a bit, stop, do some activity, walk for a bit more, stop,
etc. But how can we tell this is golf?
Our ability to detect this activity using traditional rules has hit a wall. But maybe
there’s a better way.
Enter machine learning.

From Programming to Learning


Let’s look back at the diagram that we used to demonstrate what traditional program‐
ming is (Figure 1-8). Here we have rules that act on data and give us answers. In our
activity detection scenario, the data was the speed at which the person was moving;
from that we could write rules to detect their activity, be it walking, biking, or run‐
ning. We hit a wall when it came to golfing, because we couldn’t come up with rules
to determine what that activity looks like.

Figure 1-8. The traditional programming flow

But what would happen if we were to flip the axes around on this diagram? Instead of
us coming up with the rules, what if we were to come up with the answers, and along
with the data have a way of figuring out what the rules might be?
Figure 1-9 shows what this would look like. We can consider this high-level diagram
to define machine learning.

From Programming to Learning | 5


Another Random Scribd Document
with Unrelated Content
what good cause he had for taking such a step; he was used to such
childish folly, and did not allow it to trouble him in the least.
Nevertheless, there is no doubt that nothing would have pleased him
more; but, as a prudent man, he did not wish to cut himself adrift
from Salzburg before having secured a safe anchorage at Munich.
After enjoying to their close the pleasures of the Carnival, which
lasted too long for the father, they returned to Salzburg on March
7,1775. In April the Archbishop of Salzburg was honoured by a visit
from the Archduke Maximilian, youngest son of Maria Theresa (b.
1749), afterwards Archbishop of Cologne; he had been spending the
Carnival in Paris, where his want of tact had placed the Queen in
considerable embarrassment,13 and had also paid a short visit to
Munich. Court festivities were arranged, chiefly consisting of musical
performances, for which the singer Consuoli and Becke, the flautist,
were summoned from Munich. A serenata by Fischietti was
performed on April 22, and on the following day Mozart's "Re
Pastore," which had been very hurriedly composed. On April 24,
according to the report of one of the Archduke's suite, "Music was
the entertainment provided, as on the preceding days; at the
conclusion of the performance, young Mozart placed himself at the
piano and played various pieces from his head, with equal skill and
grace." Whether he appeared as a violinist we do not know; he had,
at any rate, composed his first violin concerto on April 14 (207 K.),
and the fact that this was followed by four others in the same year
(211, 216, 218, 219, K.) is a proof that he was applying himself
energetically to the violin; possibly because it would be easier to find
a good situation if he were an accomplished violin-player.
The next two years passed quietly and busily at Salzburg. Extracts
from a diary kept by young Schiedenhofen show how limited their
CHURCH MUSIC circle of friendly intercourse was, and Wolfgang's
—"HAFFNER-
MUSIK," 1776.
authentically dated compositions afford proofs of
his activity and progress.
The year 1776 was especially rich in church music; four masses
(257, 258, 259,261, K.) fall in this year, three of them in its last
quarter, while in March a Grand Litany in E flat major (243 K.) was
written, besides an Offertory, "Venite populi," for two choirs (260 K.).
To 1777 belong a Mass (275 K.), and a Graduale, "Sancta Maria"
(273 K.). A series of organ sonatas were furnished for the services of
the church, and for the court a number of divertimenti for wind
instruments, probably as table music. In other respects, doubtless in
consequence of the ill-will of the Archbishop, Wolfgang appears to
have held aloof from the court concerts; no symphonies belong to
this time. The serenatas were written for other occasions. On
wedding-days, fête-days, or the like, these nocturnal pieces were
usually performed in the street, not excepting the solos;14 they
were introduced by a march, in which any of the company who could
handle a bow might take part; the rest listened from the windows
above. Such music was either ordered and paid for, or offered as a
tribute of esteem.
On the wedding-day of the Salzburg citizen F. X. Spath with Elise
Haffher, daughter of the worthy merchant and Bürgermeister
Sigmund Haffner15 (July 22,1776), a serenata by Mozart was
performed, afterwards known as the "Haffner-musik" (249, 250, K.).
Another opportunity offered in the fête-day of the Countess Antonia
Lodron, for whom in 1776 and 1777 Wolfgang wrote several
specified nocturnes;16 Schiedenhofen was present at the rehearsal
of one of them, and he tells us also that on July 25, 1777, there was
a rehearsal of a serenata at the house of the grocer Gusetti,
composed by Wolfgang for his sister's fête-day; it consisted of a
symphony, a violin concerto played by himself, and a flute concerto
played by Cosel. Probably the divertimento composed in July, 1776
(251 K.) was also intended for his sister's fête-day. A Finalmusik
(185, 215, K.) produced on August 23, 1775, and a "Serenata
Nottuma" (239 K.) in January, 1776, are both for unknown
occasions.
The clavier compositions were also mainly written for pupils or
amateurs; for example, the Concerto in C major (246 K.) for the
Countess Litzow or Lützow, wife of the Commandant of Hohen-
Salzburg; that in E flat major (271 K.) for a Madame Jenomy
(January, 1777), whom Wolfgang had met in Paris; the Concerto for
three pianofortes for the Countesses Antonie, Luise, and Josepha
Lodron (242 K.), February, 1776. While the Mozarts were at Munich,
in 1775, a landed proprietor, Buron Dümitz, had ordered some
pianoforte sonatas, which were duly forwarded (279-284 K.); but he
altogether forgot to send the promised payment in return. Two four-
hand sonatas, mentioned by his father (December 8, 1777), were
probably intended for Wolfgang and his sister; Schiedenhofen heard
them play a duet on August 15, 1777.
Having taken this biograpical survey, it is now time to bestow a
closer inspection on Wolfgang's compositions.
CHAPTER VII. OPERA SERIA.
THE OPERA1 owes its rise to the attempt which was made in
Florence at the beginning of the sixteenth century to discover the
musical method of ancient tragedy and to reproduce it in conformity
GRADUAL RISE OF to the spirit of the Renaissance.2 In opposition to
OPERA.
the predominant madrigal style of part-singing,
worked out in counterpoint, there arose strivings after a method
which should give freedom and independence to the solo singer, and
which should render the poet's words comprehensible and
sympathetic to the hearer. The conviction that this was accomplished
to perfection in ancient tragedy led to a search after lost musical
traditions, traces of which are observable in the opera seria, even in
its latest development. First, recitative was introduced as a middle
course between song and ordinary speech, distinguished by accent
and rhythm, and sustained by a simple harmony, which emphasised
the dialogue. Time and effort were needed to establish this
compromise between song and speech, and to convert recitative into
the pliable, expressive instrument of musical dialogue.
The first attempt to place an opera in this stilo rappresentativo on
the stage was made by Jac. Peri with Ottavio Rinuccini's "Dafne,"
performed in 1594 at the Palazzo Corsi;3 the same poet's "Euridice"
followed in 1600, publicly performed on the occasion of the marriage
of Henry IV. with Marie de Medicis. The whole dialogue is rendered
in a simply accompanied recitative, without the introduction of
anything resembling an air; to this are added choruses, after the
example of the old tragedies, not worked out in contrapuntal form
like madrigals, as was already the custom with the intermedii of
spoken tragedies, but in simple harmonies, and in a key
corresponding to the recitatives.
A similar experiment was made in Rome in 1600 by Emilio de'
Cavalieri with his oratorio "Dell' Anima e del Corpo," and in Florence
the same year by Giulio Caccini with another, "Euridice," which
displayed the art of the singers by its numerous embellishments and
passages.
Musical language, however, could only attain its full effect when
the more elevated sentiments received their due expression in an air,
OPERA SERIA. independent in character and perfect in form. The
development of solo singing released from its contrapuntal bondage,
and made expressive by melody, was largely due to Caccini. The
merit of connecting the air with the recitative in opera—for which a
precedent was found in the monody of ancient tragedy—belongs to
Claudio Monteverde, who also made use of the whole available
instrumental wealth of the time. His operas of "Orfeo," composed in
Mantua (1607), and "Arianna" (1608) were followed in Venice,
where he was appointed kapellmeister (1613), by "Proserpina rapita"
(1630), "Adone" (1639), &c. Here, then, were the elements of the
opera seria. To follow its continuous development step by step would
require such a searching study of details as has not yet been
undertaken. The majority of existing accounts are made apparently
at random, and without any idea of connection or dependence. A
sketch of the leading points in the progress of this development will
suffice for our purpose.4
Ancient tragedy being taken as a model, it followed that the
stories of ancient mythology or history (they were always considered
on the same level) were almost exclusively chosen, although treated
for the most part in a widely different spirit.
Opera soon formed an important feature in court festivals, and it
became customary to give the text a reference to the festival or
person honoured by turning it into an allegory, in which poetical
fancy vied with personal flattery.5 In imitation of ancient tragedy
mimic dances were connected with the singing, but the union of the
arts tended more to sensual enjoyment than to poetical effect. The
naïve freedom with which the ancient myths were handled gave
ample license for gaudy costumes, scenery, and decorations, and the
same taste was carried into the fantastic outcome of these festival
representations known as the German magic opera.
The courts of Italy and France vied with each other in the costly
DEVELOPMENT OF splendour lavished on the opera by scene-
OPERA—
SCARLATTI.
painters, decorators, and costumiers; and Vienna,
Munich, Dresden, and Stuttgart were not slow to
follow their example. The elegantly printed books of the words,
adorned with careful copper-plate engravings, which were
distributed for these performances, give some idea of the style in
which they were put on the stage, and of the dazzle and glitter in
the midst of which the music became a very secondary
consideration.
Such operas as we have described could, on account of the
expense, only be given at royal courts on special occasions; but the
general public soon began to demand a share in the entertainment
and a regular repetition of it. It became the established custom to
make the opera the main festivity of the Carnival, and although
generous patrons were not wanting, prepared to support the
managers (impresarii), yet the latter, who naturally wished to make
a profit by the opera, generally found it necessary to reduce the cost
of the representations. The libretti, which sought to excite interest
by showy scenery, and a mixture of pathetic and burlesque
situations, without the least regard to consistency or psychological
accuracy, were far from satisfactory to any cultivated taste. But the
cultivation of the art of song exercised the highest of all influences
on operatic music. It had reached a height from which it was able to
govern the musical public, and to render the pleasure of the eye
subservient to that of the ear. In proportion as the vocal art asserted
its superiority, it exacted a simplification of all other means of
attraction, and the universal striving after regularity was materially
assisted by the necessity for clear and decided forms in vocal music.
This transformation of the opera, which took its final form from
poet and composer under the quickening influence of great singers,
is commonly ascribed to Alessandro Scarlatti (1659-1725). He was
the disciple, although perhaps not the pupil, of the Roman
kapellmeister, Giacomo Carissimi (who was nearly ninety in 1672),
who did such good service to the development of recitative and
dramatic solo singing, that he may be considered the founder of
modern song.
Scarlatti, excellent alike from his thorough musical knowledge, and
OPERA SERIA. from the wealth and grace of his invention,
displayed astonishing fertility in the different departments of musical
art. In the year 1715, according to his own account, he had
composed 106 operas.6 At Naples, where he passed the greater part
of his life, he founded the school from which (more especially under
his successor Francesco Durante, 1693-1755) a long list of
composers issued, who for the most part wrote admirable church
music, but whose chief mission it was to maintain throughout the
last century an uninterrupted succession of operatic music. If we
glance down the long list of the more famous—Nic. Porpora (1685 or
1687-1767), Dom. Sarri (1688-1732), Leon. Vinci (1690-1734),
Franc. Feo (1694-1740), Leon. Leo (1694-1756?), Ad. Hasse (1699-
1783), Terradeglias (17...-1754), Nic. Logroscino (17...-1763),
Pergolese (1707-1739), Pasq. Cafaro (1708-1787), Duni (1709-
1775), Dav. Perez (1711-1778), Nic. Jomelli (1714-1774), Rinaldo da
Capua (b. 1715), Tom. Traetta (1727-1779), Guglielmi (1727-1804),
Nic. Piccinni (1728-1800), Sacchini (1735-1786), Pasq. Anfossi
(1736-1797), Giac. Paisiello (1741-1816), Franc, de Majo (1745-
1774), Dom. Cimarosa (1754-1801)—we shall be astonished to find
that of the numerous members of the Neapolitan school only four
were born out of the kingdom of Naples,7 viz., Hasse, Terradeglias,
Pergolese, and Guglielmi. The rest of Italy was quite unable to
compete with this wealth.
Venice, however, took an important place in the development of
Italian opera, both by the splendour of the performances given in
the theatre, which was erected in 1637,8 and by excellent
institutions for musical education. The fame of the Venetian school
was upheld by many celebrated composers, among them Carlo
Pallavicini (16...-1688), Agost. Steffani (1655-1730). Franc. Gasparini
ITALIAN (1665-1737), Ant. Lotti (1667-1740), Giov. Porta
INFLUENCES ON
OPERA.
(16...-1740), Ant. Caldara (1678-1763), Buranello
(1703-1785), Ferd. Bertoni (1725-1813).
Bologna too had its share in the history of the opera, maintaining
a firm tradition of careful performances,9 and excellent schools for
singing and composition; Giov. Buonon-cini (1672-1752) and Gius.
Sarti (1729-1802) were trained here.
Rome was looked upon as the city where the keenest enthusiasm
either of applause or adverse criticism was to be expected,
consequently where artistic reputations were most often made or
destroyed;10 but Rome was neither the birthplace nor the seminary
of any famous operatic masters.
It is not necessary here to inquire into the details of the part taken
by Scarlatti in the erection of Italian opera as it now exists. His
operas are truly epitomes of the history of musical development, and
his many imitators and successors pass before us like the shadows
of the Homeric shades; but we have only to do with him or with
them in so far as concerns the main features of that form of operatic
composition which Mozart found ready to hand.11
The stability with which operatic development kept close to the
path which had at first been marked out was due partly to
circumstances and the influence of public opinion, partly to the
character of the Italian people. Beauty, appealing immediately and
directly to their lightly kindled imaginations, required that its sensual
charm should be clearly and unreservedly expressed; and for this
they were willing to sacrifice novelty and characterisation. Again, the
art of music was developed in accordance with natural laws; and
having once acquired forms indicative of its essential elements, it
grasped these firmly, and refused to abandon them until they had
become completely obsolete. It was the task of the great masters of
OPERA SERIA. the eighteenth century to maintain this course of
steady imperceptible progress, and, by raising to successive stages
each hardly won step towards perfection, to establish in the end a
new and more admirable whole.
The chief component parts of the opera were the recitative and
the song, or aria.12 Recitative, intended for the rendering of
conversation, approaches in rhythm and intervals as near as possible
to ordinary speech, and leaves the singer ample scope for an
animated and expressive delivery. This is assisted by a simple
harmonious accompaniment, the basses giving the fundamental, the
clavier the harmony. The simplicity of the musical treatment lends
itself to characteristic declamation, and impressive situations are
thrown into relief generally by sudden changes of harmony;
numerous instances show the importance that was attached to this
mode of delivery. But very soon it became the fashion to treat this
recitativo secco as subordinate, and the composer strove to do away
with it as far as possible. Certain turns, certain harmonic
progressions and interrupted cadences, were as indispensable to
recitative as many turns of speech are to social intercourse. As the
course and development of the action of the piece depend almost
entirely on the recitative, it follows that any neglect of the latter
must affect one of the most important elements of the opera. The
need for attaining the power of expressing a momentary passion or
inspiration which would not admit of an elaborate representation led
to the introduction of the so-called accompanied (obligate)
recitative. For this the orchestra (at first only the whole body of
stringed instruments) was made use of, and accompanied the
alternations of emotion with corresponding musical phrases or
interludes. Recitative, without abandoning its distinctive
characteristics, became more strongly accentuated, and in process of
time passed over into song. Such vocal melodies as seemed thus to
be called forth by the emotions of the situations were called cavata
RECITATIVE—THE or cavatina. At first they were considered as an
ARIA.
ingredient or embellishment of the recitative, but
later on they were treated independently. Arioso in the recitative
indicates an interpolated passage of vocal melody. A rapid
alternation of varied or contending emotions in monologue or
dialogue called for accompanied recitative, which generally passed
into a song, where a definite emotion might find its due expression.
It was here that singers and composers sought to accomplish the
highest degree of dramatic expression, and although in the aria they
might be tempted to an undue regard for musical display, to the
neglect of dramatic effect, here at least they strove for a faithful
portrayal of human sentiment.
The aria was the almost exclusive form given to regular artistic
song. Choruses, which formerly concluded every act, were
afterwards only exceptionally employed, generally when the
occasion, being a court festivity, required additional outward show;
they very seldom formed an integral part of the performance.13
Ballets, which were originally combined with the choruses, became
by degrees quite distinct, and were given between the acts of the
opera. Concerted vocal pieces were confined within limits more and
more strictly defined, until the rule came to be that in every opera
there should be a duet for the prima donna and the primo uomo,
and a terzet in which the primo tenore also took part; even the
places for these, at the end of the second and third acts, were
appointed. Further restrictions were imposed on the character of
these concerted pieces by the necessity of giving all possible effect
to the voices. They do not pretend to represent a conflict of
struggling passions, pressing onward to the catastrophe; rather does
some definite mood, the natural result of the situations which have
preceded it, find its fitting expression in their regular concerted form,
which affords ample scope for the display of varieties in quality and
style of the individual voices.
The aria, which gave expression to a fixed lyrical mood, was
seldom the culminating point of a dramatic situation; its connection
OPERA SERIA. with the action of the piece was, for the most
part, only sufficient to give it a certain local colour. It was the task of
both composer and singer to make the aria fit in to the drama; but
the claims of the vocalist were paramount in its composition. As the
canons of operatic construction became more and more strictly
defined, distinctions arose between different kinds of arie, each
having its own character and form; the aria cantabile was for
sentimental declamation, di portamento for long drawn-out tones, di
mezzo carattere for dramatic expression, aria parlante or agitata for
the expression of passion, aria di bravura (agilità) for the display of
artistic skill of every kind.14 The poet and composer had only to be
careful to suit the arie to the performers, and so to distribute them
through the opera that their variety should place the performances
of each character in their most favourable light.15 But a certain fixed
form served as a groundwork to all arie, and kept them within well-
defined bounds. It is easy to trace the simple expressive phrase as it
is extended and rounded into a well-formed melody, and then to
follow the different subjects so obtained until, by progressions and
interludes, they are welded into a whole. But this led to a petrifying
formalism, and to a tedious lengthening of the aria, which sacrificed
character to vocal display.
An aria regularly consists of two parts differing in key, time, and
measure. An allegro in common time usually begins, introduced by a
slower passage in triple time; but as to this there is no fixed rule,
and free scope as to details is given to the composer. The first
movement is broadly conceived, always with a view to the skill of the
performer; he repeats one or more of the principal melodies in
different positions, but without thematic elaboration, and inserts
runs and passages.
In the second part the composer, granting some repose to the
singer, made a display of his own art by selected harmonies,
THE ARIA. elaborate accompaniments, and so forth. It was
essential to the singer's reputation as an artist that he should be
able to vary the modulation and embellishment of the melody each
time it recurred, the composer supplying a mere outline, and leaving
the execution of the cadenzas entirely to the discretion of the
performer. This task became more difficult as the custom grew of
repeating the whole of the first part at the close of the second, thus
turning the latter into a middle movement; for no singer would be
deterred from enhancing the interest of each repetition by a fresh
mode of delivery. So that the public performers of that day displayed
their taste and cultivation not only, as at present, by execution and
declamation; they worked of necessity side by side with the
composer, whose special glory it was to inspire his singers with a
spark of his own creative genius.
The influence thus exerted by the executive artist could not fail to
determine, to a great extent, the path of development in operatic
composition. The great names of the more celebrated singers are to
us indeed but names, for contemporary notices give us no clear idea
of their performances,16 and the music written for them, deprived of
the direct charm of their personal impression, affords a most
imperfect standard of judgment.
From the middle of the last century the tendency to sacrifice all
consideration to execution (bravura) became more and more
marked; until at last, dramatic propriety, and the soul-inspiring calm
of beautiful song, were alike buried beneath the weight of
ornamentation and exaggerated flourishes,17 serving only to display
the pretensions of the vocalist and the dexterity of the composer. In
this way the dramatic element of the opera became more and more
neglected, until at last it was regarded as a superfluous and
disturbing adjunct to the vocalisation.18
OPERA SERIA. The public too grew accustomed to confine
their attention to the individual exploits of their favourites;19 and
the composer, unwilling to waste his energy on thankless parts,
followed the example, and devoted his whole powers to a few
individuals.20
The enormous salary paid to celebrated singers, male and female,
had the effect of limiting the number of principal parts to three or
four, each distinguished as primo.21 The remaining parts were
treated by both the poet and the composer as subordinate, not only
on account of the mediocre powers available for their
representation, but also and chiefly because it would have been
against the interests of the great singers that secondary characters
should attract notice or applause. They controlled all secondary
parts, suppressing or appropriating any song which they considered
too brilliant, and leaving the author to arrange the piece as best he
might.22 There was a fixed code of etiquette in all stage
arrangements. The prima donna, for instance, was entitled to have
her train borne by one, or if a princess, by two pages; she took the
place of honour at the right of the stage, being, as a rule, the most
important personage of the piece. When Faustina Hasse played
Dircea, in "Demofoonte" (1748), who is not recognised as a princess
until late in the piece, she claimed precedence over the
acknowledged Princess Creusa, and Metastasio himself was obliged
to interfere in order to induce her to yield the point.23
Thus all influences combined to mould the opera seria into a
narrow conventional form, in which all other considerations were
sacrificed to executive effect, and the display of skill and sensibility
in the rendering of the music.
We can form no clear conception whatever of the operatic
INSTRUMENTATION orchestra in its earliest form; both the use and
—THE OVERTURE.
the effect of various instruments are very
imperfectly known, and the instrumentation is consequently more or
less incomprehensible. But here too development proceeded in the
way of simplification, and at the time of Scarlatti the treatment of
instrumental accompaniment and the disposal of the orchestra was
determined as to essentials for all future times.
In the plain recitative of the dialogue, the fundamental note was
given by the bass, and the chord was struck on the piano (at which
the composer or kapellmeister conducted) and repeated as often as
necessary. In the songs and ensembles the instruments came in as
accompaniments, freed from the obligation of following a given
melody step by step with a given bass, according to the rules of
thoroughbass for filling up harmonies. Scarlatti and the earlier
masters kept this accompaniment very simple, seldom introducing
more than one part in addition to the bass and the voice. But, as
practised contrapuntists, they could handle the accompanying parts
broadly and freely, and could give animation by simple means. This
art gradually decreased, and the accompaniment, although fuller,
became more mechanical and dependent, Only here and there
suggesting contrapuntal elaboration. The orchestra was used
independently only in the symphonies which repeated the motifs of
the songs, in the short interludes of accompanied recitative, and
finally in the introductory overture or sinfonia.
Italian operatic composers began by making use of the form of
overture which Lully had established in France, beginning with an
adagio, followed by a quick movement, often in the form of a fugue,
and passing again into an adagio, which concludes the overture.
Later, the form was determined which has remained ever since, of
three movements: an allegro, a slower, shorter movement
contrasting in time, instrumentation, and expression, and a
concluding allegro, animated and often noisy.
These main features were capable of rich and varied development,
were it not that in Italy little importance was attached to the
OPERA SERIA. overture, which was commonly regarded as a
means of reducing the audience to silence and attention. The three
movements, therefore, generally preserved their gradations without
marked characteristics, and the attempt to express the effect of the
first scene by means of the overture was soon abandoned.24
The grouping of Scarlatti's orchestra was in its main points
identical with that of the present day. The stringed instruments,
violins, tenors, and basses formed its main strength; but their
application was very simple. The violon-celli go regularly with the
double-basses, and the tenors serve generally only to strengthen the
bass; where they are independent they are often divided, like the
violins, which however frequently go together. The oboe has the
chief part among the wind instruments, the flutes serving mainly for
variety and special characteristics; the bassoons strengthen the
bass, and are rarely used independently. Soon horns were employed,
and drums and trumpets when special splendour was required;
trombones were used in the churches, never in the opera.
In this manner even the largest orchestras were arranged down to
the close of the last century; an example is afforded by the
construction and arrangement of the Dresden orchestra by Hasse,
which was considered as a model.25 [See Page Image] The well-
THE ORCHESTRA— appointed bass parts are the most striking,
INSTRUMENTALIST
S.
intended as a firm foundation for the vocal
melody, which is not seldom strengthened by the
violins and oboes or flutes. But to avoid any effect of poverty, it must
not be forgotten that the accompanist at the piano filled in the
harmony. To strengthen this, and to give variety to the intonation,
was the task of the wind instruments. But when the orchestra was
treated as a whole there was seldom any attempt to render lights
and shades by alternations of the instruments; to attain this end,
concerted solo instruments were employed.
Italy was, during the eighteenth century, at once the mother and
the nurse of instrumental musicians. A succession of first-rate
violinists—Arcang. Corelli (1653-1713), Franc. Geminiani (1680-
1762), Ant. Vivaldi (16...-1743), Gius. Tartini (1692-1770), Pietro
Nardini (1722-1793), Gaet. Pugnani (1727-1803), Ant. Lolli (1733-
1802)—established the glory of violin-playing, and raised it to an
extraordinary height of excellence; while as oboists the brothers
Besozzi, Alessandro (1700-1775), Antonio (1707-1781), Gaetano
(1727-1793) were performers of the first merit. Trumpets were at
that time more especially considered as solo instruments.
Not until later could Germany compete successfully with Italy, as
far as the orchestra was concerned; in France, although the
precision of Parisian orchestras was always remarkable, the
development of instrumental music was longest delayed. Scarlatti
introduced instrumental soloists in the operatic orchestra, and the
effect was the same as on the stage; it worked against the careful
striving after a perfect whole, and the tendency of the instrumental
artists to enter into competition with the vocalists led in no small
degree to that treatment of the voice as a mere instrument which
was so much to be deplored. Notably Farinelli in 1722 established his
reputation in Rome by a contest with a wonderful trumpeter, whom
he twice vanquished in the sustenance and artistic delivery of a long
note, and in the execution of difficult passages.26
OPERA SERIA. The first step towards simplifying opera seria in
its new form was made in the diction and treatment of the plot. The
subject-matter continued to be taken from the stories of mythology
or ancient history; but effects of magic and show were abolished,
and a connected well-developed plot was substituted, simple in
action, and confined to a small number of personages. Next, the
previous mixture of the tragic and comic elements was abolished,
and everything approaching to burlesque strictly interdicted. The
chief efforts in this direction were made by the Roman Silvio
Stampiglia (d. 1722), to whom Apostolo Zeno awards more of genius
and spirit than thorough cultivation,27 and whom Arteaga calls dry
and unmusical.28 Apostolo Zeno himself (1688-1750) followed in the
same path as court poet to Charles VI. He was a man of education
and learning, and as such sought to model the opera on ancient
tragedy in its best and most manly form, and strove for a naturally
developed plot, correct delineation of character, and simplicity of
language. He proved, said Metastasio,29 that the opera and good
sense are not absolutely contradictory terms. The fact that his
operas were often and successfully performed during the first half of
the century bears testimony to the simplicity and earnestness of the
musical taste of the time; later on, as the field of music extended its
limits, his text was found pedantic.30 His indisputable merit31 was
thrown into the shade by Metastasio's works;32 these denote in a
remarkable degree the spirit of the time which produced them, a
spirit that they themselves fostered and encouraged.
Metastasio (Pietro Trapassi, 1698-1782) distinguished himself as a
boy by his talent for improvisation; he received a thorough learned
METASTASIO. education from the celebrated Roman jurist
Gravina, which led to his adoption of classical antiquity as his model;
while his connection with the singer Marianna Bulgarini early gave
him an insight into the technical requirements of the opera. He
began his career as a librettist in 1724 with "Didone" at Naples; in
1730 he went to Vienna as court poet, where he lived on the best of
terms with the Imperial family,33 and highly esteemed by the
cultivated public. Following Apostolo Zeno, he sought to supply his
operas with a true dramatic form, and he made it his chief aim to
portray the effect of different characters and passions upon the
development of the action. Metastasio had no large or powerful
conceptions, nor could he grasp strong passions; his psychological
vision is clear and cool, but limited, just as his sentiments are correct
and good, but neither wide nor free. In his dramas, therefore, the
representation of character and the plot are well-considered,
suitable, and consistent, but with a certain mediocrity running
through the whole; he chiefly concerns himself with the
exemplification of principles and experiences, and individualises but
little.34 He makes love the animating element of his drama, and the
starting point of his psychological study of motives. His characters
want neither life nor passion, but softness and veiled sensuality are
the characteristic features of what he endeavoured to make an
imitation of actual life. The public were gratified at recognising
themselves and their love affairs glorified on the stage, and were
grateful to Metastasio for allowing them to enjoy themselves in their
own way, and not preaching moderation and self-control. They
admired his language too, which is correct, and charmingly
melodious and natural in expression, not more rhetorical than the
Italian language and poetry demands, and never overlaid with
conceits.
To these qualities of a dramatic poet, Metastasio joined that of an
operatic composer; he was a musician. He had cultivated his musical
OPERA SERIA. talent by intercourse with singers and composers,
and had a ready perception of what was necessary to a work written
for composition. He sang "come un serafino" (as he writes jokingly
to Farinelli),35 played the clavier, and composed a little himself;36
he found it a pleasant incitement to poetical activity to seat himself
at the clavier and improvise. He said himself he had never written a
song without composing it himself, according to his own conception
of its musical character.37
Metastasio confines the development of the plot as a rule to the
recitative and the arie (or duet, or terzet), expressing at the close of
each scene the sentiment which is the result of the previous action.
This they always did so clearly and precisely that the composer had
both incentive and scope for musical treatment.
The too numerous figures and metaphors (which he was fond of
borrowing from the sea) express the taste of the time, and so far
from troubling the musician, gave him opportunities for musical
painting which was sure to be admired. The melodious language met
the music half way, while the simple yet varied rhythm, the contrast
of ideas, and the construction of the verse, aided the composer,
without fettering him, in the musical phrasing of his work.
It was no wonder that Metastasio reigned supreme over the stage
and its composers, and that he was the model of the later operatic
poets; they succeeded best in imitating his defects, and gave
Naumann occasion to say with justice, "The oldest of Metastasio's
operas is more pleasing to me than any written by our present
poets."
Metastasio was well aware that the poet only supplies a stem to
the opera, which the composer clothes with foliage and blossom;38
but he was far from allowing the composer absolute dominion over
CONDITIONS OF the poet, and prided himself on the fact that his
LIBRETTO-
WRITING.
operas had been played with applause as
tragedies without music both in France and
Germany.39
He chose to consider the composer as the interpreter of the poet,
and bound to follow his indications of character and style.40 This
was in his opinion the chief merit of the old composers, and in his
later years he was never weary of deploring the decline of music,
which was the consequence of the license taken by vocalists,
destroying alike truth and beauty of expression.41
The poet not less than the composer found himself hemmed in by
conditions as well as by traditional formulas. He too performed his
task to order, and was hampered by circumstances, and by the
limited means at his command in his choice of subject and
characters.
It was in no way favourable to Zeno and Metastasio that they
received their commissions from the court;42 besides the direct
influence of the taste of the somme padrone, the whole atmosphere
tended to effeminacy and a uniform level in style. The impresarii
chose the libretti for the composers they had engaged, partly
according to the applause the subjects had already received, but
more to suit the singers they had at command. They were altered to
suit the occasion sometimes by the poet himself, but more often
some local poet undertook the necessary curtailments and additions,
whereby the work seldom profited.43
The absolute monarchy of Zeno and Metastasio, whom all other
poets slavishly imitated, would alone suffice to explain the fact that
in the course of the last century opera seria received the fixed and
unalterable form it still retains; we have seen that the tendency was
the same as regards the music. This makes it comprehensible that in
reading the text or the scores in the present day we have so lively
an impression that they are but copies of one original. In no art does
the feeling for what is enduring pass so easily and quickly into the
taste for what pleases the age as in music. What affords most
delight to the present often expresses only a transitory mood with a
momentary truth, and when the smoke and the fragrance which
surrounded it have disappeared, only an empty form remains; just
as a mask keeps the impression of the features without the play of
the muscles, which alone give life and expression.
CHAPTER VIII. MOZART'S EARLY
OPERAS.
MOZART found rules as to the form and technicalities of the opera
1 seria rigidly laid down even to the minutest details, and he was the
less tempted to disregard these, since the extraordinary ease of his
invention prevented his ever finding a prescribed form to be a
burdensome restriction. Mozart's mission was not to overstep the
bounds of custom, but quietly and gradually to bring to perfection all
that was genuine and true in the diverse elements of his time. He
found the opera already in the hands of the vocalists, and execution
had by this time asserted its victory over characterisation. He did not
attempt to enter the lists against singers and public, but contented
himself with striving for fair conditions. He was willing to write to the
satisfaction of the singers, and for the display of their powers, but
"MITRIDATE." he saw no necessity for sacrificing to this object
either musical beauty or dramatic force. At times the dramatic
situations in Mozart's early operas are true and even striking; but the
dramatic element yields on the whole to execution and euphony. It
must not be overlooked that the apprehension of dramatic truth and
character varies with different times and different nations, and that
the genius of first-rate artists could inspire life into what now
appears a lifeless assemblage of notes. But it must at the same time
be allowed that Mozart's operas of this period come under the
influence of a taste perverted in many respects, which the youthful
master had not yet overcome; and his forced compliance with many
purely conventional demands must of necessity have left traces on
his work as deep and lasting as those of his creative genius.
The opera of "Mitridate, Re di Ponto" (87 K.) was first adapted
from Racine by the Abbé Parini, and revised by Vitt. Am. Cigna-Santi.
The dramatis persona are as follows:—[See Page Image]
On the news of the death of Mithridates the inhabitants of
Nymphæa deliver up the keys of the town to his son Sifares. Aspasia
seeks his protection against the suit of his brother Pharaaces,
thereby betraying her partiality for Sifares, which he secretly returns.
Pharaaces attempts to force his hand on Aspasia, whereupon Sifares
throws himself between them; Arbates separates the contending
MOZART'S EARLY brothers with the news of the landing of
OPERAS.
Mithridates; they are reconciled, and agree to
keep secret from their father what has passed. Marzio promises to
the ambitious Phamaces the help of the Romans against his father.
Mithridates enters, proud and courageous in spite of the defeat he
has just suffered, and is received by his sons; he introduces to
Pharnaces his destined bride Ismene, who regards Pharnaces with
little favour. The demeanour of his sons awakens the suspicions of
Mithridates, and on Arbates revealing to him the passion of
Pharnaces for Aspasia, he falls into an extravagant rage. Pharnaces
acknowledges to Ismene that he no longer loves her; whereat,
wounded alike in her pride and her love, she complains to
Mithridates. The latter resolves to punish him, and suspecting from
Aspasia's cold demeanour towards himself that she returns the love
of Pharnaces, he sets Sifares to watch her. The lovers of course now
come to an understanding, but Aspasia virtuously commands Sifares
to leave her for ever to the fulfilment of her duty.
Mithridates, in order to test the fidelity of his sons, consults with
them on the prosecution of the war; he discovers the complicity of
Pharnaces with the Romans, and orders his imprisonment;
Pharnaces acknowledges his çuilt, but accuses Sifares of the greater
guilt of complicity with Aspasia. In order to try her, Mithridates offers
generously to resign her hand to Pharnaces, which draws from her
the confession of her love for Sifares; this so infuriates Mithridates
that he resolves to slay his two sons and Aspasia. This is the crisis at
which the second act is brought to a conclusion by a duet, in which
the lovers declare death preferable to separation.
In the third act, Ismene, repenting her resentment, strives to
soften Mithridates, and Aspasia solicits Sifares' life with an assurance
of his innocence; but, as she refuses to give her hand to Mithridates,
he maintains his resolve, and the triple execution is to take place
during a sally which he makes on the Roman host besieging the city.
Aspasia is on the point of emptying the fatal bowl, when Sifares,
who has been set free by Ismene, snatches it from her, and rushes
against the enemy. Pharnaces, who has been released from his
dungeon by the besieging Romans, is seized with compunction and
returns to his obedience, setting fire to the Roman fleet. The
Romans are defeated, but Mithridates is mortally wounded; before
he dies he unites Aspasia and Sifares, and pardons Pharnaces, who
has made his peace with Ismene.
The opera consists of twenty-four numbers without counting the
overture; they are all solo songs, except one duet and the
concluding quintet. 2 The original score appears to be lost; but
ANALYSIS OP several detached numbers of this opera are
"MITRIDATE."
preserved in different forms of composition,
showing that Mozart had made various experiments, more,
doubtless, to please the singers than himself. Of the first air of
Mithridates (7), "Se di lauri il crino adomo," there are four different
sketched studies; Aspasia's song (13), "Nel grave tormento," is
begun in a different form, but breaks off at once; five other numbers
are completely worked out, but have given place to later
arrangements. 3
This opera comes in all respects within the rules of the existing
opera seria. Musical etiquette is strictly adhered to; the principal and
secondary parts are divided in the usual way; the secondary parts
are easier (not always simpler), and their character is tamer and less
important, so that they may act as foils and connecting links to the
principal parts. The chief singers had to be furnished with
opportunities for making effect as soon as they appeared; and must
have at least one great aria in each act. All this is carefully provided
for. The compass and executive skill of the artists, more especially of
Bernasconi and d' Ettore, must have been extraordinary. The division
of the aria into two movements, which prevails here as elsewhere,
favours the elaboration of details by affording more than one
principal subject. We must not expect to find a uniform florid song,
the ornamental passages growing out of and entwining the chief
melody, like an architectural ornamentation; they form an integral
part of the composition. The taste in such passages is essentially
MOZART'S EARLY fleeting, for it depended chiefly on the skill of the
OPERAS.
individual performer; what is most admired in one
age is least pleasing to the next. The same dismemberment made
itself apparent too, in the cantilene. The various vocal tricks, long
notes, sustained melodies, long jumps, syncopated passages, &c., to
which due effect had to be given, could not be thrown together
without some connecting principle. For this the subjects of the songs
were made use of, but the effect was still disjointed and inartistic.
The detached phrases were usually still further separated by a full or
a half cadenza, to which an instrumental interlude was often
attached. No doubt this wealth of variety was then considered a
great charm; now we miss unity of form and conception. The turns
of harmony are generally monotonous and poor, the form of the
cadenza with its trills is just as stereotyped as that of the present
day with its suspended sixth, and both the singer and the public
expected and required that this should be so. No doubt the freedom
which was allowed to the singer in delivery often gave quite a
different form to the cadenza, but the want of conception could at
best but be concealed.
These shortcomings are not to be ascribed in Mozart's case to
youthful immaturity, but to the musical conditions of the time at
which he wrote; they are equally observable in the works of the
most experienced contemporary musicians, and were indeed hardly
regarded as blemishes. The question involuntarily arises what there
was in these early operas which could so enchant the public and
draw from a master like Hasse the prediction that this youth would
eclipse them all. A witty artist once declared that the public always
requires novelty, but it must be novelty that they are acquainted
with; anything really new demands too great an effort of
comprehension from them. In this case, no doubt, the public,
agreeably prepossessed by the readiness with which the work
complied with all existing conditions, were quick to appreciate the
skill and taste which were manifest, as well as a certain youthful
freshness, and here and there traits more significant still of genius;
traits in which Hasse recognised the germ of future development.
We, who know Mozart in the full perfection of his powers, seek
ANALYSIS OF eagerly in these earlier works for such indications
"MITRIDATE."
as there are of his future greatness. Sometimes,
even in the bravura songs, pure, grand touches of melody light up
their conventional surroundings; these are usually in the second
part, and in the minor key. The more dramatic "situation-songs" in
which the composer made fewer concessions to the singers, are not
only conciser in form, but more pregnant and original in expression.
The most striking among them is the song of Aspasia (4). Upon
the news of the arrival of Mithridates, whereby she knows Sifares to
be in danger, and her love for him rendered hopeless, she utters
these words:—

Nel sen mi palpita dolente il core


Mi chiama a piangere il mio dolore,
Non resistere, non so restar.

Ma se di lagrime umido è il ciglio


È solo, credimi, il tuo periglio
La cagion barbara del mio penar.

Grief, which seems too deep for words, here breaks forth in such
an uncontrollable flood of song, expressed with so much truth and
nature, that a dramatic artist like Bernasconi would be sure to make
an extraordinary effect by it. The simple, purely musical means
employed, the expressive flowing melodies, rich harmonies, suitable
accompaniments, and charming moderation of expression—all these
show us the genuine Mozart.
Should it be objected that the milk-and-water heroism of the piece
is still further debased by gallantry in powder and gold lace, we can
nevertheless claim for it, after all deductions made, a certain amount
of stateliness and dignity. These qualities are indeed displayed more
according to court etiquette than to classical antiquity, but they are
unmistakably there, conformably to the manners of the time and the
nation, and their artistic significance is not small. Mithridates, who
has most of individual character after Aspasia, never forgets, as
Sonnleithner justly observes, that he is first tenor as well as king;
but on the other hand he always remembers that he is king as well
as first tenor.
MOZART'S EARLY The text of the opera "Lucio Silla," composed in
OPERAS.
1772 (135 K.), was written by Giovanni da
Camera, and according to the preface, revised by Metastasio. The
programme runs:—[See Page Image]
Cecilio, a senator, banished by Silla, has secretly returned to Rome
to learn the fate of his betrothed Junia, daughter of C. Marius; his
friend Cinna warns him that Silla has spread the rumour of his death
in order to win the hand of Junia; Cinna counsels him to meet her in
a burial-place. Silla, whose suit has been repulsed by Junia, resolves
to slay her. Cecilio awaits his betrothed in the dusky burial-place,
surrounded by the trophies of Roman heroes. She enters,
accompanied by noble youths and maidens, who call for vengeance
on Silla, and lament by the urn of her father. When she is alone,
Cecilio reveals himself. She takes him at first for a ghost, and they
then express their joy in a duet.
In the second act Aufidio, Silla's evil counsellor, advises him
publicly to declare Junia as his betrothed, and thereby reconcile the
contending factions; she will not be able to oppose the universal
wish. Celia, his sister, who always counsels well, informs him of the
ill-success of her appeal to Junia; he promises to unite Celia to her
lover Cinna. Silla has scarcely departed, when Cecilio rushes in to
murder him in obedience to a vision; Cinna counsels postponement,
to which Cecilio at last consents. Ciàna is now so engrossed in his
plans for revenge that he scarcely heeds Celia, who tells him of their
approaching happiness, and tries to persuade Junia to a feigned
submission, and the murder of Silla in his bed-chamber. But she
refuses to be guilty of high treason, and he resolves to slay Silla
himself.
Junia, who declares that she will never give her hand to Silla, is
threatened with death, but nevertheless counsels Cecilio, who
wishes to avenge her, to remain in concealment. Celia seeks in vain
to persuade her by the portrayal of her own happiness, but cannot
"LUCIO SILLA." stifle gloomy anticipations. Silla announces from
the capitol his intended union with Junia, and is answered by
acclamations, but Junia endeavours to stab herself, which is
prevented. Cecilio rushes in with drawn sword, is disarmed, and his
death on the following day decreed by Silla; Cinna, entering also
with drawn sword, sees that his plot has failed, and feigns to have
come to Silla's protection. A terzet between Junia, Cecilio, and Silla
concludes the act.
In the third act Cecilio in fetters is informed by Cinna of the ill-
success of his plot, and calls on him for vengeance. Junia declares
her resolve to slay herself before Cecilio. Aufidio comes to fetch him,
and the lovers take leave.
Silla declares before the assembled people that this day shall give
him vengeance and his heart's desire. Junia accuses him as the
mur» derer of her betrothed, and calls on the people to avenge her.
Silla pardons her and Cecilio, and unites the loving pair. Seized with
compunction Cinna reveals his plot against Silla; he, too, receives
pardon and the hand of Celia. Finally Silla forgives Aufidio his evil
counsels, lays down the dictatorship, and restores freedom to Rome.
The consideration of such a libretto as this renders
comprehensible the esteem in which Metastasio's texts were held.
There is no trace of psychological study of motive; Silla, a sort of
distorted Titus, alternates between cruelty and remorse, and finally
empties a perfect cornucopia of generosity on to the stage; Junia
too is unequal and weak. The situations are one and all as if
purposely arranged to lead to nothing; the poet has with difficulty
disposed the numerous scenes so as to introduce the necessary
songs in their proper order. And the verse itself is very far removed
from the grace and melody of Metastasio.
The score of the opera is preserved entire in Mozart's handwriting;
it is in three parts, and has 610 pages. It contains besides the
overture twenty-three numbers, among them three choruses (6, 17,
23), one duet (7), and one terzet (18). No wonder that the
composer paid court to the singers! The mishap that deprived the
opera of its tenor has been already narrated (p. 142). As the part
devolved in the end on a very unpractised singer, the greater part of
it was omitted, leaving only what was necessary for the coherence of
the plot. The two songs (5, 13) are written for a singer whose voice
and execution do not rise above the average, without any passages,
MOZART'S EARLY and with a moderate compass; the more
OPERAS.
elaborate instrumentation alone betrays that they
are intended for a principal performer. Two other songs for Silla
which are in the libretto were not composed at all, in order, no
doubt, as Sonnleithner conjectures, to give the tenor as little as
possible to do.
All the more stress is laid on the parts of De Amicis and Rauzzini.
Junia has four songs, which are all for a singer of the first rank. The
special bravura song (II) is in the second act, "Ah, se il crudel
periglio del caro ben ramento." Long passages of varied structure
are here the chief considerations. One example among many will
serve to show that Mozart was right in afterwards calling them
"dreadful":—[See Page Image]
Notwithstanding the bravura character of this song, its style is far
from well defined; that of the entering song, "Della sponde
tenebrose" (4), and of the third aria (16) is more marked. This last,
"Parto, m' affretto, ma nel partire il cor si spezza, mi manca la
anima," consists of a continuous and progressive allegro assai. An
agitated phrase for the first violins—supported by an accompaniment
for the second, runs through it almost without intermission; the
"LUCIO SILLA"— harmonising is interesting and varied; particularly
JUNIA.
effective is the immediate juxtaposition of major
and minor keys; the whole song is strikingly expressive of an
unsettled wavering mood.
Passages such as—[See Page Image] are brilliant, but not,
properly speaking, characteristic. At least they do not stamp the
actual situation with individuality; they seem designed only to define
the character and mood of the acting personage in their main
features, like the masks of ancient tragedy. The more detailed
analysis was left to the art and individuality of the performer, to
whom the composer offered only the means of combining dramatic
force with song. We can still recognise the essential features of the
characters; but we are quite unable to realise either the animation
with which great artists inspired them, or the effect they produced
on the minds of contemporaries. It is a mistake to consider bravura
and character as opposite terms; ornamental passages are quite
susceptible of characteristic expression, if they are delivered at the
right time and in the right way. Junia's songs express the character
of a proud strong Roman woman, and an opportunity for dramatic
analysis is offered to the performer even in the more florid songs.
But the true dramatic expression is undisturbed in Junia's last song
(22), "Fra i pensier più funesti di morte veder parmi l' esangue
consorte." The long adagio, followed by an allegro, is a distinct
foreshadowing of the later form. The treatment of the orchestra too
is significant. The flutes, oboes, and bassoons are in unison, and
contrast with the stringed instruments, after a fashion not usual at
the time: and in the allegro the orchestra is in significant opposition
to the voice part, which is simple and unadorned, although
calculated to give due effect to a fine voice; its dramatic expression
is quite excellent.
MOZART'S EARLY In the part of Cecilio, written for Rauzzini, the
OPERAS.
regard paid to the singer is very apparent both in
the compass of the voice, which comprises two octaves, and in the
style. He was what may be called a scholarly singer, theoretically
educated, and a composer himself, and difficulties are introduced
evidently with a view to this. Thus, for instance, the recitative
preceding his second aria is full of curious, sometimes harsh, turns
and transitions in the harmonies; in the third aria such jumps as the
following occur—[See Page Image] requiring no small certainty of
execution. The first song (2), introduced by a fine expressive
recitative, begins, as these male sopranos loved, with a long-
sustained note, and'contains various brilliant passages; but it is quite
without original invention. The second song (9) expresses a proud,
free mood with strength and animation; the last (21) can only be
explained as a freak of the performer. Cecilio, in the act of being led
to execution, moved by Junia's tears, turns to her with the words—

Pupille amate
Non lagrimate!

These tender, trifling words, are treated by Mozart with an


exquisite grace which is quite foreign to the character and the
situation of Cecilio, and, as Sonnleithner observes, would be much
more suitable to a soubrette. Probably Rauzzini chose this way of
ingratiating himself with the public.
Besides the solo songs the opera contains a duet for J unia and
Cecilio, and a terzet for the same and Silla, which are cleverly
constructed, but not otherwise remarkable. The duet (7) consists of
an andante and a somewhat tedious allegro, in which the voices go
together for the most part in thirds or sixths, with little attempt at
"LUCIO SILLA"— imitation. The terzet is well conceived. Each of
ENSEMBLES.
the three voices has a characteristic motif, which
is not elaborated, but set in contrast with the others; afterwards the
lovers are set in opposition to Silla, and the expression is heightened
by occasional use of the three voices together; in short, some traces
are here discernible of the talent for musical architecture which
Mozart afterwards displayed is so remarkable a degree.
The scene which precedes the close of the first act deserves
special notice; it is both conceived and executed with true dramatic
force. In a hall (atrium), decorated with the trophies of his
ancestors, Cecilio awaits in the twilight the coming of Junia. The
varied emotions roused in him by the contemplation of the graves of
departed heroes, and the yearnings of love, are graphically
expressed in an accompanied recitative. Junia appears, escorted by
noble Romans of both sexes. The chorus calling on the spirits of the
heroes for support and vengeance is serious to solemnity, with
striking harmonies and an independent treatment of parts, giving
animation to the whole—an altogether excellent piece of music, with
much dramatic effect. Junia joins in with a prayer to the shade of
her father. The pain of a proud, strong spirit is expressed in a simple
and dignified adagio, which gives a fine soprano voice full scope for
the display of its capabilities. The prayer is followed by a curse
pronounced on Silla by the chorus, powerful and animated, and a
fitting close to this truly dramatic musical scene. A resemblance to
the first chorus in Gluck's "Orfeo," pointed out by Sonnleithner, is too
slight to be considered more than a mere suggestion.
Among the secondary parts that of Celia has the most
independence of character. Her two first songs (3 and 10) are, on
the whole, simple and graceful, especially the second. Passages in
Cinna's three songs (1, 12, 20) and in the air for the second tenor,
Aufidio, are calculated to display the powers of the artists, but the
songs, as a whole, have little or no individuality.
There are two choruses besides that which we have noted, but
neither of them are so impressive. In the second act Silla's
appearance on the capitol is greeted by a chorus which is powerful,
MOZART'S EARLY and supported by a running accompaniment. The
OPERAS.
last act is brought to a conclusion by a chorus,
alternating with the solo voices, but the movement is unimportant.
The overture consists of the usual three movements (Molto allegro
4-4, Andante 2-4, Molto allegro 3-8), and pretends to no connection
with the opera itself, being altogether after the ordinary pattern. The
treatment of the orchestra is not unusual. Trumpets are frequently
used, and sometimes kettledrums; but this is of little moment—more
interesting is the fact that the wind instruments are often freer and
less subordinate to the strings than usual. An attempt is evident to
render the accompaniment full and lively; the second violins have
characteristic and occasionally imitative passages. But these are
merely attempts; the influence of the traditional form overpowers all
endeavours after a freer method; it displays itself in many
mechanical habits, as, for instance, in the harmonic turn which
almost invariably precedes the singers' cadenzas:—[See Page Image]
The two festival operas composed in 1771 and 1772 belong in
essentials to the opera seria, but were subject to certain special
rules. The festa (azione) teatrale, also called serenata, were
arranged with immediate reference to the person in whose honour
they were given. They were usually also allegorical, the advantage of
this kind of poetry being that it was capable of expressing more or
less open flattery. A pastoral character was almost always given to
the treatment of the old myths, so that the dramatic element was
thrown into the background, and the brilliancy of the entertainment
was left to depend principally on the magnificent costumes and
scenery. The musical treatment became more openly and
unreservedly undramatic, and the composer was satisfied with
affording a means of display to the singers. The serenata was in the
traditional three acts, but not bound by the scenic divisions of the
"ASCANIO IN opera seria; as it originally served as an interlude
ALBA," 1771.
to other festivities, it was usually also shorter. As
a rule, it was only performed once; and took the second rank after
the opera seria. 4 It was on this account that the festival piece was
intrusted to young Mozart, the opera to Hasse.
In "Ascanio in Alba" (111 K.) Parini 5 had endeavoured to produce
a work worthy of a festivity such as the marriage of the Archduke
Ferdinand with the Duchess Marie Beatrice d'Este. Divinities, heroes,
and shepherds form the dramatis persona, and there are abundant
choruses, ballets, and spectacular effects, with no lack of flattering
by-play. The programme will serve to show what distinguished artists
6 were engaged to represent this piece:—[See Page Image]
Venus, preceded and accompanied by a chorus of genü and
graces, descends from heaven with her grandson Ascanio, and
informs him that she desires to unite him with Silvia, a lovely and
virtuous nymph of this her beloved land. Silvia is of the race of
Hercules, and Cupid having caused her to see Ascanio in a vision,
she already glows with secret love for him. Ascanio is filled with joy,
and being counselled by Venus to prove Silvia's constancy before
declaring himself to her, he expresses impatience at this
postponement of his happiness. Fauno comes to the sacrifice with a
chorus of shepherds, and reverently extols the goodness of Venus to
the country and the people. Silvia then draws near, accompanied by
Aceste and a chorus of nymphs and shepherds. The priest Aceste
informs Silvia, whom he has brought up, that Venus herself intends
to unite her to Ascanio, and to found a new city with their progeny,
MOZART'S EARLY and expresses his joy in a long aria. Silvia is
OPERAS.
amazed, and declares her love for the youth
whom she has seen in her dreams; Aceste consoles her by saying
that Venus must have sent the dreams, and she in her turn sings a
long song denoting her joy. After all have retired to prepare the
sacrifice Ascanio declares in an aria his delight with the charming
Silvia; but Venus exacts that he shall yet make trial of her virtue.
A ballet follows this act, in which the nymphs and graces astonish
the shepherds by changing the grove into a splendid temple, the
first building of the newly founded city.
Silvia beholds this new erection with admiration, and utters her
longing for the yet unknown beloved, in which she is supported by a
chorus of shepherdesses. When Ascanio appears she recognises her
lover in him; but as he feigns not to know her, she remains doubtful,
and Fauno confirms her in the error that it is not he; she swoons.
Ascanio laments that he cannot show himself in his true form, and
departs, whereupon she revives, and makes known her anguish and
determination to remain true to her duty in a long recitative and
aria. Then he returns, and throws himself at her feet. She repulses
him with the words, "Io son d' Ascanio," and flees, which gives him
opportunity for a song full of tender admiration. Aceste, to whom
she confides all, praises her for her virtue. Venus appears with the
chorus of nymphs and shepherds, and presents Ascanio to Silvia as
her spouse. After the lovers and Aceste have announced their joy in
a terzet, Venus exhorts the young rulers to fulfil their duties faithfully
to their subjects, and ascends to Olympus among the expressions of
gratitude uttered by Aceste in the name of the people; and a joyful
chorus brings the whole to a conclusion.
The description which Fauno gives of the guardian divinity of the
country, and the address of Aceste to Venus as she departs, contain
so many allusions to Maria Theresa that non-recognition was
impossible. Silvia too, of the race of Hercules (the name of Ercole
was common in the family of D'Este), the pupil of Minerva and the
muses, the pattern of virtue and modesty, is undoubtedly the
Princess Beatrice, whose intellect, literary cultivation, and amiability
were universally admired. 7 There was less to be said of the
Archduke Ferdinand; nothing could be made of him but a fair youth
with rosy cheeks. It is worthy of note that although mutual liking
founded on beauty and spiritual endowments is highly extolled, yet,
as became a royal wedding, the subjection of inclination to duty is
"ASCANIO IN made the theme of highest praise. The union had
ALBA," 1771.
not been consummated without difficulty, 8 and
some anxiety was felt as to the relations of the young couple.
"The Archduke and his wife are well and very happy," writes L.
Mozart, "which must be a great satisfaction to Her Majesty the
Empress, because it was feared that he would not think much of his
wife, she not being beautiful; but she is uncommonly amiable,
pleasant and virtuous, consequently beloved by every one, and she
has quite captivated the Archduke, for she has the best heart and
the most engaging manners in the world."
The original score, in two volumes of 480 pages, is preserved: it
contains twenty-two numbers. At the close of the first act we have
the bass part of the ballet in nine numbers, written by a copyist, and
affixed, doubtless as a guide to the conductor. L. Mozart writes
expressly that the ballet which connects the two acts was to be
composed by Wolfgang (September 7, 1771); there must have been
a special score for the manager of the ballet which has not been
preserved.
We cannot help wondering that Hasse should have founded his
prophecy of Mozart's future greatness on this opera, for it seems to
us less original than its predecessors. It certainly displays talent and
assurance, but there is not an original idea in any of the fourteen
songs to be compared with those of the former operas. The
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!

textbookfull.com

You might also like