Scikit-Learn

Total Page:16

File Type:pdf, Size:1020Kb

Scikit-Learn Scikit-Learn i Scikit-Learn About the Tutorial Scikit-learn (Sklearn) is the most useful and robust library for machine learning in Python. It provides a selection of efficient tools for machine learning and statistical modeling including classification, regression, clustering and dimensionality reduction via a consistence interface in Python. This library, which is largely written in Python, is built upon NumPy, SciPy and Matplotlib. Audience This tutorial will be useful for graduates, postgraduates, and research students who either have an interest in this Machine Learning subject or have this subject as a part of their curriculum. The reader can be a beginner or an advanced learner. Prerequisites The reader must have basic knowledge about Machine Learning. He/she should also be aware about Python, NumPy, Scipy, Matplotlib. If you are new to any of these concepts, we recommend you take up tutorials concerning these topics, before you dig further into this tutorial. Copyright & Disclaimer Copyright 2019 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at [email protected] ii Scikit-Learn Table of Contents About the Tutorial ........................................................................................................................................... ii Audience .......................................................................................................................................................... ii Prerequisites .................................................................................................................................................... ii Copyright & Disclaimer .................................................................................................................................... ii Table of Contents ........................................................................................................................................... iii 1. Scikit-Learn — Introduction ...................................................................................................................... 1 What is Scikit-Learn (Sklearn)? ........................................................................................................................ 1 Origin of Scikit-Learn ....................................................................................................................................... 1 Community & contributors.............................................................................................................................. 1 Prerequisites .................................................................................................................................................... 2 Installation ....................................................................................................................................................... 2 Features ........................................................................................................................................................... 3 2. Scikit-Learn ― Modelling Process ............................................................................................................. 4 Dataset Loading ............................................................................................................................................... 4 Splitting the dataset ........................................................................................................................................ 6 Train the Model ............................................................................................................................................... 7 Model Persistence ........................................................................................................................................... 8 Preprocessing the Data ................................................................................................................................... 9 Binarisation ...................................................................................................................................................... 9 Mean Removal ................................................................................................................................................. 9 Scaling ............................................................................................................................................................ 10 Normalisation ................................................................................................................................................ 11 3. Scikit-Learn — Data Representation ....................................................................................................... 13 Data as table .................................................................................................................................................. 13 Data as Feature Matrix .................................................................................................................................. 13 Data as Target array ...................................................................................................................................... 14 iii Scikit-Learn 4. Scikit-Learn ― Estimator API ................................................................................................................... 16 What is Estimator API? .................................................................................................................................. 16 Use of Estimator API ...................................................................................................................................... 16 Guiding Principles .......................................................................................................................................... 17 Steps in using Estimator API .......................................................................................................................... 18 Supervised Learning Example ........................................................................................................................ 18 Unsupervised Learning Example ................................................................................................................... 23 5. Scikit-Learn — Conventions .................................................................................................................... 26 Purpose of Conventions ................................................................................................................................ 26 Various Conventions ...................................................................................................................................... 26 6. Scikit-Learn ― Linear Modeling .............................................................................................................. 31 Linear Regression .......................................................................................................................................... 32 Logistic Regression ........................................................................................................................................ 34 Ridge Regression ........................................................................................................................................... 37 Bayesian Ridge Regression ............................................................................................................................ 40 LASSO (Least Absolute Shrinkage and Selection Operator)........................................................................... 43 Multi-task LASSO ........................................................................................................................................... 45 Elastic-Net...................................................................................................................................................... 47 MultiTaskElasticNet ....................................................................................................................................... 51 7. Scikit-Learn — Extended Linear Modeling ............................................................................................... 54 Introduction to Polynomial Features ............................................................................................................. 54 Streamlining using Pipeline tools .................................................................................................................. 55 8. Scikit-Learn ― Stochastic Gradient Descent ............................................................................................ 57 SGD Classifier ................................................................................................................................................
Recommended publications
  • Sagemath and Sagemathcloud
    Viviane Pons Ma^ıtrede conf´erence,Universit´eParis-Sud Orsay [email protected] { @PyViv SageMath and SageMathCloud Introduction SageMath SageMath is a free open source mathematics software I Created in 2005 by William Stein. I http://www.sagemath.org/ I Mission: Creating a viable free open source alternative to Magma, Maple, Mathematica and Matlab. Viviane Pons (U-PSud) SageMath and SageMathCloud October 19, 2016 2 / 7 SageMath Source and language I the main language of Sage is python (but there are many other source languages: cython, C, C++, fortran) I the source is distributed under the GPL licence. Viviane Pons (U-PSud) SageMath and SageMathCloud October 19, 2016 3 / 7 SageMath Sage and libraries One of the original purpose of Sage was to put together the many existent open source mathematics software programs: Atlas, GAP, GMP, Linbox, Maxima, MPFR, PARI/GP, NetworkX, NTL, Numpy/Scipy, Singular, Symmetrica,... Sage is all-inclusive: it installs all those libraries and gives you a common python-based interface to work on them. On top of it is the python / cython Sage library it-self. Viviane Pons (U-PSud) SageMath and SageMathCloud October 19, 2016 4 / 7 SageMath Sage and libraries I You can use a library explicitly: sage: n = gap(20062006) sage: type(n) <c l a s s 'sage. interfaces .gap.GapElement'> sage: n.Factors() [ 2, 17, 59, 73, 137 ] I But also, many of Sage computation are done through those libraries without necessarily telling you: sage: G = PermutationGroup([[(1,2,3),(4,5)],[(3,4)]]) sage : G . g a p () Group( [ (3,4), (1,2,3)(4,5) ] ) Viviane Pons (U-PSud) SageMath and SageMathCloud October 19, 2016 5 / 7 SageMath Development model Development model I Sage is developed by researchers for researchers: the original philosophy is to develop what you need for your research and share it with the community.
    [Show full text]
  • Tuto Documentation Release 0.1.0
    Tuto Documentation Release 0.1.0 DevOps people 2020-05-09 09H16 CONTENTS 1 Documentation news 3 1.1 Documentation news 2020........................................3 1.1.1 New features of sphinx.ext.autodoc (typing) in sphinx 2.4.0 (2020-02-09)..........3 1.1.2 Hypermodern Python Chapter 5: Documentation (2020-01-29) by https://twitter.com/cjolowicz/..................................3 1.2 Documentation news 2018........................................4 1.2.1 Pratical sphinx (2018-05-12, pycon2018)...........................4 1.2.2 Markdown Descriptions on PyPI (2018-03-16)........................4 1.2.3 Bringing interactive examples to MDN.............................5 1.3 Documentation news 2017........................................5 1.3.1 Autodoc-style extraction into Sphinx for your JS project...................5 1.4 Documentation news 2016........................................5 1.4.1 La documentation linux utilise sphinx.............................5 2 Documentation Advices 7 2.1 You are what you document (Monday, May 5, 2014)..........................8 2.2 Rédaction technique...........................................8 2.2.1 Libérez vos informations de leurs silos.............................8 2.2.2 Intégrer la documentation aux processus de développement..................8 2.3 13 Things People Hate about Your Open Source Docs.........................9 2.4 Beautiful docs.............................................. 10 2.5 Designing Great API Docs (11 Jan 2012)................................ 10 2.6 Docness.................................................
    [Show full text]
  • Quick Tour of Machine Learning (機器 )
    Quick Tour of Machine Learning (_hx習速遊) Hsuan-Tien Lin (林軒0) [email protected] Department of Computer Science & Information Engineering National Taiwan University (國Ë台c'xÇ訊工程û) Ç料科x愛}者t會û列;動, 2015/12/12 Hsuan-Tien Lin (NTU CSIE) Quick Tour of Machine Learning 0/128 Learning from Data Disclaimer just super-condensed and shuffled version of • • my co-authored textbook “Learning from Data: A Short Course” • my two NTU-Coursera Mandarin-teaching ML Massive Open Online Courses • “Machine Learning Foundations”: www.coursera.org/course/ntumlone • “Machine Learning Techniques”: www.coursera.org/course/ntumltwo —impossible to be complete, with most math details removed live interaction is important • goal: help you begin your journey with ML Hsuan-Tien Lin (NTU CSIE) Quick Tour of Machine Learning 1/128 Learning from Data Roadmap Learning from Data What is Machine Learning Components of Machine Learning Types of Machine Learning Step-by-step Machine Learning Hsuan-Tien Lin (NTU CSIE) Quick Tour of Machine Learning 2/128 Learning from Data What is Machine Learning Learning from Data :: What is Machine Learning Hsuan-Tien Lin (NTU CSIE) Quick Tour of Machine Learning 3/128 learning: machine learning: Learning from Data What is Machine Learning From Learning to Machine Learning learning: acquiring skill with experience accumulated from observations observations learning skill machine learning: acquiring skill with experience accumulated/computed from data data ML skill What is skill? Hsuan-Tien Lin (NTU CSIE) Quick Tour of Machine Learning 4/128 , machine learning: Learning from Data What is Machine Learning A More Concrete Definition skill improve some performance measure (e.g.
    [Show full text]
  • Understanding Support Vector Machines
    Chapter 7 Applying the same steps to compare the predicted values to the true values, we now obtain a correlation around 0.80, which is a considerable improvement over the previous result: > model_results2 <- compute(concrete_model2, concrete_test[1:8]) > predicted_strength2 <- model_results2$net.result > cor(predicted_strength2, concrete_test$strength) [,1] [1,] 0.801444583 Interestingly, in the original publication, I-Cheng Yeh reported a mean correlation of 0.885 using a very similar neural network. For some reason, we fell a bit short. In our defense, he is a civil engineering professor; therefore, he may have applied some subject matter expertise to the data preparation. If you'd like more practice with neural networks, you might try applying the principles learned earlier in this chapter to beat his result, perhaps by using different numbers of hidden nodes, applying different activation functions, and so on. The ?neuralnet help page provides more information on the various parameters that can be adjusted. Understanding Support Vector Machines A Support Vector Machine (SVM) can be imagined as a surface that defnes a boundary between various points of data which represent examples plotted in multidimensional space according to their feature values. The goal of an SVM is to create a fat boundary, called a hyperplane, which leads to fairly homogeneous partitions of data on either side. In this way, SVM learning combines aspects of both the instance-based nearest neighbor learning presented in Chapter 3, Lazy Learning – Classifcation Using Nearest Neighbors, and the linear regression modeling described in Chapter 6, Forecasting Numeric Data – Regression Methods. The combination is extremely powerful, allowing SVMs to model highly complex relationships.
    [Show full text]
  • How to Access Python for Doing Scientific Computing
    How to access Python for doing scientific computing1 Hans Petter Langtangen1,2 1Center for Biomedical Computing, Simula Research Laboratory 2Department of Informatics, University of Oslo Mar 23, 2015 A comprehensive eco system for scientific computing with Python used to be quite a challenge to install on a computer, especially for newcomers. This problem is more or less solved today. There are several options for getting easy access to Python and the most important packages for scientific computations, so the biggest issue for a newcomer is to make a proper choice. An overview of the possibilities together with my own recommendations appears next. Contents 1 Required software2 2 Installing software on your laptop: Mac OS X and Windows3 3 Anaconda and Spyder4 3.1 Spyder on Mac............................4 3.2 Installation of additional packages.................5 3.3 Installing SciTools on Mac......................5 3.4 Installing SciTools on Windows...................5 4 VMWare Fusion virtual machine5 4.1 Installing Ubuntu...........................6 4.2 Installing software on Ubuntu....................7 4.3 File sharing..............................7 5 Dual boot on Windows8 6 Vagrant virtual machine9 1The material in this document is taken from a chapter in the book A Primer on Scientific Programming with Python, 4th edition, by the same author, published by Springer, 2014. 7 How to write and run a Python program9 7.1 The need for a text editor......................9 7.2 Spyder................................. 10 7.3 Text editors.............................. 10 7.4 Terminal windows.......................... 11 7.5 Using a plain text editor and a terminal window......... 12 8 The SageMathCloud and Wakari web services 12 8.1 Basic intro to SageMathCloud...................
    [Show full text]
  • Using a Support Vector Machine to Analyze a DNA Microarray∗
    Using a Support Vector Machine to Analyze a DNA Microarray∗ R. Morelli Department of Computer Science, Trinity College Hartford, CT 06106, USA [email protected] January 15, 2008 1 Introduction A DNA microarray is a small silicon chip that is covered with thousands of spots of DNA of known sequence. Biologists use microarrays to study gene expression patterns in a wide range of medical and scientific applications. Analysis of microarrays has led to discovery of genomic patterns that distinguish cancerous from non-cancerous cells. Other researchers have used microarrays to identify the genes in the brains of fish that are associated with certain kinds of mating behavior. Microarray data sets are very large and can only be analyzed with the help of computers. A support vector machine (SVM) is a powerful machine learning technique that is used in a variety of data mining applications, including the analysis of DNA microarrays. 2 Project Overview In this project we will learn how to use an SVM to recognize patterns in microarray data. Using an open source software package named libsvm and downloaded data from a cancer research project, we will to train an SVM to distinguish between gene expression patterns that are associated with two different forms of leukemia. Although this project will focus on SVMs and machine learning techniques, we will cover basic concepts in biology and genetics that underlie DNA analysis. We will gain experience using SVM software and emerge from this project with an improved understanding of how machine learning can be used to recognize important patterns in vast amounts of data.
    [Show full text]
  • An Introduction to Numpy and Scipy
    An introduction to Numpy and Scipy Table of contents Table of contents ............................................................................................................................ 1 Overview ......................................................................................................................................... 2 Installation ...................................................................................................................................... 2 Other resources .............................................................................................................................. 2 Importing the NumPy module ........................................................................................................ 2 Arrays .............................................................................................................................................. 3 Other ways to create arrays............................................................................................................ 7 Array mathematics .......................................................................................................................... 8 Array iteration ............................................................................................................................... 10 Basic array operations .................................................................................................................. 11 Comparison operators and value testing ....................................................................................
    [Show full text]
  • Arxiv:1612.07993V1 [Stat.ML] 23 Dec 2016 Until Recently, No Package Providing Multiple Semi-Supervised Learning Meth- Ods Was Available in R
    RSSL: Semi-supervised Learning in R Jesse H. Krijthe1,2 1 Pattern Recognition Laboratory, Delft University of Technology 2 Department of Molecular Epidemiology, Leiden University Medical Center [email protected] Abstract. In this paper, we introduce a package for semi-supervised learning research in the R programming language called RSSL. We cover the purpose of the package, the methods it includes and comment on their use and implementation. We then show, using several code examples, how the package can be used to replicate well-known results from the semi-supervised learning literature. Keywords: Semi-supervised Learning, Reproducibility, Pattern Recog- nition, R Introduction Semi-supervised learning is concerned with using unlabeled examples, that is, examples for which we know the values for the input features but not the corre- sponding outcome, to improve the performance of supervised learning methods that only use labeled examples to train a model. An important motivation for investigations into these types of algorithms is that in some applications, gath- ering labels is relatively expensive or time-consuming, compared to the cost of obtaining an unlabeled example. Consider, for instance, building a web-page classifier. Downloading millions of unlabeled web-pages is easy. Reading them to assign a label is time-consuming. Effectively using unlabeled examples to improve supervised classifiers can therefore greatly reduce the cost of building a decently performing prediction model, or make it feasible in cases where labeling many examples is not a viable option. While the R programming language [] offers a rich set of implementations of a plethora of supervised learning methods, brought together by machine learning packages such as caret and mlr there are fewer implementations of methods that can deal with the semi-supervised learning setting.
    [Show full text]
  • Crop Monitoring System Using Image Processing and Environmental Data
    Crop Monitoring System Using Image Processing and Environmental Data Shadman Rabbi - 18341015 Ahnaf Shabik - 13201013 Supervised by: Dr. Md. Ashraful Alam Department of Computer Science and Engineering BRAC University Declaration We, hereby declare that this thesis is based on the results found by ourselves. Materials of work found by other researcher are mentioned by reference. This thesis, neither in whole or in part, has been previously submitted for any degree. ______________________ Signature of Supervisor (Dr. Md. Ashraful Alam) ___________________ Signature of Author (Shadman Rabbi) ___________________ Signature of Author (Ahnaf Shabik) i Acknowledgement Firstly we would like to thank the almighty for enabling us to initiate our research, to put our best efforts and successfully conclude it. Secondly, we offer our genuine and heartiest appreciation to our regarded Supervisor Dr. Md. Ashraful Alam for his contribution, direction and support in leading the research and preparation of the report. His involvement, inclusion and supervision have inspired us and acted as a huge incentive all through our research. Last but not the least, we are grateful to the resources, seniors, companions who have been indirectly but actively helpful with the research. Especially Monirul Islam Pavel, Ekhwan Islam, Touhidul Islam and Tahmidul Haq has propelled and motivated us through this journey. We would also like to acknowledge the help we got from various assets over the internet; particularly from fellow researchers’ work. ii Table of Contents Declaration
    [Show full text]
  • Homework 2 an Introduction to Convolutional Neural Networks
    Homework 2 An Introduction to Convolutional Neural Networks 11-785: Introduction to Deep Learning (Spring 2019) OUT: February 17, 2019 DUE: March 10, 2019, 11:59 PM Start Here • Collaboration policy: { You are expected to comply with the University Policy on Academic Integrity and Plagiarism. { You are allowed to talk with / work with other students on homework assignments { You can share ideas but not code, you must submit your own code. All submitted code will be compared against all code submitted this semester and in previous semesters using MOSS. • Overview: { Part 1: All of the problems in Part 1 will be graded on Autolab. You can download the starter code from Autolab as well. This assignment has 100 points total. { Part 2: This section of the homework is an open ended competition hosted on Kaggle.com, a popular service for hosting predictive modeling and data analytic competitions. All of the details for completing Part 2 can be found on the competition page. • Submission: { Part 1: The compressed handout folder hosted on Autolab contains four python files, layers.py, cnn.py, mlp.py and local grader.py, and some folders data, autograde and weights. File layers.py contains common layers in convolutional neural networks. File cnn.py contains outline class of two convolutional neural networks. File mlp.py contains a basic MLP network. File local grader.py is foryou to evaluate your own code before submitting online. Folders contain some data to be used for section 1.3 and 1.4 of this homework. Make sure that all class and function definitions originally specified (as well as class attributes and methods) in the two files layers.py and cnn.py are fully implemented to the specification provided in this write-up.
    [Show full text]
  • Xgboost: a Scalable Tree Boosting System
    XGBoost: A Scalable Tree Boosting System Tianqi Chen Carlos Guestrin University of Washington University of Washington [email protected] [email protected] ABSTRACT problems. Besides being used as a stand-alone predictor, it Tree boosting is a highly effective and widely used machine is also incorporated into real-world production pipelines for learning method. In this paper, we describe a scalable end- ad click through rate prediction [15]. Finally, it is the de- to-end tree boosting system called XGBoost, which is used facto choice of ensemble method and is used in challenges widely by data scientists to achieve state-of-the-art results such as the Netflix prize [3]. on many machine learning challenges. We propose a novel In this paper, we describe XGBoost, a scalable machine learning system for tree boosting. The system is available sparsity-aware algorithm for sparse data and weighted quan- 2 tile sketch for approximate tree learning. More importantly, as an open source package . The impact of the system has we provide insights on cache access patterns, data compres- been widely recognized in a number of machine learning and sion and sharding to build a scalable tree boosting system. data mining challenges. Take the challenges hosted by the machine learning competition site Kaggle for example. A- By combining these insights, XGBoost scales beyond billions 3 of examples using far fewer resources than existing systems. mong the 29 challenge winning solutions published at Kag- gle's blog during 2015, 17 solutions used XGBoost. Among these solutions, eight solely used XGBoost to train the mod- Keywords el, while most others combined XGBoost with neural net- Large-scale Machine Learning s in ensembles.
    [Show full text]
  • User Guide Release 1.18.4
    NumPy User Guide Release 1.18.4 Written by the NumPy community May 24, 2020 CONTENTS 1 Setting up 3 2 Quickstart tutorial 9 3 NumPy basics 33 4 Miscellaneous 97 5 NumPy for Matlab users 103 6 Building from source 111 7 Using NumPy C-API 115 Python Module Index 163 Index 165 i ii NumPy User Guide, Release 1.18.4 This guide is intended as an introductory overview of NumPy and explains how to install and make use of the most important features of NumPy. For detailed reference documentation of the functions and classes contained in the package, see the reference. CONTENTS 1 NumPy User Guide, Release 1.18.4 2 CONTENTS CHAPTER ONE SETTING UP 1.1 What is NumPy? NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides a multidi- mensional array object, various derived objects (such as masked arrays and matrices), and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation and much more. At the core of the NumPy package, is the ndarray object. This encapsulates n-dimensional arrays of homogeneous data types, with many operations being performed in compiled code for performance. There are several important differences between NumPy arrays and the standard Python sequences: • NumPy arrays have a fixed size at creation, unlike Python lists (which can grow dynamically). Changing the size of an ndarray will create a new array and delete the original.
    [Show full text]