Python Machine Learning By Example: The easiest way to get into machine learning
5/5
()
About this ebook
Data science and machine learning are some of the top buzzwords in the technical world today. A resurging interest in machine learning is due to the same factors that have made data mining and Bayesian analysis more popular than ever. This book is your entry point to machine learning.
This book starts with an introduction to machine learning and the Python language and shows you how to complete the setup. Moving ahead, you will learn all the important concepts such as, exploratory data analysis, data preprocessing, feature extraction, data visualization and clustering, classification, regression and model performance evaluation. With the help of various projects included, you will find it intriguing to acquire the mechanics of several important machine learning algorithms – they are no more obscure as they thought. Also, you will be guided step by step to build your own models from scratch. Toward the end, you will gather a broad picture of the machine learning ecosystem and best practices of applying machine learning techniques.
Through this book, you will learn to tackle data-driven problems and implement your solutions with the powerful yet simple language, Python. Interesting and easy-to-follow examples, to name some, news topic classification, spam email detection, online ad click-through prediction, stock prices forecast, will keep you glued till you reach your goal.
Read more from Yuxi (Hayden) Liu
Python Machine Learning By Example: Unlock machine learning best practices with real-world use cases Rating: 0 out of 5 stars0 ratingsPython Machine Learning By Example Rating: 4 out of 5 stars4/5R Deep Learning Projects: Master the techniques to design and develop neural network models in R Rating: 0 out of 5 stars0 ratingsPyTorch 1.x Reinforcement Learning Cookbook: Over 60 recipes to design, develop, and deploy self-learning AI models using Python Rating: 0 out of 5 stars0 ratings
Related to Python Machine Learning By Example
Related ebooks
Machine Learning Algorithms: Popular algorithms for data science and machine learning Rating: 0 out of 5 stars0 ratingsDeep Learning By Example: A hands-on guide to implementing advanced machine learning algorithms and neural networks Rating: 0 out of 5 stars0 ratingsGo Machine Learning Projects: Eight projects demonstrating end-to-end machine learning and predictive analytics applications in Go Rating: 0 out of 5 stars0 ratingsHands-On Data Science and Python Machine Learning: Perform data mining and machine learning efficiently using Python and Spark Rating: 0 out of 5 stars0 ratingsHands-On Neural Network Programming with C#: Add powerful neural network capabilities to your C# enterprise applications Rating: 0 out of 5 stars0 ratingsMastering Machine Learning Algorithms: Expert techniques to implement popular machine learning algorithms and fine-tune your models Rating: 0 out of 5 stars0 ratingsKeras Reinforcement Learning Projects: 9 projects exploring popular reinforcement learning techniques to build self-learning agents Rating: 0 out of 5 stars0 ratingsStatistics for Machine Learning Rating: 3 out of 5 stars3/5R Machine Learning Projects: Implement supervised, unsupervised, and reinforcement learning techniques using R 3.5 Rating: 0 out of 5 stars0 ratingsR Deep Learning Essentials.: A step-by-step guide to building deep learning models using TensorFlow, Keras, and MXNet Rating: 0 out of 5 stars0 ratingsDeep Learning with PyTorch: A practical approach to building neural network models using PyTorch Rating: 0 out of 5 stars0 ratingsPractical Convolutional Neural Networks: Implement advanced deep learning models using Python Rating: 0 out of 5 stars0 ratingsPractical Computer Vision: Extract insightful information from images using TensorFlow, Keras, and OpenCV Rating: 0 out of 5 stars0 ratingsHands-on Machine Learning with JavaScript: Solve complex computational web problems using machine learning Rating: 0 out of 5 stars0 ratingsEnsemble Machine Learning: A beginner's guide that combines powerful machine learning algorithms to build optimized models Rating: 0 out of 5 stars0 ratingsMachine Learning With Go: Leverage Go's powerful packages to build smart machine learning and predictive applications, 2nd Edition Rating: 0 out of 5 stars0 ratingsApache Mahout Essentials Rating: 0 out of 5 stars0 ratingsArtificial Intelligence By Example: Develop machine intelligence from scratch using real artificial intelligence use cases Rating: 0 out of 5 stars0 ratingsMachine Learning with scikit-learn Quick Start Guide: Classification, regression, and clustering techniques in Python Rating: 0 out of 5 stars0 ratingsLearning Data Mining with Python Rating: 0 out of 5 stars0 ratingsMastering Machine Learning with scikit-learn - Second Edition Rating: 0 out of 5 stars0 ratingsMastering Numerical Computing with NumPy: Master scientific computing and perform complex operations with ease Rating: 0 out of 5 stars0 ratingsPractical Machine Learning with Python: Real-World Applications Rating: 0 out of 5 stars0 ratingsLearning Data Mining with Python: Use Python to manipulate data and build predictive models Rating: 0 out of 5 stars0 ratings
Programming For You
Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsJavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5HTML & CSS: Learn the Fundaments in 7 Days 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/5C# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsExcel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 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/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsC Programming For Beginners: The Simple Guide to Learning C Programming Language Fast! Rating: 5 out of 5 stars5/5Beginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5Coding with JavaScript For Dummies Rating: 0 out of 5 stars0 ratingsHTML in 30 Pages 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/5
Reviews for Python Machine Learning By Example
1 rating0 reviews
Book preview
Python Machine Learning By Example - Yuxi (Hayden) Liu
Title Page
Python Machine Learning By Example
Easy-to-follow examples that get you up and running with machine learning
Yuxi (Hayden) Liu
BIRMINGHAM - MUMBAI
Copyright
Credits
About the Author
Yuxi (Hayden) Liu is currently a data scientist working on messaging app optimization at a multinational online media corporation in Toronto, Canada. He is focusing on social graph mining, social personalization, user demographics and interests prediction, spam detection, and recommendation systems. He has worked for a few years as a data scientist at several programmatic advertising companies, where he applied his machine learning expertise in ad optimization, click-through rate and conversion rate prediction, and click fraud detection. Yuxi earned his degree from the University of Toronto, and published five IEEE transactions and conference papers during his master's research. He finds it enjoyable to crawl data from websites and derive valuable insights. He is also an investment enthusiast.
About the Reviewer
Alberto Boschetti is a data scientist with strong expertise in signal processing and statistics. He holds a PhD in telecommunication engineering and currently lives and works in London. In his work projects, he faces challenges daily, spanning across natural language processing (NLP), machine learning, and distributed processing. He is very passionate about his job and always tries to be updated on the latest developments of data science technologies, attending meetups, conferences, and other events. He is the author of Python Data Science Essentials, Regression Analysis with Python, and Large Scale Machine Learning with Python, all published by Packt.
I would like to thank my family, my friends, and my colleagues. Also, a big thanks to the open source community.
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 [email protected] 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/1783553111.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Table of Contents
Credits
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
Getting Started with Python and Machine Learning
What is machine learning and why do we need it?
A very high level overview of machine learning
A brief history of the development of machine learning algorithms
Generalizing with data
Overfitting, underfitting and the bias-variance tradeoff
Avoid overfitting with cross-validation
Avoid overfitting with regularization
Avoid overfitting with feature selection and dimensionality reduction
Preprocessing, exploration, and feature engineering
Missing values
Label encoding
One-hot-encoding
Scaling
Polynomial features
Power transformations
Binning
Combining models
Bagging
Boosting
Stacking
Blending
Voting and averaging
Installing software and setting up
Troubleshooting and asking for help
Summary
Exploring the 20 Newsgroups Dataset with Text Analysis Algorithms
What is NLP?
Touring powerful NLP libraries in Python
The newsgroups data
Getting the data
Thinking about features
Visualization
Data preprocessing
Clustering
Topic modeling
Summary
Spam Email Detection with Naive Bayes
Getting started with classification
Types of classification
Applications of text classification
Exploring naive Bayes
Bayes' theorem by examples
The mechanics of naive Bayes
The naive Bayes implementations
Classifier performance evaluation
Model tuning and cross-validation
Summary
News Topic Classification with Support Vector Machine
Recap and inverse document frequency
Support vector machine
The mechanics of SVM
Scenario 1 - identifying the separating hyperplane
Scenario 2 - determining the optimal hyperplane
Scenario 3 - handling outliers
The implementations of SVM
Scenario 4 - dealing with more than two classes
The kernels of SVM
Choosing between the linear and RBF kernel
News topic classification with support vector machine
More examples - fetal state classification on cardiotocography with SVM
Summary
Click-Through Prediction with Tree-Based Algorithms
Brief overview of advertising click-through prediction
Getting started with two types of data, numerical and categorical
Decision tree classifier
The construction of a decision tree
The metrics to measure a split
The implementations of decision tree
Click-through prediction with decision tree
Random forest - feature bagging of decision tree
Summary
Click-Through Prediction with Logistic Regression
One-hot encoding - converting categorical features to numerical
Logistic regression classifier
Getting started with the logistic function
The mechanics of logistic regression
Training a logistic regression model via gradient descent
Click-through prediction with logistic regression by gradient descent
Training a logistic regression model via stochastic gradient descent
Training a logistic regression model with regularization
Training on large-scale datasets with online learning
Handling multiclass classification
Feature selection via random forest
Summary
Stock Price Prediction with Regression Algorithms
Brief overview of the stock market and stock price
What is regression?
Predicting stock price with regression algorithms
Feature engineering
Data acquisition and feature generation
Linear regression
Decision tree regression
Support vector regression
Regression performance evaluation
Stock price prediction with regression algorithms
Summary
Best Practices
Machine learning workflow
Best practices in the data preparation stage
Best practice 1 - completely understand the project goal
Best practice 2 - collect all fields that are relevant
Best practice 3 - maintain consistency of field values
Best practice 4 - deal with missing data
Best practices in the training sets generation stage
Best practice 5 - determine categorical features with numerical values
Best practice 6 - decide on whether or not to encode categorical features
Best practice 7 - decide on whether or not to select features and if so, how
Best practice 8 - decide on whether or not to reduce dimensionality and if so how
Best practice 9 - decide on whether or not to scale features
Best practice 10 - perform feature engineering with domain expertise
Best practice 11 - perform feature engineering without domain expertise
Best practice 12 - document how each feature is generated
Best practices in the model training, evaluation, and selection stage
Best practice 13 - choose the right algorithm(s) to start with
Naive Bayes
Logistic regression
SVM
Random forest (or decision tree)
Neural networks
Best practice 14 - reduce overfitting
Best practice 15 - diagnose overfitting and underfitting
Best practices in the deployment and monitoring stage
Best practice 16 - save, load, and reuse models
Best practice 17 - monitor model performance
Best practice 18 - update models regularly
Summary
Python Machine Learning By Example
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: May 2017
Production reference: 1290517
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78355-311-2
www.packtpub.com
Preface
Data science and machine learning are some of the top buzzwords in the technical world today. A resurging interest in machine learning is due to the same factors that have made data mining and Bayesian analysis more popular than ever. This book is your entry point to machine learning.
What this book covers
Chapter 1, Getting Started with Python and Machine Learning, is the starting point for someone who is looking forward to enter the field of ML with Python. You will get familiar with the basics of Python and ML in this chapter and set up the software on your machine.
Chapter 2, Exploring the 20 Newsgroups Dataset with Text Analysis Algorithms, explains important concepts such as getting the data, its features, and pre-processing. It also covers the dimension reduction technique, principal component analysis, and the k-nearest neighbors algorithm.
Chapter 3, Spam Email Detection with Naive Bayes, covers classification, naive Bayes, and its in-depth implementation, classification performance evaluation, model selection and tuning, and cross-validation. Examples such as spam e-mail detection are demonstrated.
Chapter 4, News Topic Classification with Support Vector Machine, covers multiclass classification, Support Vector Machine, and how it is applied in topic classification. Other important concepts, such as kernel machine, overfitting, and regularization, are discussed as well.
Chapter 5, Click-Through Prediction with Tree-Based Algorithms, explains decision trees and random forests in depth over the course of solving an advertising click-through rate problem.
Chapter 6, Click-Through Prediction with Logistic Regression, explains in depth the logistic regression classifier. Also, concepts such as categorical variable encoding, L1 and L2 regularization, feature selection, online learning, and stochastic gradient descent are detailed.
Chapter 7, Stock Price Prediction with Regression Algorithms, analyzes predicting stock market prices using Yahoo/Google Finance data and maybe additional data. Also, it covers the challenges in finance and brief explanations of related concepts.
Chapter 8, Best Practices, aims to foolproof your learning and get you ready for production.
After covering multiple projects in this book, the readers will have gathered a broad picture of the ML ecosystem using Python.
What you need for this book
The following are required for you to utilize this book:
scikit-learn 0.18.0
Numpy 1.1
Matplotlib 1.5.1
NLTK 3.2.2
pandas 0.19.2
GraphViz
Quandl Python API
You can use a 64-bit architecture, 2GHz CPU, and 8GB RAM to perform all the steps in this book. You will require at least 8GB of hard disk space.
Who this book is for
This book is for anyone interested in entering data science with machine learning. Basic familiarity with Python is assumed.
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: The target_names key gives the newsgroups names.
Any command-line input or output is written as follows:
ls -1 enron1/ham/*.txt | wc -l
3672
ls -1 enron1/spam/*.txt | wc -l
1500
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: Heterogeneity Activity Recognition Data Set.
Warnings or important notes appear in a box like this.
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 [email protected], 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.
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/Python-Machine-Learning-By-Example. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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 [email protected] 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 [email protected], and we will do our best to address the problem.
Getting Started with Python and Machine Learning
We kick off our Python and machine learning journey with the basic, yet important concepts of machine learning. We will start with what machine learning is about, why we need it, and its evolution over the last few decades. We will then discuss typical machine learning tasks and explore several essential techniques of working with data and working with models. It is a great starting point of the subject and we will learn it in a fun way. Trust me. At the end, we will also set up the software and tools needed in this book.
We will get into details for the topics mentioned:
What is machine learning and why do we need it?
A very high level overview of machine learning
Generalizing with data
Overfitting and the bias variance trade off
Cross validation
Regularization
Dimensions and features
Preprocessing, exploration, and feature engineering
Missing Values
Label encoding
One hot encoding
Scaling
Polynomial features
Power transformations
Binning
Combining models
Bagging
Boosting
Stacking
Blending
Voting and averaging
Installing software and setting up
Troubleshooting and asking for help
What is machine learning and why do we need it?
Machine learning is a term coined around 1960 composed of two words—machine corresponding to a computer, robot, or other device, and learning an activity, or event patterns, which humans are good at.
So why do we need machine learning, why do we want a machine to learn as a human? There are many problems involving huge datasets, or complex calculations for instance, where it makes sense to let computers do all the work. In general, of course, computers and robots don't get tired, don't have to sleep, and may be cheaper. There is also an emerging school of thought called active learning or human-in-the-loop, which advocates combining the efforts of machine learners and humans. The idea is that there are routine boring tasks more suitable for computers, and creative tasks more suitable for humans. According to this philosophy, machines are able to learn, by following rules (or algorithms) designed by humans and to do repetitive and logic tasks desired by a human.
Machine learning does not involve the traditional type of programming that uses business rules. A popular myth says that the majority of the code in the world has to do with simple rules possibly programmed in Cobol, which covers the bulk of all the possible scenarios of client interactions. So why can't we just hire many software programmers and continue programming new rules?
One reason is that defining, maintaining, and updating rules becomes more and more expensive over time. The number of possible patterns for an activity or event could be enormous and therefore exhausting all enumeration is not practically feasible. It gets even more challenging to do so when