Java Data Science Cookbook
By Rushdi Shams
()
About this ebook
- This book provides modern recipes in small steps to help an apprentice cook become a master chef in data science
- Use these recipes to obtain, clean, analyze, and learn from your data
- Learn how to get your data science applications to production and enterprise environments effortlessly
This book is for Java developers who are familiar with the fundamentals of data science and want to improve their skills to become a pro.
Related to Java Data Science Cookbook
Related ebooks
Mastering Scala Machine Learning Rating: 0 out of 5 stars0 ratingsScala Programming for Big Data Analytics: Get Started With Big Data Analytics Using Apache Spark Rating: 0 out of 5 stars0 ratingsInstant Jsoup How-to Rating: 0 out of 5 stars0 ratingsSpring Boot Persistence Best Practices: Optimize Java Persistence Performance in Spring Boot Applications Rating: 0 out of 5 stars0 ratingsSpring Integration Essentials Rating: 3 out of 5 stars3/5Natural Language Processing with Java and LingPipe Cookbook Rating: 0 out of 5 stars0 ratingsScala Data Analysis Cookbook Rating: 0 out of 5 stars0 ratingsLucene 4 Cookbook Rating: 0 out of 5 stars0 ratingsLo-Dash Essentials Rating: 0 out of 5 stars0 ratingsMastering Java for Data Science Rating: 5 out of 5 stars5/5Java for Data Science Rating: 0 out of 5 stars0 ratingsDistributed Computing in Java 9 Rating: 0 out of 5 stars0 ratingsScala Test-Driven Development Rating: 0 out of 5 stars0 ratingsInstant MapReduce Patterns – Hadoop Essentials How-to Rating: 0 out of 5 stars0 ratingsJava 9 with JShell Rating: 0 out of 5 stars0 ratingsRESTful Java Web Services Security Rating: 0 out of 5 stars0 ratingsApache Mahout Clustering Designs Rating: 0 out of 5 stars0 ratingsLearning Modular Java Programming Rating: 0 out of 5 stars0 ratingsTalend Open Studio Cookbook Rating: 2 out of 5 stars2/5Getting Started with Hazelcast - Second Edition Rating: 0 out of 5 stars0 ratingsApache Hive Cookbook Rating: 0 out of 5 stars0 ratingsAWS Key Management Service and AWS CloudHSM Third Edition Rating: 0 out of 5 stars0 ratingsBuilding Python Real-Time Applications with Storm Rating: 0 out of 5 stars0 ratingsASP.NET 3.5 CMS Development Rating: 0 out of 5 stars0 ratingsLearning Continuous Integration with Jenkins Rating: 0 out of 5 stars0 ratingsChaos Engineering A Clear and Concise Reference Rating: 0 out of 5 stars0 ratingsAWS CloudFormation A Complete Guide - 2021 Edition Rating: 0 out of 5 stars0 ratingsRestlet in Action: Developing RESTful web APIs in Java Rating: 0 out of 5 stars0 ratingsJava Complete Self-Assessment Guide Rating: 0 out of 5 stars0 ratingsMicroservices with Azure A Complete Guide - 2019 Edition Rating: 0 out of 5 stars0 ratings
Programming For You
HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Python Projects for Beginners: A Ten-Week Bootcamp Approach to Python Programming Rating: 0 out of 5 stars0 ratingsLearn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 0 out of 5 stars0 ratingsJava for Beginners: A Crash Course to Learn Java Programming in 1 Week Rating: 5 out of 5 stars5/5The Unofficial Guide to Open Broadcaster Software: OBS: The World's Most Popular Free Live-Streaming Application Rating: 0 out of 5 stars0 ratingsPYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Hacking: Ultimate Beginner's Guide for Computer Hacking in 2018 and Beyond: Hacking in 2018, #1 Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5The Little SAS Book: A Primer, Sixth Edition Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Teach Yourself C++ Rating: 4 out of 5 stars4/5Pokemon Go: Guide + 20 Tips and Tricks You Must Read Hints, Tricks, Tips, Secrets, Android, iOS Rating: 5 out of 5 stars5/5
Reviews for Java Data Science Cookbook
0 ratings0 reviews
Book preview
Java Data Science Cookbook - Rushdi Shams
Table of Contents
Java Data Science Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it...
How it works...
There's more...
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Obtaining and Cleaning Data
Introduction
Retrieving all filenames from hierarchical directories using Java
Getting ready
How to do it...
Retrieving all filenames from hierarchical directories using Apache Commons IO
Getting ready
How to do it...
Reading contents from text files all at once using Java 8
How to do it...
Reading contents from text files all at once using Apache Commons IO
Getting ready
How to do it...
Extracting PDF text using Apache Tika
Getting ready
How to do it...
Cleaning ASCII text files using Regular Expressions
How to do it...
Parsing Comma Separated Value (CSV) Files using Univocity
Getting ready
How to do it...
Parsing Tab Separated Value (TSV) file using Univocity
Getting ready
How to do it...
Parsing XML files using JDOM
Getting ready
How to do it...
Writing JSON files using JSON.simple
Getting ready
How to do it...
Reading JSON files using JSON.simple
Getting ready
How to do it ...
Extracting web data from a URL using JSoup
Getting ready
How to do it...
Extracting web data from a website using Selenium Webdriver
Getting ready
How to do it...
Reading table data from a MySQL database
Getting ready
How to do it...
2. Indexing and Searching Data
Introduction
Indexing data with Apache Lucene
Getting ready
How to do it...
How it works...
Searching indexed data with Apache Lucene
Getting ready
How to do it...
3. Analyzing Data Statistically
Introduction
Generating descriptive statistics
How to do it...
Generating summary statistics
How to do it...
Generating summary statistics from multiple distributions
How to do it...
There's more...
Computing frequency distribution
How to do it...
Counting word frequency in a string
How to do it...
How it works...
Counting word frequency in a string using Java 8
How to do it...
Computing simple regression
How to do it...
Computing ordinary least squares regression
How to do it...
Computing generalized least squares regression
How to do it...
Calculating covariance of two sets of data points
How to do it...
Calculating Pearson's correlation of two sets of data points
How to do it...
Conducting a paired t-test
How to do it...
Conducting a Chi-square test
How to do it...
Conducting the one-way ANOVA test
How to do it...
Conducting a Kolmogorov-Smirnov test
How to do it...
4. Learning from Data - Part 1
Introduction
Creating and saving an Attribute-Relation File Format (ARFF) file
How to do it...
Cross-validating a machine learning model
How to do it...
Classifying unseen test data
Getting ready
How to do it...
Classifying unseen test data with a filtered classifier
How to do it...
Generating linear regression models
How to do it...
Generating logistic regression models
How to do it...
Clustering data points using the KMeans algorithm
How to do it...
Clustering data from classes
How to do it...
Learning association rules from data
Getting ready
How to do it...
Selecting features/attributes using the low-level method, the filtering method, and the meta-classifier method
Getting ready
How to do it...
5. Learning from Data - Part 2
Introduction
Applying machine learning on data using Java Machine Learning (Java-ML) library
Getting ready
How to do it...
Classifying data points using the Stanford classifier
Getting ready
How to do it...
How it works...
Classifying data points using Massive Online Analysis (MOA)
Getting ready
How to do it...
Classifying multilabeled data points using Mulan
Getting ready
How to do it...
6. Retrieving Information from Text Data
Introduction
Detecting tokens (words) using Java
Getting ready
How to do it...
Detecting sentences using Java
Getting ready
How to do it...
Detecting tokens (words) and sentences using OpenNLP
Getting ready
How to do it...
Retrieving lemma, part-of-speech, and recognizing named entities from tokens using Stanford CoreNLP
Getting ready
How to do it...
Measuring text similarity with Cosine Similarity measure using Java 8
Getting ready
How to do it...
Extracting topics from text documents using Mallet
Getting ready
How to do it...
Classifying text documents using Mallet
Getting ready
How to do it...
Classifying text documents using Weka
Getting ready
How to do it...
7. Handling Big Data
Introduction
Training an online logistic regression model using Apache Mahout
Getting ready
How to do it...
Applying an online logistic regression model using Apache Mahout
Getting ready
How to do it...
Solving simple text mining problems with Apache Spark
Getting ready
How to do it...
Clustering using KMeans algorithm with MLib
Getting ready
How to do it...
Creating a linear regression model with MLib
Getting ready
How to do it...
Classifying data points with Random Forest model using MLib
Getting ready
How to do it...
8. Learn Deeply from Data
Introduction
Creating a Word2vec neural net using Deep Learning for Java (DL4j)
How to do it...
How it works...
There's more
Creating a Deep Belief neural net using Deep Learning for Java (DL4j)
How to do it...
How it works...
Creating a deep autoencoder using Deep Learning for Java (DL4j)
How to do it...
How it works...
9. Visualizing Data
Introduction
Plotting a 2D sine graph
Getting ready
How to do it...
Plotting histograms
Getting ready
How to do it...
Plotting a bar chart
Getting ready
How to do it...
Plotting box plots or whisker diagrams
Getting ready
How to do it...
Plotting scatter plots
Getting ready
How to do it...
Plotting donut plots
Getting ready
How to do it...
Plotting area graphs
Getting ready
How to do it...
Java Data Science Cookbook
Java Data Science Cookbook
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: March 2017
Production reference: 1240317
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78712-253-6
www.packtpub.com
Credits
About the Author
Rushdi Shams has a PhD on application of machine learning in Natural Language Processing (NLP) problem areas from Western University, Canada. Before starting work as a machine learning and NLP specialist in industry, he was engaged in teaching undergrad and grad courses. He has been successfully maintaining his YouTube channel named Learn with Rushdi
for learning computer technologies.
I would like to acknowledge the Almighty Allah for giving me the strength, support, and knowledge to finish the book.
I extend my thanks to my family members, friends, and colleagues for continuous support, encouragement, and constructive criticism.
I would also like to thank Ajith and Cheryl from Packt for their continuous and spontaneous collaboration with me.
About the Reviewer
Prashant Verma started his IT career in 2011 as a Java developer at Ericsson, working in the telecom domain. After a couple of years of Java EE experience, he moved into the big data domain, and has worked on almost all the popular big data technologies such as Hadoop, Spark, Kafka, Flume, Mongo, Cassandra, and so on. He has also worked in Scala and Python. Currently, he works with QA Infotech as Lead Data Engineer, working on solving e-learning domain problems using data analytics and machine learning.
Prashant has also worked on Apache Spark for Java Developers, Packt as a Technical Reviewer.
I want to thank Packt Publishing for giving me the chance to review the book, as well as my employer and my family for their patience while I was busy working on this book.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787122530.
If you'd like to join our team of regular reviewers, you can e-mail us at customerreviews@packtpub.com. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
To my lovely wife, Mah-Zereen, and adorable daughter, Ruayda.
Preface
Data science is a popular field for specialization nowadays and covers the broad spectrum of artificial intelligence, such as data processing, information retrieval, machine learning, natural language processing, big data, deep neural networks, and data visualization. In this book, we will understand the techniques that are both modern and smart and presented as easy-to-follow recipes for over 70 problems.
Keeping in mind the high demand for quality data scientists, we have compiled recipes using core Java as well as well-known, classic, and state-of-the-art data science libraries written in Java. We start with the data collection and cleaning process. Then we see how the obtained data can be indexed and searched. Afterwards, we cover statistics both descriptive and inferential and their application to data. Then, we have two back-to-back chapters on the application of machine learning on data that can be foundation for building any smart system. Modern information retrieval and natural language processing techniques are also covered. Big data is an emerging field, and a few aspects of this popular field are also covered. We also cover the very basics of deep learning using deep neural networks. Finally, we learn how to represent data and information obtained from data using meaningful visuals or graphs.
The book is aimed at anyone who has an interest in data science and plans to apply data science using Java to understand underlying data better.
What this book covers
Chapter 1, Obtaining and Cleaning Data, covers different ways to read and write data as well as to clean it to get rid of noise. It also familiarizes the readers with different data file types, such as PDF, ASCII, CSV, TSV, XML, and JSON. The chapter also covers recipes for extracting web data.
Chapter 2, Indexing and Searching Data, covers how to index data for fast searching using Apache Lucene. The techniques described in this chapter can be seen as the basis for modern-day search techniques.
Chapter 3, Analyzing Data Statistically, covers the application of Apache Math API to collect and analyze statistics from data. The chapter also covers higher level concepts such as the statistical significance test, which is the standard tool for researchers when they compare their results with benchmarks.
Chapter 4, Learning from Data - Part 1, covers basic classification, clustering, and feature selection exercises using the Weka machine learning Workbench.
Chapter 5, Learning from Data - Part 2, is a follow-up chapter that covers data import and export, classification, and feature selection using another Java library named the Java Machine Learning (Java-ML) Library. The chapter also covers basic classification with the Stanford Classifier and Massive Online Access (MOA).
Chapter 6, Retrieving Information from Text Data, covers the application of data science to text data for information retrieval. It covers the application of core Java as well as popular libraries such as OpenNLP, Stanford CoreNLP, Mallet, and Weka for the application of machine learning to information extraction and retrieval tasks.
Chapter 7, Handling Big Data, covers the application of big data platforms for machine learning, such as Apache Mahout and Spark-MLib.
Chapter 8, Learn Deeply from Data, covers the very basics of deep learning using the Deep Learning for Java (DL4j) library. We cover the word2vec algorithm, belief networks, and auto-encoders.
Chapter 9, Visualizing Data, covers the GRAL package to generate an appealing and informative display based on data. Among the many functionalities of the package, fundamental and basic plots have been selected.
What you need for this book
We have used Java to solve real-world data science problems. Our focus was to deliver content that can be effective for anyone who wants to know how to solve problems with Java. A minimum knowledge of Java is required, such as classes, objects, methods, arguments and parameters, exceptions, and exporting Java Archive (JAR) files. The code is well supported with narrations, information, and tips to help the readers understand the context and purpose. The theories behind the problems solved in this book, on many occasions, are not thoroughly discussed, but references for interested readers are provided whenever necessary.
Who this book is for
The book is for anyone who wants to know how to solve real-world problems related to data science using Java. The book, as it is very comprehensive in terms of coverage, can also be very useful for practitioners already engaged with data science and looking for solving issues in their projects using Java.
Sections
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
Getting ready
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
How to do it...
This section contains the steps required to follow the recipe.
How it works...
This section usually consists of a detailed explanation of what happened in the previous section.
There's more...
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
See also
This section provides helpful links to other useful information for the recipe.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Among them, you will find a folder named lib, which is the folder of interest.
A block of code is set as follows:
classVals = new ArrayList
for (int i = 0; i < 5; i++){
classVals.add(class
+ (i + 1));
}
Any command-line input or output is written as follows:
@relation MyRelation
@attribute age numeric
@attribute name string
@attribute dob date yyyy-MM-dd
@attribute class {class1,class2,class3,class4,class5}
@data
35,'John Doe',1981-01-20,class3
30,'Harry Potter',1986-07-05,class1
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: Select System info from the Administration panel.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors .
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Java-Data-Science-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/ . Check them out!
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/JavaDataScienceCookbook_ColorImages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at copyright@packtpub.com with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com, and we will do our best to address the problem.
Chapter 1. Obtaining and Cleaning Data
In this chapter, we will cover the following recipes:
Retrieving all file names from hierarchical directories using Java
Retrieving all file names from hierarchical directories using Apache Commons IO
Reading contents from text files all at once using Java 8
Reading contents from text files all at once using Apache Commons IO
Extracting PDF text using Apache Tika
Cleaning ASCII text files using Regular Expressions
Parsing Comma Separated Value files using Univocity
Parsing Tab Separated Value files using Univocity
Parsing XML files using JDOM
Writing JSON files using JSON.simple
Reading JSON files using JSON.simple
Extracting web data from a URL using JSoup
Extracting web data from a website using Selenium Webdriver
Reading table data from MySQL database
Introduction
Every data scientist needs to deal with data that is stored on disks in several formats, such as ASCII text, PDF, XML, JSON, and so on. Also, data can be stored in database tables. The first and foremost task for a data scientist before doing any analysis is to obtain data from these data sources and of these formats, and apply data-cleaning techniques to get rid of noises present in them. In this chapter, we will see recipes to accomplish this important task.
We will be using external Java libraries (Java archive files or simply JAR files) not only for this chapter