100% found this document useful (5 votes)
61 views

Download Complete (Ebook) Machine Learning with Python Cookbook, 2nd Edition (First Early Release) by Kyle Gallatin, Chris Albon ISBN 9781098135713, 1098135717 PDF for All Chapters

The document provides information on various ebooks available for download, particularly focusing on the 'Machine Learning with Python Cookbook, 2nd Edition' by Kyle Gallatin and Chris Albon. It includes links to different versions of the cookbook and other related titles, as well as a brief introduction to the content covered in the first chapter about using NumPy for machine learning. The document emphasizes the importance of NumPy in handling data structures like vectors and matrices in machine learning workflows.

Uploaded by

rinnyicet
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 (5 votes)
61 views

Download Complete (Ebook) Machine Learning with Python Cookbook, 2nd Edition (First Early Release) by Kyle Gallatin, Chris Albon ISBN 9781098135713, 1098135717 PDF for All Chapters

The document provides information on various ebooks available for download, particularly focusing on the 'Machine Learning with Python Cookbook, 2nd Edition' by Kyle Gallatin and Chris Albon. It includes links to different versions of the cookbook and other related titles, as well as a brief introduction to the content covered in the first chapter about using NumPy for machine learning. The document emphasizes the importance of NumPy in handling data structures like vectors and matrices in machine learning workflows.

Uploaded by

rinnyicet
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/ 81

Download the Full Ebook and Access More Features - ebooknice.

com

(Ebook) Machine Learning with Python Cookbook, 2nd


Edition (First Early Release) by Kyle Gallatin,
Chris Albon ISBN 9781098135713, 1098135717

https://ebooknice.com/product/machine-learning-with-python-
cookbook-2nd-edition-first-early-release-44867920

OR CLICK HERE

DOWLOAD EBOOK

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


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

Start reading on any device today!

(Ebook) Machine Learning with Python Cookbook, 2nd Edition


by Kyle Gallatin; Chris Albon ISBN 9781098135720,
1098135725
https://ebooknice.com/product/machine-learning-with-python-
cookbook-2nd-edition-50501882

ebooknice.com

(Ebook) Machine Learning with Python Cookbook: Practical


Solutions from Preprocessing to Deep Learning (2nd Ed,
Release 5) by Chris Albon ISBN 9781491989388, 1491989386
https://ebooknice.com/product/machine-learning-with-python-cookbook-
practical-solutions-from-preprocessing-to-deep-learning-2nd-ed-
release-5-49184412
ebooknice.com

(Ebook) Machine Learning with Python Cookbook by Chris


Albon ISBN 9781491989388, 1491989386

https://ebooknice.com/product/machine-learning-with-python-
cookbook-48982446

ebooknice.com

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;


Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com
(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena
Alfredsson, Hans Heikne, Sanna Bodemyr ISBN 9789127456600,
9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com

(Ebook) Cambridge IGCSE and O Level History Workbook 2C -


Depth Study: the United States, 1919-41 2nd Edition by
Benjamin Harrison ISBN 9781398375147, 9781398375048,
1398375144, 1398375047
https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044

ebooknice.com

(Ebook) Thoughtful Machine Learning with Python Early


Release by Matthew Kirk ISBN 9781491924068, 1491924063

https://ebooknice.com/product/thoughtful-machine-learning-with-python-
early-release-11566556

ebooknice.com

(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT


II Success) by Peterson's ISBN 9780768906677, 0768906679

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

ebooknice.com

(Ebook) Machine Learning for Financial Risk Management


with Python: Algorithms for Modeling Risk (Early Release)
by Abdullah Karasan ISBN 9781492085256, 1492085251
https://ebooknice.com/product/machine-learning-for-financial-risk-
management-with-python-algorithms-for-modeling-risk-early-
release-34605294
ebooknice.com
Machine Learning with
Python Cookbook
SECOND EDITION
Practical Solutions from Preprocessing to Deep Learning

With Early Release ebooks, you get books in their earliest form—the author’s
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.

Kyle Gallatin and Chris Albon


Machine Learning with Python Cookbook
by Kyle Gallatin and Chris Albon
Copyright © 2023 Kyle Gallatin. 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: Nicole Butterfield
Development Editor Jeff Bleiel
Production Editor: Christopher Faucher
Interior Designer: David Futato
Cover Designer: Karen Montgomery
April 2018: First Edition
October 2023: Second Edition
Revision History for the Early Release
2022-08-24: First Release
See http://oreilly.com/catalog/errata.csp?isbn=9781098135720 for
release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc.
Machine Learning with Python Cookbook, the cover image, and
related trade dress are trademarks of O’Reilly Media, Inc.
The views expressed in this work are those of the authors and do
not represent the publisher’s views. While the publisher and the
authors have used good faith efforts to ensure that the information
and instructions contained in this work are accurate, the publisher
and the authors 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-098-13566-9
Chapter 1. Working with
Vectors, Matrices and Arrays
in NumPy

A NOTE FOR EARLY RELEASE READERS


With Early Release ebooks, you get books in their earliest form—the authors’
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.
This will be the 1st chapter of the final book.
If you have comments about how we might improve the content and/or
examples in this book, or if you notice missing material within this chapter,
please reach out to the authors at [email protected].

1.0 Introduction
NumPy is a foundational tool of the Python machine learning stack.
NumPy allows for efficient operations on the data structures often
used in machine learning: vectors, matrices, and tensors. While
NumPy is not the focus of this book, it will show up frequently
throughout the following chapters. This chapter covers the most
common NumPy operations we are likely to run into while working
on machine learning workflows.

1.1 Creating a Vector

Problem
You need to create a vector.
Solution
Use NumPy to create a one-dimensional array:

# Load library
import numpy as np

# Create a vector as a row


vector_row = np.array([1, 2, 3])

# Create a vector as a column


vector_column = np.array([[1],
[2],
[3]])

Discussion
NumPy’s main data structure is the multidimensional array. A vector
is just an array with a single dimension. In order to create a vector,
we simply create a one-dimensional array. Just like vectors, these
arrays can be represented horizontally (i.e., rows) or vertically (i.e.,
columns).

See Also
Vectors, Math Is Fun
Euclidean vector, Wikipedia

1.2 Creating a Matrix

Problem
You need to create a matrix.

Solution
Use NumPy to create a two-dimensional array:
# Load library
import numpy as np

# Create a matrix
matrix = np.array([[1, 2],
[1, 2],
[1, 2]])

Discussion
To create a matrix we can use a NumPy two-dimensional array. In
our solution, the matrix contains three rows and two columns (a
column of 1s and a column of 2s).
NumPy actually has a dedicated matrix data structure:

matrix_object = np.mat([[1, 2],


[1, 2],
[1, 2]])

matrix([[1, 2],
[1, 2],
[1, 2]])

However, the matrix data structure is not recommended for two


reasons. First, arrays are the de facto standard data structure of
NumPy. Second, the vast majority of NumPy operations return
arrays, not matrix objects.

See Also
Matrix, Wikipedia
Matrix, Wolfram MathWorld
1.3 Creating a Sparse Matrix

Problem
Given data with very few nonzero values, you want to efficiently
represent it.

Solution
Create a sparse matrix:

# Load libraries
import numpy as np
from scipy import sparse

# Create a matrix
matrix = np.array([[0, 0],
[0, 1],
[3, 0]])

# Create compressed sparse row (CSR) matrix


matrix_sparse = sparse.csr_matrix(matrix)

Discussion
A frequent situation in machine learning is having a huge amount of
data; however, most of the elements in the data are zeros. For
example, imagine a matrix where the columns are every movie on
Netflix, the rows are every Netflix user, and the values are how many
times a user has watched that particular movie. This matrix would
have tens of thousands of columns and millions of rows! However,
since most users do not watch most movies, the vast majority of
elements would be zero.
A sparse matrix is a matrix in which most elements are 0. Sparse
matrices only store nonzero elements and assume all other values
will be zero, leading to significant computational savings. In our
solution, we created a NumPy array with two nonzero values, then
converted it into a sparse matrix. If we view the sparse matrix we
can see that only the nonzero values are stored:

# View sparse matrix


print(matrix_sparse)

(1, 1) 1
(2, 0) 3

There are a number of types of sparse matrices. However, in


compressed sparse row (CSR) matrices, (1, 1) and (2, 0)
represent the (zero-indexed) indices of the non-zero values 1 and 3,
respectively. For example, the element 1 is in the second row and
second column. We can see the advantage of sparse matrices if we
create a much larger matrix with many more zero elements and then
compare this larger matrix with our original sparse matrix:

# Create larger matrix


matrix_large = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[3, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

# Create compressed sparse row (CSR) matrix


matrix_large_sparse = sparse.csr_matrix(matrix_large)

# View original sparse matrix


print(matrix_sparse)

(1, 1) 1
(2, 0) 3

# View larger sparse matrix


print(matrix_large_sparse)

(1, 1) 1
(2, 0) 3
As we can see, despite the fact that we added many more zero
elements in the larger matrix, its sparse representation is exactly the
same as our original sparse matrix. That is, the addition of zero
elements did not change the size of the sparse matrix.
As mentioned, there are many different types of sparse matrices,
such as compressed sparse column, list of lists, and dictionary of
keys. While an explanation of the different types and their
implications is outside the scope of this book, it is worth noting that
while there is no “best” sparse matrix type, there are meaningful
differences between them and we should be conscious about why
we are choosing one type over another.

See Also
Sparse matrices, SciPy documentation
101 Ways to Store a Sparse Matrix

1.4 Pre-allocating Numpy Arrays

Problem
You need to pre-allocate arrays of a given size with some value.

Solution
NumPy has functions for generating vectors and matrices of any size
using 0s, 1s, or values of your choice.

# Load library
import numpy as np

# Generate a vector of shape (1,5) containing all zeros


vector = np.zeros(shape=5)
# View the vector
print(vector)

array([0., 0., 0., 0., 0.])

# Generate a matrix of shape (3,3) containing all ones


matrix = np.full(shape=(3,3), 1)

# View the vector


print(matrix)

array([[1., 1., 1.],


[1., 1., 1.],
[1., 1., 1.]])

Discussion
Generating arrays prefilled with data is useful for a number of
purposes, such as making code more performant or having synthetic
data to test algorithms with. In many programming languages, pre-
allocating an array of default values (such as 0s) is considered
common practice.

1.5 Selecting Elements

Problem
You need to select one or more elements in a vector or matrix.

Solution
NumPy’s arrays make it easy to select elements in vectors or
matrices:

# Load library
import numpy as np

# Create row vector


vector = np.array([1, 2, 3, 4, 5, 6])

# Create matrix
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Select third element of vector


vector[2]

# Select second row, second column


matrix[1,1]

Discussion
Like most things in Python, NumPy arrays are zero-indexed, meaning
that the index of the first element is 0, not 1. With that caveat,
NumPy offers a wide variety of methods for selecting (i.e., indexing
and slicing) elements or groups of elements in arrays:

# Select all elements of a vector


vector[:]

array([1, 2, 3, 4, 5, 6])

# Select everything up to and including the third element


vector[:3]

array([1, 2, 3])

# Select everything after the third element


vector[3:]

array([4, 5, 6])
# Select the last element
vector[-1]

# Reverse the vector


vector[::-1]

array([6, 5, 4, 3, 2, 1])

# Select the first two rows and all columns of a matrix


matrix[:2,:]

array([[1, 2, 3],
[4, 5, 6]])

# Select all rows and the second column


matrix[:,1:2]

array([[2],
[5],
[8]])

1.6 Describing a Matrix

Problem
You want to describe the shape, size, and dimensions of the matrix.

Solution
Use the shape, size, and ndim attributes of a NumPy object:

# Load library
import numpy as np

# Create matrix
matrix = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])

# View number of rows and columns


matrix.shape

(3, 4)

# View number of elements (rows * columns)


matrix.size

12

# View number of dimensions


matrix.ndim

Discussion
This might seem basic (and it is); however, time and again it will be
valuable to check the shape and size of an array both for further
calculations and simply as a gut check after some operation.

1.7 Applying Functions Over Each Element

Problem
You want to apply some function to all elements in an array.

Solution
Use NumPy’s vectorize method:

# Load library
import numpy as np

# Create matrix
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Create function that adds 100 to something


add_100 = lambda i: i + 100

# Create vectorized function


vectorized_add_100 = np.vectorize(add_100)

# Apply function to all elements in matrix


vectorized_add_100(matrix)

array([[101, 102, 103],


[104, 105, 106],
[107, 108, 109]])

Discussion
NumPy’s vectorize class converts a function into a function that
can apply to all elements in an array or slice of an array. It’s worth
noting that vectorize is essentially a for loop over the elements
and does not increase performance. Furthermore, NumPy arrays
allow us to perform operations between arrays even if their
dimensions are not the same (a process called broadcasting). For
example, we can create a much simpler version of our solution using
broadcasting:

# Add 100 to all elements


matrix + 100

array([[101, 102, 103],


[104, 105, 106],
[107, 108, 109]])
1.8 Finding the Maximum and Minimum Values

Problem
You need to find the maximum or minimum value in an array.

Solution
Use NumPy’s max and min methods:

# Load library
import numpy as np

# Create matrix
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Return maximum element


np.max(matrix)

# Return minimum element


np.min(matrix)

Discussion
Often we want to know the maximum and minimum value in an
array or subset of an array. This can be accomplished with the max
and min methods. Using the axis parameter we can also apply the
operation along a certain axis:

# Find maximum element in each column


np.max(matrix, axis=0)
array([7, 8, 9])

# Find maximum element in each row


np.max(matrix, axis=1)

array([3, 6, 9])

1.9 Calculating the Average, Variance, and


Standard Deviation

Problem
You want to calculate some descriptive statistics about an array.

Solution
Use NumPy’s mean, var, and std:

# Load library
import numpy as np

# Create matrix
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Return mean
np.mean(matrix)

5.0

# Return variance
np.var(matrix)

6.666666666666667

# Return standard deviation


np.std(matrix)
2.5819888974716112

Discussion
Just like with max and min, we can easily get descriptive statistics
about the whole matrix or do calculations along a single axis:

# Find the mean value in each column


np.mean(matrix, axis=0)

array([ 4., 5., 6.])

1.10 Reshaping Arrays

Problem
You want to change the shape (number of rows and columns) of an
array without changing the element values.

Solution
Use NumPy’s reshape:

# Load library
import numpy as np

# Create 4x3 matrix


matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])

# Reshape matrix into 2x6 matrix


matrix.reshape(2, 6)

array([[ 1, 2, 3, 4, 5, 6],
[ 7, 8, 9, 10, 11, 12]])
Discussion
reshape allows us to restructure an array so that we maintain the
same data but it is organized as a different number of rows and
columns. The only requirement is that the shape of the original and
new matrix contain the same number of elements (i.e., the same
size). We can see the size of a matrix using size:

matrix.size

12

One useful argument in reshape is -1, which effectively means “as


many as needed,” so reshape(1, -1) means one row and as
many columns as needed:

matrix.reshape(1, -1)

array([[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]])

Finally, if we provide one integer, reshape will return a 1D array of


that length:

matrix.reshape(12)

array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

1.11 Transposing a Vector or Matrix

Problem
You need to transpose a vector or matrix.
Solution
Use the T method:

# Load library
import numpy as np

# Create matrix
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Transpose matrix
matrix.T

array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])

Discussion
Transposing is a common operation in linear algebra where the
column and row indices of each element are swapped. One nuanced
point that is typically overlooked outside of a linear algebra class is
that, technically, a vector cannot be transposed because it is just a
collection of values:

# Transpose vector
np.array([1, 2, 3, 4, 5, 6]).T

array([1, 2, 3, 4, 5, 6])

However, it is common to refer to transposing a vector as converting


a row vector to a column vector (notice the second pair of brackets)
or vice versa:

# Tranpose row vector


np.array([[1, 2, 3, 4, 5, 6]]).T
array([[1],
[2],
[3],
[4],
[5],
[6]])

1.12 Flattening a Matrix

Problem
You need to transform a matrix into a one-dimensional array.

Solution
Use flatten:

# Load library
import numpy as np

# Create matrix
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Flatten matrix
matrix.flatten()

array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Discussion
flatten is a simple method to transform a matrix into a one-
dimensional array. Alternatively, we can use reshape to create a
row vector:

matrix.reshape(1, -1)
array([[1, 2, 3, 4, 5, 6, 7, 8, 9]])

One more common method to flatten arrays is the ravel method.


Unlike flatten which returns a copy of the original array, ravel
operates on the original object itself and is therefore slightly faster.
It also lets us flatten lists of arrays, which we can’t do with the
flatten method. This operation is useful for flattening very large
arrays and speeding up code.

# Create one matrix


matrix_a = np.array([[1, 2],
[3, 4]])

# Create a second matrix


matrix_b = np.array([[5, 6],
[7, 8]])

# Create a list of matrices


matrix_list = [matrix_a, matrix_b]

# Flatten the entire list of matrices


np.ravel(matrix_list)

array([1, 2, 3, 4, 5, 6, 7, 8])

1.13 Finding the Rank of a Matrix

Problem
You need to know the rank of a matrix.

Solution
Use NumPy’s linear algebra method matrix_rank:

# Load library
import numpy as np
# Create matrix
matrix = np.array([[1, 1, 1],
[1, 1, 10],
[1, 1, 15]])

# Return matrix rank


np.linalg.matrix_rank(matrix)

Discussion
The rank of a matrix is the dimensions of the vector space spanned
by its columns or rows. Finding the rank of a matrix is easy in
NumPy thanks to matrix_rank.

See Also
The Rank of a Matrix, CliffsNotes

1.14 Getting the Diagonal of a Matrix

Problem
You need to get the diagonal elements of a matrix.

Solution
Use diagonal:

# Load library
import numpy as np

# Create matrix
matrix = np.array([[1, 2, 3],
[2, 4, 6],
[3, 8, 9]])
# Return diagonal elements
matrix.diagonal()

array([1, 4, 9])

Discussion
NumPy makes getting the diagonal elements of a matrix easy with
diagonal. It is also possible to get a diagonal off from the main
diagonal by using the offset parameter:

# Return diagonal one above the main diagonal


matrix.diagonal(offset=1)

array([2, 6])

# Return diagonal one below the main diagonal


matrix.diagonal(offset=-1)

array([2, 8])

1.15 Calculating the Trace of a Matrix

Problem
You need to calculate the trace of a matrix.

Solution
Use trace:

# Load library
import numpy as np

# Create matrix
matrix = np.array([[1, 2, 3],
[2, 4, 6],
[3, 8, 9]])
# Return trace
matrix.trace()

14

Discussion
The trace of a matrix is the sum of the diagonal elements and is
often used under the hood in machine learning methods. Given a
NumPy multidimensional array, we can calculate the trace using
trace. We can also return the diagonal of a matrix and calculate its
sum:

# Return diagonal and sum elements


sum(matrix.diagonal())

14

See Also
The Trace of a Square Matrix

1.16 Calculating Dot Products

Problem
You need to calculate the dot product of two vectors.

Solution
Use NumPy’s dot:

# Load library
import numpy as np

# Create two vectors


vector_a = np.array([1,2,3])
vector_b = np.array([4,5,6])

# Calculate dot product


np.dot(vector_a, vector_b)

32

Discussion
The dot product of two vectors, a and b, is defined as:

where ai is the ith element of vector a. We can use NumPy’s dot


function to calculate the dot product. Alternatively, in Python 3.5+
we can use the new @ operator:

# Calculate dot product


vector_a @ vector_b

32

See Also
Vector dot product and vector length, Khan Academy
Dot Product, Paul’s Online Math Notes

1.17 Adding and Subtracting Matrices

Problem
You want to add or subtract two matrices.
Solution
Use NumPy’s add and subtract:

# Load library
import numpy as np

# Create matrix
matrix_a = np.array([[1, 1, 1],
[1, 1, 1],
[1, 1, 2]])

# Create matrix
matrix_b = np.array([[1, 3, 1],
[1, 3, 1],
[1, 3, 8]])

# Add two matrices


np.add(matrix_a, matrix_b)

array([[ 2, 4, 2],
[ 2, 4, 2],
[ 2, 4, 10]])

# Subtract two matrices


np.subtract(matrix_a, matrix_b)

array([[ 0, -2, 0],


[ 0, -2, 0],
[ 0, -2, -6]])

Discussion
Alternatively, we can simply use the + and - operators:

# Add two matrices


matrix_a + matrix_b

array([[ 2, 4, 2],
[ 2, 4, 2],
[ 2, 4, 10]])
1.18 Multiplying Matrices

Problem
You want to multiply two matrices.

Solution
Use NumPy’s dot:

# Load library
import numpy as np

# Create matrix
matrix_a = np.array([[1, 1],
[1, 2]])

# Create matrix
matrix_b = np.array([[1, 3],
[1, 2]])

# Multiply two matrices


np.dot(matrix_a, matrix_b)

array([[2, 5],
[3, 7]])

Discussion
Alternatively, in Python 3.5+ we can use the @ operator:

# Multiply two matrices


matrix_a @ matrix_b

array([[2, 5],
[3, 7]])

If we want to do element-wise multiplication, we can use the *


operator:
# Multiply two matrices element-wise
matrix_a * matrix_b

array([[1, 3],
[1, 4]])

See Also
Array vs. Matrix Operations, MathWorks

1.19 Inverting a Matrix

Problem
You want to calculate the inverse of a square matrix.

Solution
Use NumPy’s linear algebra inv method:

# Load library
import numpy as np

# Create matrix
matrix = np.array([[1, 4],
[2, 5]])

# Calculate inverse of matrix


np.linalg.inv(matrix)

array([[-1.66666667, 1.33333333],
[ 0.66666667, -0.33333333]])

Discussion
The inverse of a square matrix, A, is a second matrix A–1, such that:
where I is the identity matrix. In NumPy we can use linalg.inv
to calculate A–1 if it exists. To see this in action, we can multiply a
matrix by its inverse and the result is the identity matrix:

# Multiply matrix and its inverse


matrix @ np.linalg.inv(matrix)

array([[ 1., 0.],


[ 0., 1.]])

See Also
Inverse of a Matrix

1.20 Generating Random Values

Problem
You want to generate pseudorandom values.

Solution
Use NumPy’s random:

# Load library
import numpy as np

# Set seed
np.random.seed(0)

# Generate three random floats between 0.0 and 1.0


np.random.random(3)

array([ 0.5488135 , 0.71518937, 0.60276338])


Discussion
NumPy offers a wide variety of means to generate random numbers,
many more than can be covered here. In our solution we generated
floats; however, it is also common to generate integers:

# Generate three random integers between 0 and 10


np.random.randint(0, 11, 3)

array([3, 7, 9])

Alternatively, we can generate numbers by drawing them from a


distribution:

# Draw three numbers from a normal distribution with mean


0.0
# and standard deviation of 1.0
np.random.normal(0.0, 1.0, 3)

array([-1.42232584, 1.52006949, -0.29139398])

# Draw three numbers from a logistic distribution with mean


0.0 and scale of 1.0
np.random.logistic(0.0, 1.0, 3)

array([-0.98118713, -0.08939902, 1.46416405])

# Draw three numbers greater than or equal to 1.0 and less


than 2.0
np.random.uniform(1.0, 2.0, 3)

array([ 1.47997717, 1.3927848 , 1.83607876])

Finally, it can sometimes be useful to return the same random


numbers multiple times to get predictable, repeatable results. We
can do this by setting the “seed” (an integer) of the pseudorandom
generator. Random processes with the same seed will always
produce the same output. We will use seeds throughout this book so
that the code you see in the book and the code you run on your
computer produces the same results.
Chapter 2. Loading Data

A NOTE FOR EARLY RELEASE READERS


With Early Release ebooks, you get books in their earliest form—the authors’
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.
This will be the 2nd chapter of the final book.
If you have comments about how we might improve the content and/or
examples in this book, or if you notice missing material within this chapter,
please reach out to the authors at [email protected].

2.0 Introduction
The first step in any machine learning endeavor is to get the raw
data into our system. The raw data might be a logfile, dataset file,
database, or cloud blob store such as Amazon S3. Furthermore,
often we will want to retrieve data from multiple sources.
The recipes in this chapter look at methods of loading data from a
variety of sources, including CSV files and SQL databases. We also
cover methods of generating simulated data with desirable
properties for experimentation. Finally, while there are many ways to
load data in the Python ecosystem, we will focus on using the
pandas library’s extensive set of methods for loading external data,
and using scikit-learn—an open source machine learning library in
Python—for generating simulated data.
2.1 Loading a Sample Dataset

Problem
You want to load a preexisting sample dataset from the scikit-learn
library.

Solution
scikit-learn comes with a number of popular datasets for you to use:

# Load scikit-learn's datasets


from sklearn import datasets

# Load digits dataset


digits = datasets.load_digits()

# Create features matrix


features = digits.data

# Create target vector


target = digits.target

# View first observation


features[0]

array([ 0., 0., 5., 13., 9., 1., 0., 0.,


0., 0., 13.,
15., 10., 15., 5., 0., 0., 3., 15.,
2., 0., 11.,
8., 0., 0., 4., 12., 0., 0., 8.,
8., 0., 0.,
5., 8., 0., 0., 9., 8., 0., 0.,
4., 11., 0.,
1., 12., 7., 0., 0., 2., 14., 5.,
10., 12., 0.,
0., 0., 0., 6., 13., 10., 0., 0.,
0.])
Discussion
Often we do not want to go through the work of loading,
transforming, and cleaning a real-world dataset before we can
explore some machine learning algorithm or method. Luckily, scikit-
learn comes with some common datasets we can quickly load. These
datasets are often called “toy” datasets because they are far smaller
and cleaner than a dataset we would see in the real world. Some
popular sample datasets in scikit-learn are:
load_boston
Contains 503 observations on Boston housing prices. It is a good
dataset for exploring regression algorithms.

load_iris
Contains 150 observations on the measurements of Iris flowers.
It is a good dataset for exploring classification algorithms.

load_digits
Contains 1,797 observations from images of handwritten digits. It
is a good dataset for teaching image classification.
To see more details on any of the datasets above, you can print the
DESCR attribute:

# Load scikit-learn's datasets


from sklearn import datasets

# Load digits dataset


digits = datasets.load_digits()

# Print the attribute


print(digits.DESCR)

.. _digits_dataset:

Optical recognition of handwritten digits dataset


--------------------------------------------------
**Data Set Characteristics:**

:Number of Instances: 1797


:Number of Attributes: 64
:Attribute Information: 8x8 image of integer pixels in
the range 0..16.
:Missing Attribute Values: None
:Creator: E. Alpaydin (alpaydin '@' boun.edu.tr)
:Date: July; 1998
...

See Also
scikit-learn toy datasets
The Digit Dataset

2.2 Creating a Simulated Dataset

Problem
You need to generate a dataset of simulated data.

Solution
scikit-learn offers many methods for creating simulated data. Of
those, three methods are particularly useful: make_regression,
make_classification, and make_blobs.
When we want a dataset designed to be used with linear regression,
make_regression is a good choice:

# Load library
from sklearn.datasets import make_regression

# Generate features matrix, target vector, and the true


coefficients
features, target, coefficients = make_regression(n_samples
= 100,
n_features
= 3,

n_informative = 3,
n_targets
= 1,
noise =
0.0,
coef =
True,

random_state = 1)

# View feature matrix and target vector


print('Feature Matrix\n', features[:3])
print('Target Vector\n', target[:3])

Feature Matrix
[[ 1.29322588 -0.61736206 -0.11044703]
[-2.793085 0.36633201 1.93752881]
[ 0.80186103 -0.18656977 0.0465673 ]]
Target Vector
[-10.37865986 25.5124503 19.67705609]

If we are interested in creating a simulated dataset for classification,


we can use make_classification:

# Load library
from sklearn.datasets import make_classification

# Generate features matrix and target vector


features, target = make_classification(n_samples = 100,
n_features = 3,
n_informative = 3,
n_redundant = 0,
n_classes = 2,
weights = [.25,
.75],
random_state = 1)

# View feature matrix and target vector


print('Feature Matrix\n', features[:3])
print('Target Vector\n', target[:3])
Feature Matrix
[[ 1.06354768 -1.42632219 1.02163151]
[ 0.23156977 1.49535261 0.33251578]
[ 0.15972951 0.83533515 -0.40869554]]
Target Vector
[1 0 0]

Finally, if we want a dataset designed to work well with clustering


techniques, scikit-learn offers make_blobs:

# Load library
from sklearn.datasets import make_blobs

# Generate feature matrix and target vector


features, target = make_blobs(n_samples = 100,
n_features = 2,
centers = 3,
cluster_std = 0.5,
shuffle = True,
random_state = 1)

# View feature matrix and target vector


print('Feature Matrix\n', features[:3])
print('Target Vector\n', target[:3])

Feature Matrix
[[ -1.22685609 3.25572052]
[ -9.57463218 -4.38310652]
[-10.71976941 -4.20558148]]
Target Vector
[0 1 1]

Discussion
As might be apparent from the solutions, make_regression
returns a feature matrix of float values and a target vector of float
values, while make_classification and make_blobs return a
feature matrix of float values and a target vector of integers
representing membership in a class.
scikit-learn’s simulated datasets offer extensive options to control the
type of data generated. scikit-learn’s documentation contains a full
description of all the parameters, but a few are worth noting.
In make_regression and make_classification,
n_informative determines the number of features that are used
to generate the target vector. If n_informative is less than the
total number of features (n_features), the resulting dataset will
have redundant features that can be identified through feature
selection techniques.
In addition, make_classification contains a weights
parameter that allows us to simulate datasets with imbalanced
classes. For example, weights = [.25, .75] would return a
dataset with 25% of observations belonging to one class and 75% of
observations belonging to a second class.
For make_blobs, the centers parameter determines the number
of clusters generated. Using the matplotlib visualization library,
we can visualize the clusters generated by make_blobs:

# Load library
import matplotlib.pyplot as plt

# View scatterplot
plt.scatter(features[:,0], features[:,1], c=target)
plt.show()
See Also
make_regression documentation
make_classification documentation
make_blobs documentation

2.3 Loading a CSV File

Problem
You need to import a comma-separated values (CSV) file.

Solution
Use the pandas library’s read_csv to load a local or hosted CSV
file:

# Load library
import pandas as pd

# Create URL
url =
'https://raw.githubusercontent.com/chrisalbon/sim_data/mast
er/data.csv'

# Load dataset
dataframe = pd.read_csv(url)

# View first two rows


dataframe.head(2)

integer datetime category


0 5 2015-01-01 00:00:00 0
1 5 2015-01-01 00:00:01 0

Discussion
There are two things to note about loading CSV files. First, it is often
useful to take a quick look at the contents of the file before loading.
It can be very helpful to see how a dataset is structured beforehand
and what parameters we need to set to load in the file. Second,
read_csv has over 30 parameters and therefore the documentation
can be daunting. Fortunately, those parameters are mostly there to
allow it to handle a wide variety of CSV formats. For example, CSV
files get their names from the fact that the values are literally
separated by commas (e.g., one row might be 2,"2015-01-01
00:00:00",0); however, it is common for “CSV” files to use other
characters as separators, like tabs. pandas’ sep parameter allows us
to define the delimiter used in the file. Although it is not always the
case, a common formatting issue with CSV files is that the first line
of the file is used to define column headers (e.g., integer,
datetime, category in our solution). The header parameter
allows us to specify if or where a header row exists. If a header row
does not exist, we set header=None.
2.4 Loading an Excel File

Problem
You need to import an Excel spreadsheet.

Solution
Use the pandas library’s read_excel to load an Excel spreadsheet:

# Load library
import pandas as pd

# Create URL
url =
'https://raw.githubusercontent.com/chrisalbon/sim_data/mast
er/data.xlsx'

# Load data
dataframe = pd.read_excel(url, sheet_name=0, header=1)

# View the first two rows


dataframe.head(2)

5 2015-01-01 00:00:00 0
0 5 2015-01-01 00:00:01 0
1 9 2015-01-01 00:00:02 0

Discussion
This solution is similar to our solution for reading CSV files. The main
difference is the additional parameter, sheetname, that specifies
which sheet in the Excel file we wish to load. sheetname can
accept both strings containing the name of the sheet and integers
pointing to sheet positions (zero-indexed). If we need to load
multiple sheets, include them as a list. For example, sheetname=
[0,1,2, "Monthly Sales"] will return a dictionary of pandas
DataFrames containing the first, second, and third sheets and the
sheet named Monthly Sales.

2.5 Loading a JSON File

Problem
You need to load a JSON file for data preprocessing.

Solution
The pandas library provides read_json to convert a JSON file into
a pandas object:

# Load library
import pandas as pd

# Create URL
url =
'https://raw.githubusercontent.com/chrisalbon/sim_data/mast
er/data.json'

# Load data
dataframe = pd.read_json(url, orient='columns')

# View the first two rows


dataframe.head(2)

category datetime integer


0 0 2015-01-01 00:00:00 5
1 0 2015-01-01 00:00:01 5

Discussion
Importing JSON files into pandas is similar to the last few recipes we
have seen. The key difference is the orient parameter, which
indicates to pandas how the JSON file is structured. However, it
might take some experimenting to figure out which argument
(split, records, index, columns, and values) is the right one.
Another helpful tool pandas offers is json_normalize, which can
help convert semistructured JSON data into a pandas DataFrame.

See Also
json_normalize documentation

2.6 Loading a parquet file

Problem
You need to load a parquet file.

Solution
The pandas read_parquet function allows us to read in parquet
files:

# Load library
import pandas as pd

# Create URL
url = 'https://machine-learning-python-
cookbook.s3.amazonaws.com/data.parquet'

# Load data
dataframe = pd.read_parquet(url)

# View the first two rows


dataframe.head(2)

category datetime integer


0 0 2015-01-01 00:00:00 5
category datetime integer
1 0 2015-01-01 00:00:01 5

Discussion
Paruqet is a popular data storage format in the large data space. It
is often used with big data tools such as hadoop and spark. While
Pyspark is outside the focus of this book, it’s highly likely companies
operating a large scale will use an efficient data storage format such
as parquet and it’s valuable to know how to read it into a dataframe
and manipulate it.

See Also
Apache Parquet Documentation

2.7 Querying a SQLite Database

Problem
You need to load data from a database using the structured query
language (SQL).

Solution
pandas’ read_sql_query allows us to make a SQL query to a
database and load it:

# Load libraries
import pandas as pd
from sqlalchemy import create_engine

# Create a connection to the database


database_connection = create_engine('sqlite:///sample.db')

# Load data
Discovering Diverse Content Through
Random Scribd Documents
Esta ocasion mi deseo,
No tengo de despreciarla.
En oyéndome, me iré.
D.ª BInés,
eat. esa puerta guarda,
Ya que es fuerza que le oiga,
A precio de que se vaya.
(Va Inés hácia la puerta.)

D. Dieg
Yo.salí, Beatriz hermosa,
De Valencia... (Vuelve Inés, muy asustada.)
Inés. ¡Ay desdichada!
D.ª B¿Qué
eat. es eso?
Inés. Mi señor viene.
D.ª B¡Triste
eat. de mí!
Inés. Ea, ¿qué aguardas?
Del aposento de anoche
Hoy el sagrado nos valga.
D. Dieg
¡Qué
. desdichado que ha sido
Siempre mi amor! (Escóndese.)
D.ª Beat. ¡Qué tirana
Ha sido siempre mi estrella!
Inés. ¿Qué te turbas y desmayas?
No temas, que mi señor
No trae recelo de nada,
Pues entra en su cuarto ántes
Que en el tuyo.
D.ª Beat. ¡Ay, Inés, cuánta
Es mi pena!

ESCENA XIX.
DON JUAN, DON CÁRLOS.—DOÑA BEATRIZ, INÉS; DON DIEGO,
al paño.

D. Juan
(Ap.. á Cárlos.) Yo venía,
Cárlos, como digo, á casa.
Cuando ví que un hombre en ella
Entró: en la calle me aguarda,
Y por ventana ni puerta
Dejes que ninguno salga.
D. Cárl
Entra
. y fía, que seguras
Tienes, Don Juan, las espaldas. (Vase.)
D. Juan
Beatriz...
.
D.ª Beat. Hermano.
D. Juan. ¿Qué hacias?
D.ª BAquí
eat. con Inés estaba.
D. Juan
Está. bien.
D.ª Beat. ¿Adónde vas?
D. Juan
¿Es. novedad que en mi casa
Éntre yo donde quisiere?
D.ª BNo
eatlo. es; pero extraño...
D. Juan. Aparta.
D.ª BEleatmodo
. de hablarme.
D. Juan. Quita
De delante.
D.ª B(Ap.)
eat. ¡Pena extraña!
D. Dieg
(Ap.. al paño.) Hácia este aposento viene;
Salida tiene á otra cuadra:
Quiero ver si más seguro
Lugar mis recelos hallan. (Vase.)
D. Juan
Desta
. suerte he de salir
De una vez de dudas tantas. (Saca la espada.)
D.ª B(Ap.)
eat. Para entrar al aposento
(¡Ay de mí!) la espada saca.
(Entra Don Juan en el cuarto donde estaba Don Diego.)

Inés. Muertes de hombres ha de haber.


D.ª BInés,
eat. la suerte está echada.
Inés. Y echada á perder, señora.
D.ª BSin
eat.vida estoy y sin alma.
Inés. Pues cualquiera dellas es
Importantísima alhaja.
Huyamos.
D.ª Beat. Aun para huir
Aliento y valor me falta.
Inés. Don Diego del aposento
Salió, pues que no le halla
En él.

ESCENA XX.
LEONOR, y luego DON DIEGO.—DOÑA BEATRIZ, INÉS.

Leonor .
(Dentro.) ¡Ay de mí infelice!
D.ª BPasando
eat. de cuadra en cuadra,
Dió adonde estaba Isabel.
Ella de verle se espanta,
Y huyendo dél, hasta aquí
Viene... A este lado te aparta.
(Retíranse las dos, y sale Leonor con luz, y tras ella Don Diego.)

Leonor
Hombre,
. que más me pareces
Sombra, ilusion ó fantasma,
¿Qué me quieres? ¿No bastó
El echarme de mi casa,
Sino tambien de la ajena?
D. Dieg
Mujer,
. que más me retratas
Fantasma, ilusion ó sombra,
¿Mis desdichas no me bastan,
Sin las que tú ahora me añades,
Pues segunda vez me matas?
Pero no, pues hoy...

ESCENA XXI.
DON JUAN.—LEONOR, DON DIEGO; DOÑA BEATRIZ é INÉS,
retiradas.

D. Juan. En vano
Aunque el centro en sus entrañas
Te esconda, podrás, Don Diego.
D. Dieg
Detened,
. Don Juan, la espada;
Que aunque vuestra casa está
En esta parte agraviada,
No vuestro honor; y si puedo
Satisfacer con palabras
Al empeño, mejor es;
Pues es cosa averiguada
Que es la venganza mejor
No haber menester venganza.
D. Juan . Don Diego Centellas es.
(Ap.)
Con Leonor está: aquí hallan
Mis sospechas el mejor
Desengaño. Albricias, alma;
Que aunque esta es desgracia, es
Más tolerable desgracia.
D.ª B(Ap.
eat.á Inés.) Suspenso el acero, al verle,
Se quedó. Oye lo que hablan.
D. Dieg
Yo,. Don Juan, amé en la corte
A Leonor, que es esta dama,
En cuya casa una noche
Me sucedió una desgracia.
Viene á Valencia, y teniendo
Noticia que en vuestra casa
Estaba...
Leonor .
(Ap.) ¡Ay de mí!
D. Dieg. Esta noche
Me atreví á entrar aquí á hablarla.
D.ª B(Ap.
eat.á Inés.) ¡Qué buena disculpa, Inés,

Si ahora Isabel conformara


Con ella! Haz señas que diga
Que sí, que es ella la dama.
(Hace Inés señas á Leonor.)

LeonorDon
. Juan, cuanto aquí has oido,
Es verdad; Don Diego es causa
De mi fortuna, y por quien
Desterrada de mi patria,
De mi padre aborrecida,
De mi esposo despreciada,
En este estado, este traje
Vivo, sirviendo á tu hermana.
Inés. (Ap. á su ama.)
La seña entendió.
D.ª Beat. Y lo finge
Tan bien, que áun á mí me engaña.
LeonorPero
. diga él si yo aquí
Ni allá le di...
D. Juan. Calla, calla.
LeonorOcasion...
.
D. Juan. No te disculpes.
(Ap. ¿Hay mujer más desgraciada?)
Inés. (Ap. á Beatriz.) Mucho la debes, señora,
Pues se culpa por tu causa.
D.ª BSólo
eat. que lo haya creido
Mi hermano, es lo que nos falta.
D. Juan . ¿Qué haré? que aunque esté seguro
(Ap.)
Yo, que lo esté Cárlos falta.

ESCENA XXII.
DON CÁRLOS.—Dichos.

D. Cárl
(Ap.. desde la puerta.)
Habiendo en la calle oido
Ruido acá dentro de espadas,
Dejo la puerta, y á hallar
Vengo á Don Juan... Mas las armas
Tienen suspensas los dos.
Desde aquí oiré lo que tratan;
Que quizás será su honor
Conveniencia á la desgracia.
D. Dieg
Esta
. es vuestra ofensa, y pues
A ser agravio no pasa,
Mirad si os estará bien,
O remitirla ó vengarla.
D. Juan
Don. Diego, vuestras disculpas
Convienen con señas várias
Que yo tengo de Leonor.
D. Cárl
¿Qué
. escucho? ¡Pena tirana!
A Leonor nombró, y Don Diego...
D. Juan
Pero
. una pregunta falta.
¿Es esta la primer noche
Que aquí habeis entrado á hablarla?
D. Dieg
(Ap.. Malicia trae la pregunta.
Por sí ó por no he de salvarla.)
No, que anoche entré por esa
Puerta, y por esa ventana
Salí: sabida la culpa,
¿Qué importa la circunstancia?
D. Juan
Importa
. más que pensais.
D. Cárl . Contra mí es contra quien paran
(Ap.)
Los celos de Don Juan, ¡cielos!
D.ª B(eat
Ap. .Ya que lo ha creido, salga
Yo ahora.) Pues, ten de mí, (Sale.)
Don Juan, la desconfianza,
Y mira lo que me envía,
Para servirme, tu dama.
(Aparte á Leonor.)

Perdona, amiga, y prosigue.


Leonor . á Doña Beatriz.)
(Ap.
No entiendo lo que me mandas.
D. Juan
No. es tiempo deso, Beatriz,
Pues aunque con señas tantas
Me satisfaga Don Diego,
Estar Leonor en mi casa
Por órden de quien á ella
La envió, á mí no me saca
De la obligacion en que
Me pone mi sangre hidalga;
Y así, aunque por ella venga,
Y no por tí, eso me basta
Para que el atrevimiento
Castigue yo. (Sale Don Cárlos.)
D. Cárl. Aquesa instancia
Pues me toca á mí el sentirla,
Tambien me toca el vengarla.
Leonor . ¡Qué miro! ¿Cárlos aquí?
(Ap.)
Esto sólo me faltaba.
D. Dieg
Pues
. ¿quién sois vos, que quereis
Tomar ahora la demanda?
D. Cárl
Bien
. pudierais conocerme;
Que razones teneis hartas.
Yo soy aquel que por muerto
Os dejó; y ahora trata
Acabar lo que empezado
Dejó entónces.
Leonor. ¡Pena extraña!
D. Dieg
Antes
. pienso que venís
A que yo tome venganza
Hoy de todo.
D. Juan. A vuestro lado,
Cárlos, estoy.
D. Dieg. No me espanta
La ventaja de los dos. (Riñen.)

ESCENA XXIII.
GINÉS, gente.—Dichos.

Ginés(Dentro.)
. Aquí son las cuchilladas.
Entrad todos. (Salen Ginés y gente.)
Gin. y gente. ¿Qué es aquesto?
D.ª B(Ap.
eat.á Inés.) Inés, esas luces mata,
Por si podemos así
Excusar desdichas tantas.
(Apaga la luz, y riñen.)

GinésNadie
. tire, estando á oscuras.
D. Juan
Ved . todos que esta es mi casa.
GinésEncienda
. usted una luz,
Y lo verán.
Leonor. ¡Qué desgracia!
D. Dieg . La puerta hallé: esto no es
(Ap.)
Volver al riesgo la cara,
Sino fiar á mejor
Ocasion mis esperanzas. (Vase.)
D.ª B(Ap.)
eat. A mi cuarto me retiro

Llena de confusas ánsias. (Vase.)


Inés. (Ap.) Tan buena hacienda hemos hecho,
Que de puro buena, es mala. (Vase.)
GinésSeñor,
. ¿dónde estás, que ya
El cirujano te aguarda?
D. Cárl
¡Muere,
. traidor!
Ginés. Muerto soy,
Que mandarlo vusted basta.
(Ap. El diablo que más espere,
A que de véras lo hagan.) (Vase.)
Uno. Muerto está uno: por si viene
Justicia, de aquesta casa
Salgamos. Huyamos todos. (Vase la gente.)
D. Juan
¡Hola!
. Aquí unas luces saca...
Mas yo por ellas iré. (Vase.)
Leonor . De confusa y de turbada,
(Ap.)
Tropezando en mis desdichas
De aquí no muevo las plantas.
D. Cárl
El .puesto he de sustentar;
Que aunque siento que se vayan
Todos, no he de faltar yo
De donde saqué la espada.

ESCENA XXIV.
DON JUAN, con luz.—LEONOR, DON CÁRLOS.

D. Juan
Ya.hay luz aquí.
Leonor. Cárlos, tente.
D. Juan
¿Solos
. los dos?
D. Cárl. ¿Qué te espantas?
Porque si yo á mi enemigo
No puedo volver la espalda,
Hallándome con Leonor,
Con mi enemigo me hallas;
Pero enemigo de quien
La victoria es huir.
(Quiere irse, y detiénele Don Juan.)

D. Juan. Aguarda.
D. Cárl
Déjame,
. que en seguimiento
De esotro, huyendo á este, salga.
D. Juan
Ya.no hay tras quien.
Leonor. ¡Quién pudiera
Rasgarse el pecho, y que hablara
El corazon con acciones,
Y no la voz con palabras!
D. Cárl
Fuera
. el corazon tambien
Traidor; que ser tuyo basta.
Leonor
Fuera
. leal, por ser mio.
D. Cárl
¡Bien
. el lance lo declara,
Que acabo de ver! ¡Ay fiera!
Cuando no consideraras
Las finezas que me debes,
Consideraras que estabas
En casa de Don Juan.
Leonor. Pues
¿Qué culpa contra mí hallas
En las locuras de un hombre?
D. Cárl
Ninguna.
. Ahorremos demandas
Y respuestas.—Primo, amigo,
Pues tan felizmente acaba
Para tí aquella ocasion,
Que detuvo mi jornada,
Cuanto infeliz para mí,
Adios; que aunque con infamia
Salga de Valencia, es fuerza
Que della esta noche salga.
Diga mi enemigo que huyo;
Que no quiero honor ni fama.
A esa mujer, porque en fin
La quise bien, te la encarga
Mi amistad, no para que
La tengas más en tu casa,
Sino para que la dejes
Que en cas de Don Diego vaya.
Logre él felice su amor;
Y ella gustosa... Mas nada
Digo. Adios, Don Juan.
Leonor. ¡Ay, cielos!
Espera, Cárlos.
D. Cárl. ¿Que áun hablas?
Leonor
Si.yo supe...
D. Cárl. No prosigas.
Leonor
Que
. aquí...
D. Cárl. No me digas nada.
Leonor
¿No?
. Pues yo... sí... Hablar no puedo.
Vista y aliento me faltan.
¡Jesus mil veces! (Desmáyase.)
D. Juan. Cayó
En mis brazos desmayada.
D. Cárl
Tenla,
. Don Juan. ¡Ay, Leonor!
Que te adoro, aunque me matas,
Y es muy distinto sentir
Tu traicion que tu desgracia.
D. Juan
En. lágrimas y gemidos
Se le han vuelto las palabras.
Esperad, Cárlos, á que
Entre al cuarto de mi hermana
Con ella.
D. Cárl. Sí, Don Juan, id.
Algun remedio se le haga...
Mas dejadla que se muera,
Pues para otro amor se guarda.
D. Juan
Despues
. veremos los dos
Lo que hemos de hacer. (Éntrala Don Juan.)
D. Cárl. ¡Mal haya
Rendimiento tan postrado,
Pasion tan avasallada,
Afecto tan abatido,
Y voluntad tan postrada,
A más quejas, más amor,
A más agravios, más ánsias,
A más traicion, más firmeza!
Mas ¿qué me admira y espanta?
Que quien no ama los defectos,
No puede decir que ama.
JORNADA TERCERA.

ESCENA PRIMERA.
DON CÁRLOS, DON JUAN.

D. Cárl
¿Volvió
. del desmayo?
D. Juan. Sí,
Pero volvió de manera,
Que pienso que mejor fuera
No haber vuelto.
D. Cárl. ¿Cómo así?
D. Juan
Como
. al instante que allí
Restauró el perdido aliento,
Fué tan grande el sentimiento
Que de tenerle ha tenido,
Que á un tiempo cobró el sentido
Y perdió el entendimiento,
Segun los extremos son
Que hace confusa y turbada.
D. Cárl
¿Qué
. dice?
D. Juan. Que es desdichada,
Sin oirla su razon.
D. Cárl
¡Oh,
. mal haya mi pasion!
D. Juan
Vos. ¿qué habeis determinado?
D. Cárl
Dos. cosas he imaginado,
Y sólo, Don Juan, quisiera
Que nadie me las oyera
Sin estar enamorado.
¿Quereis que os diga, Don Juan,
Sobre tantas confusiones,
Fantasías é ilusiones
Como á mí vienen y van,
Cuáles son las que me dan
Más gusto cuando las toco,
Cuáles las que me provoco
Más á ejecutarlas?
D. Juan. Sí.
D. Cárl
No. os habeis de reir de mí,
Pues confieso que estoy loco.
Si en este estado pudiera
Yo conseguir que á Leonor
Todo su perdido honor
Don Diego satisfaciera,
Que honrada y en paz volviera
Con su padre á su lugar,
Fuera la más singular
Venganza: y á esta mujer
La sabré hacer un placer
Cuando ella espera un pesar.
Leonor está enamorada,
Don Diego lo está tambien
(Dígalo el lance): pues bien,
¿Qué pierdo yo? Todo y nada.
Y así, en pena tan airada
Como tengo y he tenido,
Sólo este me ha parecido
Que despicarme sabrá:
Ganemos á Leonor, ya
Que á Leonor hemos perdido.
D. Juan
Es.vuestra resolucion
Tan honrada como vuestra;
Y bien en su efecto muestra
Ser hija de una pasion
Tan noble.
D. Cárl. Pues á su accion
¿Qué medio, Don Juan, pondremos?
D. Juan
No. sé, porque si queremos
A Don Diego hablar yo y vos,
Por lo mismo que los dos
El casamiento tratemos,
Él no lo hará; que no fuera
Justo que un hombre otorgara,
Por más que él lo deseara,
Lo que el galan le pidiera
De su dama. De manera
Que otra persona ha de haber.
D. Cárl
Pues
. lo que se puede hacer
Es que á su padre digais
Como á Leonor ocultais,
Y él lo podrá disponer.
D. Juan
Tiene
. eso un inconveniente.
D. Cárl
¿Qué?
.
D. JuanEl
. empeño de los dos:
Fuera de que entónces vos
No haceis la accion.
D. Cárl. Cuerdamente
Decís. ¿Quién habrá que intente
Esta plática mover?
D. Juan
Ya.sé yo quién ha de ser:
Veréis que todo lo allana.
D. Cárl
¿Quién?
.
D. Juan. Doña Beatriz, mi hermana;
Que es en efecto mujer
Con quien, lo uno, no habrá
Duelo en la proposicion;
Y lo otro, es debida accion
Suya el honrar á quien ya
Dentro de su casa está
Declarada por quien es.
D. Cárl
Bien
. pensais.
D. Juan. Escondéos pues,
Miéntras yo á tratarlo llego.
D. Cárl
Yo,. ¿por qué?
D. Juan. Porque Don Diego
Ni el padre os vea hasta despues.
D. Cárl
¿Yo. esconderme?
D. Juan. O deshacer
Toda nuestra pretension.
D. Cárl
Yo.lo haré con condicion
Que nadie lo ha de saber
Sino vos.
D. Juan. Así ha de ser.
D. Cárl
Pues
. id con Dios. (Ap. ¡Ay, Leonor,
Cuánto debes á mi amor,
Pues te da, fiera homicida,
Sobre un agravio la vida,
Sobre otro agravio el honor!)
(Escóndese, y cierra por dentro.)

ESCENA II.
DON JUAN.

D. Juan
Si .á conseguir esto llego,
A nadie le está mejor,
Pues quedo bien con Leonor,
Con su padre y con Don Diego,
Y vengo á mirarme luégo
Sin el empeño á que he estado
Por Don Cárlos obligado;
Y así tengo de esforzar
Esta accion, hasta quedar
Gustoso y desengañado.

ESCENA III.
DOÑA BEATRIZ.—DON JUAN.

D.ª B¿Está
eat. Don Cárlos aquí?
D. Juan
No,. Beatriz.
D.ª Beat. Pues yo á tu cuarto
Sólo á buscarle venía.
D. Juan
Cuando
. le dió aquel desmayo
A Leonor, le dejé aquí,
Y aquí al volver no le hallo.
(Ap. Ni áun mi hermana ha de pensar
Que se ha escondido Don Cárlos.)
D.ª BSin
eat.duda que su valor
Tras Don Diego le ha llevado.
D. Juan
Yo,. por no saber adónde
Hallarle podré, no salgo
Tras él; mas tú, ¿qué le quieres?
D.ª BDecirle,
eat. Don Juan, que cuando
Por amante y por rendido
No fuese, por cortesano
Y caballero tuviese
De su dama, que llorando
Está, lástima.
D. Juan. ¿Qué dice?
D.ª BQue
eat. con solo hablar á Cárlos
Consuelo tendrá.
D. Juan. Pues si él
No está aquí y solos estamos,
Una cosa á tu cordura
He de fiar, Beatriz.
D.ª Beat. Harto
Será que fíes de mí
Nada, porque quien te ha dado
Ocasion para que della
Desconfíes, Don Juan, tanto
Que presumas que ha podido
Ocasionar el cuidado
Con que anoche entraste en casa,
Parece que es muy contrario
Que fíes y desconfíes
A un mismo tiempo.
D. Juan. Excusado
Será, Beatriz, que yo haga
Dese sentimiento caso,
Sabiendo tú cuanto estimo
Tu virtud y tu recato.
Y en fin, tú sola, Beatriz,
Podrás hoy de riesgos tantos
Como amenazan las vidas
De Don Diego y de Don Cárlos,
Y áun la mia (pues es fuerza
Hallarme en el duelo de ambos),
Librarnos.
D.ª Beat. ¿Yo? ¿de qué suerte?
D. Juan
Desta
. suerte: oye y sabráslo.
Yo intento, por ser quien es
Leonor, cuidar del amparo
De su honor y su opinion;
Pero si llego á tratarlo
Yo con Don Diego, no sé
Lo que hará, y es empeñarnos
Para haber de conseguirlo,
Haber de llegar á hablarlo:
Y así á tí, Beatriz, te toca;
Que á las mujeres es dado
Tratarlo con suaves medios;
No á nosotros, y más cuando
La mujer está en tu casa,
Y son tu primo y tu hermano
Comprendidos en el riesgo:
Razones que me la han dado,
Para que llames...
D.ª Beat. ¿A quién?
D. Juan
A Don
. Diego; y procurando
Darle á entender cuánto está
Ofendido tu recato
De que á tu casa se atreva,
Proponerle que, pues tantos
Peligros debe á esta dama,
Se disponga á remediarlos;
Que como con ella case,
A todos deja obligados.
Y esto ha de ser sin que entienda
Que nosotros le rogamos,
Sino que sale de tí.
D.ª BDigo,
eat. Don Juan, que has pensado
Bien, y que yo lo haré así.
D. Juan
Pues
. yo voy á ver si á Cárlos
Hallo: tú, si al tuyo vuelves,
Haz que cierren ese cuarto. (Vase Don Juan.)

ESCENA IV.
DOÑA BEATRIZ.

D.ª BYo
eatle
. cerraré. ¿A qué más
Puedo llegar, pues me hallo
Obligada á ser yo misma
Tercera de mis agravios
Y cómplice de mis celos?
¿Qué puedo hacer? Pero vamos
Al exámen, celos mios;
Y pues le da libre el paso
Hoy en su casa á Don Diego
Quien ayer lo estorbó tanto,
Sepamos dél qué responde.
Salgamos ó no salgamos
De una vez de este delirio,
Desta pena, deste encanto.—
Inés.

ESCENA V.
LEONOR; despues, DON CÁRLOS al paño.—DOÑA BEATRIZ.

LeonorSeñora.
.
D.ª Beat. Leonor,
¿Tú respondes?
Leonor. Si has llamado
A una criada, ¿qué mucho
Que responda quien lo es tanto?
(Sale Don Cárlos al paño.)

D. Cárl
La .voz de Leonor oí;
Y así la puerta entreabro,
Por verla convalecida
De aquel penoso letargo.
D.ª BSieatayer,
. Leonor, mi ignorancia
Te tuvo en aqueste estado,
Hoy mi advertencia, Leonor,
Te pone en lugar más alto.
Mi amiga eres. (Ap. Mi enemiga
Diré mejor.)
Leonor. Si he llegado
A perder, señora, el nombre
De criada tuya, no en vano
De la ventura que pierdo,
Me libra el honor que gano.
Tu esclava soy, y te pido,
Si puede merecer algo
Quien vino á tu casa sólo
A causar asombros tantos,
Me trates como hasta aquí.
D.ª B¿Cómo
eat. puedo, Leonor, cuando
Por ser quien eres y estar
En mi casa, darte trato
Esposo?
Leonor. En eternidades
Prospere el cielo tus años.
Pero Cárlos no querrá,
Que está celoso.
D.ª Beat. No es Cárlos.
Leonor
Pues
. ¿quién?
D.ª Beat. Don Diego Centellas.
Leonor
No. te empeñes en tratarlo;
Que ántes me daré la muerte,
Que dé á Don Diego la mano.
D.ª B¿Luego
eat. tú nunca has querido
A Don Diego?
Leonor. Aspid pisado
Entre las flores de Abril,
Víbora herida en los campos,
Rabiosa tigre en las selvas,
Cruel sierpe en los peñascos,
No es tan fiera para mí,
Como él lo es.
D.ª Beat. A espacio, á espacio;
Que aunque le desprecies quiero,
No que le desprecies tanto.
D. Cárl
(Al .paño.) ¡Ah, traidora! Ella me vió
Esconder, pues así ha hablado.
D.ª BYo
eatpensaba
. que te hacía
Lisonja; que quien ha estado
Por tí á la muerte en Madrid,
Y que te viene buscando,
No entendí que te ofendia.
Leonor
Pues
. ¡si supieras bien cuánto
Me ofende!...
D.ª Beat. Yo lo veré
Presto, para que salgamos
De este oscuro laberinto
Él, tú, yo, Don Juan y Cárlos. (Vase.)
ESCENA VI.
DON CÁRLOS, á la puerta del cuarto.—LEONOR.

D. Cárl . Fuése Beatriz, y Leonor


(Ap.)
(¡Ay cielos!) sola ha quedado.
Llorando está. Mas ¿qué importa,
Si es tan equívoco el llanto,
Que aunque está llorando veo,
No por quién está llorando?
Leonor
Ahora
. sí, piadosos cielos...
D. Cárl . ¡Oh celos!
(Ap.)
Leonor
Que
. solos podrán mis labios...
D. Cárl . ¡Oh agravios!
(Ap.)
Leonor
Quejarse
. al viento mejor.
D. Cárl . ¡Oh amor!
(Ap.)
Leonor
¿Quién
. le dirá á mi dolor
La razon que ha de culparme?
D. Cárl . Yo lo dijera, á dejarme
(Ap.)
Celos, agravios y amor.
Leonor
¿Cuándo
. yo ocasion he dado...
D. Cárl . ¡Fiero hado!
(Ap.)
Leonor
A .mi desdicha importuna...
D. Cárl . ¡Cruel fortuna!
(Ap.)
Leonor
Que
. así el honor atropella?
D. Cárl . ¡Dura estrella!
(Ap.)
Leonor
¿Pues
. cómo, si nunca della
Di ocasion, me da castigos?
D. Cárl . No sin causa hay enemigos
(Ap.)
Hado, fortuna y estrella.
Leonor
Quien
. inocente se mira...
D. Cárl . Es mentira.
(Ap.)
Leonor
En. la ciega confusion...
D. Cárl . Es traicion.
(Ap.)
Leonor
De. tan conocido daño...
D. Cárl . Es engaño.
(Ap.)
Leonor
¿Cuándo,
. Amor, el desengaño
Verán otros, que tú ves?
D. Cárl . Nunca, que todo eso es
(Ap.)
Mentira, traicion y engaño.—
Sin duda están contra mí
Hoy los cielos conjurados,
Pues me tienen persuadido
A que sabe que oigo cuanto
Diciendo está. Mas ¿qué importa?
Que aqueste metal humano
El mismo sonido tiene
Cuando es fino y cuando es falso;
Y así, pues basta el oirlo,
¿Para qué es examinarlo?
Leonor
¡Ay,
. Cárlos, si tú me oyeras! (Llaman.)
D. Cárl . ¡Ay, Leonor! si... Mas llamaron
(Ap.)
A la puerta: á cerrar vuelvo
Yo la mia.
Leonor. ¿Que áun hablando
Sin efecto, no faltó
Quien viniese á embarazarlo?
Veré quién es, por si puedo
Quedarme sola otro rato.
¿Quién es?

ESCENA VII.
DON PEDRO.—LEONOR; DON CÁRLOS, al paño.

D. Ped. El señor Don Juan


¿Está en casa? (Ap. ¡Cielo santo!
¡Qué miro!)
Leonor. Ahora salió...
Mas ¡qué veo! (Huye.)
D. Ped. Estoy turbado.
(Vase Leonor hácia donde está Don Cárlos, que sin dejarse ver de Don Pedro, abre la
puerta.)

D. Cárl
(Ap.. á ella al abrir.)
No temas, Leonor, que yo
Te recibiré en mis brazos.
D. Ped
Cerró
. la puerta tras sí.
Mas ¿qué importa, si yo basto,
En defensa de mi honor,
A dar asombros y espanto
Al mundo? Caiga en el suelo;
Que despues de hecha pedazos,
Haré lo mismo de aquella
Tirana, que...

ESCENA VIII.
DOÑA BEATRIZ.—DON PEDRO; DON CÁRLOS, oculto.

D.ª Beat. ¡En este cuarto


Golpes y voces! ¿Qué es esto?
D. Ped
Es. un furor, es un pasmo,
Una desesperacion,
Un horror, una ira, un rayo,
Que ha de abrasar cuanto encuentre,
Que intente ponerse al paso.
D.ª BPues
eat. ¿cómo este atrevimiento
En mi casa? ¿Quién ha dado
Ocasion, para que así
Haya podido empeñaros
Una cólera?
D. Ped. Una fiera.
Que aquí se oculta.
D.ª Beat. Esperáos.
¿Es Leonor?
D. Ped. ¿Pues quién pudiera,
Sino ella, obligarme á tanto?
D.ª B(eat
Ap. .¡Esto nos faltaba solo!
Otro amante, y destos años,
Tras Don Cárlos y Don Diego,
Que pusiese en paz á entrambos.)
Pues bien, aunque vos tuvieseis
Razones, que yo no alcanzo,
Para buscarla ofendido,
¿Os atreveis temerario
A entrar aquí?
D. Ped. Sí, que yo
En mí la disculpa traigo
Para mayores extremos;
Y así, perdonad si os trato,
Sin más atencion, señora.
D.ª BEn
eatesta
. casa, es engaño
Pensar que no habrá...

ESCENA IX.
DON JUAN.—DON PEDRO, DOÑA BEATRIZ; DON CÁRLOS, oculto.

D. Juan. ¿Qué es esto?


D.ª B¿Qué
eat. ha de ser? Aqueste anciano
Caballero en busca viene
Tambien de Leonor, y ha dado
En que ha de romper las puertas
Desta casa.
D. Juan. Paso, paso,
Beatriz; que el señor Don Pedro,
Ni te ha ofendido, ni ha errado,
Porque, como dueño della,
A todos puede mandarnos.
D. Ped
Señor
. Don Juan, no gastemos
Cumplimientos excusados.
Ni soy dueño, ni ser quiero
Más que un forastero, que hallo
(Cuando fiado de vos,
A veros vengo y hablaros)
En vuestra casa á mi hija.
Cerrada está en ese cuarto.
Abrid vos, ó abriré yo,
Echando la puerta abajo.
D.ª B(Ap.)
eat. Su padre es.

D. Juan .
(Ap.) ¿Cómo saldré
De lance tan apretado?
Ya él la vió: ¿qué he de decirle?
D. Ped
¿Qué
. pensais? Determináos.
D. Juan
Por. cierto, señor Don Pedro...
(Ap. Mucho haré, si desta salgo.)
¡Muy buen agradecimiento
Es ese de mi cuidado!
Pues desde ayer que me hice
De vuestras fortunas cargo,
Busqué á Leonor, y la traje
A mi casa, donde al lado
La hallais de mi hermana, adonde
Satisfaceros aguardo
De suerte, que á vuestra casa
Volvais contento y honrado.
Mas si desto os disgustais,
De todo alzaré la mano.
D. Ped
Dadme,
. Don Juan, vuestros piés,
Y perdonadme; que airado
Al verla, razon no tuve
Para discurrir á tanto;
Que no sabe discurrir
En su dicha un desdichado.
Arrastróme la pasion;
Mas ya, á vuestros piés postrado
Os hago dueño de todo.
D. Juan
¿Qué. haceis, señor? Levantáos.
D. Ped
Y .vos perdonad, señora,
El disgusto que os he dado.
Soy noble, estoy ofendido.
D.ª BAeat
haber,
. señor, alcanzado
Quien sois, de otra suerte hubiera
Pretendido reportaros.
D. Juan
¿Llamaste
. á Don Diego?
D.ª Beat. Sí,
Inés fué ahora á llamarlo.
D. Juan
Venid
. conmigo, señor
Don Pedro, para que vamos
A hacer una diligencia
Importante en este caso.
Leonor con Beatriz segura
Queda.
D.ª BeatY . yo, señor, me encargo
De dar cuenta della.
D. Ped. Basta
Quedar con vos. (Ap. ¡Cielo santo!
Venga la muerte, si llego
A ver mi honor restaurado.)
D. Juan
(Ap.. Yo no sé dónde le lleve.)
Habla tú á Don Diego en tanto,
Porque en esa diligencia
Está mi dicha.
(Vanse Don Juan y Don Pedro.)

D.ª Beat. Y mi daño.—


Leonor, abre: yo estoy sola.

ESCENA X.
LEONOR; DON CÁRLOS, oculto.—DOÑA BEATRIZ.

Leonor .
(Dentro.) Con ese seguro salgo.
D. Cárl
(Ap.. á Leonor, al salir ella.)
Ni á Beatriz, Leonor, la digas
Que aquí estoy.
Leonor . á Don Cárlos.)
(Ap.
No haré. (Adelántase.)
D.ª Beat. De extraño
Lance tu vida escapó.
Leonor
En. esta cuadra sagrado
Hallé.
D.ª Beat
No. fué poca dicha
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like