Getting Started With Artificial Intelligence
Getting Started With Artificial Intelligence
Artificial Intelligence
A Practical Guide to Building
Enterprise Applications
Tom Markiewicz
& Josh Zheng
Getting Started with Artificial
Intelligence
A Practical Guide to Building
Enterprise Applications
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Getting Started with Artificial
Intelligence, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the authors have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the authors disclaim all responsi‐
bility for errors or omissions, including without limitation responsibility for damages resulting from
the use of or reliance on this work. Use of the information and instructions contained in this work is
at your own risk. If any code samples or other technology this work contains or describes is subject
to open source licenses or the intellectual property rights of others, it is your responsibility to ensure
that your use thereof complies with such licenses and/or rights.
This work is part of a collaboration between O’Reilly and IBM. See our statement of editorial inde‐
pendence.
978-1-492-02779-9
[LSI]
Table of Contents
3. Chatbots. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
What Is a Chatbot? 19
The Rise of Chatbots 20
How to Build a Chatbot 21
Challenges of Building a Successful Chatbot 28
Best Practices 28
Industry Case Studies 34
Summary 35
4. Computer Vision. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Capabilities of Computer Vision for the Enterprise 38
How to Use Computer Vision 41
Computer Vision on Mobile Devices 42
Best Practices 43
iii
Use Cases 45
Existing Challenges in Computer Vision 47
Implementing a Computer Vision Solution 48
Summary 48
5. AI Data Pipeline. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Preparing for a Data Pipeline 51
Sourcing Big Data 51
Storage: Apache Hadoop 52
Hadoop as a Data Lake 52
Discovery: Apache Spark 53
Summary 54
6. Looking Forward. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
What Makes Enterprises Unique? 56
Current Challenges, Trends, and Opportunities 57
Scalability 60
Social Implications 60
Summary 61
iv | Table of Contents
CHAPTER 1
Introduction to Artificial Intelligence
Beyond the buzzwords, media coverage, and hype, artificial intelligence techni‐
ques are becoming a fundamental component of business growth across a wide
range of industries. And while the various terms (algorithms, transfer learning,
deep learning, neural networks, NLP, etc.) associated with AI are thrown around
in meetings and product planning sessions, it’s easy to be skeptical of the poten‐
tial impact of these technologies.
Today’s media represents AI in many ways, both good and bad—from the fear of
machines taking over all human jobs and portrayals of evil AIs via Hollywood to
the much-lauded potential of curing cancer and making our lives easier. Of
course, the truth is somewhere in between.
While there are obviously valid concerns about how the future of artificial intelli‐
gence will play out (and the social implications), the reality is that the technology
is currently used in companies across all industries.
AI is used everywhere—IoT (Internet of Things) and home devices, commercial
and industrial robots, autonomous vehicles, drones, digital assistants, and even
wearables. And that’s just the start. AI will drive future user experiences that are
immersive, continuous, ambient, and conversational. These conversational serv‐
ices (e.g., chatbots and virtual agents) are currently exploding, while AI will con‐
tinue to improve these contextual experiences.
Despite several stumbles over the past 60–70 years of effort on developing artifi‐
cial intelligence, the future is here. If your business is not incorporating at least
some AI, you’ll quickly find you’re at a competitive disadvantage in today’s rap‐
idly evolving market.
1
Just what are these enterprises doing with AI? How are they ensuring an AI
implementation is successful (and provides a positive return on investment)?
These are only a few of the questions we’ll address in this book. From natural
language understanding to computer vision, this book will provide you a high-
level introduction to the tools and techniques to better understand the AI land‐
scape in the enterprise and initial steps on how to get started with AI in your own
company.
It used to be that AI was quite expensive, and a luxury reserved for specific
industries. Now it’s accessible for everyone in every industry, including you. We’ll
cover the modern enterprise-level AI techniques available that allow you to both
create models efficiently and implement them into your environment. While not
meant as an in-depth technical guide, the book is intended as a starting point for
your journey into learning more and building applications that implement AI.
Avoiding an AI Winter
Modern AI as we know it started in earnest in the 1950s. While it’s not necessary
to understand the detailed history of AI, it is helpful to understand one particular
concept—the AI winter—as it shapes the current environment.
There were two primary eras of artificial intelligence research where high levels
of excitement and enthusiasm for the technology never lived up to expectations,
causing funding, interest, and continued development to dry up. The buildup of
hype followed by disappointment is the definition of an AI winter.
So why are we now seeing a resurgence in AI interest? What’s the difference
today that’s making AI so popular in the enterprise, and should we fear another
AI winter? The short answer is likely no—we expect to avoid another AI winter
this time around due primarily to much more (or big) data and the advent of bet‐
ter processing power and GPUs. From the tiny supercomputers we all carry in
our pockets to the ever-expanding role of IoT, we’re generating more data now, at
an ever-increasing rate. For example, IDC estimates that 180 zettabytes of data
will be created globally in 2025, up from less than 10 zettabytes in 2015.
Figure 1-1. Deep learning performance (image courtesy of Andrew Ng, Deeplearn‐
ing.ai course on Coursera)
Conceptually, this chart illustrates how the performance of deep learning algo‐
rithms improves with an increasing amount of data—data that we now have in
abundance and that is growing at an exponential rate.
So why does it matter whether we understand the AI winter? Well, if companies
are going to invest in AI, it’s essential to avoid the hyperbole of the past and keep
expectations based in reality. While the current situation is much more likely to
justify the enthusiasm, that excitement still needs to be tempered with real-world
results to avoid another AI winter. As (future) AI practitioners, that’s something
we can all agree would challenge your businesses.
Machine Learning
In 1959 Arthur L. Samuel, an IBM researcher and Stanford professor, is said to
have stated that “machine learning is the field of study that gives computers the
ability to learn without being explicitly programmed,” thereby becoming the
originator of the term.
Essentially, machine learning is a subset of AI focused on having computers pro‐
vide insights into problems without explicitly programming them to do so. Most
of the tools and techniques that today refer to AI are representative of machine
learning. There are three main types of machine learning—supervised learning,
unsupervised learning, and reinforcement learning.
By looking at many labeled data points and examples of historical problems,
supervised learning algorithms can help solve similar problems under new cir‐
cumstances. Supervised learning trains on large volumes of historical data and
then builds general rules to be applied to future problems. The better the training
set data, the better the output. In supervised learning, the system learns from
these human-labeled examples.
While supervised learning relies on labeled or structured data (think rows in a
database), unsupervised learning trains on unlabeled or unstructured data (the
text of a book). These algorithms explore the data and try to find structure. Here,
widely used unsupervised learning algorithms are cluster analysis and market
basket analysis. Naturally, this tends to be more difficult, as the data has no pre‐
existing labels to assist the algorithms in understanding the data. While more
challenging to process, as we’ll discuss later, unstructured data makes up the vast
majority of data that enterprises need to process today.
Finally, there’s reinforcement learning as a machine learning technique. Rein‐
forcement learning takes an approach similar to behavioral psychology. Instead
of training a model with predefined training sets (i.e., where you know the pre‐
Deep Learning
No book on developing AI applications in the enterprise would be complete
without a discussion of deep learning. One way to understand deep learning is to
think of it as a subset of AI that attempts to develop computer systems that learn
using neural networks like those in the human brain. While machine learning is
mostly about optimization, deep learning is more focused on creating algorithms
to simulate how the human brain’s neurons work.
Deep learning algorithms are composed of an interconnected web of nodes called
neurons and the edges that join them together. Neural nets receive inputs, per‐
form calculations, and then use this output to solve given problems.
One of the ultimate goals of AI is to have computers think and learn like human
beings. Using neural networks that are based on the human brain’s decision-
making process, deep learning is a set of computational techniques that move us
closest to that goal.
According to Stanford professor Chris Manning, around the year 2010 deep
learning techniques started to outperform other machine learning techni‐
ques. Shortly after that, in 2012, Geoffrey Hinton at the University of Toronto led
a team creating a neural network that learned to recognize images. Additionally,
that year Andrew Ng led a team at Google that created a system to recognize cats
in YouTube videos without explicitly training it on cats.
By building multiple layers of abstraction, deep learning technology can also
solve complex semantic problems. Traditional AI follows a linear programming
structure, thus limiting the ability for a computer to learn without human inter‐
vention. However, deep learning replaces this existing approach with self-
learning and self-teaching algorithms enabling more advanced interpretation of
data. For example, traditional AI could read a zip code and mailing address off of
an envelope, but deep learning could also infer from the envelope’s color and date
sent that the letter contains a holiday card.
Next Steps | 7
CHAPTER 2
Natural Language Processing
Humans have been creating the written word for thousands of years, and we’ve
become pretty good at reading and interpreting the content quickly. Intention,
tone, slang, and abbreviations—most native speakers of a language can process
this context in both written and spoken word quite well. But machines are
another story. As early as the 1950s computer scientists began attempts at using
software to process and analyze textual components, sentiment, parts of speech,
and the various entities that make up a body of text. Until relatively recently, pro‐
cessing and analyzing language has been quite a challenge.
Ever since IBM’s Watson won on the game show Jeopardy!, the promise of
machines being able to understand language has slowly edged closer. In today’s
world, where people live out their lives through social media, the opportunity to
gain insights from the millions of words of text being produced every day has led
to an arms race. New tools allow developers to easily create models that under‐
stand words used in the context of their industry. This leads to better business
decisions and has resulted in a high-stakes competition in many industries to be
the first to deliver.
Strikingly, 90% of the world’s data was created in the past two years, and 80% of
that data is unstructured. Insights valuable to the enterprise are hidden in this
data—which ranges from emails to customer support discussions to research
reports. This information is incredibly useful if it can be found, interpreted, and
utilized. When an enterprise can harness this massive amount of unstructured
data and transform it into something meaningful, there are endless possibilities
for improving business process, reducing costs, and enhancing products and
services.
Alternatively, those companies without the ability to handle their unstructured
data suffer lost revenue, missed business opportunities, and increased costs, all
likely without knowledge of it happening.
9
Interpreting this unstructured data is quite difficult. In fact, processing human-
generated (not machine) words (or natural language) is considered an AI-hard
or AI-complete problem. In other words, it’s a challenge that brings the full effort
of AI to bear on the problem and isn’t easily solved by a single algorithm
designed for a particular purpose.
In this chapter, we’ll give an overview of NLP, discuss some industry examples
and use cases, and look at some strategies for implementing NLP in enterprise
applications.
Overview of NLP
Natural language processing is essentially the ability to take a body of text and
extract meaning from it using a computer. While computational language is very
structured (think XML or JSON) and easily understood by a machine, written
words by humans are quite messy and unstructured—meaning when you write
about a house, friend, pet, or a phone in a paragraph, there’s no explicit reference
that labels each of them as such.
For example, take this simple sentence:
I drove my friend Mary to the park in my Tesla while listening to music on my
iPhone.
For a human reader, this is an easily understandable sentence and paints a clear
picture of what’s happening. But for a computer, not so much. For a machine, the
sentence would need to be broken down into its structured parts. Instead of an
entire sentence, the computer would need to see both the individual parts or enti‐
ties along with the relations between these entities.
Humans understand that Mary is a friend and that a Tesla is likely a car. Since we
have the context of bringing our friend along with us, we intuitively rule out that
we’re driving something else, like a bicycle. Additionally, after many years of pop‐
ularity and cultural references, we all know that an iPhone is a smartphone.
None of the above is understood by a computer without assistance. Now let’s take
a look at how that sentence could be written as structured data from the outset. If
developers had made time in advance to structure the data in our sentence, in
XML you’d see the following entities:
<friend>Mary</friend>
<car>Tesla</car>
<phone>iPhone</phone>
But obviously, this can’t happen on the fly without assistance. As mentioned pre‐
viously, we have significantly more unstructured data than structured. And
unless time is taken to apply the correct structure to the text in advance, we have
a massive problem that needs solving. This is where NLP enters the picture.
Entities
Likely the most common use case for natural language processing, entities are the
people, places, organizations, and things in your text. In our initial example sen‐
tence, we identified several entities in the text—friend, car, and phone.
Relations
How are entities related? Natural language processing can identify whether there
is a relationship between multiple entities and tell the type of relation between
them. For example, a “createdBy” relation might connect the entities “iPhone”
and “Apple.”
Concepts
One of the more magical aspects of NLP is extracting general concepts from the
body of text that may not explicitly appear in the corpus. This is a potent tool.
For example, analysis of an article about Tesla may return the concepts “electric
cars“ or “Elon Musk,” even if those terms are not explicitly mentioned in the text.
Keywords
NLP can identify the important and relevant keywords in your content. This
allows you to create a base of words from the corpus that are important to the
business value you’re trying to drive.
Semantic Roles
Semantic roles are the subjects, actions, and the objects they act upon in the text.
Take the sentence, “IBM bought a company.” In this sentence the subject is
“IBM,” the action is “bought,” and the object is “company.” NLP can parse senten‐
Categories
Categories describe what a piece of content is about at a high level. NLP can ana‐
lyze text and then place it into a hierarchical taxonomy, providing categories to
use in applications. Depending on the content, categories could be one or more
of sports, finance, travel, computing, and so on. Possible applications include
placing relevant ads alongside user-generated content on a website or displaying
all the articles talking about a particular subject.
Emotion
Whether you’re trying to understand the emotion conveyed by a post on social
media or analyze incoming customer support tickets, detecting emotions in text
is extremely valuable. Is the content conveying anger, disgust, fear, joy, or sad‐
ness? Emotion detection in NLP will assist in solving this problem.
Sentiment
Similarly, what is the general sentiment in the content? Is it positive, neutral, or
negative? NLP can provide a score as to the level of positive or negative sentiment
of the text. Again, this proves to be extremely valuable in the context of customer
support. This enables automatic understanding of sentiment related to your
product on a continual basis.
Now that we’ve covered what constitutes natural language processing, let’s look at
some examples to illustrate how NLP is currently being used across various
industries.
Customer Support
A recent study has shown that companies lose more than $62 billion annually
due to poor customer service, a 51% increase since 2013. Therefore, there’s obvi‐
ously a need for ways to improve customer support.
Companies are using natural language processing in a variety of ways in cus‐
tomer support. For each incoming support ticket, the content can be analyzed to
obtain its sentiment, relevant keywords, and a categorization. This process can be
used to route the support ticket faster to the correct representative and in some
cases to automatically respond to the request (this can then be extended with
chatbots, as we’ll see in the next chapter).
Natural language processing can also assist in making sure support representa‐
tives are both consistent as well as nonaggressive (or any other trait the company
is looking to minimize) in their language. When preparing a reply to a support
question, an application incorporated with NLP can provide a suggested vocabu‐
lary to assist this process.
These approaches to customer support can make the overall system much faster,
more efficient, and easier to maintain, and subsequently reduce costs over a tra‐
ditional ticketing system.
Business Intelligence
According to Gartner, the market for business intelligence (BI) software is
expected to reach $18.3 billion in 2017. Unfortunately, one of the common prob‐
lems associated with BI is the reliance on running complex queries to access the
mostly structured data. This presents two major problems. First, how does a
company access the bigger set of unstructured data, and second, how can this
data be queried on a more ad hoc basis without the need for developers to write
complex queries?
The inability to use unstructured data, both internal and external, for business
decision making is a critical problem. Natural language processing allows all
users, especially nontechnical experts, to ask questions of the data as opposed to
needing to write a complex query of the database. This allows the business users
to ask questions of the data without having to request developer resources to
make it happen. This democratizes BI within the enterprise and frees up crucial
Additional Topics
We have discussed just a few industry examples, but there are many more. For
example, natural language processing is used in brand management. Customers
are talking about brands every day across multiple channels. How does a com‐
pany both monitor what’s said about the brand as well as understand the content
and sentiment? Relatedly, market intelligence is another area often improved
through natural language processing.
There are also other examples that, while more specific to a particular domain or
industry, illustrate the power of natural language processing for improving busi‐
ness results. An example of this is the legal industry. NLP is being used by
numerous companies to review cases and other legal documents to alleviate the
need for expensive lawyers and paralegals to do so. Not only do legal professio‐
nals save time by not having to read every word personally, but the firms also
reduce error rates by having a machine quickly process many thousands of words
quickly as opposed to a human reader who can quickly tire. Interestingly, while
one may think this leads to a reduction in jobs (particularly for the relatively
Practical Tip
Now that you’ve read some examples of natural language processing used in the
enterprise, take a minute to think about your industry. First, in what areas have
you seen the approach applied in your field? Second, brainstorm some examples
of how NLP can be used in your company. Finally, start to think of what you may
need to implement these as solutions. We’ll discuss options as the book proceeds,
but challenge yourself to think of what’s required to improve your applications
with NLP.
• Apache NLP
• Stanford CoreNLP
• NLTK for Python
• SyntaxNet
While these are some of the more popular options, there’s a collection of open
source libraries for natural language processing in almost every programming
language. For example, if you use Ruby, you can find a collection of small libra‐
ries at http://rubynlp.org. The same goes for PHP: http://php-nlp-tools.com. At this
point, there’s typically no need to reinvent the wheel, or in this case the algo‐
rithm!
Nevertheless, while there are many options to implement natural language pro‐
cessing using open source as a starting point, from a cost-benefit perspective, it
can often make sense for enterprise applications to utilize one of the numerous
third-party services.
Currently, several companies provide APIs offered as software as a service. From
IBM Watson’s Natural Language Understanding to Azure Text Analytics to Ama‐
zon’s Lex, utilizing a hosted service API can reduce developer time and save these
vital resources for other aspects of the application development.
Practical Tip
When comparing NLP tools, take care to examine how the service is composed.
Most third-party providers like IBM Watson bundle together several algorithms
to create their product. Either plan to mix and match to meet your needs or care‐
fully examine what the specific natural language processing API offers to meet
your application’s needs.
Training Models
If you develop natural language processing from scratch in your enterprise, you’ll
be creating custom models by default. But when you’re using third-party solu‐
tions or open source options, the out-of-the-box solution will cover only the
majority of cases and it will be decidedly non-domain-specific. If you want to
improve the accuracy and reliability of your output, you’ll want to create and
train a custom model. This is especially true if you’re using a third-party service.
While there are a variety of ways to accomplish training a model, the details are
beyond the scope of this book, as they vary depending on the particular solution.
Using IBM Watson’s NLU service as an example, you can train a custom model
using the Watson Knowledge Studio (WKS). WKS is a web-based tool that ena‐
bles domain experts to train a custom natural language processing model without
the need for programming. Both developers and nontechnical end users can
upload relevant documents and then annotate them for their domain-specific
entities and relations. They can then use this data to train a custom model via
machine learning and publish it to the Watson NLU APIs for use in their applica‐
tions.
Practical Tip
Take a minute and visit your Twitter, Facebook, or LinkedIn feeds. Read through
the posts and imagine being able to programmatically read and understand every
piece of text almost instantaneously. What would you do with that insight? How
could you incorporate this new knowledge into your enterprise application?
Summary
Natural language processing is a powerful tool used in a wide range of enterprise
applications. Since text appears almost everywhere, NLP provides an essential
building block for all enterprise applications utilizing artificial intelligence.
In this vein, natural language processing also forms the backbone for creating
conversational applications, more commonly known as chatbots. In the next
chapter, we’ll discuss these in more detail.
Challenges of NLP | 17
CHAPTER 3
Chatbots
What Is a Chatbot?
So what exactly is a chatbot? A chatbot is a way to expose a business’s service or
data via a natural language interface. It’s important to understand that as an
interface, the chatbot is only as good as the underlying service or data. So if
19
you’re thinking about building a chatbot, first make sure your services and data
are solid. How do you know if your services and data are in good shape? Imagine
the service you’re providing has a traditional web or mobile interface. Would that
still be a useful service? If the answer is “no,” then your service is not ready for a
chatbot interface either.
If built well, chatbots can help your business cut costs and establish additional
revenue streams. A virtual customer support agent can reduce headcount and
exponentially scale your real-time customer support capabilities. A conversa‐
tional commerce chatbot gives your business a whole new channel to engage with
your customers via messaging platforms.
20 | Chapter 3: Chatbots
As more users spend time on messaging apps, companies are looking at ways to
reach users through these channels. It turns out there is a large amount of con‐
textual data buried in these messages. We make dinner plans, inquire about
stores, and look to purchase goods. Companies are now looking to help users by
embedding chatbots inside these message channels to answer questions or assist
with various tasks.
The Backend
Text classifiers
Let’s first discuss and expand upon one NLP technology in particular—text clas‐
sifiers. It was not until recently that text classifiers became easy to use and avail‐
able on the cloud. They’re an important part of chatbots. If you were to approach
building a customer support chatbot from scratch, the task probably seems over‐
whelming. After all, even in a narrow domain such as customer support, there
22 | Chapter 3: Chatbots
Intent. You usually start building a chatbot with intents. An intent is the purpose
of a user’s input. This can be a question about your business hours or a complaint
about the registration process. The response of your chatbot to this intent is
entirely up to you. It might be a paragraph that answers the question or an action
such as starting the password reset process. Another way to think about intents is
that they’re the verbs for your chatbots to act on. They dictate what your chatbots
will do next.
To train your chatbot to recognize an intent, first determine the action you’d like
to map to this intent—for example, provide information on business hours. Then
supply the framework with examples of user inputs that would require this
action. The business hours scenario would include example inputs such as the
following: “What time are you open?” “Are you open on weekends?” “I can’t find
your hours of operation.” Usually, a minimum of five inputs is needed, but more
is better. Remember, it might be tempting to make up these examples, but it is
always better to draw these from past data. The more similar these examples are
to real-world user requests, the better your chatbot will perform. With Watson
Conversation, an intent (really a text classifier) is built from these examples so
the service will recognize similar inputs in the future, even if they’re not exact
matches.
Let’s see this in action. The most common intent for a chatbot is to greet the user.
When a user first comes in contact with your chatbot, it needs to introduce itself.
This is an excellent opportunity to establish the context of the chatbot, state its
purpose, and set boundaries. Figure 3-1 shows an example of some common
greetings that a developer might deploy using Watson Conversation’s Intents tab.
Entities. If intents are the verbs for a chatbot to act on, then entities are the
nouns. They’re the keywords in a user’s input. If a particular word differentiates
one input from another, it probably should be an entity.
For example, if a user wants to find the business hours of a bank’s branch, the
location of the bank would be one of the entities. Specifically, if a user asks,
“What are the hours for the Austin branch?” provide business hours would be the
intent and Austin would be the entity.
Figure 3-2 shows an example of a cuisine entity in Watson Conversation’s Entities
tab.
24 | Chapter 3: Chatbots
Figure 3-2. An example of a cuisine entity, which encompasses a list of different cui‐
sines that you’d like your chatbot to recognize
The screenshot in Figure 3-3 shows an example of a dialog tree, starting with the
blue Greeting node at the top left. The screen on the right shows the detailed
view of this node when it’s selected. In this case, the condition that triggers this
node is the welcome condition, which the system understands to be the start of
the conversation. You can then dictate the response of the chatbot via
the “Respond with” section. Here, the chatbot introduces itself as the Watson
RecipeBot.
Context variable. A context variable contains the information shared between the
framework and your application. It’s the way to exchange information between
your business logic and the framework.
Watson Conversation provides a context object that lets you store any key/value
pair as context variables. In Figure 3-4, the context object stores all the variables
related to the user’s pizza order. The variables are updated as the user progresses
through the ordering process. If the chatbot recognizes the reset intent, it will set
all pizza parameters to null so the user can restart the order.
26 | Chapter 3: Chatbots
Figure 3-4. Arriving at the Reset node leads the chatbot to tell the user “Let’s start
over” and resets all context variables
Human in the loop. Embedding a human into your chatbot has two significant
benefits.
First, humans are an excellent way to bootstrap your chatbot before it gathers
enough data to operate autonomously. If the chatbot is not confident about its
response, it can ask the human for approvals or edits before sending it to the end
user. Another setup is to have the chatbot provide multiple responses, and have
the human choose the most appropriate one.
The second benefit is that humans are the best way to prevent your chatbot from
utterly failing your users. There are a few ways to detect if the conversation needs
to be routed to a human:
• The chatbot doesn’t understand the user’s input—this usually means the user
input doesn’t match any of your established intents.
• The conversation is taking too long, or a circular pattern is detected.
• Negative sentiment is caught in the user’s input.
• The user directly asks to talk to a real person.
Practical Tip
It takes at least six months to create a chatbot that’s useful, so make sure to give
yourself or your development team enough of a runway.
While the next section will discuss some best practices, there is not a one-size-
fits-all solution. Your best option is to put the chatbot in front of real customers
and iterate through user feedback. If you’re a product manager or developer, this
should sound familiar. Keep in mind that chatbots are a nascent field in the
enterprise, so you’ll be one of the first in your industry. Nothing but trial and
error will help you discover the problems and edge cases specific to your domain.
Best Practices
In this section, we’ll introduce some basic best practices for building chatbots.
Most of these focus on user experience because it is the most important aspect of
an enterprise chatbot, especially in ecommerce and customer support.
28 | Chapter 3: Chatbots
Tip #1: Introduce Your Chatbot to First-Time Users
When a user comes across your chatbot for the first time, they will not know how
to interact with it. In fact, this might be the first time this user has interacted with
any chatbot. At this point, the worst thing you can do is to present the user with a
blank screen.
One way to create a better user experience is to immediately introduce the user to
the chatbot’s capabilities and explain how to converse with it. A welcome message
(something short, simple, and motivating) is usually best followed by a helpful
paragraph describing the chatbot.
Best Practices | 29
Figure 3-5. The list of possible greetings to the user: one of these is selected at ran‐
dom
Of course, you don’t need response variation at every dialog node. It’s important
to have them in nodes that your users commonly visit, such as greeting and
thank you nodes. Informational nodes are typically visited only once per cus‐
tomer, so response variations are not as necessary.
30 | Chapter 3: Chatbots
help intent is like having an emergency eject button that gets your users to safety.
Better yet, the help menu should have an option to talk to a human support
agent. This is important because your users are most likely already a bit frustra‐
ted by the time they’re asking for help. The option to talk to a human reminds
them that they’re not alone, and their problem will be solved even if the chatbot
didn’t work as intended.
The start over intent is self-explanatory. Sometimes a user has gone down an
incorrect path and realizes it’s easier to start over. At this point, it’s useful to have
an intent that registers messages such as “I want to start over” or “Let’s restart this
conversation.” Including all these intents will save your users a lot of time and
frustration.
Practical Tip
Another way to acquire some context around your users is to integrate with a
customer relationship mangement (CRM) system or a third-party database. If
you’re on Facebook Messenger, you can pull information about your user from
their profile. Remember, starting a conversation with even some basic knowledge
of your user (name, occupation, location, etc.) can make your chatbot seem more
familiar and start the interaction off on the right foot.
Best Practices | 31
Let’s go with a pizza-ordering scenario. Figure 3-6 shows each slot containing one
piece of information we need from the user. The dialog won’t move on until we’ve
gathered all the required pieces.
If the user accidentally entered “small” for the size of the pizza, she can simply
say, “actually I meant large” to fix the mistake. This is because when we’re at this
node, Watson Conversation automatically checks all user inputs for the defined
entities such as size (small, medium, large) or toppings (pepperoni, mushroom,
cheese). And in this case when Watson Conversation sees the entity value
“large” in the phrase “actually I meant large,” it updates the slot with that value.
Unfortunately, this trick will not work if entering the pizza size fills all slots, and
the dialog moves on to the next node.
32 | Chapter 3: Chatbots
Tip #7: Be Careful About Creating a Personality
Creating a personality for your chatbot is tempting. After all, it can be a crucial
differentiator. An example of a fun personality is Facebook’s weather bot Poncho.
Poncho is quite sassy. Figure 3-7 shows an example of his banter while delivering
the weather.
Figure 3-7. Poncho providing more than just information about the weather
Poncho will even behave differently based on your politeness. If you’re rude to
him, he’ll ask you to apologize. If you continue to be aggressive, he won’t respond
for 24 hours.
As you can see, personality can add to the user experience, but it’s also chal‐
lenging to get right. If you’re not confident in your ability to create an engaging
personality, we recommend holding off on the attempt. Particularly in use
cases like customer support, being friendly is often enough. But if you do
decide to implement a personality, keep the voice consistent throughout the
application and make sure it doesn’t overshadow the primary task you’re trying
to accomplish.
Best Practices | 33
Industry Case Studies
Autodesk: Customer Support
Autodesk is known for its 3D design and engineering software. As the company
switched from a desktop licensing model to a SaaS model, its reach improved.
But with that surge came an increase in customer inquiries. Sometimes with
heavy volume and complex issues, the resolution time for questions was 1.5 days
or more.
Autodesk’s staff of about 350 customer support agents handles roughly one mil‐
lion customer and partner contacts per year. About half of these are simple acti‐
vation code requests, changes of address, contract problems, and technical issues.
Gregg Spratto, Vice President of Operations at Autodesk, said: “A lot of what my
team does is just problem recognition, trying to identify what the person wants
or is asking.”
This sounds like a problem for chatbots. Starting last year, Autodesk built a vir‐
tual agent called Autodesk Virtual Agent (AVA), designed to answer common
customer queries quickly. It was first trained from chat logs, use cases, and forum
posts. It analyzed more than 14 million sentences for keywords, entities, phrases,
clusters, and other speech and language patterns.
AVA is deployed as a web UI that calls Watson Conversation and Autodesk enter‐
prise systems. The web application also handles the authentication and some
business logic. But being an enterprise deployment means that even a simple
action like getting an activation code requires several services to be called in a
particular order with contingent flows and error handling. After helping Auto‐
desk overcome many of these deployment issues, IBM eventually gave complete
ownership over to Autodesk. The most recent numbers from Autodesk show:
• AVA has had 146,652 conversations, a 35% increase quarter over quarter
(QoQ).
• AVA has helped 45,514 customers total, a 54% increase QoQ.
• Resolution takes an average of 5.6 minutes, compared to the original 38
hours with human support agents.
• Autodesk estimates a support agent headcount savings of 12–15.
34 | Chapter 3: Chatbots
Staples built an intelligent Easy Button such that when a customer speaks to it,
the Watson Conversation service extracts the customer’s intent and entities. The
system currently understands five intents: product ordering, product reordering,
shipment tracking, checking on reward summaries, and processing back-to-
school lists from scanned images provided by customers. Entities are office prod‐
ucts contained in the company’s vast catalog, such as pens, toner, and paper, each
of which has its own stock keeping unit (SKU).
After Watson Conversation recognizes the intent and entity of a request such as
“I want to reorder black pens,” it calls the Staples personalization engine. This
engine combs through the customer’s purchasing history to identify the pen (an
excellent use of contextual information). Finally, if the system is confident it has
identified the correct SKU, it uses voice feedback to confirm the purchase with
the customer. If the system is not entirely confident about the user order, it sug‐
gests a variety of pens based on past orders. Staples also deploys human support
agents in the loop. If the chatbot cannot confidently return a customer’s request,
it forwards the request to a live agent who can help the customer.
Summary
Remember, it’s easy to get started with chatbots, but it takes patience and hard
work to create a truly successful one. Don’t try to develop general intelligence!
Define the correct scope for your chatbot and keep in mind that context is vital,
as the medium has much less bandwidth for communication. We’ll leave you
with this analogy from one of our colleagues. Building a chatbot is much like
training a new hire—they probably only know a little on their first day, but
through coaching and supervision they’ll eventually become a productive
employee. It’s essential for your users to see your chatbot as a human, but it’s
equally crucial for you to do the same. In the next chapter, we’ll switch gears and
talk about computer vision.
Summary | 35
CHAPTER 4
Computer Vision
Take a moment and look up from this book. Examine the room around you
and take a quick inventory of what you see. Perhaps a desk, some chairs, book‐
shelves, and maybe even your laptop. Identifying these items is an effortless
process for a human, even a young child.
Speaking of children, it’s quite easy to teach them the difference between multiple
objects. Over time, parents show them objects or pictures and then repeat the
name or description. Show them a picture of an apple, and then repeat the word
apple. In the kitchen, hand them an apple, and then repeat the word apple. Even‐
tually, through much repetition, the child learns what an apple is along with its
many color and shape variations—red, green, yellow. Over time, we provide
information as to what is a correct example and what isn’t. But how does this
translate to machines? How can we train computers to recognize patterns visu‐
ally, as the human brain does?
Training computer vision models is done in much the same way as teaching chil‐
dren about objects visually. Instead of a person being shown physical items and
having them identified, however, the computer vision algorithms are provided
many examples of images that have been tagged with their contents. In addition
to these positive examples, negative examples are also added to the training. For
example, if we’re training for images of cars, we may also include negative exam‐
ples of airplanes, trucks, and even boats.
Giving computers the ability to see opens up a world of possibilities for many
industries—from recognizing human faces for security to automating processes
that would take a human days, if not weeks. Let’s take one industry as a quick
example—insurance. Using computer vision to quickly, accurately, and objec‐
tively receive an automated analysis of images—for example, of a fender bender
or a weather-damaged roof—allows insurance companies to deliver better service
to their clients.
37
Machine learning is pattern recognition through learned examples. Nothing
exemplifies this more than computer vision. Just as NLP provides a core func‐
tionality of AI in the enterprise, computer vision extends a machine’s ability to
recognize and process images.
Object Localization
Another capability of computer vision is object localization. Sometimes your
application’s requirements will include not just classifying what is in the image,
but also understanding the position of the particular object in relation to every‐
thing else. This is where object localization comes into play. Localization finds a
Custom Classifiers
Most of the time, you don’t need to recognize everything. If you’re looking to
identify or classify only a small set of objects, custom classifiers could be the right
tool. Most of the large third-party platforms provide some mechanism for build‐
ing custom visual classifiers, allowing you to train the computer vision algo‐
rithms to recognize specific content within your images. Custom classifiers
extend general tagging to meet your application’s particular needs to recognize
your visual content, and primarily exist to gain higher accuracy by reducing the
search space of your visual classifier.
At a high level, when creating a custom classifier, you’ll need to have a collection
of images that are identified as positive and negative examples. For example, if
Most computer vision uses deep learning algorithms (discussed in Chapter 1),
specifically convolutional neural networks (CNNs). If you’re interested in build‐
ing CNNs from scratch and going more in depth with deep learning for com‐
puter vision, there are a wide variety of resources available. We recommend
Andrew Ng’s Deep Learning specialization on Coursera as well as fast.ai. Addi‐
tionally, the following resources dive deeper into relevant computer vision topics:
We’ll make a simple request using curl to the API as follows, referencing our
image as the image URL parameter:
curl "https://gateway-a.watsonplatform.net/visual-recognition/api/
v3/classify?api_key=YOURAPIKEY&url=
https://visual-recognition-demo.ng.bluemix.net/images/samples/7.jpg
&version=2016-05-20"
Submitting this API request returns the following JSON:
{
"classes": [
{
"class": "harbor",
"score": 0.903,
"type_hierarchy": "/shelter/harbor"
},
{
"class": "shelter",
Best Practices
Next, we’ll look at some best practices in developing applications with computer
vision. First, though, an overall rule of thumb is the more quality images for
training, the better. We’ll discuss what makes good training images shortly, but in
general, the more good images you can provide for training, the better the
results.
The accuracy of custom classifiers depends on the quality of your training data as
well as process. Data from IBM Watson has shown that clients “who closely con‐
trolled their training processes have observed greater than 98% accuracy for their
use cases.” This accuracy was based on the ground truth for their classification
problem and data set.
Best Practices | 43
Quality Training Images
Let’s now take a quick look at some guidelines for good training images. There
are several characteristics of good training images. The images in your training
and testing sets should ideally resemble each other in as many ways as possible.
For example, be sure they’re similar in regards to angle, lighting, distance, and
the size of the subject.
Also, make sure the training images represent what the test image will show. For
example, if your test images show baskets of apples, then a close-up of a single
apple would not be a good training image (Figures 4-4 and 4-5). Just because
there’s an apple in the image doesn’t mean it meets the criteria for good training
images.
Figure 4-4. A single apple on a table (photo courtesy of adrianbartel, Creative Com‐
mons License 2.0)
Use Cases
Now that we’ve discussed computer vision in some detail, let’s take a look at some
industry examples and use cases.
Satellite Imaging
When a drought in California reached crisis level in April 2015, Governor Jerry
Brown issued the state’s first mandatory water restrictions. All cities and towns
were instructed to reduce water usage by 25% in 10 months. Achieving this
required measures more effective than just asking residents to use less water.
Specifically, the state needed to run ad campaigns targeted to property owners
who were using more water than necessary. Unfortunately, the state didn’t even
have water consumption data on such a granular level.
Scientists at OmniEarth came up with the idea of analyzing aerial images to iden‐
tify these property owners. They first trained IBM Watson’s Visual Recognition
service on a set of aerial images containing individual homes with different topo‐
graphical features, including pools, grass, turf, shrubs, and gravel. They then fed a
massive amount of similar aerial imagery to Watson for classification. Partnering
with water districts, cities, and counties, the scientists at OmniEarth could then
quickly identify precisely which land parcels needed to reduce water consump‐
tion, and by how much. For examples, they identified swimming pools in 150,000
parcels in just 12 minutes.
Use Cases | 45
Armed with this knowledge, OmniEarth helped water districts make specific rec‐
ommendations to property owners and governments. Such recommendations
included replacing a patch or percentage of turf with mulch, rocks, or a more
drought-tolerant species, or draining and filling a swimming pool less frequently.
Summary
Computers “see” very differently than humans, and almost always within the
context of how they are trained. The computer vision topics covered in this chap‐
ter have hopefully inspired you to use vision as a powerful tool to increase the
utility of your enterprise applications. As we’ve discussed, numerous industries
are already taking advantage of computer vision with great success. How might
you incorporate computer vision in your applications?
Now that we’ve covered some of the major use cases of AI in the enterprise (NLP,
chatbots, and computer vision), let’s take a look at our data and how it gets pro‐
cessed in AI data pipelines.
There are now more mobile devices than people on the planet and each is collect‐
ing data every second on our habits, physical activity, locations traveled, and
daily preferences. Daily, we create 2.5 quintillion bytes of data from a wide vari‐
ety of sources. And it’s coming from everywhere. Just think of all the sources col‐
lecting data—IoT sensors in the home, social media posts, pictures, videos, all
our purchase transactions, as well as GPS location data monitoring our every
move.
Data is even touted as being more important and valuable than oil. For that rea‐
son, companies are creating vast repositories of raw data (typically called data
lakes) of both historical and real-time data. Being able to apply AI to this enor‐
mous quantity of data is a dream of many companies across industries. To do so,
you have to pick the right set of tools not only to store the data but also to access
the data as efficiently as possible. Current tools are evolving, and the way in
which you store and present your data must change accordingly. Failure to do so
will leave you and your data behind. To illustrate this point, MIT professor Erik
Brynjolfsson performed a study that found firms using data-driven decision
making are 5% more productive and profitable than competitors. Additional
research shows that organizations using analytics see a payback of $13.01 for
every dollar spent.
As we’ve seen so far, if large amounts of high-quality data are a prerequisite for a
successful implementation of AI in the enterprise, then a process for obtaining
and preparing the data is equally critical.
In previous chapters, we’ve covered some of the major applications of AI in the
enterprise, from NLP to chatbots to computer vision. We’ve also discussed the
49
importance of data to all of these implementations. What we’ve implied, yet
haven’t actually touched on to this point, is the concept of a data pipeline that
forms the backbone for all these AI implementations.
Whether you use off-the-shelf technology or build your own, these AI solutions
can’t be effective without a data pipeline. With the numerous third-party solu‐
tions in the market like IBM Watson, it’s easy to forget that with even the simplest
implementation, you need to have a data pipeline. For example, in a computer
vision solution you still need to find representative images, train them, and then
provide a mechanism for repeating this loop with new and better data as the
algorithm improves. With NLP, you still need to feed the APIs source text to pro‐
cess and then often train custom models with data from your domain. With chat‐
bots, your initial data pipeline would focus on the known questions and answers
from your existing customer support logs and then building a process to capture
new data to feed back into the chatbot. From SaaS all the way to developing your
own AI solutions, data pipeline needs grow even larger—and more critical to the
overall implementation of AI in our enterprise applications.
Not only is the data pipeline a crucial component of performing AI, but it also
applies elsewhere in the enterprise—specifically in analytics and business intelli‐
gence. While the intricacies of creating a full AI data pipeline are outside the
scope of this book, next we’ll provide a high-level guide for getting started.
So what exactly is a data pipeline for AI? Dataconomy defines a data pipeline as
“an ideal mix of software technologies that automate the management, analysis
and visualization of data from multiple sources, making it available for strategic
use.” Data preparation, a data platform, and discovery are all significant pieces of
an effective pipeline. Unfortunately, a data pipeline can be one of the most expen‐
sive parts of the enterprise AI solution.
Key to this process is making sure data can be accessed in an integrated manner
instead of sitting in different silos, both internal and external to the enterprise.
This ability to access and analyze real-time or at least recent data is key to an AI
data pipeline (Figure 5-1).
As we’ll discuss in the next few sections, outside of the actual data itself, the two
most popular components of an AI data pipeline are Apache Hadoop and Apache
Spark. In fact, an IBM study of organizations with more than 1,000 employees
from 90 countries showed that 57% of surveyed firms either already had or plan‐
ned to implement a pipeline based on Hadoop/Spark.
Spark itself doesn’t have a persistent data store and instead keeps data in memory
for processing. It’s important to reiterate that Spark isn’t a database, but instead
connects to external data sources, usually Hadoop’s HDFS, but also anything
commercial or open source that developers are already using and/or familiar
with, such as HBase, Cassandra, MapR, MongoDB, Hive, Google Cloud, and
Amazon S3. Selecting a database for your application is outside the scope of this
Summary
Big data is being captured everywhere and rapidly increasing. Where is your data
stored and what can you do now to future-proof for machine learning? While the
enterprise typically embraces the tried and true—and in this case, Hadoop and
Spark—there are other technologies that show great promise and are being
embraced in research as well as startup companies. Some of these open source
projects include TensorFlow, Caffe, Torch, Chainer, and Theano.
We’ve covered some of the basics of AI, discussed essential technologies like NLP
and chatbots, and now provided an overview of the AI data pipeline. Though
various tools and techniques have been discussed throughout, in the next chap‐
ter, we’ll wrap up the discussion of AI in the enterprise with a look at how to
move forward and really begin your AI journey.
Over the next decade, AI won’t replace managers, but managers who use AI will
replace those who don’t.
—Erik Brynjolfsson and Andrew McAfee, Harvard Business Review, 2017
55
unstructured data becomes a primary focus for developers of enterprise applica‐
tions using AI.
We’ll next discuss some aspects of enterprises that make them particularly unique
compared to other types of companies. Then we’ll examine some current chal‐
lenges, trends, and opportunities for bringing AI to the enterprise. We’ll wrap up
the chapter by exploring the topics of scalability and societal impact of AI on an
organization.
Data Confinement
Data is the competitive advantage for many companies and becomes a prized
asset for the enterprise. The challenge is how to balance where the data resides
while still enabling the use of a variety of AI techniques and approaches. For
example, if all of a company’s data resides on-premises, how can the company use
a SaaS service like the IBM Watson APIs for some of its machine learning needs?
Enterprise requirements concerning their data’s physical location is a challenge
that will bring about new models for data confinement. In addition to keeping
data on-premises, companies also have the options to keep the data in the cloud,
or use hybrid models to meet their unique needs. Innovative deployment models
are already being used by third-party enterprise AI vendors to meet their clients’
data needs. For example, IBM Watson offers its services in three different deploy‐
ment models: dedicated, hybrid, and the public cloud.
Little Data
Enterprises have smaller or less data compared to consumer applications. We’ve
talked a lot about big data in previous chapters, but the truth is that while big
data exists in the enterprise, it’s typically on a much smaller scale than consumer-
facing applications. In addition to less data, the information that does exist is fre‐
quently locked up, inaccessible, and unable to be shared for various reasons
(including IP and regulations). So the crucial issue here is how to obtain high
accuracy in the algorithms using much less data. The typical solution to working
efficiently with a small amount of data is a technique called transfer learning.
Transfer learning is an approach that can use much smaller amounts of data, as
opposed to deep learning, which needs lots of data. Transfer learning allows the
leveraging of existing labeled data from a different (though very related) domain
than the one in which we’re trying to solve the business problem. What’s interest‐
ing about this approach is that even as humans we learn from relatively small
amounts of data—we don’t learn from scratch, nor do we learn from large
amounts of data. We’re able to learn from the collection of experiences we’ve
gained somewhere else. Transfer learning is an approach that mimics this human
process, which parallels deep learning’s relationship to how the brain works.
In the enterprise, there are different workspaces or domain areas, so how do we
use what we’ve learned in one workspace to inform another in an efficient man‐
Social Implications
While not necessarily a technical aspect of building AI applications in the enter‐
prise, societal implications of AI are also important to discuss. Despite the stops
and starts over the years, as well as concerns about the impact of automation on
jobs and society, the potential of AI in the enterprise is only increasing—the ben‐
efits are too significant. For example, McKinsey Global Institute found that “45%
of work activities could potentially be automated by today’s technologies, and
80% of that is enabled by machine learning.”
Summary
Building enterprise AI applications is more about augmenting than replacing
human intelligence. In this chapter, we examined this topic as well what makes
enterprises unique, especially their data. We also discussed some of the challenges
in enterprise AI including data confinement, little and inaccessible data, and
social accountability. While each of these poses problems, they’re also opportuni‐
ties to make better applications and improve the enterprise development process.
We’ve covered a lot of ground in this book, but hopefully, we’ve provided you a
starting point to apply AI in your enterprise applications. The future is always
cloudy, but one thing is sure—AI is here to stay and will be necessary for your
enterprise applications to remain relevant today and into the future. Good luck
with your development efforts!
Summary | 61
About the Authors
Tom Markiewicz is a developer advocate for IBM Watson. He has a BS in aero‐
space engineering and an MBA. Before joining IBM, Tom was the founder of
multiple startups. His preferred programming languages are Ruby and Swift. In
his free time, Tom is an avid rock climber, trail runner, and skier.
Josh Zheng is a developer advocate for IBM Watson. Before joining IBM, he was
a full-stack developer at a political data mining company in DC. His favorite lan‐
guage is Python, followed by JavaScript. Since Josh has a background in robotics,
he still likes to dabble in hardware as well. Outside of work, he likes to build
robots and play soccer.