The Wayback Machine - https://web.archive.org/web/20241119213427/https://www.geeksforgeeks.org/learning-model-building-scikit-learn-python-machine-learning-library/
Open In App

Learning Model Building in Scikit-learn

Last Updated : 04 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Scikit-learn has emerged as a powerful and user-friendly Python library. Its simplicity and versatility make it a better choice for both beginners and seasoned data scientists to build and implement machine learning models. In this article, we will explore about Sklearn.

Pre-requisite: Getting started with machine learning 

What is Scikit-learn?

Scikit-learn is an open-source Python library that implements a range of machine learning, pre-processing, cross-validation, and visualization algorithms using a unified interface. It is an open-source machine-learning library that provides a plethora of tools for various machine-learning tasks such as Classification, Regression, Clustering, and many more.

Installation of Scikit- learn

The latest version of Scikit-learn is 1.1 and it requires Python 3.8 or newer.

Scikit-learn requires:  

  • NumPy
  • SciPy as its dependencies.

Before installing scikit-learn, ensure that you have NumPy and SciPy installed. Once you have a working installation of NumPy and SciPy, the easiest way to install scikit-learn is using pip: 

!pip install -U scikit-learn

Let us get started with the modeling process now.

Step 1: Load a Dataset

A dataset is nothing but a collection of data. A dataset generally has two main components: 

  • Features: (also known as predictors, inputs, or attributes) they are simply the variables of our data. They can be more than one and hence represented by a feature matrix (‘X’ is a common notation to represent feature matrix). A list of all the feature names is termed feature names.
  • Response: (also known as the target, label, or output) This is the output variable depending on the feature variables. We generally have a single response column and it is represented by a response vector (‘y’ is a common notation to represent response vector). All the possible values taken by a response vector are termed target names.

Loading exemplar dataset: scikit-learn comes loaded with a few example datasets like the iris and digits datasets for classification and the boston house prices dataset for regression. 

Given below is an example of how one can load an exemplar dataset: 

Python
# load the iris dataset as an example 
from sklearn.datasets import load_iris 
iris = load_iris() 
  
# store the feature matrix (X) and response vector (y) 
X = iris.data 
y = iris.target 
  
# store the feature and target names 
feature_names = iris.feature_names 
target_names = iris.target_names 
  
# printing features and target names of our dataset 
print("Feature names:", feature_names) 
print("Target names:", target_names) 
  
# X and y are numpy arrays 
print("\nType of X is:", type(X)) 
  
# printing first 5 input rows 
print("\nFirst 5 rows of X:\n", X[:5])

Output: 

Feature names: ['sepal length (cm)','sepal width (cm)',
'petal length (cm)','petal width (cm)']
Target names: ['setosa' 'versicolor' 'virginica']
Type of X is:
First 5 rows of X:
[[ 5.1 3.5 1.4 0.2]
[ 4.9 3. 1.4 0.2]
[ 4.7 3.2 1.3 0.2]
[ 4.6 3.1 1.5 0.2]
[ 5. 3.6 1.4 0.2]]

Loading external dataset: Now, consider the case when we want to load an external dataset. For this purpose, we can use the pandas library for easily loading and manipulating datasets.

To install pandas, use the following pip command:  

! pip install pandas

In pandas, important data types are:

  • Series: Series is a one-dimensional labeled array capable of holding any data type.
  • DataFramet: is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object.

Note: The CSV file used in the example below can be downloaded from here: weather.csv

Python
import pandas as pd 
  
# reading csv file 
data = pd.read_csv('weather.csv') 
  
# shape of dataset 
print("Shape:", data.shape) 
  
# column names 
print("\nFeatures:", data.columns) 
  
# storing the feature matrix (X) and response vector (y) 
X = data[data.columns[:-1]] 
y = data[data.columns[-1]] 
  
# printing first 5 rows of feature matrix 
print("\nFeature matrix:\n", X.head()) 
  
# printing first 5 values of response vector 
print("\nResponse vector:\n", y.head())

Output: 

Shape: (366, 22)
Features: Index(['MinTemp', 'MaxTemp', 'Rainfall', 'Evaporation', 'Sunshine',
'WindGustDir', 'WindGustSpeed', 'WindDir9am', 'WindDir3pm',
'WindSpeed9am', 'WindSpeed3pm', 'Humidity9am', 'Humidity3pm',
'Pressure9am', 'Pressure3pm', 'Cloud9am', 'Cloud3pm', 'Temp9am',
'Temp3pm', 'RainToday', 'RISK_MM', 'RainTomorrow'],
dtype='object')
Feature matrix:
MinTemp MaxTemp Rainfall Evaporation Sunshine WindGustDir \
0 8.0 24.3 0.0 3.4 6.3 NW
1 14.0 26.9 3.6 4.4 9.7 ENE
2 13.7 23.4 3.6 5.8 3.3 NW
3 13.3 15.5 39.8 7.2 9.1 NW
4 7.6 16.1 2.8 5.6 10.6 SSE
WindGustSpeed WindDir9am WindDir3pm WindSpeed9am ... Humidity9am \
0 30.0 SW NW 6.0 ... 68
1 39.0 E W 4.0 ... 80
2 85.0 N NNE 6.0 ... 82
3 54.0 WNW W 30.0 ... 62
4 50.0 SSE ESE 20.0 ... 68
Humidity3pm Pressure9am Pressure3pm Cloud9am Cloud3pm Temp9am \
0 29 1019.7 1015.0 7 7 14.4
1 36 1012.4 1008.4 5 3 17.5
2 69 1009.5 1007.2 8 7 15.4
3 56 1005.5 1007.0 2 7 13.5
4 49 1018.3 1018.5 7 7 11.1
Temp3pm RainToday RISK_MM
0 23.6 No 3.6
1 25.7 Yes 3.6
2 20.2 Yes 39.8
3 14.1 Yes 2.8
4 15.4 Yes 0.0
[5 rows x 21 columns]
Response vector:
0 Yes
1 Yes
2 Yes
3 Yes
4 No
Name: RainTomorrow, dtype: object

Step 2: Splitting the Dataset

One important aspect of all machine learning models is to determine their accuracy. Now, in order to determine their accuracy, one can train the model using the given dataset and then predict the response values for the same dataset using that model and hence, find the accuracy of the model. 
But this method has several flaws in it, like: 

  • The goal is to estimate the likely performance of a model on out-of-sample data.
  • Maximizing training accuracy rewards overly complex models that won’t necessarily generalize our model.
  • Unnecessarily complex models may over-fit the training data.

A better option is to split our data into two parts: the first one for training our machine learning model, and the second one for testing our model. 

To summarize

  • Split the dataset into two pieces: a training set and a testing set.
  • Train the model on the training set.
  • Test the model on the testing set and evaluate how well our model did.

Advantages of train/test split

  • The model can be trained and tested on different data than the one used for training.
  • Response values are known for the test dataset; hence predictions can be evaluated.
  • Testing accuracy is a better estimate than training accuracy of out-of-sample performance.

Consider the example below: 

Python
# load the iris dataset as an example
from sklearn.datasets import load_iris
iris = load_iris()

# store the feature matrix (X) and response vector (y)
X = iris.data
y = iris.target

# splitting X and y into training and testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1)

# printing the shapes of the new X objects
print("X_train Shape:",  X_train.shape)
print("X_test Shape:", X_test.shape)

# printing the shapes of the new y objects
print("Y_train Shape:", y_train.shape)
print("Y_test Shape: ",y_test.shape)

Output: 

X_train Shape: (90, 4)
X_test Shape: (60, 4)
Y_train Shape: (90,)
Y_test Shape: (60,)

The train_test_split function takes several arguments which are explained below:  

  • X, y: These are the feature matrix and response vector which need to be split.
  • test_size: It is the ratio of test data to the given data. For example, setting test_size = 0.4 for 150 rows of X produces test data of 150 x 0.4 = 60 rows.
  • random_state: If you use random_state = some_number, then you can guarantee that your split will be always the same. This is useful if you want reproducible results, for example in testing for consistency in the documentation (so that everybody can see the same numbers).

Step 3: Training the Model

Now, it’s time to train some prediction models using our dataset. Scikit-learn provides a wide range of machine learning algorithms that have a unified/consistent interface for fitting, predicting accuracy, etc.
The example given below uses KNN (K nearest neighbors) classifier.

Note: We will not go into the details of how the algorithm works as we are interested in understanding its implementation only. 

Now, consider the example below: 

Python
# load the iris dataset as an example
from sklearn.datasets import load_iris
iris = load_iris()

# store the feature matrix (X) and response vector (y)
X = iris.data
y = iris.target

# splitting X and y into training and testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1)

# training the model on training set
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)

# making predictions on the testing set
y_pred = knn.predict(X_test)

# comparing actual response values (y_test) with predicted response values (y_pred)
from sklearn import metrics
print("KNN model accuracy", metrics.accuracy_score(y_test, y_pred))

# making prediction for out of sample data
sample = [[3, 5, 4, 2], [2, 3, 5, 4]]
preds = knn.predict(sample)
pred_species = [iris.target_names[p] for p in preds]
print("Predictions", pred_species)

Output: 

kNN model accuracy: 0.983333333333
Predictions: ['versicolor', 'virginica']

Important points to note from the above code:  

  • We create a knn classifier object using: 
 knn = KNeighborsClassifier(n_neighbors=3)
  • The classifier is trained using X_train data. The process is termed fitting. We pass the feature matrix and the corresponding response vector. 
 knn.fit(X_train, y_train)
  • Now, we need to test our classifier on the X_test data. knn.predict method is used for this purpose. It returns the predicted response vector, y_pred. 
 y_pred = knn.predict(X_test)
  • Now, we are interested in finding the accuracy of our model by comparing y_test and y_pred. This is done using the metrics module’s method accuracy_score: 
print(metrics.accuracy_score(y_test, y_pred))
  • Consider the case when you want your model to make predictions out of sample data. Then, the sample input can simply be passed in the same way as we pass any feature matrix. 
sample = [[3, 5, 4, 2], [2, 3, 5, 4]]
preds = knn.predict(sample)

Features of Scikit-learn

  • Simple and efficient tools for data mining and data analysis. It features various classification, regression, and clustering algorithms including support vector machines, random forests, gradient boosting, k-means, etc.
  • Accessible to everybody and reusable in various contexts.
  • Built on the top of NumPy, SciPy, and matplotlib.
  • Open source, commercially usable – BSD license.

Benefits of using Scikit-learn Libraries

  • Consistent interface to machine learning models
  • Provides many tuning parameters but with sensible defaults.
  • Exceptional documentation
  • Rich set of functionalities for companion tasks.
  • Active community for development and support.

Conclusion

Scikit-learn stands as stone in the field of machine learning, providing a straightforward yet powerful toolset for building and deploying models. Whether you are a beginner explore the basics or an experienced data scientist tackle complex problems.  



Similar Reads

Building a Custom Estimator for Scikit-learn: A Comprehensive Guide
Scikit-learn is a powerful machine learning library in Python that offers a wide range of tools for data analysis and modeling. One of its best features is the ease with which you can create custom estimators, allowing you to meet specific needs. In this article, we will walk through the process of building a custom estimator in Scikit-learn, compl
5 min read
Building and Implementing Decision Tree Classifiers with Scikit-Learn: A Comprehensive Guide
A decision tree classifier is a well-liked and adaptable machine learning approach for classification applications. It creates a model in the shape of a tree structure, with each internal node standing in for a "decision" based on a feature, each branch for the decision's result, and each leaf node for a regression value or class label. Decision tr
10 min read
Passing Parameters to Scikit-Learn Keras Model Functions
Scikit-Learn and Keras are two powerful libraries in Python that are widely used for machine learning and deep learning tasks. Scikit-Learn provides a variety of tools for model selection, data preprocessing, and model evaluation, while Keras offers a simple and intuitive interface for building deep learning models. Combining these libraries allows
4 min read
Save and Load Machine Learning Models in Python with scikit-learn
In this article, let's learn how to save and load your machine learning model in Python with scikit-learn in this tutorial. Once we create a machine learning model, our job doesn't end there. We can save the model to use in the future. We can either use the pickle or the joblib library for this purpose. The dump method is used to create the model a
4 min read
Compare Stochastic Learning Strategies for MLPClassifier in Scikit Learn
A stochastic learning strategy is a method for training a Machine Learning model using stochastic optimization algorithms. These algorithms update the model's weights and biases using a randomly selected subset of the training data, rather than using the entire dataset. This can improve convergence speed and help avoid local minima What is MLPClass
5 min read
Comparison of Manifold Learning methods in Scikit Learn
In machine learning, manifold learning is crucial in order to overcome the challenges posed by high-dimensional and non-linear data. Reducing the amount of features in a dataset is done using the dimensionality reduction technique. When working with high-dimensional data, where each data point has a number of properties, it is extremely useful. A d
4 min read
Image Denoising using Dictionary Learning in Scikit Learn
Scikit-learn's image denoising technique uses dictionary learning to represent the image as a sparse combination of elements from a dictionary, which helps to reduce the amount of noise in the image. The compressed version of the image is represented by the dictionary, which is a set of basis vectors. The noise is subsequently eliminated by setting
6 min read
Identifying Overfitting in Machine Learning Models Using Scikit-Learn
Overfitting is a critical issue in machine learning that can significantly impact the performance of models when applied to new, unseen data. Identifying overfitting in machine learning models is crucial to ensuring their performance generalizes well to unseen data. In this article, we'll explore how to identify overfitting in machine learning mode
7 min read
Building a Machine Learning Model Using J48 Classifier
What is the J48 Classifier? J48 is a machine learning decision tree classification algorithm based on Iterative Dichotomiser 3. It is very helpful in examine the data categorically and continuously. Note: To build our J48 machine learning model we’ll use the weka tool. What is Weka? Weka is an open-source tool developed by the University of Waikato
3 min read
Data Preprocessing, Analysis, and Visualization for building a Machine learning model
In this article, we are going to see the concept of Data Preprocessing, Analysis, and Visualization for building a Machine learning model. Business owners and organizations use Machine Learning models to predict their Business growth. But before applying machine learning models, the dataset needs to be preprocessed. So, let's import the data and st
5 min read
Building Your First Machine Learning Model
Today, we're exploring a comprehensive guide to building a wine quality prediction model using some of the most powerful tools and libraries available in Python. Whether you're a beginner looking to understand the basics or an experienced data scientist aiming to refine your skills, this guide has something for everyone. In this tutorial, we'll wal
5 min read
Map Data to a Normal Distribution in Scikit Learn
A Normal Distribution, also known as a Gaussian distribution, is a continuous probability distribution that is symmetrical around its mean. It is defined by its norm, which is the center of the distribution, and its standard deviation, which is a measure of the spread of the distribution. The normal distribution is often used to model continuous an
5 min read
ML | Implement Face recognition using k-NN with scikit-learn
k-Nearest Neighbors: k-NN is one of the most basic classification algorithms in machine learning. It belongs to the supervised learning category of machine learning. k-NN is often used in search applications where you are looking for “similar” items. The way we measure similarity is by creating a vector representation of the items, and then compare
5 min read
Implementing PCA in Python with scikit-learn
In this article, we will learn about PCA (Principal Component Analysis) in Python with scikit-learn. Let's start our learning step by step. WHY PCA? When there are many input attributes, it is difficult to visualize the data. There is a very famous term ‘Curse of dimensionality in the machine learning domain.Basically, it refers to the fact that a
4 min read
Probability Calibration for 3-class Classification in Scikit Learn
Probability calibration is a technique to map the predicted probabilities of a model to their true probabilities. The probabilities predicted by some classification algorithms like Logistic Regression, SVM, or Random Forest may not be well calibrated, meaning they may not accurately reflect the true probabilities of the target classes. This can lea
4 min read
Pipelines - Python and scikit-learn
The workflow of any machine learning project includes all the steps required to build it. A proper ML project consists of basically four main parts are given as follows: Gathering data: The process of gathering data depends on the project it can be real-time data or the data collected from various sources such as a file, database, survey and other
4 min read
How To Create/Customize Your Own Scorer Function In Scikit-Learn?
A well-known Python machine learning toolkit called Scikit-learn provides a variety of machine learning tools and methods to assist programmers in creating sophisticated machine learning models. A strong framework for assessing the effectiveness of these models using a variety of metrics and scoring functions is also offered by Scikit-learn. To ass
4 min read
Clustering Performance Evaluation in Scikit Learn
In this article, we shall look at different approaches to evaluate Clustering Algorithms using Scikit Learn Python Machine Learning Library. Clustering is an Unsupervised Machine Learning algorithm that deals with grouping the dataset to its similar kind data point. Clustering is widely used for Segmentation, Pattern Finding, Search engine, and so
3 min read
Ledoit-Wolf vs OAS Estimation in Scikit Learn
Generally, Shrinkage is used to regularize the usual covariance maximum likelihood estimation. Ledoit and Wolf proposed a formula which is known as the Ledoit-Wolf covariance estimation formula; This close formula can compute the asymptotically optimal shrinkage parameter with minimizing a Mean Square Error(MSE) criterion feature. After that, one r
4 min read
SVM with Univariate Feature Selection in Scikit Learn
Support Vector Machines (SVM) is a powerful machine learning algorithm used for classification and regression analysis. It is based on the idea of finding the optimal boundary between two classes that maximizes the margin between them. However, the challenge with SVM is that it requires a large amount of computational power and is sensitive to the
10 min read
How to Install Scikit-Learn on Linux?
In this article, we are going to see how to install Scikit-Learn on Linux. Scikit-Learn is a python open source library for predictive data analysis. It is built on NumPy, SciPy, and matplotlib. It is written in Python, Cython, C, and C++ language. It is available for Linux, Unix, Windows, and Mac. Method 1: Installing Scikit-Learn from source Step
2 min read
How to Install Scikit-Learn on MacOS?
In this article, we will learn how to install Scikit-Learn in Python on MacOS. The scikit-learn is a Python module for machine learning built on top of SciPy and is distributed under the 3-Clause BSD license. Installation:Method 1: Using pip to install Scikit-Learn Package Follow the below steps to install the Scikit-Learn package on macOS using pi
2 min read
Isotonic Regression in Scikit Learn
Isotonic regression is a regression technique in which the predictor variable is monotonically related to the target variable. This means that as the value of the predictor variable increases, the value of the target variable either increases or decreases in a consistent, non-oscillating manner. Mathematically, isotonic regression can be formulated
6 min read
Clustering Text Documents using K-Means in Scikit Learn
Clustering text documents is a typical issue in natural language processing (NLP). Based on their content, related documents are to be grouped. The k-means clustering technique is a well-liked solution to this issue. In this article, we'll demonstrate how to cluster text documents using k-means using Scikit Learn. K-means clustering algorithm The k
2 min read
Create a Scatter Plot using Sepal length and Petal_width to Separate the Species Classes Using scikit-learn
In this article, we are going to see how to create Scatter Plot using Sepal length and Petal_width to Separate the Species classes using scikit-learn in Python. The Iris Dataset contains 50 samples of three Iris species with four characteristics (length and width of sepals and petals). Iris setosa, Iris virginica, and Iris versicolor are the three
2 min read
Save classifier to disk in scikit-learn in Python
In this article, we will cover saving a Save classifier to disk in scikit-learn using Python. We always train our models whether they are classifiers, regressors, etc. with the scikit learn library which require a considerable time to train. So we can save our trained models and then retrieve them when required. This saves us a lot of time. Seriali
3 min read
Joint Feature Selection with multi-task Lasso in Scikit Learn
This article is likely to introduces the concepts of Lasso and multitask Lasso regression and demonstrates how to implement these methods in Python using the scikit-learn library. The article is going to cover the differences between Lasso and multitask Lasso and provide guidance on which method to prefer in different situations. It may also provid
7 min read
Multiple Linear Regression With scikit-learn
In this article, let's learn about multiple linear regression using scikit-learn in the Python programming language. Regression is a statistical method for determining the relationship between features and an outcome variable or result. Machine learning, it's utilized as a method for predictive modeling, in which an algorithm is employed to forecas
8 min read
Classifier Comparison in Scikit Learn
In scikit-learn, a classifier is an estimator that is used to predict the label or class of an input sample. There are many different types of classifiers that can be used in scikit-learn, each with its own strengths and weaknesses. Let's load the iris datasets from the sklearn.datasets and then train different types of classifier using it. C/C++ C
3 min read
How to Extract the Decision Rules from scikit-learn Decision-tree?
You might have already learned how to build a Decision-Tree Classifier, but might be wondering how the scikit-learn actually does that. So, in this article, we will cover this in a step-by-step manner. You can run the code in sequence, for better understanding. Decision-Tree uses tree-splitting criteria for splitting the nodes into sub-nodes until
4 min read
three90RightbarBannerImg