Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
114 views

Download full Applied Natural Language Processing with Python: Implementing Machine Learning and Deep Learning Algorithms for Natural Language Processing 1st Edition Taweh Beysolow Ii ebook all chapters

Learning

Uploaded by

beriscrasthi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views

Download full Applied Natural Language Processing with Python: Implementing Machine Learning and Deep Learning Algorithms for Natural Language Processing 1st Edition Taweh Beysolow Ii ebook all chapters

Learning

Uploaded by

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

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Applied Natural Language Processing with Python:


Implementing Machine Learning and Deep Learning
Algorithms for Natural Language Processing 1st
Edition Taweh Beysolow Ii
https://textbookfull.com/product/applied-natural-language-
processing-with-python-implementing-machine-learning-and-
deep-learning-algorithms-for-natural-language-
processing-1st-edition-taweh-beysolow-ii/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Python Natural Language Processing Advanced machine


learning and deep learning techniques for natural language
processing 1st Edition Jalaj Thanaki
https://textbookfull.com/product/python-natural-language-processing-
advanced-machine-learning-and-deep-learning-techniques-for-natural-
language-processing-1st-edition-jalaj-thanaki/
textboxfull.com

Deep Learning for Natural Language Processing Develop Deep


Learning Models for Natural Language in Python Jason
Brownlee
https://textbookfull.com/product/deep-learning-for-natural-language-
processing-develop-deep-learning-models-for-natural-language-in-
python-jason-brownlee/
textboxfull.com

Deep learning in natural language processing Deng

https://textbookfull.com/product/deep-learning-in-natural-language-
processing-deng/

textboxfull.com

Deep Learning for Natural Language Processing (MEAP V07)


Stephan Raaijmakers

https://textbookfull.com/product/deep-learning-for-natural-language-
processing-meap-v07-stephan-raaijmakers/

textboxfull.com
Deep Learning in Natural Language Processing 1st Edition
Li Deng

https://textbookfull.com/product/deep-learning-in-natural-language-
processing-1st-edition-li-deng/

textboxfull.com

Natural language processing with TensorFlow Teach language


to machines using Python s deep learning library 1st
Edition Thushan Ganegedara
https://textbookfull.com/product/natural-language-processing-with-
tensorflow-teach-language-to-machines-using-python-s-deep-learning-
library-1st-edition-thushan-ganegedara/
textboxfull.com

Machine Learning with PySpark: With Natural Language


Processing and Recommender Systems 1st Edition Pramod
Singh
https://textbookfull.com/product/machine-learning-with-pyspark-with-
natural-language-processing-and-recommender-systems-1st-edition-
pramod-singh/
textboxfull.com

Natural Language Processing with Python Cookbook 1st


Edition Krishna Bhavsar

https://textbookfull.com/product/natural-language-processing-with-
python-cookbook-1st-edition-krishna-bhavsar/

textboxfull.com

Introduction to Deep Learning Using R: A Step-by-Step


Guide to Learning and Implementing Deep Learning Models
Using R Taweh Beysolow Ii
https://textbookfull.com/product/introduction-to-deep-learning-using-
r-a-step-by-step-guide-to-learning-and-implementing-deep-learning-
models-using-r-taweh-beysolow-ii/
textboxfull.com
Applied Natural
Language Processing
with Python
Implementing Machine Learning
and Deep Learning Algorithms for
Natural Language Processing

Taweh Beysolow II
Applied Natural
Language Processing
with Python
Implementing Machine
Learning and Deep Learning
Algorithms for Natural
Language Processing

Taweh Beysolow II
Applied Natural Language Processing with Python
Taweh Beysolow II
San Francisco, California, USA

ISBN-13 (pbk): 978-1-4842-3732-8     ISBN-13 (electronic): 978-1-4842-3733-5


https://doi.org/10.1007/978-1-4842-3733-5
Library of Congress Control Number: 2018956300
Copyright © 2018 by Taweh Beysolow II
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 Suresh John
Development Editor: Siddhi Chavan
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 orders-ny@springer-sbm.com, 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 rights@apress.com, or visit http://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 http://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-3732-8. For more detailed information, please visit http://www.apress.com/
source-code.
Printed on acid-free paper
To my family, friends, and colleagues for their continued
support and encouragement to do more with myself than
I often can conceive of doing
Table of Contents
About the Author���������������������������������������������������������������������������������ix

About the Technical Reviewer�������������������������������������������������������������xi


Acknowledgments�����������������������������������������������������������������������������xiii
Introduction����������������������������������������������������������������������������������������xv

Chapter 1: What Is Natural Language Processing?������������������������������1


The History of Natural Language Processing��������������������������������������������������������2
A Review of Machine Learning and Deep Learning����������������������������������������������4
NLP, Machine Learning, and Deep Learning Packages with Python����������������4
Applications of Deep Learning to NLP�����������������������������������������������������������10
Summary������������������������������������������������������������������������������������������������������������12

Chapter 2: Review of Deep Learning��������������������������������������������������13


Multilayer Perceptrons and Recurrent Neural Networks������������������������������������13
Toy Example 1: Modeling Stock Returns with the MLP Model�����������������������15
Vanishing Gradients and Why ReLU Helps to Prevent Them��������������������������27
Loss Functions and Backpropagation������������������������������������������������������������29
Recurrent Neural Networks and Long Short-Term Memory��������������������������30
Toy Example 2: Modeling Stock Returns with the RNN Model�����������������������32
Toy Example 3: Modeling Stock Returns with the LSTM Model���������������������40
Summary������������������������������������������������������������������������������������������������������������41

v
Table of Contents

Chapter 3: Working with Raw Text����������������������������������������������������43


Tokenization and Stop Words������������������������������������������������������������������������������44
The Bag-of-Words Model (BoW)��������������������������������������������������������������������������50
CountVectorizer���������������������������������������������������������������������������������������������51
Example Problem 1: Spam Detection������������������������������������������������������������53
Term Frequency Inverse Document Frequency���������������������������������������������57
Example Problem 2: Classifying Movie Reviews�������������������������������������������62
Summary������������������������������������������������������������������������������������������������������������74

Chapter 4: Topic Modeling and Word Embeddings����������������������������77


Topic Model and Latent Dirichlet Allocation (LDA)����������������������������������������������77
Topic Modeling with LDA on Movie Review Data�������������������������������������������81
Non-Negative Matrix Factorization (NMF)�����������������������������������������������������������86
Word2Vec������������������������������������������������������������������������������������������������������������90
Example Problem 4.2: Training a Word Embedding (Skip-Gram)�������������������94
Continuous Bag-of-Words (CBoW)��������������������������������������������������������������������103
Example Problem 4.2: Training a Word Embedding (CBoW)�������������������������105
Global Vectors for Word Representation (GloVe)�����������������������������������������������106
Example Problem 4.4: Using Trained Word Embeddings with LSTMs����������111
Paragraph2Vec: Distributed Memory of Paragraph Vectors (PV-DM)����������������115
Example Problem 4.5: Paragraph2Vec Example with Movie
Review Data������������������������������������������������������������������������������������������������116
Summary����������������������������������������������������������������������������������������������������������118

Chapter 5: Text Generation, Machine Translation, and Other


Recurrent Language Modeling Tasks������������������������������121
Text Generation with LSTMs�����������������������������������������������������������������������������122
Bidirectional RNNs (BRNN)��������������������������������������������������������������������������126

vi
Table of Contents

Creating a Name Entity Recognition Tagger������������������������������������������������������128


Sequence-to-Sequence Models (Seq2Seq)������������������������������������������������������133
Question and Answer with Neural Network Models������������������������������������������134
Summary����������������������������������������������������������������������������������������������������������141
Conclusion and Final Statements���������������������������������������������������������������������142

Index�������������������������������������������������������������������������������������������������145

vii
About the Author
Taweh Beysolow II is a data scientist and
author currently based in San Francisco,
California. He has a bachelor’s degree in
economics from St. Johns University and a
master’s degree in applied statistics from
Fordham University. His professional
experience has included working at Booz
Allen Hamilton, as a consultant and in various
startups as a data scientist, specifically
focusing on machine learning. He has applied machine learning to federal
consulting, financial services, and agricultural sectors.

ix
About the Technical Reviewer
Santanu Pattanayak currently works at GE
Digital as a staff data scientist and is the author
of the deep learning book Pro Deep Learning
with TensorFlow: A Mathematical Approach
to Advanced Artificial Intelligence in Python
(Apress, 2017). He has more than eight years of
experience in the data analytics/data science
field and a background in development and
database technologies. Prior to joining GE,
Santanu worked at companies such as RBS,
Capgemini, and IBM. He graduated with a degree in electrical engineering
from Jadavpur University, Kolkata, and is an avid math enthusiast. Santanu
is currently pursuing a master’s degree in data science from the Indian
Institute of Technology (IIT), Hyderabad. He also devotes his time to data
science hackathons and Kaggle competitions, where he ranks within the
top 500 across the globe. Santanu was born and brought up in West Bengal,
India, and currently resides in Bangalore, India, with his wife.

xi
Acknowledgments
A special thanks to Santanu Pattanayak, Divya Modi, Celestin Suresh
John, and everyone at Apress for the wonderful experience. It has been a
pleasure to work with you all on this text. I couldn’t have asked for a better
team.

xiii
Introduction
Thank you for choosing Applied Natural Language Processing with Python
for your journey into natural language processing (NLP). Readers should
be aware that this text should not be considered a comprehensive study
of machine learning, deep learning, or computer programming. As such,
it is assumed that you are familiar with these techniques to some degree.
Regardless, a brief review of the concepts necessary to understand the
tasks that you will perform in the book is provided.
After the brief review, we begin by examining how to work with raw
text data, slowly working our way through how to present data to machine
learning and deep learning algorithms. After you are familiar with some
basic preprocessing algorithms, we will make our way into some of the
more advanced NLP tasks, such as training and working with trained
word embeddings, spell-check, text generation, and question-and-answer
generation.
All of the examples utilize the Python programming language and
popular deep learning and machine learning frameworks, such as scikit-­
learn, Keras, and TensorFlow. Readers can feel free to access the source
code utilized in this book on the corresponding GitHub page and/or try
their own methods for solving the various problems tackled in this book
with the datasets provided.

xv
CHAPTER 1

What Is Natural
Language
Processing?
Deep learning and machine learning continues to proliferate throughout
various industries, and has revolutionized the topic that I wish to discuss
in this book: natural language processing (NLP). NLP is a subfield of
computer science that is focused on allowing computers to understand
language in a “natural” way, as humans do. Typically, this would refer to
tasks such as understanding the sentiment of text, speech recognition, and
generating responses to questions.
NLP has become a rapidly evolving field, and one whose applications
have represented a large portion of artificial intelligence (AI)
breakthroughs. Some examples of implementations using deep learning
are chatbots that handle customer service requests, auto-spellcheck on cell
phones, and AI assistants, such as Cortana and Siri, on smartphones. For
those who have experience in machine learning and deep learning, natural
language processing is one of the most exciting areas for individuals to
apply their skills. To provide context for broader discussions, however, let’s
discuss the development of natural language processing as a field.

© Taweh Beysolow II 2018 1


T. Beysolow II, Applied Natural Language Processing with Python,
https://doi.org/10.1007/978-1-4842-3733-5_1
Chapter 1 What Is Natural Language Processing?

The History of Natural Language Processing


Natural language processing can be classified as a subset of the broader
field of speech and language processing. Because of this, NLP shares
similarities with parallel disciplines such as computational linguistics,
which is concerned with modeling language using rule-based models.
NLP’s inception can be traced back to the development of computer science
in the 1940s, moving forward along with advances in linguistics that led to
the construction of formal language theory. Briefly, formal language theory
models language on increasingly complex structures and rules to these
structures. For example, the alphabet is the simplest structure, in that it is
a collection of letters that can form strings called words. A formal language
is one that has a regular, context-free, and formal grammar. In addition to
the development of computer sciences as a whole, artificial intelligence’s
advancements also played a role in our continuing understanding of NLP.
In some sense, the single-layer perceptron (SLP) is considered to be the
inception of machine learning/AI. Figure 1-1 shows a photo of this model.

Figure 1-1. Single-layer perceptron

The SLP was designed by neurophysiologist Warren McCulloch and


logician Walter Pitt. It is the foundation of more advanced neural network
models that are heavily utilized today, such as multilayer perceptrons.

2
Chapter 1 What Is Natural Language Processing?

The SLP model is seen to be in part due to Alan Turing’s research in the
late 1930s on computation, which inspired other scientists and researchers
to develop different concepts, such as formal language theory.
Moving forward to the second half of the twentieth century, NLP starts
to bifurcate into two distinct groups of thought: (1) those who support a
symbolic approach to language modelling, and (2) those who support a
stochastic approach. The former group was populated largely by linguists
who used simple algorithms to solve NLP problems, often utilizing pattern
recognition. The latter group was primarily composed of statisticians
and electrical engineers. Among the many approaches that were popular
with the second group was Bayesian statistics. As the twentieth century
progressed, NLP broadened as a field, including natural language
understanding (NLU) to the problem space (allowing computers to react
accurately to commands). For example, if someone spoke to a chatbot and
asked it to “find food near me,” the chatbot would use NLU to translate this
sentence into tangible actions to yield a desirable outcome.
Skip closer to the present day, and we find that NLP has experienced
a surge of interest alongside machine learning’s explosion in usage over
the past 20 years. Part of this is due to the fact that large repositories of
labeled data sets have become more available, in addition to an increase in
computing power. This increase in computing power is largely attributed
to the development of GPUs; nonetheless, it has proven vital to AI’s
development as a field. Accordingly, demand for materials to instruct
data scientists and engineers on how to utilize various AI algorithms has
increased, in part the reason for this book.
Now that you are aware of the history of NLP as it relates to the present
day, I will give a brief overview of what you should expect to learn. The
focus, however, is primarily to discuss how deep learning has impacted
NLP, and how to utilize deep learning and machine learning techniques to
solve NLP problems.

3
Chapter 1 What Is Natural Language Processing?

 Review of Machine Learning and Deep


A
Learning
You will be refreshed on important machine learning concepts,
particularly deep learning models such as multilayer perceptrons (MLPs),
recurrent neural networks (RNNs), and long short-term memory (LSTM)
networks. You will be shown in-depth models utilizing toy examples before
you tackle any specific NLP problems.

 LP, Machine Learning, and Deep Learning


N
Packages with Python
Equally important as understanding NLP theory is the ability to apply it in
a practical context. This book utilizes the Python programming language,
as well as packages written in Python. Python has become the lingua
franca for data scientists, and support of NLP, machine learning, and
deep learning libraries is plentiful. I refer to many of these packages when
solving the example problems and discussing general concepts.
It is assumed that all readers of this book have a general understanding
of Python, such that you have the ability to write software in this language.
If you are not familiar with this language, but you are familiar with others,
the concepts in this book will be portable with respect to the methodology
used to solve problems, given the same data sets. Be that as it may, this
book is not intended to instruct users on Python. Now, let’s discuss some of
the technologies that are most important to understanding deep learning.

TensorFlow
One of the groundbreaking releases in open source software, in addition
to machine learning at large, has undoubtedly been Google’s TensorFlow.
It is an open source library for deep learning that is a successor to Theano,
a similar machine learning library. Both utilize data flow graphs for

4
Chapter 1 What Is Natural Language Processing?

computational processes. Specifically, we can think of computations as


dependent on specific individual operations. TensorFlow functionally
operates by the user first defining a graph/model, which is then operated
by a TensorFlow session that the user also creates.
The reasoning behind using a data flow graph rather than another
computational format computation is multifaceted, however one of the
more simple benefits is the ability to port models from one language to
another. Figure 1-2 illustrates a data flow graph.

Graph of Nodes, also called operations (ops)


biases

weights Add Softmax


MatMul Xent
inputs

targets

Figure 1-2. Data flow graph diagram

For example, you may be working on a project where Java is the


language that is most optimal for production software due to latency
reasons (high-frequency trading, for example); however, you would like to
utilize a neural network to make predictions in your production system.
Rather than dealing with the time-consuming task of setting up a training
framework in Java for TensorFlow graphs, something could be written in
Python relatively quickly, and then the graph/model could be restored by
loading the weights in the production system by utilizing Java. TensorFlow
code is similar to Theano code, as follows.

    #Creating weights and biases dictionaries


    weights = {'input': tf.Variable(tf.random_normal([state_
size+1, state_size])),

5
Chapter 1 What Is Natural Language Processing?

        'output': tf.Variable(tf.random_normal([state_size,
n_classes]))}
    biases = {'input': tf.Variable(tf.random_normal([1, state_
size])),
        'output': tf.Variable(tf.random_normal([1, n_classes]))}

    #Defining placeholders and variables


    X = tf.placeholder(tf.float32, [batch_size, bprop_len])
    Y = tf.placeholder(tf.int32, [batch_size, bprop_len])
    init_state = tf.placeholder(tf.float32, [batch_size, state_
size])
    input_series = tf.unstack(X, axis=1)
    labels = tf.unstack(Y, axis=1)
    current_state = init_state
    hidden_states = []

    #Passing values from one hidden state to the next


    for input in input_series: #Evaluating each input within
the series of inputs
        input = tf.reshape(input, [batch_size, 1]) #Reshaping
input into MxN tensor
        input_state = tf.concat([input, current_state], axis=1)
#Concatenating input and current state tensors
        _hidden_state = tf.tanh(tf.add(tf.matmul(input_
state, weights['input']), biases['input'])) #Tanh
transformation
        hidden_states.append(_hidden_state) #Appending the next
state
        current_state = _hidden_state #Updating the current state

TensorFlow is not always the easiest library to use, however, as there


often serious gaps between documentation for toy examples vs. ­real-­
world examples that reasonably walk the reader through the complexity of
implementing a deep learning model.
6
Chapter 1 What Is Natural Language Processing?

In some ways, TensorFlow can be thought of as a language inside of


Python, in that there are syntactical nuances that readers must become
aware of before they can write applications seamlessly (if ever). These
concerns, in some sense, were answered by Keras.

Keras
Due to the slow development process of applications in TensorFlow,
Theano, and similar deep learning frameworks, Keras was developed for
prototyping applications, but it is also utilized in production engineering
for various problems. It is a wrapper for TensorFlow, Theano, MXNet, and
DeepLearning4j. Unlike these frameworks, defining a computational graph
is relatively easy, as shown in the following Keras demo code.

def create_model():
    model = Sequential()
    model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
                       input_shape=(None, 40, 40, 1),
                       padding='same', return_sequences=True))
    model.add(BatchNormalization())

    model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),


                       padding='same', return_sequences=True))
    model.add(BatchNormalization())
    
    model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
                       padding='same', return_sequences=True))
    model.add(BatchNormalization())

    model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),


                       padding='same', return_sequences=True))
    model.add(BatchNormalization())

    model.add(Conv3D(filters=1, kernel_size=(3, 3, 3),

7
Chapter 1 What Is Natural Language Processing?

                   activation='sigmoid',
                   padding='same', data_format='channels_last'))
    model.compile(loss='binary_crossentropy', optimizer='adadelta')
    return model

Although having the added benefit of ease of use and speed with
respect to implementing solutions, Keras has relative drawbacks when
compared to TensorFlow. The broadest explanation is that Keras
users have considerably less control over their computational graph
than TensorFlow users. You work within the confines of a sandbox
when using Keras. TensorFlow is better at natively supporting more
complex operations, and providing access to the most cutting-edge
implementations of various algorithms.

Theano
Although it is not covered in this book, it is important in the progression
of deep learning to discuss Theano. The library is similar to TensorFlow
in that it provides developers with various computational functions (add,
matrix multiplication, subtract, etc.) that are embedded in tensors when
building deep learning and machine learning models. For example, the
following is a sample Theano code.

(code redacted please see github)


X, Y = T.fmatrix(), T.vector(dtype=theano.config.floatX)
    weights = init_weights(weight_shape)
    biases = init_biases(bias_shape)
    predicted_y = T.argmax(model(X, weights, biases), axis=1)

    cost = T.mean(T.nnet.categorical_crossentropy(predicted_y, Y))


    gradient = T.grad(cost=cost, wrt=weights)
    update = [[weights, weights - gradient * 0.05]]

8
Chapter 1 What Is Natural Language Processing?

    train = theano.function(inputs=[X, Y], outputs=cost,


updates=update, allow_input_downcast=True)
    predict = theano.function(inputs=[X], outputs=predicted_y,
allow_input_downcast=True)

    for i in range(0, 10):


        print(predict(test_x_data[i:i+1]))

if __name__ == '__main__':

    model_predict()

When looking at the functions defined in this sample, notice that T is


the variable defined for a tensor, an important concept that you should
be familiar with. Tensors can be thought of as objects that are similar
to vectors; however, they are distinct in that they are often represented
by arrays of numbers, or functions, which are governed by specific
transformation rules unique unto themselves. Tensors can specifically be
a single point or a collection of points in space-time (any function/model
that combines x, y, and z axes plus a dimension of time), or they may be a
defined over a continuum, which is a tensor field. Theano and TensorFlow
use tensors to perform most of the mathematical operations as data is
passed through a computational graph, colloquially known as a model.
It is generally suggested that if you do not know Theano, you should
focus on mastering TensorFlow and Keras. Those that are familiar with
the Theano framework, however, may feel free to rewrite the existing
TensorFlow code in Theano.

9
Chapter 1 What Is Natural Language Processing?

Applications of Deep Learning to NLP


This section discusses the applications of deep learning to NLP.

Introduction to NLP Techniques and Document


Classification
In Chapter 3, we walk through some introductory techniques, such as
word tokenization, cleaning text data, term frequency, inverse document
frequency, and more. We will apply these techniques during the course
of our data preprocessing as we prepare our data sets for some of the
algorithms reviewed in Chapter 2. Specifically, we focus on classification
tasks and review the relative benefits of different feature extraction
techniques when applied to document classification tasks.

T opic Modeling
In Chapter 4, we discuss more advanced uses of deep learning, machine
learning, and NLP. We start with topic modeling and how to perform it via
latent Dirichlet allocation, as well as non-negative matrix factorization.
Topic modeling is simply the process of extracting topics from documents.
You can use these topics for exploratory purposes via data visualization or
as a preprocessing step when labeling data.

W
 ord Embeddings
Word embeddings are a collection of models/techniques for mapping
words (or phrases) to vector space, such that they appear in a high-­
dimensional field. From this, you can determine the degree of similarity,
or dissimilarity, between one word (or phrase, or document) and another.
When we project the word vectors into a high-dimensional space, we can
envision that it appears as something like what’s shown in Figure 1-3.

10
Chapter 1 What Is Natural Language Processing?

walked

swam

walking

swimming

Verb tense
Figure 1-3. Visualization of word embeddings

Ultimately, how you utilize word embeddings is up to your own


interpretation. They can be modified for applications such as spell check,
but can also be used for sentiment analysis, specifically when assessing
larger entities, such as sentences or documents in respect to one another.
We focus simply on how to train the algorithms and how to prepare data to
train the embeddings themselves.

Language Modeling Tasks Involving RNNs


In Chapter 5, we end the book by tackling some of the more advanced NLP
applications, which is after you have been familiarized with preprocessing
text data from various format and training different algorithms.
Specifically, we focus on training RNNs to perform tasks such as name
entity recognition, answering questions, language generation, and
translating phrases from one language to another.

11
Chapter 1 What Is Natural Language Processing?

Summary
The purpose of this book is to familiarize you with the field of natural
language processing and then progress to examples in which you
can apply this knowledge. This book covers machine learning where
necessary, although it is assumed that you have already used machine
learning models in a practical setting prior.
While this book is not intended to be exhaustive nor overly academic,
it is my intention to sufficiently cover the material such that readers are
able to process more advanced texts more easily than prior to reading
it. For those who are more interested in the tangible applications of NLP
as the field stands today, it is the vast majority of what is discussed and
shown in examples. Without further ado, let’s begin our review of machine
learning, specifically as it relates to the models used in this book.

12
CHAPTER 2

Review of Deep
Learning
You should be aware that we use deep learning and machine learning
methods throughout this chapter. Although the chapter does not provide
a comprehensive review of ML/DL, it is critical to discuss a few neural
network models because we will be applying them later. This chapter also
briefly familiarizes you with TensorFlow, which is one of the frameworks
utilized during the course of the book. All examples in this chapter use toy
numerical data sets, as it would be difficult to both review neural networks
and learn to work with text data at the same time.
Again, the purpose of these toy problems is to focus on learning how
to create a TensorFlow model, not to create a deployable solution. Moving
forward from this chapter, all examples focus on these models with text data.

 ultilayer Perceptrons and Recurrent


M
Neural Networks
Traditional neural network models, often referred to as multilayer
perceptron models (MLPs), succeed single-layer perceptron models (SLPs).
MLPs were created to overcome the largest shortcoming of the SLP model,
which was the inability to effectively handle data that is not linearly
separable. In practical cases, we often observe that multivariate data is

© Taweh Beysolow II 2018 13


T. Beysolow II, Applied Natural Language Processing with Python,
https://doi.org/10.1007/978-1-4842-3733-5_2
Chapter 2 Review of Deep Learning

non-linear, rendering the SLP null and void. MLPs are able to overcome
this shortcoming—specifically because MLPs have multiple layers. We’ll
go over this detail and more in depth while walking through some code to
make the example more intuitive. However, let’s begin by looking at the
MLP visualization shown in Figure 2-1.

Figure 2-1. Multilayer perceptron

Each layer of an MLP model is connected by weights, all of which are


initialized randomly from a standard normal distribution. The input layer
has a set number of nodes, each representative of a feature within a neural
network. The number of hidden layers can vary, but each of them typically
has the same number of nodes, which the user specifies. In regression, the
output layer has one node. In classification, it has K nodes, where K is the
number of classes.
Next, let’s have an in-depth discussion on how an MLP works and
complete an example in TensorFlow.

14
Chapter 2 Review of Deep Learning

T oy Example 1: Modeling Stock Returns


with the MLP Model
Let’s imagine that we are trying to predict Ford Motor Company (F)
stock returns given the returns of other stocks on the same day. This is a
regression problem, given that we are trying to predict a continuous value.
Let’s begin by defining an mlp_model function with arguments that will be
used later, as follows:

def mlp_model(train_data=train_data, learning_rate=0.01,


iters=100, num_hidden1=256):

This Python function contains all the TensorFlow code that forms the
body of the neural network. In addition to defining the graph, this function
invokes the TensorFlow session that trains the network and makes
predictions. We’ll begin by walking through the function, line by line, while
tying the code back to the theory behind the model.
First, let’s address the arguments in our function: train_data is the
variable that contains our training data; in this example; it is the returns of
specific stocks over a given period of time. The following is the header of
our data set:

0  0.002647 -0.001609  0.012800  0.000323  0.016132 -0.004664


-0.018598
1  0.000704  0.000664  0.023697 -0.006137 -0.004840  0.003555
-0.006664
2  0.004221  0.003600  0.002469 -0.010400 -0.008755 -0.002737  
0.025367
3  0.003328  0.001605  0.050493  0.006897  0.010206  0.002260
-0.007156
4  0.001397  0.004052 -0.009965 -0.012720 -0.019235 -0.002255  
0.017916

15
Chapter 2 Review of Deep Learning

5 -0.009326 -0.003754 -0.014506 -0.006607 -0.034865  0.011463  


0.003844
6  0.008446  0.005747  0.022830  0.009312  0.021757 -0.000319  
0.023982
7  0.002705  0.002623  0.007636  0.020099 -0.007433 -0.008303
-0.004330
8 -0.011224 -0.009530 -0.008161 -0.003230 -0.015381 -0.003381
-0.010674
9  0.012496  0.010942  0.016750  0.007777  0.001233  0.008724  
0.033367

Each of the columns represent the percentage return of a stock on a


given day, with our training set containing 1180 observations and our test
set containing 582 observations.
Moving forward, we come to the learning rate and activation function.
In machine learning literature, the learning rate is often represented by the
symbol η (eta). The learning rate is a scalar value that controls the degree
to which the gradient is updated to the parameter that we wish to change.
We can exemplify this technique when referring to the gradient descent
update method. Let’s first look at the equation, and then we can break it
down iteratively.

1 N
( )
2
Si =1 hq ( x ) - y i
i
q t +1 = q t - h (2.1)
N

q t +1 = q t - h
1
N
( i
)
Si =1 2 hq ( x ) - y i Ñq hq ( x )
i

In Equation 2.1, we are updating some parameter, θ, at a given


time step, t. hθ(x)i is equal to the hypothesized label/value, y being the
actual label/value, in addition to N being equal to the total number of
observations in the data set we are training on.
∇θhθ(x)i is the gradient of the output with respect to the parameters of
the model.

16
Chapter 2 Review of Deep Learning

Each unit in a neural network (with the exception of the input layer)
receives the weighted sum of inputs multiplied by weights, all of which are
summed with a bias. Mathematically, this can be described in Equation 2.2.

y = f ( x ,w T ) + b (2.2)

In neural networks, the parameters are the weights and biases. When
referring to Figure 2-1, the weights are the lines that connect the units in
a layer to one another and are typically initialized by randomly sampling
from a normal distribution. The following is the code where this occurs:

    
weights = {'input': tf.Variable(tf.random_normal([train_x.
shape[1], num_hidden])),
            
'hidden1': tf.Variable(tf.random_normal([num_
hidden, num_hidden])),
            
'output': tf.Variable(tf.random_normal([num_hidden,
1]))}

    
biases = {'input': tf.Variable(tf.random_normal([num_
hidden])),
            
'hidden1': tf.Variable(tf.random_normal([num_
hidden])),
            'output': tf.Variable(tf.random_normal([1]))}

Because they are part of the computational graph, weights and biases
in TensorFlow must be initialized as TensorFlow variables with the tf.
Variable(). TensorFlow thankfully has a function that generates numbers
randomly from a normal distribution called tf.random_normal(), which
takes an array as an argument that specifies the shape of the matrix that you
are creating. For people who are new to creating neural networks, choosing
the proper dimensions for the weight and bias units is a typical source of
frustration. The following are some quick pointers to keep in mind :

• When referring to the weights, the columns of a given


layer need to match the rows of the next layer.

17
Chapter 2 Review of Deep Learning

• The columns of the weights for every layer must match


the number of units for each layer in the biases.

• The output layer columns for the weights dictionary


(and array shape for the bias dictionary) should be
representative of the problem that you are modeling.
(If regression, 1; if classification, N, where N = the
number of classes).

You might be curious as to why we initialize the weights and biases


randomly. This leads us to one of the key components of neural networks’
success. The easiest explanation is to imagine the following two scenarios:

• All weights are initialized to 1. If all the weights are


initialized to 1, every neuron is passed the same value,
equal to the weighted sum, plus the bias, and then put
into some activation function, whatever this value may be.

• All weights are initialized to 0. Similar to the prior


scenario, all the neurons are passed the same value,
except that this time, the value is definitely zero.

The more general problem associated with weights that are initialized
at the same location is that it makes the network susceptible to getting
stuck in local minima. Let’s imagine an error function, such as the one
shown in Figure 2-2.

18
Exploring the Variety of Random
Documents with Different Content
kouluhuoneen ja oli nyt maailmallinen teikarinulikka, joka muutamia
päiviä ennen tepastellessaan roimahousut yllään, oli nostanut
hämmästyttävää pahennusta. Harmaamunkki-veli Johannes oli asian
aiheesta esiveljensä luvalla saarnannut roimahousu-perkeleestä ja
itse kirkkoherra olisi ehkä tehnyt samoin, ellei asia oikeimmiten
hänestä olisi näyttänyt naurettavalta ja hän olisi ollut pormestarin
pöytäystävä.

Lauri vetäisi auki jonkun laatikon ja sieppasi siitä esiin pari


painettua plakaattia; toisessa oli karkea puupiirros. Nämä kädessä
tuli hän ulos Fabben luo ja käski tätä tavallisella rehevällä äänellään,
joka päivä päivältä yhä reheni, seuraamaan itseään alas
rantapuodille. Kirkkoherra oli vielä makuulla, ja koska Lauri tosin
aikoi saada Fabben äänekkääksi, mutta ei kuitenkaan tahtonut
herättää opettajaansa, jota hän vielä, vaikka jotenkin vähän, arasteli,
oli hän aijottua koettansa varten valinnut syrjäisen rantapuodin,
jonka ovi aukeni Vetterille päin.

Lauri istahti hakkuupölkyn päähän ja viittasi Fabbelle sijaa kumoon


käännetyn veneen pohjalle, jonka emäpuun päällä tosin ei ollut
mukava istua, mutta paremman puutteessa sentään kävi laatuun.
Fabbe tarkasti Lauria, joka istui vedenkalvosta heijastavan valon
välkkeessä, ja hän ajatteli itsekseen: kyllä tuo on äitinsä ilmetty kuva,
vaikka rumennettu. Ei jälkeäkään Gudmund mestarista.

— Fabbe, sanoi Lauri, sinun pitää retkilläsi kulettaa näitä


lentolehtiä laukussasi, ja minne vaan poikkeat taloihin, talonpoikien
tuvissa tai herrastalojen keittiöissä, lukea ne julki. Niissä puhutaan
merkillisistä asioista, joita kaikkien kristittyjen tarvitsee tietää. Siten
sinun maankiertelysi tuottaa edes jotakin hyvää. Siksi sanoinkin
äidilleni, joka tahtoi että isä peruuttamattomasti määräisi sinun
valittavaksesi jommankumman, joko työhön jäämisen tai erot
ikipäiviksi — sanoin: äiti, anna Fabben vieläkin lähteä Jumalan
turvissa ja palata taasen tänne! Toinen plakaatti, tuo, jossa on
puupiirros, sopii paremmin laulettavaksi kuin lausuttavaksi; ja laula
se heille niin, että se oikein täryyttää selkäpiitä, sillä siinä kerrotaan
perin kummasta enteestä, joka on lähetetty meille varotukseksi, opin
ja elämän parantamiseksi. Sinulla on vankka ääni etkä hätää eksy
nuotin tolalta. Tässä on paperi ja kummituksen kuva siinä ihan
semmoisena kuin se nähtiin, ja alla on värssyt. Mitäs siitä tuumaat?

— Hyi! sanoi Fabbe piirroksen nähdessään, ompas se kamala


otus. Onko se kala olevinaan?

— Kala se on. Laulas nyt, niin saat jotain tietää siitä, samalla kun
laulat!

Fabbe katseli tekstiin ja lauloi. Laulu kajahteli pitkin vedenpintaa,


niin että joku kalastaja, joka ulompana järvellä oli ruvennut
verkkoansa kokemaan, käänsi päänsä maata kohden:

Pyhä kristikunta, kuule sie, jota synti ja saatana raastaa


nyt hurjemmin kuin milloinkaan! Tahon oudon kumman haastaa.
Kala Tyber-joesta Ruomissa, kala ongest' ilmi saapui;
sen pyrstössä nähtiin kirjoitus, sen verhona munkinkaapu.

Sen seljässä roikkui kapuussi ja suuss' oli piispanhanko;


sen kauhea suu oli ammollaan — kai tuo oli lemmon lanko!
Se paavinkruunua niskallaan piti: selvitäs tämä pulma!
Kas siinäpä kala, kala hirmuinen, kala katsoa kauhea, julma.

Ja kardinaalit ne selvittää kalan pulmaa koetti ja huomaa:


Kah selvänä pyrstössä kirjotus on: Paapelin portto on — Ruoma!
Tulevaisten aikain kurjuutta tämä tietää, kristikunta.
Sitä mieti, mies, sitä vaimo myös! Älä torku synnin unta!

Fabben laulaessa ristiriitaiset tunteet liikkuivat Laurissa. Laulu ei


tehnyt häneen ollenkaan sitä vaikutusta, jota hän oli odottanut.
Häntä halutti nauraa, jota hän piti perkeleen viettelyksenä, ja häntä
halutti lyödä sälliä tahallisena ilvehtijänä vasten suuta, jota
mielijohdetta hän oli taipuisa luulemaan taivaasta tulleeksi. Vielä oli
viimeinen säejakso jälellä, kun Lauri karkasi pystyyn, survaisi
nyrkkinsä seinäpalkkiin ja huusi: Vaiti, Fabbe!

— Mikäs hätänä? kysäisi Fabbe kummastuneen näköisenä;


teenhän niinkuin
Lauri käski.

Lauri rauhottui ja sanoi: huomaan ettei sinun sovi laulaa tuota


veisua. Sinä saatat sen naurettavaksi tuolla laulutavallasi ja
ammottamalla punakan naamasi suupieliä. Sun tulee sen sijaan
lukea se julki kuulijoillesi vakavasti ja pontevasti. Lue nyt näytteeksi
tuo värssy! — Hän osotti sormellaan 2 värssyä. Fabbe luki:

Sen seljässä roikkui kapuussi ja suuss' oli piispanhanko;


sen kauhea suu oli ammollaan — kai tuo oli lemmon lanko.
Se paavinkruunua niskallaan piti: selvitäs tämä pulma!
Kas siinäpä kala, kala hirmuinen, kala katsoa kauhea, julma.

— Ei sinun lausuntosi tyydytä minua, sanoi Lauri.

— Enkös lue oikein sisältä? kysyi Fabbe. Luulinhan sen tempun


osaavani.
— Kyllä, mutta sinä panet koron hassusti. Esimerkiksi: korotat
kalaa liiaksi. Korotat niin, ikäänkuin kamaluus ja kauheus olisi siinä,
että aave oli kalanmuotoinen.

— Kalahan se oli.

Lauri repi maltittomasti tukkaansa.

— Älä sitä etupäässä terota, että se oli kala, vaan että se oli
hirvittävä, pahaa ennustava kala. Se on luettava näin:

Kas siinäpä kala, kala hirmuinen, kala katsoa kauhea, julma.

— Jollen osaa lukea mieliksi, niin periköön Lauri plakaattinsa


takaisin.

— No, sanoi Lauri, lue niin hyvin kuin osaat! Ja tuo plakaatit
mukanasi kun palaat! Jäljennöksiä otettakoon niistä halusti. Hyvästi,
Fabbe, onnea matkallesi.

Fabbe pisti paperit laukkuunsa ja lähti.

Hän suuntasi kulkunsa edemmäs itäänpäin, sivuten kirkon ja torin


sekä saapui nummelle. Tällä kanervakankaan palstalla oli tärkeä
tehtävänsä kaupungin ja paikkakunnan elämässä, sillä siellä pidettiin
härkämarkkinoita, siellä koulupojat telmivät lomahetkillään, siellä
sunnuntaisin porvarit harjoittelivat jousipyssyllä ampumista, sinne
paikkakunnan vapaasukuiset toisinaan toivat näytteille pienen
parvensa haarniskoitua ratsuväkeä, ja jolloinkulloin oli siellä
turnajaisiakin pidetty. Nummen toiselta laiteelta kohosi ränstynyt
linna, jonka tornien ja muurijanan päälle Gösta kuningas oli
panettanut lautakatteet säilyttääkseen niitä kunnes ne vastedes
saataisiin uudestaan rakennetuiksi. Tästä oitis etelään seisoi
hietaharjulla, Munkkijärven rannalla, komean jalaviston keskellä
harmaaveljistön luostari, muurilla aidattuna. Munkit eivät olleet niitä,
jotka uneen hukkasivat huomenhetkiänsä. Fabbe näki heitä kolme
tai neljä luostarin tiiliuunilla harjun juurella; he olivat alottaneet
työnsä samaan aikaan kuin vasarat alkoivat kalkkua Gudmund
mestarin talossa ja kaupungin muissa pajoissa. Fabbe tervehti heitä
heiluttamalla hattuansa ja he vastasivat tervehtimällä. Kaalitarhassa
puuhasi pari ikäkulua valkopartaista veljeä, ja portin suulla istuivat
tämän veljeskunnan ainoat lihavat: kyökkimestari ja portinvartia.
Tämä oli odottanut Fabbea, ja kun portinkello kilahti ja Fabbe pääsi,
sisään luostarinpihaan, seisoi hänen edessään pieni esiveli Mathias,
ruskeat silmänsä syvällä kuopissaan, ja saattoi hänet oikopäätä
kapitulisaliin, jonka ikkunoista idänaurinko säteili sisään
lasimaalausten lävitse, valaisten kirjavalla värivälkkeellään tummia
kaappeja ja rahia kuvaveistoksineen. Yksi kaappi avattiin ja esiveli
otti esille pari kolme painettua paperia, ojensi nämä vastahakoisen
näköisenä Fabbelle sekä pyysi häntä ottamaan ne laukkuunsa ja,
sopivan tilaisuuden sattuessa, lukemaan niitä talonpojille.

Fabbe silmäili, ennenkuin kääri paperit kokoon, ylintä, jossa oli


kuvattuna kummallinen kalantapainen otus, ja luki seuraavan
värssyn:

Pyhä kristikunta, kuule sie, jota valheen oppi jo raastaa


nyt julmemmin kuin milloinkaan! Tahon oudon kumman haastaa:
Nyt Rheinin virrasta perjantaisin kurkottaa kala, huutaa:
Voi syntisjoukkoa! Kuuletkos sa Lutherusta valhesuuta!

Fabben lukiessa punehtuivat esiveljen kuihtuneet posket. Hänen


esimiehensä, provinsiaali, oli hänelle jättänyt nämä painotuotteet ja
käskenyt häntä tekemään mitä hän nyt teki. Hän laski katseensa
maahan.

— Taivaan herra! Entä jos tämä ei olekaan totta — ja minä epäilen


pahasti!…

Esiveljen ruumis oli jo aikaa asettanut taloutensa paaston ja


lihankurituksen kannalle eikä siitä sanottavasti kärsinyt. Mutta
omaantuntoon nousi tuontuostakin epäilyksiä, joista hän hiljakseen
riutui varjon näköiseksi.
V.

JÖNKÖPINGIN LINNASSA.

Kun Fabbe nyt oli niin likellä linnaa, ei hän tahtonut mennä siitä
sivutse hyvästi jättämättä sikäläisiä tuttaviaan. Hataraa laskusiltaa
myöten, joka ratisi ja ritisi saumoissaan kun se ohjesäännön
mukaisesti iltasin nostettiin ja aamusin laskettiin, pääsi kuivuneen
vallihaudan yli, johon linnansotilaat olivat kaalitarhoja istuttaneet.
Vallin halki aukeni kahden ruostuneen vallipyssyn alitse holvi
päättyen porttiin. Fabbe soitti: halkioin portinkello kilistä rämähteli
surkeasti, vastahakoinen lukko naukui nuivasti avainta
väännettäissä, ja Fabbe tervehti linnan vahtimestaria sekä
nelimiehistä linnanväkeä, joka täysilukuisena oli pihalla tornin
edustalla. Vahtimestari oli kuudenkymmenen ikäinen, pitkä, varteva
mies, vielä voimissaan. Yksi noista neljästä käveli vartioiden vankilan
edustalla; hän oli valkopartainen ja näytti käyvän seitsemättä
vuosikymmentänsä. Yksi ainoa oli nuori, se joka vahtimestarin
kanssa vuorotellen ratsasti lennättämässä tietoja esivallalle.

— Kevät on käsissä, virkkoi vahtimestari; eilen ennen sitä


varmaan tiennyt, tiedän sen ainakin nyt, koska Fabbe ilmestyy
matkatamineissa. Minnekäpäin aijot tällä kertaa lähteä?
— En tiedä.

— Etkö tiedä?

— En. Vapaa sälli ei suunnittele retkiänsä niin säntilleen eikä välitä


minne sitä mennään, kun vain matka sujuu. Siinä se matkan
hauskuus onkin. Olenpa sentään tuuminut kulkea Östbon
kihlakunnan kautta.

— Varusta sitte mukaasi hyvät aseet, muuten sinut vie rosvo-


Oden. Kaksi kuukautta takaperin hirtti hän herra Ture Jönsinpojan
voudin siellä.

— Hirsipuu on voudinkiikku. Minä en ole vouti.

— Hirttää hän muitakin ihmisiä. Mitäs sanoisit tästä aseesta,


raahaisitko ehkä sen mukaasi? Vahtimestari näytti kaksinkäsin
pidettävää miekkaa, joka seisoi vahtihuoneen eteisen nurkassa,
semmoista jota jalkasoturit siihen aikaan käyttivät ja jota kannettiin
pitkin selkää ripustettuna. — Katsoppas Fabbe, kuinka sinun tulee
tätä pidellä, jos rosvo-Odenin tielle joudut. Vai ehkä osaatkin?

— En.

— Kumma, että aseiden takojat eivät itse osaa aseita käytettä.

— Ei sen kummempaa, kuin että se, joka veistää sirostelee


saarnastuolin, ei silti osaa saarnata. Löytyypä sentään seppiä
sellaisiakin, jotka käyttelevät aseita siinä kuin mikä soturi ikään. Eipä
kukaan siinä kohden luullakseni voita meidän vanhinta sälliä Adam
Klasea, mainitakseni ainoastaan hänet.
— Sitten hän tietää neuvoa sinua, että sinun pitää nojata
miekanpontta tällä tapaa vyötä vastaan, kietoa toinen kätesi kahvan
ympäri ja toisella pitää säilän nahotettua osaa. Siten voit sekä pistää
että iskeä miekalla. Se on aimo ase. Mutta sanopas minulle, Fabbe,
miksi muutamat asesepät tekevät panssarin oluksiin suorat laikat ja
laittavat näihin sisäpuolelle kapean syrjän? Sinä et sitä tiedä, mutta
minä tiedän. Semmoiset sepät soisivat kaikki vapaasukuiset
menemään hornan kitaan. Jos jalkasoturi näet saa pertuskansa
kiinni isketyksi tämmöiseen oluslaikkaan, kiskaisee hän ratsumiehen
nurinniskoin mäkeen. Mutta seisonhan tässä jaaritellen enkä ajattele
että meidän on juotava läksiäismalja Fabben kanssa. Alas kellariin!
Lasketaanpas vähän tapintakaista haarikkaan!

— Montakos tääll' on pahantekijää vartioitavana? kysyi Fabbe.

— Tätä nykyä ei yhtään. Mutta vartioidaan vaan järjestyksen


vuoksi. Kaikki mikä roiston nimellistä on, karkaa Slatten luo, kuten
rosvo-Odenin nimi oikeastaan on, ja siellä he ovat hyvässä turvassa,
kunnes Gösta kuningas näkee hyväksi asiaan ryhtyä, sillä Ture
Jönsinpoika ei uskalla häntä hätyyttää.

Alhaalla kellarissa maisteltiin olvikultaa ilomielin. Fabbe laulaa


loilotti ruotsalaisia, tanskalaisia ja saksalaisia juomalauluja.
Linnanvahtimestari lauloi hartaasti Engelbrektin laulua.

— Olen säästänyt erään uutisen viimeiseksi, sanoi Fabbe,


juotuaan niin paljo kuin uskalsi, sillä juopuneena hän ei uskaltanut
ilmaantua Talavidiin. Tiedättehän, että Slatte joku viikko takaperin
sieppasi asekuorman, jonka Gudmund mestari oli Kalmariin
lähettänyt. Se tapahtui, kuten olette kuulleet, Stigamon tienoilla.
Mutta ette vielä tiedä, mitä eilen iltahämärässä tapahtui, vaikka koko
kaupunki sen tietää suuruspäivissä. Kuormarattaat näet tulivat ajaen
rantatietä meidän pihakujaan, jossa kolme miestä purki ne tyhjäksi.
Yksi heistä jättää portilla kirjeen, osotetun Gudmund mestarille. Mitä
luulette kirjeessä sanotun? Sain omin silmin lukea sen. Se oli Slatten
kirjottama. Hän kiitti vaihtokaupasta ja toivoi että sitä pidettäisiin
edullisena molemmin puolin. Senkin rakkari! Ryöstöä kruununtiellä
hän sanoo vaihtokaupaksi.

— Edullinen vaihtokauppa, jossa toinen antaa selkään ja


selkäänsä saanut antaa tavaroita, vahtimestari virkkoi.

— Slatte tarkotti sitä tavaraa, jota oli pihakujalle purettu: villoja,


kankaita, nahkoja, turkiksia, talia, hunajaa. Gudmund mestari seisoi
ällistyneenä nähdessään korvauksen eikä tiennyt pitikö hänen ne
pitämän vai järveenkö heittämän. Mutta Margareeta rouva ja nuori
herra Lauri, ylioppilas, katselivat tavaroita mielihyvällä ja korjasivat
ne talteen. Niin minäkin olisin tehnyt. Mestari on muutamissa
seikoissa kummallinen. Alkaapa taaskin sataa. Tänään sadetta,
huomenna poutaa, vaeltaja aina iloisella tuulella. Kiitos ja hyvästi!
VI.

TALAVIDIN MAJATALOSSA.

Fabbe astua hitusteli sateen vihmoessa "Länsi-ahteita" ylöspäin,


seisahtui hiukan aikaa Talavidin veräjällä ja näytti hajamieliseltä. Ei
hän ollut kahden vaiheella siitä, pitikö käydä talossa vai olla
käymättä. Kolmenkolmatta vuoden aikana ei hän kertaakaan ollut
Talavidin sivutse kulkenut sisällä poikkeamatta; tavallisesti jäi hän
ensi matkapäivän jälkeen sinne yöksi lähteäkseen aamuselta
varhain kululle.

Majatalossa oli matala selkähirsitupa, eli väentupa jossa


arkiaskareita toimitettiin, sekä molemmin puolin tätä tilavat yliset
solineen, toiset emäntää ja talonväkeä varten, toiset parempia
matkustajia varten, jotka tahtoivat jäädä yöksi tai kauvemminkin
viipyä.

Fabben astuessa kynnyksen yli tupaan, seisoi Birgit ja piika takan


ääressä. Hän tervehti, päästi repun soljesta, kirvotti kaulastaan
teräslangan monine lukkoineen ja istui penkin ja pöydän väliin oven
suuhun astiahyllyn alle, jolla kirkkaita tinakaluja kiillotti saviastiat
välissä. Tupa näytti ulkoa tullessa hämärältä; semminkin sadesäällä
pääsi päivänvaloa katto-ikkunan härännahkaruuduista varsin niukalti
sisään eikä sisäikkunakaan tuvan perällä ylärahin puolella paljoa
parantanut valaisua. Eipä Fabbe aluksi selvästi erottanut mitään
tuonnempana sitä suurta kattopalkkia, joka oli huoneen huonomman
ja paremman puolen välirajana. Hän tuijottikin vain Birgitiin mitään
muuta havaitsematta, eikä huomannut Svante tohtoria, joka istui
seinäikkunan ääressä kirjotellen vihkoonsa, eikä myöskään pikku
Gunnaria, joka lautapelinappuloista rakenteli lattialle tornia ja nyt
suurin, tutkivin silmin katseli miestä, puolittain tunnustellen häntä
ennen näkemäkseen.

Fabben "hyvään päivään" vastasi Birgit virkkamalla: Vai niin,


oletko täällä taas.

— Anna minulle aamiaista, hyvä Pirjetta!

Aamiainen tuotiin kenenkään mitään puhumatta. Ruokaa pöytään


sääliessään katsoi Birgit sälliä tiukasti silmiin ja sanoi matalalla
äänellä: ennen tulit kumminkin selvänä tänne. Viime vuonna olit
päihtynyt. Niin olet nytkin. Ensi vuonna tulet kai juopuneena.
Alasmäkeä menet, Heikki parka!

— Niin menen, Jumala paratkoon! Pirjetta, annas mulle kipponen


oltta!

— En tippaakaan! Häpeä vähä! Birgit käänsi hänelle selkänsä.


Fabbe näytti olevan pahoillaan, mutta söi hyvällä halulla.

Tuvassa oltiin taaskin ääneti. Kuului ainoastaan astiain ja


pöytäkalujen hiljaista kalinaa sekä sateen ropinaa katolta. Fabben
silmät tottuivat vähitellen puolihämyyn.
— No, katsopas, onhan täällä pikku Gunnar! Ja Svante tohtori!

— Päivää, Heikki, sanoi tohtori. Olet lähdössä kesäretkellesi.

— Niin kyllä. Olen oikeastaan maankulkijaksi luotu. Taitaapa


tohtorikin joinkin määrin olla sitä. Kai kohta käytte Gudmund
mestaria katsomassa? Siellä voivat kaikki hyvin ja kaikki on
entisellään, paitsi että kumppanini ovat uskonasioissa alkaneet eri
köyttä vetää. Yksi on hyvä catholicus ja hänellä on joukkonsa; toinen
on luthericus ja johtaa joukkoansa; kolmannen epäillään olevan
anabaptisticus. Neljäs on Fabbicus mies joukoton ja se olen minä.
Lauri paisuu ja venyy oikein aika mieheksi. Hän on jo isänsä
mittainen, mutta hartevampi, ääneltään ja olennoltaan kahta
rohkeampi. Hän kuuluu kohta matkustavan Wittenbergiin. Pikku
Gunnar — Jumala siunatkoon sinua, pieni keruubi ja seraafi —
näyttää myöskin kasvavan.

Hetken aikaa ollaan ääneti, jolla välin Fabbe urkkii ympärilleen.

— Anteeksi, herra tohtori, mutta missä villakoira on?

— Mikä villakoira? Ei minulla koskaan ole villakoiraa ollut.

— Onhan herra tohtorin villakoira musta väriltään?

— Se olematonko villakoira?

— Niin, ja onhan sillä punaiset silmärenkaat, jotka kiiluvat


pimeässä?

— Häpee, Heikki! nuhteli Birgit.


Svante tohtorin mielestä ei kannattanut vastata, hän kysyi: Onko
Fabbe teidän sukunimenne, Henrik?

— Ei. Nimeni on kirkon kirjoissa Henrik Seffrensen Aarhus'ista.


Olen syntyäni tanskalainen, Jumal' avittakoon. Isäni oli maankulkija,
eikä omena kauas puusta pyörähdä. Yhdentoista vuotiaana — silloin
olin "den lille Dreng" (sievä poika vilkkuri), jos tahdotte uskoa —
jouduin Jönköpingiin ja pääsin sepänoppiin Gudmund mestarin
isävainajalle, sittekun hän oli varma tiedossaan että olin oikein
avioliitossa syntynyt. Jumala siunatkoon sen miehen muistoa,
siunatkoon hänen poikaansa ja poikansatytärtä Margitia! Jumala
siunatkoon samoin — olkoon menneeksi minun puolestani, jos Hän
sen suo — Margareeta rouvaa ja Lauri herraakin kaupanpäälliseksi!
Olenpa nyt, kuten tohtori tietää, korkean arvoluokan saavuttanut
taidetakoja. Sen puolesta on minua kyllä onnestanut. Jönköpingin
entinen kirkkoherra mainitsi minua nimellä Faber vagus, joka, kuten
tiedätte, merkitsee semmoista seppää, joka on maankulkija,
maantienpolkija, seppä huijari. Lauri, joka silloin oli pieni, kuuli tuon
ja antoi minulle nimen Fabbe Vagge. Kaikki Gudmundin
perheenjäsenet nimittivät minua sitte Fabbe Vaggeksi. Nyt on Vagge
jäänyt unohduksiin, mutta Fabben tuntee koko Jönköping. Se on
minun nimeni nykyään. Saman niminen on poikanikin, jota en ole
nähnyt enkä päässyt kurittamaan, sentähden etten eräänä aamuna
kahdeksantoista vuotta sitte tullut käyttäneeksi ainoaa tilaisuutta
kosia hänen kaunista, kunniallista, kunnollista äitiänsä, joka siitä
syystä ei synnyttänyt häntä maailmaan.

Fabbe söi suurustansa edelleen. Tuokion perästä hän kysyi:

— Suokaa anteeksi, herra tohtori, mutta tulittehan tohtoriksi


samalla kertaa kuin tohtori Faust?
— En minä ole tohtori Faustia koskaan nähnyt.

— Rostockissako vai Wittenbergissä vai Leipzigissäkö te yhdessä


lueskelitte ja opiskelitte? Eikös se ollut ikävä että perkele hänen vei?
Vai ehkei perkele häntä vienytkään? Tähän aikaan valehdellaan niin
paljon. Mutta tämä — Fabbe veti väskystään esiin lentokirjaset —
tämä on kaiketi epäilemätöntä totta?

Fabbe astui Svante tohtorin luo, kumarsi ja pani plakaatit pöydälle


hänen eteensä.

Svante, vilkaistuaan veisuun kalasta, jonka oli kuultu kiljuvan


Rhein-virrassa, tunsi heti kirjasimista että se oli kotoisin piispa
Hannu Braskin Nyköpingiin perustamasta kirjapainosta. Arkkiveisu
toisesta kalasta, paavikalasta, oli painettu Lybeckissä. Samoin eräs
lentolehti nimeltä Trias romana eli roomalainen kolminaisuus, joka
pursui parjauksia paavilaiskirkkoa vastaan. Neljännen lentokirjasen
nimenä oli: myöntävä vastaus kysymykseen, onko Martinus Luther
perkeleen sikiöksi sanottava.

— Heikki, miksi levität sinä valheita? Onko se sinusta hauskaa?


kysyi
Svante. Vai luuletko että noita kaloja on nähty?

Niitä on niin monta kummallista kalaa, sanoi Fabbe, ja ehkä niitä


on tutkittu olvikippojen ja viinilasien lävitse. Enkä minä uskalla
vannoa, ovatko ne valaskaloja vai valekaloja. Onpa oppineitakin
miehiä, jotka niitä uskovat.

Pihalta kuului hevosjalkain kapsetta, ja sisään astui nuori


pormestarinpoika, Jönköpingin Alkibiades, herra Arvi Niilonpoika,
vaakunallinen mies. Sadeviitan riisuttuaan, seisoi hän siinä
punainen, kultaneuloksilla kirjailtu mekko yllään sekä muutenkin
hienosti puettuna, hienommin kuin mitä isoiset muuten matkoillaan
katsovat sopivaksi. Hän tervehti jäykänlaisesti Svante tohtoria ja
istahti hänen pöytänsä ääreen. Korottaen ääntänsä, niin että
Fabbekin sen kuuli, ilmotti hän olevansa matkalla herra Ture
Jönsinpoika Roosin luokse, saatuaan häneltä kutsun vieraspitoihin,
joita hän toimitti muutamille yläpapeille ja aatelisille
Länsigöötanmaalla ja Smoolannissa. Olipa hänen isäänsäkin pitoihin
pyydetty, mutta asianhaaroilta tämä ei päässyt tulemaan. Sitä
tärkeämpi siis, että hän, Arvi, sinne saapuisi.

Fabbe, joka oli palannut paikalleen rahille oven suuhun, lausui nyt
onnentoivotuksia sen johdosta että Arvi herra niin nuorella ijällä oli
päässyt niin ylhäisten seurusteluun. Fabbe lisäsi arvelunsa, että Arvi
herrasta kai piakkoin tulee valtakunnan neuvos. Eipä hän olisi
ensimmäinen suvustaan, joka niin korkealle nousisi. Pietari
Maununpoika, joka on Gudmund mestarin orpana, on saman
kunnian asteelle kiivennyt.

Arvi herra kääntyi puhuttelemaan Fabbea ja sanoi: Hyvää päivää!


Sinäkin matkalla. Sinua ajanee kiire, kun et kerjennyt odottaa että
minä puhuttelisin sinua, vaan riensit ensin puhumaan minulle.

Fabbe lupasi toiste muistaa, kuinka komea herra Arvi on, eikä
ennen aikojaan rientää puhumaan. Pitäisikö hänen myös odottaa
sopivaa aikaa laulaakseen? Ja kun Arvi herra ei suvainnut vastata
tähän kysymykseen, alkoi Fabbe lasketella jonkun tuntemattoman
tekemää laulua, joka hiljan oli levinnyt kartanolaisten keskelle ja
sieltä siirtynyt syvemmälle kansaan:

Jalo ruusu[1] on Turemme uskollisuus, johon paavi ja kirkko


voi luottaa, ja Braski ja maamme ja myös kuninkuus, jolle
Gösta nyt loistoa tuottaa. Ja ruusuista vaan ihaillen puhutaan.
Pelinoppa se pöydällä pyörii; Ture tuultako pelkäisi
linnassaan? Tuuli viirtä vaan heitellen hyörii.

Jalo ruusu on Turenime uskollisuus, sulo-ruusu on


herramme Ture: Kristianille, Göstalle sen ihanuus oli tuttu,
sen sai tuta Sture. Ja ruusuista vaan ihaillen puhutaan, niit' ei
kose tuuli kun vyörii. Ture tuultako pelkäisi linnassaan? Tuuli
viirtä vaan heitellen hyörii.

[1] Viittaus Ture Jönson Roos nimeen.

Arvi herra ei ollut laulua kuulevinaan, vaan jutteli tohtorin kanssa


sill'aikaa kuin sälli lauloi. Sen jälkeen hän kääntyi tämän puoleen ja
pyysi häntä katsomaan hevostensa kenkäin laitaa, koska hänen
satulahevosensa näytti vähän arastelevan jalkaansa. He menivät
katoksen alle, jonne herran kolme hevosta oli suojaan viety ja
ratsurenki nosti toista hevosenjalkaa toisensa perään, mutta Fabbe
ei havainnut mitään moitittavaa kengityksessä. Sen jälkeen Arvi otti
Fabben vähän syrjemmälle.

— Fabbe, virkkoi Arvi, minua ei miellyttänyt laulu, jonka lauloit


herra
Ture Jönsinpojasta.

— Olisi se kai saattanut parempikin olla.

— Se oli pilkkalaulu.

— Ja minä kun luulin, että siinä kiitettiin Ture herraa!

— Fabbe, sinä olet senkin elävä, mutta sinä et ole tyhmä.


— Minä olen tyhmä elävä.

— Asia on se, että minun puolestani muuten halusti saisit laulaa


Ture herrasta mitä mielit, mutta koska minua on kutsuttu
vierailemaan hänen kotiinsa, menettelisin mielestäni katalasti häntä
kohtaan, jos hyväksyen tai väliäpitämättä kuulisin häijyillä sanoilla
solvaistavan miestä, joka kohtelee minua ystävällisesti ja ojentaa
minulle kätensä.

Fabben kasvot ilmaisivat hyväksymistä. Hän katsoi nuorukaiseen


ja lausui: nytpä vasta tunnenkin Arvi herran!

— Mitä tarkotat?

— Nyt olitte sen pojan näköinen, joka tapasi juosta pajoissa


meidän luonamme ja ottaa selkoa kaikesta siellä, ja josta me sällit
kaikki niin paljo pidimme — tarkotan sitä poikaa, jota Lauri tietysti
tahtoi pitää kannuskurissa, hän kun oli väkevämpi ja ainakin tahtoo
kaikkia hallita, niinpä nyt jo isäänsäkin, mutta Arvi ei suostunutkaan
rupeamaan tuolle koiraksi, vaan huitoi uljaasti hoikilla käsivarsillaan
toista vastaan, joka oli käsivartensa ja nyrkkinsä moukarilta perinyt.
Niin, Arvi on istunut monet tuntikaudet Gudmund mestarin
maalarimajassa ja huvikseen katsellut hänen maalauksiaan, jutellut
hänen kanssaan niitä näitä ja piirustellut koreita taloja, kartanoita ja
sotalinnoja mestarin ohjausten mukaan. Lauri kävi harvoin
maalarimajassa ja hänen käytyänsä oli Gudmund mestari melkein
aina pahoillaan. Sen Arvi tietää paremmin kuin minä. Margit ja Arvi
ovat olleet ikäänkuin mestarin lohdutuksena. Kun äsken
väentuvassa tunkeilin päällenne, Arvi herra, loruillani, oli olven höyry
noussut päähäni — sitä on siellä vieläkin — ja unohdin, kuinka pikaa
poika pahasesta tulee nuorukainen. Yhtenä päivänä saattaa tuota
"nulikaksi" nimitellä ja toisena päivänä saa seistä hattu kädessä
"herraa" kumarrellen. Se ei ole hyvä.

— Miks'ei se ole hyvä?

— Tarkotan sitä, että Herramme ei ole mielestäni oikein sopivasti


säätänyt noin nopeaa siirtoaskelta. Tämän sanon tietysti
tyhmyydessäni, sillä Herran viisauden perille emme pääse; me
olemme pöllöpäitä. Minä sanon vain, että kahdentoistavuotias poika
nulikka kaikessa kokemattomuudessaan ja tuhman uljuudessaan
toisinaan on viisaampi kuin kahdeksantoistavuotias nuorukainen.
Ainakin edellinen harvoin on hupsu, mutta jälkimmäinen on useinkin.
Ja hupsu on hupsu, niinpä niinkin, vaikka hän, kuten Arvi herra,
pitäisikin yllään kullalla kirjattua punaröijyä.

— Nepä olivat kovat sanat.

— Mutta ne eivät olleet haukkumasanoja. Niissä oli ajateltavaa.

— Arvia ei ollenkaan haluttanut kääntää sällin sanoja pilaksi.


Hänestä tuntui seppä osanneen ihan naulan päähän. Hän oli usein
sanonut itselleen: sinusta on tullut narri, mutta ehkä asia korjautuu
aikaa myöten.

Eipä Arvi kuitenkaan nyt tahtonut tästä puhua.

— Minnekäs tällä kertaa aijot kulkusi ohjata, Fabbe?

— En tiedä.

— Isälleni, joka toissapäivänä tapasi sinut kadulla, sanoit aikovasi


kulkea Östbon kihlakunnan kautta.
— Ei, isänne neuvoi minua sitä suuntaa sukimaan. Mutta minuapa
ei haluta kulkea pormestarien ohjeiden mukaan. Minä mielin kulkea
omia oikkujani noudatellen.

— Mutta jos nyt niin kävisi ja sinä joutuisit Slatten tielle, sanon
sulle: älä ole arka!

— En minä ole juuri luonnostani pelkuri, vaikka kerran pelkäsinkin


tänään. Se oli silloin, kun seisoin tässä veräjän kohdalla ja tunsin
juoneeni oltta liiaksi linnanvahtimestarin tykönä. Pelkäsin, että Birgit
kohtelisi minua tullessani ynseästi, ja niin hän tekikin.

— Sanonpa sinulle että Slatte on parempi kuin miksi häntä


mainitaan.

— Minulla on syytä niin uskoa.

— Herra Ture Jönsinpojan täytyy tietysti moittia häntä voutinsa


hirttämisestä, jopa, jos niiksi joutuu, rangaistakin häntä siitä. Mutta
Ture on isälleni sanonut, että, ellei Slatte olisi sitä voutia hirttänyt,
hän itse olisi sen tehnyt.

Fabbe irvisti suutansa epäilevästi.

— Herra Ture sanoo paraaksi, mitä voitaisiin tehdä järjestyksen


palauttamiseksi, että luvattaisiin Slattelle turvallisuutta; hän saisi
lempeän tuomion ja pantaisiin Gösta kuninkaan maaherraksi
levottomimpaan osaan Smoolantia. Jos nyt sattuisit joutumaan
Slatten pariin, niin voit kertoa tämän hänelle. Saat senkin sanoa, että
isäni soisi hänen parastaan ja tahtoisi häntä tavata.

— Täytynee kai sitte lähteäni astumaan Slatten pesäpaikoille tätä


sanaa hänelle viemään. Haiskahtaahan se seikkailulle, enkä minä
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like