Python Machine Learning By Example
4/5
()
Machine Learning
Logistic Regression
Data Preprocessing
Overfitting
Data Analysis
Click-Through Prediction
Random Forest
Machine Learning Algorithms
Text Classification
Support Vector Machines
About this ebook
- Learn the fundamentals of machine learning and build your own intelligent applications
- Master the art of building your own machine learning systems with this example-based practical guide
- Work with important classification and regression algorithms and other machine learning techniques
This book is for anyone interested in entering the data science stream with machine learning. Basic familiarity with Python is assumed.
Yuxi (Hayden) Liu
Yuxi(Hayden)Liu是加拿大多伦多市一家跨国网络媒体公司的数据科学家,他从事消息应用优化工作。他的研究方向是社交网络挖掘、社交个性化(social personalization)、用户人口统计学特征和兴趣预测、垃圾信息监测和推荐系统。他曾在多家程序化广告投放公司工作,担任数据科学家职位,他将机器学习专业知识应用于广告优化、点击率和转化率预测、点击欺诈检测等。Yuxi拥有多伦多大学的硕士学位,研究生期间曾发表过5篇IEEE期刊文章和会议论文。他喜欢爬取网络数据,并从中获取有价值的信息。他还热衷于投资。
Related to Python Machine Learning By Example
Related ebooks
Python Machine Learning - Third Edition: Machine Learning and Deep Learning with Python, scikit-learn, and TensorFlow 2, 3rd Edition Rating: 4 out of 5 stars4/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5Building Machine Learning Systems with Python Rating: 4 out of 5 stars4/5Advanced Machine Learning with Python Rating: 0 out of 5 stars0 ratingsPython Data Science Essentials - Second Edition Rating: 4 out of 5 stars4/5Data Science with Jupyter: Master Data Science skills with easy-to-follow Python examples Rating: 0 out of 5 stars0 ratingsMachine Learning For Beginners Guide Algorithms: Supervised & Unsupervsied Learning. Decision Tree & Random Forest Introduction Rating: 0 out of 5 stars0 ratingsPython Machine Learning: Introduction to Machine Learning with Python Rating: 0 out of 5 stars0 ratingsPractical Data Analysis Rating: 4 out of 5 stars4/5NumPy Essentials Rating: 0 out of 5 stars0 ratingsDeep Learning with Keras: Beginner’s Guide to Deep Learning with Keras Rating: 3 out of 5 stars3/5Python for AI: Applying Machine Learning in Everyday Projects Rating: 0 out of 5 stars0 ratingsHands-on Supervised Learning with Python Rating: 0 out of 5 stars0 ratingsPrinciples of Data Science: A beginner's guide to essential math and coding skills for data fluency and machine learning Rating: 0 out of 5 stars0 ratingsPython Machine Learning Projects: Learn how to build Machine Learning projects from scratch (English Edition) Rating: 0 out of 5 stars0 ratingsMathematics for Machine Learning: A Deep Dive into Algorithms Rating: 0 out of 5 stars0 ratingsMachine Learning in Python: Hands on Machine Learning with Python Tools, Concepts and Techniques Rating: 5 out of 5 stars5/5Ultimate Neural Network Programming with Python Rating: 0 out of 5 stars0 ratingsLearn Algorithmic Trading: Build and deploy algorithmic trading systems and strategies using Python and advanced data analysis Rating: 0 out of 5 stars0 ratingsMachine Learning in Python: Essential Techniques for Predictive Analysis Rating: 4 out of 5 stars4/5Python Machine Learning Illustrated Guide For Beginners & Intermediates:The Future Is Here! Rating: 5 out of 5 stars5/5
Programming For You
PHP, MySQL, & JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5PowerShell 7 for IT Professionals Rating: 1 out of 5 stars1/5Proxmox Administration Essentials: Definitive Reference for Developers and Engineers Rating: 0 out of 5 stars0 ratingsiOS 26 App Development Essentials - SwiftUI Edition: Developing iOS 26 Apps using SwiftUI, Swift and Xcode 26 Rating: 0 out of 5 stars0 ratingsLearn SAP BI in 24 Hours Rating: 3 out of 5 stars3/5The Book of Powershell Rating: 0 out of 5 stars0 ratingsSAP Service Management - Advanced Configuration Guide 2 Rating: 0 out of 5 stars0 ratingsCreating ELearning Games with Unity Rating: 0 out of 5 stars0 ratingsProgramming in Python: Learn the Powerful Object-Oriented Programming Rating: 0 out of 5 stars0 ratingsSwipe This!: The Guide to Great Touchscreen Game Design Rating: 4 out of 5 stars4/5Learning LEGO MINDSTORMS EV3 Rating: 5 out of 5 stars5/5Python For Kids For Dummies Rating: 0 out of 5 stars0 ratingsOntotext GraphDB in Practice: The Complete Guide for Developers and Engineers Rating: 0 out of 5 stars0 ratingsJavaScript Made Easy: A Beginner's Practical Guide to Coding Interactive Web Pages Rating: 0 out of 5 stars0 ratingsUnity Multiplayer Games Rating: 5 out of 5 stars5/5Web Designer's Idea Book, Volume 4: Inspiration from the Best Web Design Trends, Themes and Styles Rating: 4 out of 5 stars4/5Job Ready Python Rating: 0 out of 5 stars0 ratingsGood Luck Have Fun: The Rise of eSports Rating: 3 out of 5 stars3/5Beginning Programming with Java For Dummies Rating: 5 out of 5 stars5/5PHP & MySQL Practice It Learn It Rating: 4 out of 5 stars4/5Learn to Code with Scratch: Let Your Kids' Creative Ideas Come to Life by Coding Them into Programs Rating: 0 out of 5 stars0 ratingsHacking Android Rating: 5 out of 5 stars5/5Video Game of the Year: A Year-by-Year Guide to the Best, Boldest, and Most Bizarre Games from Every Year Since 1977 Rating: 0 out of 5 stars0 ratings
Reviews for Python Machine Learning By Example
7 ratings0 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 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/1783553111.
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!
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 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.
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 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.
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 it comes to events that are dynamic, ever-changing, or evolve in real-time. It
