Flat 10% & upto 50% off + 10% Cashback + Free additional Courses. Hurry up
  • Live Instructor-led Classes
  • Expert Education
  • 24*7 Support
  • Flexible Schedule

Python Scikit-Learn Cheat Sheet

If you are finding it hard to remember all the different commands to perform different operations in Scikit Learn then don’t worry, you are not alone, it happens more often than you would think.

At Intellipaat, we make sure that our learners get the best out of our e-learning services and that is exactly why we have come up with this Sklearn Cheat-Sheet to support our learners, in case they need a handy reference to help them get started with Scikit in python training.

This cheat sheet has been designed assuming that you have a basic knowledge of python and machine learning but need a quick reference to turn to when you need to look up the commands in Scikit.

Download the printable PDF of this cheat sheet

Python Scikit-Learn Cheat Sheet

What is Scikit Learn?

Scikit-Learn or “sklearn is a free, open source machine learning library for the Python programming language. It’s simple yet efficient tool for data mining, Data analysis and Machine Learning. It features various machine learning algorithms and also supports Python’s scientific and numerical libraries, that is, SciPy and NumPy respectively. Get back to learn Python for all other topics..

Learn Python in 16 hrs from experts


Import Convention

Before you can start using Scikit-learn, you need to remember that it is a Python library and you need to import it. To do that all you have to do is type the following command:

import sklearn 



The process of converting raw data set into a meaningful and clean data set is referred to as Preprocessing of data. This is a ‘must- follow’ technique before you can feed your data set to a machine learning algorithm. There are mainly three steps that you need to follow while preprocessing the data. The steps are listed below:

1. Data Loading:

You need your data in numeric form stored in numeric arrays. Following are the two ways you can load the data, you can also use some other numeric array to load your data.

  • Using NumPy : >>>import numpy as np
    >>>data = np.loadtxt(‘file-name.csv’, delimiter=’,’)
  • Using Pandas : >>>import pandas as pd

2. Train-Test data:

The next step is to split your data in training data set and testing data set

>>>from sklearn.model-selection import train-test-split
>>>X-train, X-test, y-train, y-test = train-test-split(X,y, random-state=0)

3. Data Preparation:

Standardization: It makes the training process well behaved improving the numerical condition of the optimization problems.

>>>from sklearn.preprocessing import StandardScaler
>>>get-names = df.columns
>>>scaler = preprocessing.StandardScaler()
>>>scaled-df =
>>>scaled-df = pd.DataFrame(scaled-df, columns=get-names)

Normalization: It makes training less sensitive to the scale of features, also makes the data better conditioned for convergence.

>>>from sklearn.preprocessing import Normalizer
>>>x-array = np.array(df[‘Column1’])#Normalize Column1
>>>normalized-X = preprocessing.normalize([x-array])

Wish to Learn Python? Click Here


Working on a model

After making all the necessary transformation in our dataset, in order to make it algorithm-ready, we need to work on our model, that is, choosing a correct model or an algorithm that represents our dataset and will help us make the kind of predictions that we want from our chosen data set and then performing model fitting.

  • Model Choosing:
    • Supervised Learning Estimator:

Supervised learning, as the name suggests, is the kind of machine learning where we supervise the outcome by training the model with well labeled data, which means that some of the data in the dataset will already be tagged with correct answers.

a. Linear Regression:

>>> from sklearn.linear-model import LinearRegression
>>>new-lr = LinearRegression(normalize=True)

b. Support Vector Machine:

>>>from sklearn.svm import SVC
>>>new-svc = SVC(kernel=’linear’)

c. Naive Bayes:

>>>from sklearn.naive-bayes import GaussianNB
>>>new-gnb = GaussianNB()

d. KNN:

>>>from sklearn import neighbors
  • Unsupervised Learning Estimator:

Unlike Supervised learning, unsupervised learning is where we train the model with non labeled data or non classified data and let the algorithm do all the work on that dataset without any assistance.

a. Principal Component Analysis (PCA):

>>>from sklearn.decomposition import PCA
>>>new-pca= PCA(n-components=0.95)

b. K Means:

>>>from sklearn.cluster import KMeans
>>>k-means = KMeans(n-clusters=5, random-state=0)
    • Model Fitting:

The goal of implementing model fitting is to learn how well a model will generalize when trained with a dataset similar to the dataset that the model was initially trained on. The more fitting model will produce more accurate outcomes.

      • Supervised:
>>>new-, y)
>>>, y-train)
>>>, y-train)
      • unSupervised:
>>>pca-model-fit =

Become Python Certified in 16 hrs.



After getting comfortable with our dataset and model, the next step is to finally follow the main goal of machine learning algorithms, that is, to forecast outcomes and make predictions.

    • Prediction:
      Once you are done with choosing and fiting the model, you can make predictions on your dataset.

        • Supervised:
      >>>y-predict = new-svc.predict(np.random.random((3,5)))
      >>>y-predict = new-lr.predict(X-test)
      >>>y-predict = knn.predict-proba(X-test)
        • Unsupervised:
      >>>y-pred = k-means.predict(X-test)
    • Evaluate Performance:
      Evaluating the predictive performance of your model is necessary. There are multiple techniques in machine learning that can be used to organize classifiers and visualize their performance. Following are the said technologies.
  • Classification:

a. Confusion Matrix:

>>> from sklearn.metrics import confusion-matrix
>>>print(confusion-matrix(y-test, y-pred))

b. Accuracy Score

>>>knn.score(X-test, y-test)
>>> from sklearn.metrics import accuracy-score
>>>accuracy-score(y-test, y-pred)
  • Regression:

a. Mean Absolute Error:

>>> from sklearn.metrics import mean-absolute-error
>>>y-true = [3, -0.5, 2]
>>>mean-absolute-error(y-true, y-predict)

b. Mean Squared Error:

>>> from sklearn.metrics import mean-squared-error
>>>mean-squared-error(y-test, y-predict)

c. R² Score

>>> from sklearn.metrics import r2-score>>> r2-score(y-true, y-predict)

  • Clustering:

a. Homogeneity:

>>> from sklearn.metrics import homogeneity-score
>>>homogeneity-score(y-true, y-predict)

b. V-measure:

>>> from sklearn.metrics import v-measure-score
>>>metrics.v-measure-score(y-true, y-predict)

c. Cross-validation:

>>> from sklearn.cross-validation import cross-val-score
>>>print(cross-val-score(knn, X-train, y-train, cv=4))
>>>print(cross-val-score(new-lr, X, y, cv=2))
  • Model Tuning:
    This is the final step when implementing machine learning, before presenting the final outcomes. In Model tuning, models are parameterized so their behavior is tuned for a given problem. This is done by searching for the right set of parameters and we have mainly two ways of doing that:

      • Grid Search:

    In Grid search, parameter tuning is done methodically and then it evaluates model for each set of parameter that is specified in a grid.

>>> from sklearn.grid-search import GridSearchCV
>>>params = {“n-neighbors”: np.arange(1,3), “metric”: [“euclidean”, “cityblock”]}
>>> grid = GridSearchCV(estimator=knn, param-grid=params)
>>>, y-train)
>>> print(
>>> print(
    • Randomized Parameter Optimization:

In Randomised Search, random search is performed on a fixed set of parameters. The number of parameters that are used is given by n-iter.

>>> from sklearn.grid-search import RandomizedSearchCV
>>>params = {“n-neighbors”: range(1,5), “weights”: [“uniform”, “distance”]}
>>>rsearch = RandomizedSearchCV(estimator=knn, param-distributions=params,cv=4,n-iter=8, random-state=5)
>>>, y-train)
>>> print(


Download a Printable PDF of this Cheat Sheet

With this, comes the end of this Sklearn cheat sheet. You can enroll for Python Certification Training provided by Intellipaat for detailed and in-depth knowledge. This training program will guide you step by step will provide you with all the right set of skills to master one of the most popular and widely used language, Python. Not only that, you will also gain knowledge on all the important libraries and modules in python such as, like SciPy, NumPy, MatPlotLib,Scikit-learn, Pandas, Lambda function and more. Also, Intellipaat will assist you with free python interview questions by experts. You will have 24*7 technical support and assistance from the experts in respective technologies here at intellipaat throughout the certification period.

Previous Next

Download Interview Questions asked by top MNCs in 2018?

Learn SQL in 16 hrs from experts

"0 Responses on Scikit-Learn Cheat Sheet"

Leave a Message

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

Sales Offer

Sign Up or Login to view the Free Scikit-Learn Cheat Sheet.