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
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
com
https://ebooknice.com/product/machine-learning-with-python-
cookbook-2nd-edition-first-early-release-44867920
OR CLICK HERE
DOWLOAD EBOOK
ebooknice.com
https://ebooknice.com/product/machine-learning-with-python-
cookbook-48982446
ebooknice.com
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
ebooknice.com
https://ebooknice.com/product/thoughtful-machine-learning-with-python-
early-release-11566556
ebooknice.com
https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018
ebooknice.com
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.
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.
Problem
You need to create a vector.
Solution
Use NumPy to create a one-dimensional array:
# Load library
import numpy as np
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
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([[1, 2],
[1, 2],
[1, 2]])
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]])
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:
(1, 1) 1
(2, 0) 3
(1, 1) 1
(2, 0) 3
(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
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
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.
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 matrix
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
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:
array([1, 2, 3, 4, 5, 6])
array([1, 2, 3])
array([4, 5, 6])
# Select the last element
vector[-1]
array([6, 5, 4, 3, 2, 1])
array([[1, 2, 3],
[4, 5, 6]])
array([[2],
[5],
[8]])
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]])
(3, 4)
12
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.
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]])
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:
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]])
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:
array([3, 6, 9])
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
Discussion
Just like with max and min, we can easily get descriptive statistics
about the whole matrix or do calculations along a single axis:
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
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
matrix.reshape(1, -1)
matrix.reshape(12)
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])
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]])
array([1, 2, 3, 4, 5, 6, 7, 8])
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]])
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
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:
array([2, 6])
array([2, 8])
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:
14
See Also
The Trace of a Square Matrix
Problem
You need to calculate the dot product of two vectors.
Solution
Use NumPy’s dot:
# Load library
import numpy as np
32
Discussion
The dot product of two vectors, a and b, is defined as:
32
See Also
Vector dot product and vector length, Khan Academy
Dot Product, Paul’s Online Math Notes
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]])
array([[ 2, 4, 2],
[ 2, 4, 2],
[ 2, 4, 10]])
Discussion
Alternatively, we can simply use the + and - operators:
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]])
array([[2, 5],
[3, 7]])
Discussion
Alternatively, in Python 3.5+ we can use the @ operator:
array([[2, 5],
[3, 7]])
array([[1, 3],
[1, 4]])
See Also
Array vs. Matrix Operations, MathWorks
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]])
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:
See Also
Inverse of a Matrix
Problem
You want to generate pseudorandom values.
Solution
Use NumPy’s random:
# Load library
import numpy as np
# Set seed
np.random.seed(0)
array([3, 7, 9])
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_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:
.. _digits_dataset:
See Also
scikit-learn toy datasets
The Digit 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
n_informative = 3,
n_targets
= 1,
noise =
0.0,
coef =
True,
random_state = 1)
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]
# Load library
from sklearn.datasets import make_classification
# Load library
from sklearn.datasets import make_blobs
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
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)
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)
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.
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')
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
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)
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
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
# 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.)
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,
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.)
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
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.
ESCENA VII.
DON PEDRO.—LEONOR; DON CÁRLOS, al paño.
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.
ESCENA IX.
DON JUAN.—DON PEDRO, DOÑA BEATRIZ; DON CÁRLOS, oculto.
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.)
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.
ebooknice.com