100% found this document useful (9 votes)
31 views

[FREE PDF sample] (Ebook) Advanced Data Analytics Using Python: With Machine Learning, Deep Learning and NLP Examples by Mukhopadhyay, Sayan ISBN 9781484234495, 1484234499 ebooks

The document provides information about various ebooks related to advanced data analytics using Python, including topics such as machine learning, deep learning, and natural language processing. It lists multiple titles along with their authors, ISBNs, and links for downloading. Additionally, it includes details about the content structure of the book 'Advanced Data Analytics Using Python' by Sayan Mukhopadhyay, covering various chapters and topics in data analytics.

Uploaded by

altiglofft9e
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (9 votes)
31 views

[FREE PDF sample] (Ebook) Advanced Data Analytics Using Python: With Machine Learning, Deep Learning and NLP Examples by Mukhopadhyay, Sayan ISBN 9781484234495, 1484234499 ebooks

The document provides information about various ebooks related to advanced data analytics using Python, including topics such as machine learning, deep learning, and natural language processing. It lists multiple titles along with their authors, ISBNs, and links for downloading. Additionally, it includes details about the content structure of the book 'Advanced Data Analytics Using Python' by Sayan Mukhopadhyay, covering various chapters and topics in data analytics.

Uploaded by

altiglofft9e
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Download Full Version ebook - Visit ebooknice.

com

(Ebook) Advanced Data Analytics Using Python: With


Machine Learning, Deep Learning and NLP Examples
by Mukhopadhyay, Sayan ISBN 9781484234495,
1484234499
https://ebooknice.com/product/advanced-data-analytics-using-
python-with-machine-learning-deep-learning-and-nlp-
examples-55670484

Click the button below to download

DOWLOAD EBOOK

Discover More Ebook - Explore Now at 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) 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) Advanced Data Analytics Using Python : With


Architectural Patterns, Text and Image Classification, and
Optimization Techniques by Sayan Mukhopadhyay; Pratip
Samanta ISBN 9781484280058, 1484280059
https://ebooknice.com/product/advanced-data-analytics-using-python-
with-architectural-patterns-text-and-image-classification-and-
optimization-techniques-49612318
ebooknice.com

(Ebook) Advanced Data Analytics Using Python: With


Architectural Patterns, Text and Image Classification, and
Optimization Techniques [2nd Edition] by Sayan
Mukhopadhyay, Pratip Samanta ISBN 9781484280041,
https://ebooknice.com/product/advanced-data-analytics-using-python-
1484280040
with-architectural-patterns-text-and-image-classification-and-
optimization-techniques-2nd-edition-47321334
ebooknice.com

(Ebook) Natural Language Processing Recipes: Unlocking


Text Data with Machine Learning and Deep Learning Using
Python by Akshay Kulkarni, Adarsha Shivananda ISBN
9781484273500, 1484273508
https://ebooknice.com/product/natural-language-processing-recipes-
unlocking-text-data-with-machine-learning-and-deep-learning-using-
python-34204404
ebooknice.com
(Ebook) Practical Machine Learning for Streaming Data with
Python: Design, Develop, and Validate Online Learning
Models by Sayan Putatunda ISBN 9781484268667,
9781484268674, 1484268660, 1484268679
https://ebooknice.com/product/practical-machine-learning-for-
streaming-data-with-python-design-develop-and-validate-online-
learning-models-24035852
ebooknice.com

(Ebook) Natural Language Processing Recipes: Unlocking


Text Data with Machine Learning and Deep Learning Using
Python by Akshay Kulkarni, Adarsha Shivananda ISBN
9781484273517, 9781484273500, 1484273508, 1484273516
https://ebooknice.com/product/natural-language-processing-recipes-
unlocking-text-data-with-machine-learning-and-deep-learning-using-
python-34204734
ebooknice.com

(Ebook) Python Machine Learning. Machine Learning and Deep


Learning with Python, scikit-learn and TensorFlow by
Sebastian Raschka, Vahid Mirjalili ISBN 9781787125933,
1787125939
https://ebooknice.com/product/python-machine-learning-machine-
learning-and-deep-learning-with-python-scikit-learn-and-
tensorflow-6868034
ebooknice.com

(Ebook) Adaptive Machine Learning Algorithms with Python:


Solve Data Analytics and Machine Learning Problems on Edge
Devices by Chanchal Chatterjee ISBN 9781484280164,
1484280164
https://ebooknice.com/product/adaptive-machine-learning-algorithms-
with-python-solve-data-analytics-and-machine-learning-problems-on-
edge-devices-42829800
ebooknice.com

(Ebook) Deep Learning with Python: Develop Deep Learning


Models on Theano and TensorFLow Using Keras by Jason
Brownlee
https://ebooknice.com/product/deep-learning-with-python-develop-deep-
learning-models-on-theano-and-tensorflow-using-keras-7295338

ebooknice.com
Advanced
Data Analytics
Using Python
With Machine Learning,
Deep Learning and NLP Examples

Sayan Mukhopadhyay
Advanced Data
Analytics Using
Python
With Machine Learning, Deep
Learning and NLP Examples

Sayan Mukhopadhyay
Advanced Data Analytics Using Python
Sayan Mukhopadhyay
Kolkata, West Bengal, India

ISBN-13 (pbk): 978-1-4842-3449-5 ISBN-13 (electronic): 978-1-4842-3450-1


https://doi.org/10.1007/978-1-4842-3450-1
Library of Congress Control Number: 2018937906

Copyright © 2018 by Sayan Mukhopadhyay


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole
or part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical
way, and transmission or information storage and retrieval, electronic adaptation,
computer software, or by similar or dissimilar methodology now known or hereafter
developed.
Trademarked names, logos, and images may appear in this book. Rather than use a
trademark symbol with every occurrence of a trademarked name, logo, or image we use the
names, logos, and images only in an editorial fashion and to the benefit of the trademark
owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms,
even if they are not identified as such, is not to be taken as an expression of opinion as to
whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the
date of publication, neither the authors nor the editors nor the publisher can accept any
legal responsibility for any errors or omissions that may be made. The publisher makes no
warranty, express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Celestin
Development Editor: Matthew Moodie
Coordinating Editor: Divya Modi
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201)
348-4505, e-mail [email protected], or visit www.springeronline.com. Apress
Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business
Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit www.apress.
com/rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information,
reference our Print and eBook Bulk Sales web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this
book is available to readers on GitHub via the book’s product page, located at
www.apress.com/978-1-4842-3449-5. For more detailed information, please visit
www.apress.com/source-code.
Printed on acid-free paper
This is dedicated to all my math teachers,
especially to Kalyan Chakraborty.
Table of Contents
About the Author���������������������������������������������������������������������������������xi
About the Technical Reviewer�����������������������������������������������������������xiii
Acknowledgments������������������������������������������������������������������������������xv

Chapter 1: Introduction������������������������������������������������������������������������1
Why Python?���������������������������������������������������������������������������������������������������������1
When to Avoid Using Python���������������������������������������������������������������������������������2
OOP in Python�������������������������������������������������������������������������������������������������������3
Calling Other Languages in Python���������������������������������������������������������������������12
Exposing the Python Model as a Microservice���������������������������������������������������14
High-Performance API and Concurrent Programming����������������������������������������17

Chapter 2: ETL with Python (Structured Data)������������������������������������23


MySQL�����������������������������������������������������������������������������������������������������������������23
How to Install MySQLdb?�������������������������������������������������������������������������������23
Database Connection�������������������������������������������������������������������������������������24
INSERT Operation������������������������������������������������������������������������������������������24
READ Operation���������������������������������������������������������������������������������������������25
DELETE Operation������������������������������������������������������������������������������������������26
UPDATE Operation�����������������������������������������������������������������������������������������27
COMMIT Operation�����������������������������������������������������������������������������������������28
ROLL-BACK Operation�����������������������������������������������������������������������������������28

v
Table of Contents

Elasticsearch�������������������������������������������������������������������������������������������������������31
Connection Layer API�������������������������������������������������������������������������������������33
Neo4j Python Driver��������������������������������������������������������������������������������������������34
neo4j-rest-client�������������������������������������������������������������������������������������������������35
In-Memory Database������������������������������������������������������������������������������������������35
MongoDB (Python Edition)����������������������������������������������������������������������������������36
Import Data into the Collection����������������������������������������������������������������������36
Create a Connection Using pymongo�������������������������������������������������������������37
Access Database Objects������������������������������������������������������������������������������37
Insert Data�����������������������������������������������������������������������������������������������������38
Update Data���������������������������������������������������������������������������������������������������38
Remove Data�������������������������������������������������������������������������������������������������38
Pandas����������������������������������������������������������������������������������������������������������������38
ETL with Python (Unstructured Data)������������������������������������������������������������������40
E-mail Parsing�����������������������������������������������������������������������������������������������40
Topical Crawling��������������������������������������������������������������������������������������������42

Chapter 3: Supervised Learning Using Python�����������������������������������49


Dimensionality Reduction with Python���������������������������������������������������������������49
Correlation Analysis���������������������������������������������������������������������������������������50
Principal Component Analysis�����������������������������������������������������������������������53
Mutual Information����������������������������������������������������������������������������������������56
Classifications with Python���������������������������������������������������������������������������������57
Semisupervised Learning�����������������������������������������������������������������������������������58
Decision Tree�������������������������������������������������������������������������������������������������������59
Which Attribute Comes First?������������������������������������������������������������������������59
Random Forest Classifier������������������������������������������������������������������������������60

vi
Table of Contents

Naive Bayes Classifier�����������������������������������������������������������������������������������������61


Support Vector Machine��������������������������������������������������������������������������������������62
Nearest Neighbor Classifier��������������������������������������������������������������������������������64
Sentiment Analysis���������������������������������������������������������������������������������������������65
Image Recognition����������������������������������������������������������������������������������������������67
Regression with Python��������������������������������������������������������������������������������������67
Least Square Estimation��������������������������������������������������������������������������������68
Logistic Regression���������������������������������������������������������������������������������������69
Classification and Regression�����������������������������������������������������������������������������70
Intentionally Bias the Model to Over-Fit or Under-Fit������������������������������������������71
Dealing with Categorical Data�����������������������������������������������������������������������������73

Chapter 4: Unsupervised Learning: Clustering�����������������������������������77


K-Means Clustering��������������������������������������������������������������������������������������������78
Choosing K: The Elbow Method���������������������������������������������������������������������������82
Distance or Similarity Measure���������������������������������������������������������������������������82
Properties������������������������������������������������������������������������������������������������������82
General and Euclidean Distance��������������������������������������������������������������������83
Squared Euclidean Distance��������������������������������������������������������������������������84
Distance Between String-Edit Distance��������������������������������������������������������85
Similarity in the Context of Document����������������������������������������������������������������87
Types of Similarity�����������������������������������������������������������������������������������������87
What Is Hierarchical Clustering?�������������������������������������������������������������������������88
Bottom-Up Approach�������������������������������������������������������������������������������������89
Distance Between Clusters���������������������������������������������������������������������������90
Top-Down Approach��������������������������������������������������������������������������������������92
Graph Theoretical Approach��������������������������������������������������������������������������97
How Do You Know If the Clustering Result Is Good?�������������������������������������97

vii
Table of Contents

Chapter 5: Deep Learning and Neural Networks���������������������������������99


Backpropagation�����������������������������������������������������������������������������������������������100
Backpropagation Approach�������������������������������������������������������������������������100
Generalized Delta Rule��������������������������������������������������������������������������������100
Update of Output Layer Weights������������������������������������������������������������������101
Update of Hidden Layer Weights�����������������������������������������������������������������102
BPN Summary���������������������������������������������������������������������������������������������103
Backpropagation Algorithm�������������������������������������������������������������������������������104
Other Algorithms�����������������������������������������������������������������������������������������������106
TensorFlow��������������������������������������������������������������������������������������������������������106
Recurrent Neural Network��������������������������������������������������������������������������������113

Chapter 6: Time Series���������������������������������������������������������������������121


Classification of Variation���������������������������������������������������������������������������������121
Analyzing a Series Containing a Trend��������������������������������������������������������������121
Curve Fitting������������������������������������������������������������������������������������������������122
Removing Trends from a Time Series����������������������������������������������������������123
Analyzing a Series Containing Seasonality�������������������������������������������������������124
Removing Seasonality from a Time Series�������������������������������������������������������125
By Filtering��������������������������������������������������������������������������������������������������125
By Differencing��������������������������������������������������������������������������������������������126
Transformation��������������������������������������������������������������������������������������������������126
To Stabilize the Variance�����������������������������������������������������������������������������126
To Make the Seasonal Effect Additive���������������������������������������������������������127
To Make the Data Distribution Normal���������������������������������������������������������127
Stationary Time Series��������������������������������������������������������������������������������������128
Stationary Process��������������������������������������������������������������������������������������128
Autocorrelation and the Correlogram����������������������������������������������������������129
Estimating Autocovariance and Autocorrelation Functions�������������������������129

viii
Table of Contents

Time-Series Analysis with Python���������������������������������������������������������������������130


Useful Methods��������������������������������������������������������������������������������������������131
Autoregressive Processes���������������������������������������������������������������������������133
Estimating Parameters of an AR Process����������������������������������������������������134
Mixed ARMA Models�����������������������������������������������������������������������������������������137
Integrated ARMA Models�����������������������������������������������������������������������������������138
The Fourier Transform���������������������������������������������������������������������������������������140
An Exceptional Scenario�����������������������������������������������������������������������������������141
Missing Data�����������������������������������������������������������������������������������������������������143

Chapter 7: Analytics at Scale�����������������������������������������������������������145


Hadoop��������������������������������������������������������������������������������������������������������������145
MapReduce Programming���������������������������������������������������������������������������145
Partitioning Function�����������������������������������������������������������������������������������146
Combiner Function��������������������������������������������������������������������������������������147
HDFS File System����������������������������������������������������������������������������������������159
MapReduce Design Pattern�������������������������������������������������������������������������159
Spark�����������������������������������������������������������������������������������������������������������������166
Analytics in the Cloud���������������������������������������������������������������������������������������168
Internet of Things����������������������������������������������������������������������������������������������179

Index�������������������������������������������������������������������������������������������������181

ix
About the Author
Sayan Mukhopadhyay has more than
13 years of industry experience and has been
associated with companies such as Credit
Suisse, PayPal, CA Technologies, CSC, and
Mphasis. He has a deep understanding of
applications for data analysis in domains such
as investment banking, online payments,
online advertisement, IT infrastructure, and
retail. His area of expertise is in applying
high-performance computing in distributed
and data-driven environments such as real-time analysis, high-frequency
trading, and so on.
He earned his engineering degree in electronics and instrumentation
from Jadavpur University and his master’s degree in research in
computational and data science from IISc in Bangalore.

xi
About the Technical Reviewer
Sundar Rajan Raman has more than 14 years
of full stack IT experience in machine
learning, deep learning, and natural
language processing. He has six years
of big data development and architect
experience, including working with Hadoop
and its ecosystems as well as other NoSQL
technologies such as MongoDB and
Cassandra. In fact, he has been the technical
reviewer of several books on these topics.
He is also interested in strategizing using Design Thinking principles
and in coaching and mentoring people.

xiii
Acknowledgments
Thanks to Labonic Chakraborty (Ripa) and Kusumika Mukherjee.

xv
CHAPTER 1

Introduction
In this book, I assume that you are familiar with Python programming.
In this introductory chapter, I explain why a data scientist should choose
Python as a programming language. Then I highlight some situations
where Python is not a good choice. Finally, I describe some good practices
in application development and give some coding examples that a data
scientist needs in their day-to-day job.

W
 hy Python?
So, why should you choose Python?

• It has versatile libraries. You always have a ready-­


made library in Python for any kind of application.
From statistical programming to deep learning to
network application to web crawling to embedded
systems, you will always have a ready-made library in
Python. If you learn this language, you do not have to
stick to a specific use case. R has a rich set of analytics
libraries, but if you are working on an Internet of Things
(IoT) application and need to code in a device-side
embedded system, it will be difficult in R.

© Sayan Mukhopadhyay 2018 1


S. Mukhopadhyay, Advanced Data Analytics Using Python,
https://doi.org/10.1007/978-1-4842-3450-1_1
Chapter 1 Introduction

• It is very high performance. Java is also a versatile


language and has lots of libraries, but Java code runs
on a Java virtual machine, which adds an extra layer
of latency. Python uses high-performance libraries
built in other languages. For example, SciPy uses
LAPACK, which is a Fortran library for linear algebra
applications. TensorFlow uses CUDA, which is a C
library for parallel GPU processing.

• It is simple and gives you a lot of freedom to code.


Python syntax is just like a natural language. It is easy to
remember, and it does not have constraints in variables
(like constants or public/private).

When to Avoid Using Python


Python has some downsides too.

• When you are writing very specific code, Python may


not always be the best choice. For example, if you are
writing code that deals only with statistics, R is a better
choice. If you are writing MapReduce code only, Java is
a better choice than Python.

• Python gives you a lot of freedom in coding. So, when


many developers are working on a large application,
Java/C++ is a better choice so that one developer/
architect can put constraints on another developer’s
code using public/private and constant keywords.

• For extremely high-performance applications, there is


no alternative to C/C++.

2
Chapter 1 Introduction

O
 OP in Python
Before proceeding, I will explain some features of object-oriented
programming (OOP) in a Python context.
The most basic element of any modern application is an object. To
a programmer or architect, the world is a collection of objects. Objects
consist of two types of members: attributes and methods. Members can be
private, public, or protected. Classes are data types of objects. Every object
is an instance of a class. A class can be inherited in child classes. Two
classes can be associated using composition.
In a Python context, Python has no keywords for public, private, or
protected, so encapsulation (hiding a member from the outside world)
is not implicit in Python. Like C++, it supports multilevel and multiple
inheritance. Like Java, it has an abstract keyword. Classes and methods
both can be abstract.
The following code is an example of a generic web crawler that is
implemented as an airline’s web crawler on the Skytrax site and as a retail
crawler for the Mouthshut.com site. I’ll return to the topic of web crawling
in Chapter 2.

from abc import ABCMeta, abstractmethod


import BeautifulSoup
import urllib
import sys
import bleach
#################### Root Class (Abstract) ####################
class SkyThoughtCollector(object):
       __metaclass__ = ABCMeta

       baseURLString = "base_url"
       airlinesString = "air_lines"
       limitString = "limits"

3
Chapter 1 Introduction

       baseURl = ""
       airlines = []
       limit = 10

       @abstractmethod
       def collectThoughts(self):
             print "Something Wrong!! You're calling
an abstract method"

       @classmethod
       def getConfig(self, configpath):
             #print "In get Config"
             config = {}
             conf = open(configpath)
             for line in conf:
                    if ("#" not in line):
                          words = line.strip().split('=')
                          config[words[0].strip()] = words[1].
strip()
             #print config
             self.baseURl = config[self.baseURLString]
             if config.has_key(self.airlinesString):
                    self.airlines = config[self.
airlinesString].split(',')
             if config.has_key(self.limitString):
                    self.limit = int(config[self.limitString])
             #print self.airlines

       def downloadURL(self, url):


             #print "downloading url"
             pageFile = urllib.urlopen(url)

4
Chapter 1 Introduction

             if pageFile.getcode() != 200:


                    return "Problem in URL"
             pageHtml = pageFile.read()
             pageFile.close()
             return "".join(pageHtml)

       def remove_junk(self, arg):


             f = open('junk.txt')
             for line in f:
                    arg.replace(line.strip(),'')
             return arg

       def print_args(self, args):


             out =''
             last = 0
             for arg in args:
                    if args.index(arg) == len(args) -1:
                          last = 1
                    reload(sys)
                    sys.setdefaultencoding("utf-8")
                    
arg = arg.decode('utf8','ignore').
encode('ascii','ignore').strip()
                    arg = arg.replace('\n',' ')
                    arg = arg.replace('\r','')
                    arg = self.remove_junk(arg)
                    if last == 0:
                          out = out + arg + '\t'
                    else:
                          out = out + arg
             print out

5
Chapter 1 Introduction

####################### Airlines Chield #######################

class AirLineReviewCollector(SkyThoughtCollector):

      months = ['January', 'February', 'March', 'April', 'May',


'June', 'July', 'August', 'September', 'October', 'November',
'December' ]

       def __init__(self, configpath):


             #print "In Config"
       super(AirLineReviewCollector,self).getConfig(configpath)

       def parseSoupHeader(self, header):


             #print "parsing header"
             name = surname = year = month = date = country =''
             txt = header.find("h9")
             words = str(txt).strip().split(' ')
             for j in range(len(words)-1):
                    if words[j] in self.months:
                          date = words[j-1]
                          month= words[j]
                          year = words[j+1]
                          name = words[j+3]
                          surname = words[j+4]
             if ")" in words[-1]:
                    country = words[-1].split(')')[0]
             if "(" in country:
                    country = country.split('(')[1]
             else:
                    country = words[-2].split('(')[1] + country
             return (name, surname, year, month, date, country)

6
Chapter 1 Introduction

       def parseSoupTable(self, table):


             #print "parsing table"
             images = table.findAll("img")
             over_all = str(images[0]).split("grn_bar_")[1].
split(".gif")[0]
             money_value = str(images[1]).split("SCORE_")[1].
split(".gif")[0]
             seat_comfort = str(images[2]).split("SCORE_")[1].
split(".gif")[0]
             staff_service = str(images[3]).split("SCORE_")[1].
split(".gif")[0]
             catering = str(images[4]).split("SCORE_")[1].
split(".gif")[0]
             entertainment = str(images[4]).split("SCORE_")[1].
split(".gif")[0]
             if 'YES' in str(images[6]):
                    recommend = 'YES'
             else:
                    recommend = 'NO'
             status = table.findAll("p", {"class":"text25"})
             stat = str(status[2]).split(">")[1].split("<")[0]
             return (stat, over_all, money_value, seat_comfort,
staff_service, catering, entertainment, recomend)

       def collectThoughts(self):
             #print "Collecting Thoughts"
             for al in AirLineReviewCollector.airlines:
                    count = 0
                    while count < AirLineReviewCollector.limit:
                          count = count + 1
                          url = ''

7
Chapter 1 Introduction

                          if count == 1:
                                 url = AirLineReviewCollector.
baseURl + al + ".htm"
                          else:
                                 url = AirLineReviewCollector.
baseURl + al + "_"+str(count)+
".htm"
                          soup = BeautifulSoup.BeautifulSoup
(super(AirLineReviewCollector,self).
downloadURL(url))
                          blogs = soup.findAll("p",
{"class":"text2"})
                          tables = soup.findAll("table",
{"width":"192"})
                          review_headers = soup.findAll("td",
{"class":"airport"})
                          for i in range(len(tables)-1):
                                 (name, surname, year, month,
date, country) = self.parse
SoupHeader(review_headers[i])
                                 (stat, over_all, money_value,
seat_comfort, staff_service,
catering, entertainment,
recomend) = self.parseSoup
Table(tables[i])
                                 blog = str(blogs[i]).
split(">")[1].split("<")[0]
                                 args = [al, name, surname,
year, month, date, country,
stat, over_all, money_value,
seat_comfort, staff_service,
catering, entertainment,
recomend, blog]
8
Chapter 1 Introduction

                                        
super(AirLineReviewCo
llector,self).print_
args(args)

######################## Retail Chield ########################

class RetailReviewCollector(SkyThoughtCollector):
       def __init__(self, configpath):
             #print "In Config"
       super(RetailReviewCollector,self).getConfig(configpath)

       def collectThoughts(self):
             soup = BeautifulSoup.BeautifulSoup(super(RetailRev
iewCollector,self).downloadURL(RetailReviewCollect
or.baseURl))
             lines = soup.findAll("a",{"style":
"font-­size:15px;"})
             links = []
             for line in lines:
                     if ("review" in str(line)) & ("target" in
str(line)):
                          ln = str(line)
                           link = ln.split("href=")[-1].split
("target=")[0].replace("\"","").
strip()
                          links.append(link)

             for link in links:


                    
soup = BeautifulSoup.BeautifulSoup(
super(RetailReviewCollector,self).
downloadURL(link))

9
Chapter 1 Introduction

                    comment = bleach.clean(str(soup.findAll("di
v",{"itemprop":"description"})[0]),tags=[],
strip=True)
                    tables = soup.findAll("table",
{"class":"smallfont space0 pad2"})
                    parking = ambience = range = economy =
product = 0
                    for table in tables:
                          if "Parking:" in str(table):
                                 rows = table.findAll("tbody")
[0].findAll("tr")
                                 for row in rows:
                                       if "Parking:" in
str(row):
                                              parking =
str(row).
count("read-
barfull")
                                       if "Ambience" in
str(row):
                                              ambience =
str(row).
count("read-
barfull")
                                       if "Store" in str(row):
                                              range = str(row).
count("read-
barfull")

10
Chapter 1 Introduction

                                       if "Value" in str(row):


                                              
economy =
str(row).
count("read-
barfull")
                                       if "Product" in str(row):
                                              
product =
str(row).count
("smallratefull")

                    
author = bleach.clean(soup.findAll("spa
n",{"itemprop":"author"})[0], tags=[],
strip=True)
                    
date = soup.findAll("meta",{"itemprop":"dat
ePublished"})[0]["content"]
                    
args = [date, author,str(parking),
str(ambience),str(range), str(economy),
str(product), comment]
                                        
super(RetailReview
Collector,self).print_
args(args)

######################## Main Function ########################

if __name__ == "__main__":
       if sys.argv[1] == 'airline':
             instance = AirLineReviewCollector(sys.argv[2])
             instance.collectThoughts()
       else:
             if sys.argv[1] == 'retail':
                    
instance = RetailReviewCollector(sys.argv[2])
                    instance.collectThoughts()

11
Chapter 1 Introduction

             else:
                    print "Usage is"
                    print sys.argv[0], '<airline/retail>',
"<Config File Path>"

The configuration for the previous code is shown here:

base_url = http://www.airlinequality.com/Forum/
#base_url = http://www.mouthshut.com/product-reviews/Mega-Mart-­
Bangalore-reviews-925103466
#base_url = http://www.mouthshut.com/product-reviews/Megamart-­
Chennai-­reviews-925104102
air_lines = emrts,brit_awys,ual,biman,flydubai
limits = 10

I’ll now discuss the previous code in brief. It has a root class that is an
abstract class. It contains essential attributes such as a base URL and a
page limit; these are essential for all child classes. It also contains common
logic in class method functions such as the download URL, print output,
and read configuration. It also has an abstract method collectThoughts,
which must be implemented in child classes. This abstract method is
passing on a common behavior to every child class that all of them must
collect thoughts from the Web. Implementations of this thought collection
are child specific.

Calling Other Languages in Python


Now I will describe how to use other languages’ code in Python. There are
two examples here; one is calling R code from Python. R code is required
for some use cases. For example, if you want a ready-made function for the
Holt-Winter method in a time series, it is difficult to do in Python. But it is

12
Chapter 1 Introduction

available in R. So, you can call R code from Python using the rpy2 module,
as shown here:

import rpy2.robjects as ro
ro.r('data(input)')
ro.r('x <-HoltWinters(input)')

Sometimes you need to call Java code from Python. For example,
say you are working on a name entity recognition problem in the field of
natural language processing (NLP); some text is given as input, and you
have to recognize the names in the text. Python’s NLTK package does have
a name entity recognition function, but its accuracy is not good. Stanford
NLP is a better choice here, which is written in Java. You can solve this
problem in two ways.

• You can call Java at the command line using


Python code.

import subprocess

subprocess.call(['java','-cp','*','edu.
stanford.nlp.sentiment.SentimentPipeline',
'-file','foo.txt'])

• You can expose Stanford NLP as a web service and call


it as a service.

nlp = StanfordCoreNLP('http://127.0.0.1:9000')
output = nlp.annotate(sentence, properties={
"annotators": "tokenize,ssplit,parse,sentiment",
"outputFormat": "json",
# Only split the sentence at End Of Line.
We assume that this method only takes in one
single sentence.
"ssplit.eolonly": "true",

13
Chapter 1 Introduction

# Setting enforceRequirements to skip some


annotators and make the process faster
"enforceRequirements": "false"
})

E xposing the Python Model


as a Microservice
You can expose the Python model as a microservice in the same way as
your Python model can be used by others to write their own code. The best
way to do this is to expose your model as a web service. As an example, the
following code exposes a deep learning model using Flask:

from flask import Flask, request, g


from flask_cors import CORS
import tensorflow as tf
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
import pygeoip
from pymongo import MongoClient
import json
import datetime as dt
import ipaddress
import math

app = Flask(__name__)
CORS(app)

@app.before_request
def before():
       db = create_engine('sqlite:///score.db')
       metadata = MetaData(db)

14
Chapter 1 Introduction

       g.scores = Table('scores', metadata, autoload=True)


       Session = sessionmaker(bind=db)
       g.session = Session()

       client = MongoClient()
       g.db = client.frequency

       g.gi = pygeoip.GeoIP('GeoIP.dat')

       sess = tf.Session()
       new_saver = tf.train.import_meta_graph('model.obj.meta')
       new_saver.restore(sess, tf.train.latest_checkpoint('./'))
       all_vars = tf.get_collection('vars')

       g.dropped_features = str(sess.run(all_vars[0]))
       g.b = sess.run(all_vars[1])[0]
       return

def get_hour(timestamp):
       return dt.datetime.utcfromtimestamp(timestamp / 1e3).hour

def get_value(session, scores, feature_name, feature_value):


       s = scores.select((scores.c.feature_name == feature_
name) & (scores.c.feature_value == feature_value))
       rs = s.execute()
       row = rs.fetchone()
       if row is not None:
             return float(row['score'])
       else:
             return 0.0

15
Chapter 1 Introduction

@app.route('/predict', methods=['POST'])
def predict():
       input_json = request.get_json(force=True)

       features = ['size','domain','client_time','device',
'ad_position','client_size', 'ip','root']
       predicted = 0
       feature_value = ''
       for f in features:
             if f not in g.dropped_features:
                    if f == 'ip':
                          feature_value = str(ipaddress.
IPv4Address(ipaddress.ip_address
(unicode(request.remote_addr))))
                    else:
                          feature_value = input_json.get(f)
                    if f == 'ip':
                          if 'geo' not in g.dropped_features:
                                 geo = g.gi.country_name_by_
addr(feature_value)
                                 predicted = predicted + get_
value(g.session, g.scores,
'geo', geo)
                          if 'frequency' not in g.dropped_
features:
                                 res = g.db.frequency.find_
one({"ip" : feature_value})
                                 freq = 1
                                 if res is not None:
                                       freq = res['frequency']
                                 predicted = predicted + get_
value(g.session, g.scores,
'frequency', str(freq))
16
Chapter 1 Introduction

                    if f == 'client_time':
                           feature_value = get_
hour(int(feature_value))
                    predicted = predicted + get_value(g.
session, g.scores, f, feature_value)
       return str(math.exp(predicted + g.b)-1)
app.run(debug = True, host ='0.0.0.0')

This code exposes a deep learning model as a Flask web service.


A JavaScript client will send the request with web user parameters such
as the IP address, ad size, ad position, and so on, and it will return the
price of the ad as a response. The features are categorical. You will learn
how to convert them into numerical scores in Chapter 3. These scores
are stored in an in-memory database. The service fetches the score from
the database, sums the result, and replies to the client. This score will be
updated real time in each iteration of training of a deep learning model. It
is using MongoDB to store the frequency of that IP address in that site. It is
an important parameter because a user coming to a site for the first time
is really searching for something, which is not true for a user where the
frequency is greater than 5. The number of IP addresses is huge, so they
are stored in a distributed MongoDB database.

 igh-Performance API and Concurrent


H
Programming
Flask is a good choice when you are building a general solution that is
also a graphical user interface (GUI). But if high performance is the most
critical requirement of your application, then Falcon is the best choice. The
following code is an example of the same model shown previously exposed
by the Falcon framework. Another improvement I made in this code is that
I implemented multithreading, so the code will be executed in parallel.

17
Random documents with unrelated
content Scribd suggests to you:
CHAPTER XXIII.

A REPRISAL OF TREACHERY.

“Don’t be absurd, Don Manada.”


“Absurd? Dios! I was never more thoroughly in earnest in my life.”
“Nevertheless, you are absurd,” Isabel Harding smiles tantalizingly
over her champagne glass at the flushed face and glistening eyes of
her companion.
This conversation occurs shortly after midnight at an out-of-the-
way table in the arcade at the east end of the Garden.
For all it began so decorously, this year’s ball is a particularly
riotous affair and already the fantastic orgee is well under way.
Masks have been scattered to the patchouli-laden winds. Yet there
are a few discreet folks who, though they mingle with the mad
crowd, have retained their masks. As Don Manada and his
companion are comparatively removed from observation, they have
laid aside their dominos for the moment and are conversing in
earnest whispers.
Isabel Harding is so radiantly, magnificently, dangerously beautiful
that it is a terrific strain for the gentleman at her side to maintain
the least semblance of composure.
“In what does my absurdity consist?” he demands in a passionate
whisper.
“Can you ask? You tell me that you love me—which I already know
—and urge a suit which I have twice before told you is hopeless. You
profess to believe that I could learn in time to honestly return your
undoubtedly sincere affection. It is impossible. I will be honest with
you. I am not one to whom love comes slowly. I love only one man,
and he—don’t look so murderous, Don Manada—he cares nothing
for me,” she finishes, bitterly.
“Come, a truce to lovemaking!” rallies Isabel. “Don’t look so
fiercely downcast, Don Manada. Fill up the glasses and we will drink
a melancholy toast to unrequited love. We are alike unsuccessful
lovers. But we will continue to be good friends.”
“Impossible,” replies Don Manada, as he gloomily pours out the
wine. “I go to Cuba to-morrow.”
“Indeed? I trust that I am not responsible for the loss of your
society to your New York friends.”
“No, senora. I go because duty calls me, but I had expected to
wear a lighter heart than that which will accompany me.”
Don Manada is too much occupied with his despair to note the
peculiar look which Isabel darts at him from between her half-
dropped eyelids.
“Cuba?” she repeats, dreamily. “Ah, I should like to visit that
country some day.”
Don Manada looks up with swift hope. “You would, senora? Then
you shall!” he cries. “We will leave to-morrow on my vessel. I will be
your slave. You have but to speak and every wish will be gratified.
You will do me this favor,” he urges, and then, with the fervor and
descriptive powers of a Claude Melnotte, he proceeds to paint a
fascinating picture with a tropical background, his enthusiasm fired
by ravishing glances from his companion.
“Quite an escapade you have outlined,” smiled Isabel. “But it is too
prosy. If the voyage promised a dash of adventure, if it were spiced
with an element of danger, I—” she pauses and lifts the wineglass
slowly to her lips.
“Danger?” echoes Don Manada, with a curious smile. “Dios! The
voyage might not be without all the adventure your heart could
desire, senora.” He takes from his pocket a newspaper clipping and
hands it to Isabel, after a glance about him to make certain that
they are unobserved. The clipping is from the current edition of the
Hemisphere. It is a dispatch from Key West, and a portion of it reads
as follows:

“This city has been in a fever of excitement all day over


the report that an important filibustering expedition is to
leave New York this week to aid the Cuban insurgents. The
report is backed by excellent authority, and there is no doubt
that an effort will be made to send valuable assistance to the
patriots of the Antilles some time during the week. In some
way the United States authorities and the Spanish
government have got wind of the proposed expedition and
they are striving to nip it in the bud. The Spanish warship
Infanta Isabel this morning steamed from this harbor for the
purpose, one of her officers said, of intercepting the
filibusters on the high seas.
“It is also stated that a prominent and gallant member of
the Cuban revolutionary society will head the expedition, but
his identity has not been disclosed.”

Mrs. Harding glances through the clipping and hands it back with
a quizzical smile.
“So you are the prominent and gallant member of the Cuban
revolutionary society referred to?” she infers.
“Not so loud!” cautions Don Manada. “We may be overheard.
What think you of the voyage now, senora?”
“I fear it is a bit too dangerous,” replies Isabel, with a yawn. “We
should never reach Cuba.”
“Trust me,” assents Don Manada, complacently. “Once on the high
seas, the Isabel will lead the Spanish warships a pretty chase.”
“Ah, the name of your schooner is the Isabel?”
“Of our yacht—yes. Is it not happily named?”
“Perhaps so,” answers Mrs. Harding, with an enigmatic expression
in her lustrous eyes. “And where should I find your yacht in case I
should at the last moment decide to accept your offer of a merry
voyage to the tropics?”
“My yacht? I should conduct you to it,” says Don Manada in some
surprise.
“Oh, no; that would not do,” objects Isabel. “I should be driven to
it veiled just preceding its departure.”
Don Manada looks around the arcade, but there is no one within
twenty feet of their table.
“North river, foot of 23d street,” he whispers. “You will go?” as
Isabel appears to be hesitating mid conflicting emotions.
“You will promise not to make love to me during the entire
voyage?”
“I will promise anything, senora, though you have imposed an
unhappy obligation.”
“Then I think I will say—yes.”
“Bueno!” cries the delighted Don Manada, and, seizing Isabel’s
hand, he covers it with passionate kisses.
“Oh, by the way, what time do you sail?”
“At 5 o’clock.”
“Very well. I will send final word to your hotel in the morning.
Now, leave me to dream over my folly,” says Mrs. Harding,
disengaging the hand which Don Manada still tenderly holds.
Then, as the latter goes off to the wine-room to submerge his
happiness in champagne, Isabel leans back in her chair and laughs
softly. “The fool,” she sneers. “Well, all men are fools—all but one.”
“And that one?” inquires a voice behind her. She looks up startled,
to meet the calm gaze of a man of perhaps 50, with dark hair and
mustache slightly tinged with gray and the distinct air of a soldier.
“Ah, who but yourself?” returns Isabel composedly. “Sit down,
Gen. Murillo. I have much to tell you.”
The intelligence is plainly of a pleasing nature. Gen. Murillo
murmurs “Bueno!” more than once as he listens, and when she
finishes he remarks approvingly: “You have done well and may count
on my gratitude.”
“Gracias,” responds Isabel. “That is about the extent of my
Spanish, General.”
“Ah, but you will learn readily. It is simple. Hist! a gentleman
approaches. It were well if we be seen little together to-night. Until
the morrow then, adios.”
Gen. Murillo moves off toward the swirl of dancers and Isabel
surveys with an air of recognition a gentleman in the costume of
Don Caesar de Bazan, who has descended to the arcade by the
north stairway and is coming slowly toward her. Don Caesar looks
curiously after the departing form of the Spaniard; then, dropping
into a chair beside Isabel, he tosses off his mask and asks
carelessly: “Well, my dear Isabel, when do you leave for Cuba?”
“For Cuba?” repeats Mrs. Harding in simulated surprise.
“Exactly. After a glance at the gentleman who just left you I do
not need to be enlightened as to the diplomatic duties to which you
alluded last night.”
“Well, Phillip, I have few secrets that you do not share,” Isabel
says sweetly; “I leave for Cuba to-morrow.”
“So soon,” he murmurs courteously.
“The sooner the better. Every day I am near you makes eventual
separation the harder. I know that you care nothing for me,” she
goes on, her cheeks flushed crimson. “Don’t interrupt me,” as Van
Zandt seeks to interpose a protest. “I know that you care nothing for
me, not in the way I would have you feel. I have your friendship,
yes, beyond that I am nothing to you. And I—I love you, Phillip—
love you as I never expected to love a man. I make the avowal
without shame, for I know there is no possibility of a change in your
sentiments toward me. And I am going away—to-morrow,” half sobs
the woman, as she covers her face with her hands.
Van Zandt lays his hand upon Isabel’s head and smooths the dark
tresses sympathetically. She pushes the hand away.
“Courage! Tears ill become a diplomat,” declares Van Zandt. “This
is a dreary world. We seldom attain our heart’s desire, even though
the object we seek be a lowly one. Will you have some wine?” Isabel
shakes her head. She has dried her eyes and has relapsed into an
apathetic melancholy.
Van Zandt signals to a waiter. “A little wine will help lighten our
hearts,” he tells Mrs. Harding; “for believe me, mine is not less heavy
than yours. Cheer up and we will drink a toast to all unrequited
love.”
Isabel gives him a swift look of surprise. “You heard?” she
demands.
“I heard nothing,” he replies, smilingly. “What has given rise to
your question?”
“’Tis less than an hour since I offered that very toast. I have had a
proposal to-night.”
“Indeed? And you rejected it?”
“Can you ask such a question. The world is full of Don Manadas,
but there is only one—”
“So? The swarthy gentleman, with the curious white mustachios?”
interrupts Van Zandt. “I noticed you talking with him.”
“I had rejected him twice before, but his persistence is worthy of a
better cause. To-night I promised to accompany him on a
filibustering expedition to Cuba. Think of it! The fool!” sneers Isabel.
“And you will not go.”
“Most certainly not. I only half-promised. To-morrow I shall send
word that I have changed my mind.”
“And meanwhile you have accomplished something toward your
new duties, eh?” remarks Van Zandt. If Isabel Harding could read
the dark, handsome face that she loves so well, she would know
that she has lost forever the esteem of Phillip Van Zandt.
“You have betrayed the man who trusted you,” continues Van
Zandt in the same quiet and impassive voice.
“Betrayed him? And what if I did?” flashes Isabel passionately.
“Call it treachery if you will. I say it is only a reprisal of treachery.
Take me out of here, Phillip. I am sick of these lights and the music
and the scent of the flowers.”
“I will see you to a carriage,” says Van Zandt, quietly.
Ten minutes later he says good-by to her, as he prepares to close
the carriage door.
“Some day, Phillip, you will realize how much I love you,” Isabel
whispers, as she presses to her lips the hand he mechanically gives
her.
Words, words, words; but destined to have a tragic fulfillment!
Van Zandt looks after the retreating carriage with a darkening
brow. “Call it treachery if you will,” he repeats, grimly. “By George!
I’ll spike her ladyship’s guns! The cause of liberty shall not be
jeopardized by the indiscretion of its friends or the machinations of
its enemies!”
As he turns and re-enters the garden a man steps to a waiting
cab, and, indicating the carriage which is bearing off Isabel Harding,
he whispers to his driver: “Keep that rig in view till it stops.
Understand?”
CHAPTER XXIV.

FOR THE CAUSE OF LIBERTY.

“You proposed to a lady to-night.”


“What is that to you, sir?” Don Manada turns fiercely upon the
gentleman who has tapped him upon the shoulder and requested
the pleasure of a few moments’ conversation with him.
“Nothing to me, perhaps,” returns Phillip Van Zandt, quietly; “to
you much, possibly. Sit down. Or better, suppose we adjourn to the
arcade. We shall be freer from interruption there.”
“I must decline to accompany you, sir, until I have reason to
believe that the matter on which you desire to talk is of more
importance than your opening remark would indicate.”
Van Zandt surveys the Cuban with a trifle of impatience. “As you
please,” he observes. “But permit me to say that upon your
disposition to listen to what I have to impart depends the success or
failure of the expedition which is to start for Cuba to-morrow—or,
rather, to-day.”
Manada starts violently and bends a searching look upon the
other’s face. “Nothing could be of greater importance to me, sir,” he
says, and without further remark he follows Van Zandt to the little
table where an hour ago he for the third time offered Isabel Harding
his hand and heart.
“Now, to business,” remarks Van Zandt, glancing at his watch. “It
is 1:30. Thirty minutes for talk, the rest of the night for action. You
are Don Manada of the Cuban revolutionary society.” That gentleman
bows. “I am Phillip Van Zandt. That is all you need know concerning
myself. Mrs. Isabel Harding, the lady to whom you made violent love
to-night”—the Cuban scowls, but Van Zandt goes on relentlessly—“I
have known for some months. She has honored me—shall I say?—
with her deep regard. Perhaps she hinted as much to you.”
Manada leans back in his chair and looks his new acquaintance
over critically. This, then, was his rival; a negative one, to be sure,
but a rival that any man might fear.
“If it will flatter your vanity to know that the lady in question
confessed to me that she loved only one man in the world and that
that happy individual was not myself, you are welcome to the
information,” Manada offers, sarcastically.
“Thank you. But I was already aware of the fact, and it is not to
the point. You proposed to Mrs. Harding and were rejected. Stay,” as
the other colors and is about to make an angry retort: “I did not
bring you here, sir, to refresh your mind one instance in which the
usually discriminating Isabel displayed poor taste. But I repeat, she
rejected you; hence subsequently something must have occurred
between you to lead up to a rather peculiar agreement—Mrs.
Harding’s consent to accompany you on a filibustering expedition?”
“Caramba! She told you—you overheard—”
“I overheard nothing. Eavesdropping is not in my line. And she
told me little more; but enough to warrant me in stating that you
have been indiscreet, sir, to use no harsher term, and have
jeopardized not only your own welfare but that of your fellow-
countrymen.”
“You seem to be pretty familiar with my affairs, senor.”
“Not so familiar with them as the Spanish government and the
United States authorities may be,” responds Van Zandt, dryly. “All I
know of your plans I have told you. What I do not know you will tell
me now.”
An angry rejoinder trembles on Manada’s lips, but something in
the stern, quiet air of the man before him checks his wrath.
“Mrs. Harding,” resumes Van Zandt, “consented to go to Cuba with
you, did she not?”
“Practically, yes.”
“And you were to receive her final decision on the morrow?”
“Well, senor?”
“She will not go.”
“Then you persuaded her—you interfered,” cries Manada hotly.
“I did nothing of the sort. Still, I repeat, she will not go. But, stay,
perhaps she will,” murmurs Van Zandt, thoughtfully. “Perhaps her
ladyship’s plans lie deeper than I have supposed,” he thinks. “But
even if she does go, I tell you, my friend, it were far better that you
burned your vessel where it now lies than that Isabel Harding sets
foot upon its deck.”
“Your meaning?” demands Manada in a hoarse whisper.
“Your face tells me that you have guessed the truth,” Van Zandt
says more kindly. “The woman has betrayed you. She is a spy—
diplomat is the polite word—in the employ of the Spanish
government.”
“Caramba!” hisses Manada, sinking back into his chair with
colorless cheeks. “But you can furnish proof of what you assert?” he
cries almost eagerly.
Van Zandt’s lip curls. “Had you watched the fair Isabel after you
left her you would have seen join her a gentleman whose presence
in itself would have been proof sufficient—Gen. Murillo. You know
him?”
“Of the Spanish service,” murmurs Manada in crushed tones.
“Precisely. I met him at the club the other day. And if I mistake
not he has done an excellent bit of work for his government to-
night.”
“But I will find the woman,” bursts out Manada, leaping to his feet.
“Por Dios! I will search her out and—”
“You will do nothing of the kind,” interrupts Van Zandt, drawing
the excited man back into his chair. “Mrs. Harding left for her hotel
half an hour ago. Even were she here it would avail you nothing to
confront her with her—diplomacy. Gen. Murillo is already in
possession of your plans. No, my friend; the mischief is done, but
happily it is not irremediable.”
“Ah!” cries Manada, with a flash of hope.
“Now, listen to me. We have wasted too much time already. What
is the name of your vessel?”
“The Isabel.”
“So? Pretty name, but have it changed at the first opportunity.
Where does she now lie?”
“North River, foot of Twenty-third Street.”
“Excellent,” comments Van Zandt, his eyes lighting with
satisfaction. “And at what time did you intend to sail?”
“At five in the afternoon.”
“You are of course aware that both the Spanish and United States
governments are on the keen lookout for filibustering craft?”
“Certainly,” Manada replies, grimly. “But we were confident of
slipping through unmolested. We had arranged to clear for the
Bermudas, and once on the high seas we felt sure of running away
from any warships that might lie in our course.”
“Ah, your vessel is a yacht. And the cargo—of what does that
consist?”
“Two thousand rifles and 200,000 rounds of cartridges.”
“How is it loaded?”
“The ammunition is packed in kegs, ostensibly containing salt fish;
the rifles are in bags and are hidden at the bottom of bins of
potatoes in the hold.”
“The cargo could be shifted before daybreak, do you think?”
“Two or three hours should suffice.”
“Good. You must have noticed, lying in the neighborhood of your
vessel, a rather trim article in the yacht line.”
“The Semiramis? Yes. A magnificent vessel!” exclaims Manada.
Van Zandt nods. “She is my property and I believe her to be the
fastest vessel afloat in the world to-day. Now here is my plan—I
consider it the only one that will extricate you from the dilemma in
which you are placed: I will place the Semiramis at the service of the
struggling patriots of the Antilles. We will shift the Isabel’s cargo
before the night is gone, and before the sun goes down on another
day the Semiramis will be on her way to Cuba. Once without New
York bay I defy anything short of a cannon ball to overhaul her.
What say you, Don Manada?”
The Cuban’s face expresses the astonishment and joy that he
feels. To be raised suddenly from the depths of despair to the
pinnacle of hope effects a remarkable change in one of his
temperament.
“Santa Maria!” he cries, as he presses warmly Van Zandt’s hands.
“You have done me as great a service as one man can do another.
Por Dios! We shall outwit them cleverly.”
“Then let us be off,” says Van Zandt. “It is after 2 o’clock and we
have little time to spare.”
The men secure their coats and hats and ten minutes later board
a cross-town car.
“Senor Van Zandt, I owe you a debt of gratitude,” declares
Manada; “yet I find myself marveling that you, a stranger, and the
one man to win Isabel Harding’s affection, should interest yourself in
me and the cause I represent.”
“Oh, it promised an adventure; something I have long been in
need of to stir my blood to action,” replies Van Zandt, lightly.
“Besides, am I not an American, and is not the cause of liberty a
cause that appeals to every American with a spark of manhood in his
soul? Only those who know what liberty is realize its priceless
worth.”
They are now walking along West Street. Manada silently
reproaching himself with his recent folly, wraps his greatcoat more
tightly about him, and breathes a shivering malediction on the
cutting winds that sweep adown the Hudson.
The sky is overcast and a slight snow is falling. It is a good night
for the work in hand.
The river front is black and silent and the outlines of the vessels
about the pier are barely distinguishable through the driving storm.
West Street, though dimly lighted, is not deserted. From the grog-
shops come echoes of many a brawl, and every now and then a
drunken longshoreman reels or is thrown into the street and
staggers off, heaven knows where. Every half-hour or so a ferry boat
lumbers in and out of the slip, and there is a temporary bustle in the
vicinage.
“A miserable night, senor,” remarks Van Zandt, as they cross West
Street and pick their way toward the pier where lies the vessel in
which are centered now all of Don Manada’s hopes. The latter has
forgotten for the nonce his recent humiliation and is keenly alive to
the adventurous undertaking in hand.
The men plunge through the gloom, muffled to the eyes and with
heads bent before the biting blasts from the river, when their ears
are suddenly assailed by the sound of a scuffle ahead of them and a
half-choked cry for help. Quickening their steps, they run upon two
men. One of them is prone upon the pier; the other, clearly his
assailant, bends over him.
Before the scamp can rise Van Zandt deals him a blow with his
heavy cane that stretches him beside his victim. He is not a
courageous rogue, or if he is realizes that his chance for an
argument is not especially good. So when he struggles to his feet he
makes off without a word, without even an imprecation.
Van Zandt and Manada raise the prostrate form and bear it back
to the street. As the lamplight falls upon the face of the unconscious
man Van Zandt utters an ejaculation of astonishment.
“By heaven! it is Gen. Murillo! You see, my friend, that I was not
mistaken. He probably came down here to have a look at the Isabel,
and was set upon by one of the scum of the river front.”
Manada nods a silent assent. “He must not see us,” he mutters,
uneasily.
“Don’t be alarmed. He is not likely to recognize any one for a few
minutes. I hope he is not badly hurt. Off with him to yonder saloon;
or, better, to the ferryhouse. The man will be safer there, though we
are more likely to find a policeman at the saloon.”
A policeman is at the ferryhouse, however, and assistance is
summoned. Van Zandt and Manada wait until Gen. Murillo is laid in
the ambulance and the surgeon in charge has assured them that the
man is not fatally hurt; then they tell their story to the policeman
and go about their business.
“A peculiar episode,” remarks Van Zandt. “Our friend will never
know to whom he owes his rescue and perhaps his life. Our affair
must be hurried, nevertheless, for we know what his first effort will
be when he recovers consciousness.”
“Yet some day, when Cuba is free, I shall have the pleasure of
recalling the incident to his mind.”
“When Cuba is free,” repeats Van Zandt. “Well, luck favoring us,
we shall fire a shot to-day that will ring in the ears of the
government at Madrid. Here we are at the Semiramis. Where is the
Isabel?”
“Just beyond. Not twenty feet away.”
Van Zandt hails his yacht and ten minutes later he and Manada
are in the luxurious cabin, in consultation with Capt. Beals, a bluff
old Maine sea dog, who is prepared for any caprice on the part of his
employer and expresses not the least surprise when informed that
arrangements for a cruise to Cuba must be instantly set afoot.
And that morning, while the wind howls around Manhattan Island,
and drives the sleet into the eyes of belated pedestrians; while
Murillo awakens to consciousness in Bellevue Hospital and tells the
attending surgeon that, head or no head, he leaves for Cuba within
half a dozen hours; and while the last carriage load of half-drunken
sports dashes away from the Madison Square Garden, a work is in
progress aboard the Semiramis that means more to its owner than
he dreams of as he stands with folded arms in the dim light of the
ship lanterns, watching silently the transshipment of the insurgent’s
arms.
CHAPTER XXV.

TWO KINDS OF BLOCKADE.

About 9:30 of the morning following the French ball Phillip Van
Zandt drops into his favorite seat in the dining-room of the St. James
hotel and picks up the morning paper.
Scarcely had he unfolded it when his attention was attracted by
two persons seated at the table beyond him. They are Cyrus Felton
and Louise Hathaway, and the latter never looked fairer than on this
bright March morning.
“Ah, my divinity of the ball,” he murmurs. “By Eros! She is superb.
Hair, a mass of gold and the sunlight gives it just the right effect.
Purity and innocence are in those blue eyes and in every line of the
face. Knowing no evil and fearing none, and yet with the self-poise
of a queen. It almost restores one’s confidence in humanity to look
upon such a face.
“I would be glad indeed to know her, but the opportunity for an
introduction is not likely to arise. I could scarcely presume on last
night’s meeting, and besides, she would hold me to my word. What
impulse possessed her to remove her mask at my request? I’ll wager
she regretted it an instant later. Well, she did not see my face, so I
may devour her visually in perfect safety.
“And her companion?” Van Zandt goes on meditatively. “Not her
husband, assuredly. Too old for that. More likely her father, or
perhaps her guardian. They are going to Cuba, so she told me. Well,
I am going to Cuba, too. I may meet her there. Friendships are
easily cultivated in a foreign land. My dear Van Zandt, is it possible
that you are becoming interested in a woman? Careful; you forget
who you are,” he concludes bitterly, and stares moodily out upon the
crowded street.
Mr. Felton and Miss Hathaway are breakfasting leisurely,
unconscious of the interest they have aroused in the gentleman at
the next table. Mr. Felton is scanning the columns of the
Hemisphere, with particular reference to the full dispatches from
Cuba and Madrid. Suddenly he drops the paper with the
exclamation: “This is very unfortunate!”
“What is unfortunate?” inquires Miss Hathaway, sipping her coffee.
“Here is a dispatch from Havana, stating that the government has
ordered a complete blockade of the island and that all steamship
engagements to and from Cuba have been canceled for an indefinite
period.”
Miss Hathaway looks up in mild dismay. “Then we cannot leave
Saturday,” she says.
“It would seem not. Ah, here is something more. The newspaper
has looked up the report at the New York end and finds it to be true.
The steamer City of Havana of the Red Star line, this paper says, will
probably be the last passenger vessel to leave New York for Cuba
until the blockade is raised.”
“But can we not go on that?”
Mr. Felton reads on: “The City of Havana sails to-day at 11
o’clock.” Then he glances at his watch. “It is now nearly 10. Perhaps
we can make it. Wait, I will ascertain from the clerk.”
Mr. Felton rises, and as he turns to leave the dining-room Van
Zandt gets a view of his face, and he starts as if from a nightmare.
“That face again!” he breathes. “That face, which has haunted my
dreams and has been before me in my waking hours! And her
father! Merciful heaven, it cannot be. There is a limit to fate’s
grotesquerie.”
Miss Hathaway glances in Van Zandt’s direction and their eyes
meet. It is only an instant, but it leaves the girl somewhat confused
and accentuates the young man’s disorder.
At this juncture Mr. Felton returns with the information that they
have little more than an hour to reach Barclay Street and the North
River, from which point the steamer leaves.
“Then let us go at once. I am ready,” Louise says, “after I have
scribbled a note of explanation to Mr. Ashley. He was to have
lunched with us at 1 o’clock, you know.”
After they have gone Van Zandt drops his head upon his hand,
and for the space of ten minutes remains plunged in thought. Then,
to the waiter’s surprise, he leaves his breakfast untouched and quits
the dining-room.
In the office he sees Mr. Felton settling his bill. Outside the hotel a
line of “cabbies” are drawn up and these Van Zandt looks over
critically, finally signaling to one of them, a jovial, red visaged
Irishman.
“Riley, a lady and gentleman are going from this hotel to Barclay
Street and North River within a few minutes. I want you to have the
job of carrying them,” says Van Zandt.
“I’m agreeable, sor.”
“After you have secured the job, I want you to miss the steamer
which sails for Cuba at 11 o’clock. Understand?”
Riley puckers up his mouth for a whistle which he decides to
suppress.
“Sure that would not be hard, sor. It’s tin o’clock now.”
“Here they come now. Look to your job,” says Van Zandt.
Mr. Felton and Miss Hathaway emerge from the hotel, followed by
a porter with their trunks. Amid a chorus of “Keb, sir!” “Keb!” “Keb!”
in which Riley sings a heavy bass, Mr. Felton looks about him in
perplexity, and finally, as though annoyed by the importunities of
Riley, who is rather overdoing his part, he selects a rival “cabbie.”
Riley turns somewhat sheepishly to Van Zandt, who looks after the
disappearing carriage in vexation.
“Shall I run them down, sor?” asks the Irishman, with a wink
which means volumes.
“Can you prevent them reaching the pier?”
“Sure, I think so, your honor.”
“I’ll give you $50 if you do it.”
“Be hivens! I’d murdther thim for that,” exclaims Riley, as he leaps
to his box.
The two cabs proceeded at a smart pace down Fifth Avenue, but
as the congested trucking district is reached progress becomes
slower.
“Can you make the pier in time?” Mr. Felton asks the driver
anxiously, consulting his watch for the dozenth time.
“Sure thing,” is the confident response.
Neither the driver nor his passengers see the cab behind them.
Riley has his reins grasped tightly in one hand, his whip in the other,
and the expression on his round red face indicates that he is
preparing for something out of the ordinary.
They have now reached lower West Broadway, and before Mr.
Felton’s driver knows it he has become entangled in a rapidly
created blockade.
Progress now is snail-like. Mr. Felton becomes nervous, while Miss
Hathaway finds much to interest her in the seemingly inextricable
tangle of trucks, drays, horse cars, cabs, etc. Suddenly a space of a
dozen feet or so opens before them, and the driver is about to take
advantage of it when Riley gives his horse a cut with the whip and
bumps by, nearly taking a wheel off the other cab.
Then ensues a duel of that picturesque profanity without which no
truck blockade could possibly be disentangled.
Riley, who is ordinarily one of the most good-natured of mortals,
becomes suddenly sensitive under the abuse heaped upon him and
dragging the rival cabman from his box he proceeds to handle him in
a manner that affords keen delight to the onlookers.
It is a snappy morning and Riley rather enjoys the exercise he is
taking. But it is suddenly ended by a brace of policemen, who
struggle upon the scene and pounce upon the combatants.
Explanations are then in order and peace is restored. No one is
arrested.
Riley is willing to break away, for as he looks around he notes with
satisfaction that the blockade has increased to unusual proportions
and he awaits serenely its slow unraveling.
Meanwhile Mr. Felton is invoking the vials of wrath upon all
cabmen, past, present and to come. It is nearly 11:30 when they
reach the pier and, as they expect, the steamer has gone.
“’Tain’t my fault, mum,” the “cabbie” explains apologetically. “Him’s
the chap what done it,” indicating Riley, who has driven up to the
pier with the triumphant flourish of a winner in a great race.
Mr. Felton casts a withering look upon the jolly Irishman. “We may
as well return to the hotel,” he tells Louise.
At this moment Van Zandt steps from his cab, and, raising his hat,
remarks:
“I trust that the carelessness of my driver has not caused you
serious annoyance.”
“He has prevented our catching the last steamer that will sail for
Cuba in probably some months,” replies Mr. Felton, tartly.
“You blockhead!” cries Van Zandt sternly, turning to Riley, who
averts his face.
“My dear sir, it is needless for me to assure you of my profound
regret. It will not help matters. The mischief is done—and yet I think
I can repair it.”
“Repair it?” repeats Mr. Felton. “In what possible way, sir?”
“Very easily, if you desire. You were going to Havana, I presume?”
“Yes, sir.”
“My yacht sails for Santiago this afternoon at 1 o’clock. I shall be
happy to land you at that port, and you may thence proceed by rail
to Havana.”
Mr. Felton and Louise look at each other in surprise. “Really, sir,”
says the former, “you are very good, but I do not see how we can
put you to such trouble.”
“I assure you that you will not inconvenience me in the slightest.
The yacht is large and you will be the only passengers, with one
exception.”
Mr. Felton hesitates. “How badly does he want to go to Cuba?”
wonders Van Zandt and he remarks: “This will probably be your only
chance to reach Havana in some little time, if, as you say, there are
no more steamers. Really, I almost feel like insisting on your
accepting my offer, as some sort of reparation for the annoyance to
which you have been put and for which I feel partly responsible.”
“But a blockade has been declared about the island. Your yacht—”
“My yacht will land you at Santiago,” supplies Van Zandt, with a
peculiar smile. “We sail in about an hour, and we may as well
proceed to the yacht at once. For I assume that you have decided to
permit me to atone for the blackguardly behavior of my driver.”
Mr. Felton consults Miss Hathaway and the matter is decided in the
affirmative, and as Van Zandt hands them into their coupe, he tells
the driver: “North River, foot of Twenty-third Street.”
An hour later Miss Hathaway is expressing her admiration for the
beautiful yacht that is soon to bear her to the tropics, and Capt.
Beals is giving the last orders preparatory to getting under way.
As Van Zandt watches Mr. Felton cross from the pier to the deck of
the Semiramis into his dark eyes comes a glitter of almost savage
satisfaction, and he murmurs:
“I have you safe now, and by George! You will not soon escape
me!”
CHAPTER XXVI.

THE PENALTY OF PROCRASTINATION.

A pencil of sunlight has struggled through the heavy draperies at


the windows and laid a tiny straight line across the carpet in the
comfortable apartments of Jack Ashley on West Thirty-fourth Street.
The oriole timepiece on the mantel chimes the hour of 9 when that
individual awakens with a series of prodigious yawns.
Fifteen minutes more and Ashley’s toilet is complete, and with
heels elevated to a comfortable angle, he proceeds to scan the
pages of his morning paper. His own story of the French ball first
claims his attention, and with a comment of satisfaction on the size
of the headlines with which it is introduced, he runs his eye
approvingly over the dozen or so illustrations with which the article
is embellished.
A scare head of the largest size catches his eye, and with
awakening interest he reads the sensational headlines. “Gaining
Ground—Cuban Revolutionists Driving Spaniards before Them—
Hemisphere’s Exclusive Interview with Senor Manada Creates
Excitement in Washington—United States Man-of-War to Be Sent to
Cuba to protect American Interests,” and much more of the same
tenor. As Jack skims over the voluminous dispatches that follow the
head, he reads with interest one brief item, dated Santiago de Cuba,
via Nassau, N. P. It is as follows:
“The Government is redoubling its efforts to suppress the
news, and is apparently determined that the press of the
United States and elsewhere shall not learn the exact state
of affairs on the island. Nine-tenths of the local newspaper
men have been fined by the press censor. Several editions of
the leading papers have been seized, and telegrams for
transmission abroad from eastern Cuba are now absolutely
forbidden. It is also a fact that foreign correspondents have
been threatened with expulsion. The Spanish authorities
allege that the mysterious steamer fired upon by the warship
Galicia was not the American ward liner Santiago, but a rebel
vessel which the insurrectionists have purchased in the
United States and fitted up as a gunboat. A blockade of all
the ports of the island, as previously intimated, has been
formally announced.”

“It looks as if the paper would be obliged to send a man down


there,” Ashley reflects, as he struggles into his topcoat. “What a
superb day for the trial trip,” as he opens the street door and steps
into the sunlight. “And this is the day, too, that Barker is to arrest
Felton. He didn’t specify any time, probably not till afternoon,
anyway. I almost wish I wasn’t assigned to that trial trip. I should
like to interview him after the arrest. However, my story is all written
up and I can get the details of the arrest from Barker after I return
from the America. I wonder how Miss Hathaway will take the affair,”
a softer light shining in his eyes as his thoughts revert to the
beautiful ward of Cyrus Felton. “She treats him with the utmost
deference and respect, but I cannot think that she cares especially
for him. Heigho! Now for a cup of coffee and then for another tete-
a-tete with the beautiful unknown of the Raymond hotel.”
It is on the stroke of 10 as Ashley saunters up to the clerk’s desk
in the Kensington and requests that his card, upon which he has
penciled a few lines explaining his identity, be taken to Mrs.
Winthrop.
“Mrs. Winthrop?” the urbane clerk repeats. “There is no such lady
stopping here, to my knowledge.”
Ashley is nonplused. So he has been duped, he thinks, by the fair
unknown. But why has not Barker kept his agreement? A nice sort of
a shadow if he cannot follow as striking-looking a woman as “Mrs.
Winthrop.” But stay! Perhaps she has given a fictitious name, but is
actually stopping at the Kensington after all. Barker could not have
slipped upon a simple matter like that.
Abstractedly twirling his glove, Jack leans over the desk and says
in a low tone to the clerk, an old acquaintance: “Is there a rather
striking-looking young woman, with dark eyes and midnight hair,
stopping at the house?”
The clerk smiles.
“Sorry, Jack, but you are too late, I’m afraid. The beautiful Mrs.
Harding left at 9 o’clock, bag and baggage.”
Ashley turns thoughtfully away and repairs to the reading-room
for a quiet think. So her name—for the present at least—is Mrs.
Harding. But where is Barker? The detective is probably shadowing
Mrs. Harding now. Ashley concludes that there is nothing for him to
do but await Barker’s return. He has been on the watch barely half
an hour when the detective swings himself from a cable car in front
of the hotel.
“Well?” is Jack’s impatient salutation as he leads the way to a
retired corner of the reading-room.
Barker is not in exuberant spirits; his brows are knitted in a frown
and he is nervously biting his mustache.
“Well, she has gone—left town, and is apparently en route from
the country—for Cuba, I believe.”
“For Cuba!” and Jack stares at the detective in mild amaze. Verily,
either a most remarkable series of coincidences or the tangled
threads of the Raymond mystery are pointing unmistakably to the
fair isle of the Antilles.
“Yes, for Cuba. Let me impress it upon your mind in the beginning
that Mrs. Isabel Harding—that’s the name she is sailing under—is no
ordinary woman. Why—but to begin at the beginning. According to
our understanding last night, I followed her to this hotel, where I
found she was actually stopping. I naturally concluded that she
made the engagement with you in good faith, else she would have
given another hotel.”
“She did give me a fictitious name,” breaks in Jack. “Or, rather, she
led me to believe that her name was still Winthrop.”
“Did she? Well, that was useless. Anyhow, I decided to stop here
last night, to be on guard early this morning. I found that my lady
had breakfasted early. This made me suspicious and I kept close
watch of her. Shortly after 9 o’clock she settled her bill at the hotel
and with her trunks was driven to the Jersey City ferry. Of course I
followed. At the Pennsylvania depot she was joined by a foreign-
looking chap—Spaniard. Quite a distinguished-looking duffer. If you
should ever run across him you will know him by a small, crescent-
shaped scar on his left cheek. I was successful in getting close
enough to them to hear some of the conversation. It appeared from
their talk, Ashley, that your Mrs. Harding is, in addition to her other
accomplishments, a spy in the pay of the Spanish Government, and
that she has been successful in learning some of the secret plans
and plots of the Cuban filibusters in this city. She is now on her way
to Port Tampa aboard the Florida limited, and I should judge it is
their intention to proceed from Key West at once to Havana.”
“Their intention? Did the Spanish officer accompany her?”
Barker nods. “He looked as if he was right out of the hospital; his
head was bandaged. Perhaps some of the Cuban sympathizers had it
out with him. However, that episode is closed, for the present at
least. And now for Cyrus Felton. I shall take him directly to the
Tombs, and according to our compact he will be invisible to any of
the newspaper fraternity. Will you come with me to the St. James
while I nab the bird?”
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