The Wayback Machine - https://web.archive.org/web/20240930195542/https://www.geeksforgeeks.org/best-python-libraries-for-machine-learning/
Open In App

Best Python libraries for Machine Learning

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

Machine Learning, as the name suggests, is the science of programming a computer by which they are able to learn from different kinds of data. A more general definition given by Arthur Samuel is – “Machine Learning is the field of study that gives computers the ability to learn without being explicitly programmed.” They are typically used to solve various types of life problems. 

In the older days, people used to perform Machine Learning tasks by manually coding all the algorithms and mathematical and statistical formulas. This made the processing time-consuming, tedious, and inefficient. But in the modern days, it is become very much easy and more efficient compared to the older days with various python libraries, frameworks, and modules. Today, Python is one of the most popular programming languages for this task and it has replaced many languages in the industry, one of the reasons is its vast collection of libraries. Python libraries that are used in Machine Learning are: 
 

  • Numpy
  • Scipy
  • Scikit-learn
  • Theano
  • TensorFlow
  • Keras
  • PyTorch
  • Pandas
  • Matplotlib


 

Numpy


 


NumPy is a very popular python library for large multi-dimensional array and matrix processing, with the help of a large collection of high-level mathematical functions. It is very useful for fundamental scientific computations in Machine Learning. It is particularly useful for linear algebra, Fourier transform, and random number capabilities. High-end libraries like TensorFlow uses NumPy internally for manipulation of Tensors. 
 

Python3
# Python program using NumPy 
# for some basic mathematical 
# operations

import numpy as np

# Creating two arrays of rank 2
x = np.array([[1, 2], [3, 4]])
y = np.array([[5, 6], [7, 8]])

# Creating two arrays of rank 1
v = np.array([9, 10])
w = np.array([11, 12])

# Inner product of vectors
print(np.dot(v, w), "\n")

# Matrix and Vector product
print(np.dot(x, v), "\n")

# Matrix and matrix product
print(np.dot(x, y))

Output: 
 

219 

[29 67]

[[19 22]
[43 50]]


For more details refer to Numpy. 
  
 

SciPy

SciPy is a very popular library among Machine Learning enthusiasts as it contains different modules for optimization, linear algebra, integration and statistics. There is a difference between the SciPy library and the SciPy stack. The SciPy is one of the core packages that make up the SciPy stack. SciPy is also very useful for image manipulation.  

Python3
# Python script using Scipy 
# for image manipulation

from scipy.misc import imread, imsave, imresize

# Read a JPEG image into a numpy array
img = imread('D:/Programs / cat.jpg') # path of the image
print(img.dtype, img.shape)

# Tinting the image
img_tint = img * [1, 0.45, 0.3]

# Saving the tinted image
imsave('D:/Programs / cat_tinted.jpg', img_tint)

# Resizing the tinted image to be 300 x 300 pixels
img_tint_resize = imresize(img_tint, (300, 300))

# Saving the resized tinted image
imsave('D:/Programs / cat_tinted_resized.jpg', img_tint_resize)

If scipy.misc import imread, imsave,imresize does not work on your operating system then try below code instead to proceed with above code 

!pip install imageio
import imageio
from imageio import imread, imsave

Original image: 


Tinted image: 
 


Resized tinted image: 
 

resized_tinted_image


For more details refer to documentation. 
  
 

Scikit-learn


 


Scikit-learn is one of the most popular ML libraries for classical ML algorithms. It is built on top of two basic Python libraries, viz., NumPy and SciPy. Scikit-learn supports most of the supervised and unsupervised learning algorithms. Scikit-learn can also be used for data-mining and data-analysis, which makes it a great tool who is starting out with ML. 
 

Python3
# Python script using Scikit-learn 
# for Decision Tree Classifier

# Sample Decision Tree Classifier
from sklearn import datasets
from sklearn import metrics
from sklearn.tree import DecisionTreeClassifier

# load the iris datasets
dataset = datasets.load_iris()

# fit a CART model to the data
model = DecisionTreeClassifier()
model.fit(dataset.data, dataset.target)
print(model)

# make predictions
expected = dataset.target
predicted = model.predict(dataset.data)

# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))

Output: 
 

DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
max_features=None, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, presort=False, random_state=None,
splitter='best')
precision recall f1-score support

0 1.00 1.00 1.00 50
1 1.00 1.00 1.00 50
2 1.00 1.00 1.00 50

micro avg 1.00 1.00 1.00 150
macro avg 1.00 1.00 1.00 150
weighted avg 1.00 1.00 1.00 150

[[50 0 0]
[ 0 50 0]
[ 0 0 50]]


  
For more details refer to documentation. 
  
 

Theano


 


We all know that Machine Learning is basically mathematics and statistics. Theano is a popular python library that is used to define, evaluate and optimize mathematical expressions involving multi-dimensional arrays in an efficient manner. It is achieved by optimizing the utilization of CPU and GPU. It is extensively used for unit-testing and self-verification to detect and diagnose different types of errors. Theano is a very powerful library that has been used in large-scale computationally intensive scientific projects for a long time but is simple and approachable enough to be used by individuals for their own projects. 
 

Python3
# Python program using Theano
# for computing a Logistic 
# Function

import theano
import theano.tensor as T
x = T.dmatrix('x')
s = 1 / (1 + T.exp(-x))
logistic = theano.function([x], s)
logistic([[0, 1], [-1, -2]])

Output: 
 

array([[0.5, 0.73105858],
[0.26894142, 0.11920292]])


For more details refer to documentation. 
  
 

TensorFlow

TensorFlow is a very popular open-source library for high performance numerical computation developed by the Google Brain team in Google. As the name suggests, Tensorflow is a framework that involves defining and running computations involving tensors. It can train and run deep neural networks that can be used to develop several AI applications. TensorFlow is widely used in the field of deep learning research and application. 

Example 

Python3
#  Python program using TensorFlow
#  for multiplying two arrays

# import `tensorflow` 
import tensorflow as tf

# Initialize two constants
x1 = tf.constant([1, 2, 3, 4])
x2 = tf.constant([5, 6, 7, 8])

# Multiply
result = tf.multiply(x1, x2)

# Initialize the Session
sess = tf.Session()

# Print the result
print(sess.run(result))

# Close the session
sess.close()

Output: 
 

[ 5 12 21 32]

For more details refer to documentation.   

Keras

 

It provides many inbuilt methods for groping, combining and filtering data.

Keras is a very popular Machine Learning library for Python. It is a high-level neural networks API capable of running on top of TensorFlow, CNTK, or Theano. It can run seamlessly on both CPU and GPU. Keras makes it really for ML beginners to build and design a Neural Network. One of the best thing about Keras is that it allows for easy and fast prototyping.

For more details refer to documentation.   

PyTorch

PyTorch is a popular open-source Machine Learning library for Python based on Torch, which is an open-source Machine Learning library that is implemented in C with a wrapper in Lua. It has an extensive choice of tools and libraries that support Computer Vision, Natural Language Processing(NLP), and many more ML programs. It allows developers to perform computations on Tensors with GPU acceleration and also helps in creating computational graphs. 

Example

Python3
# Python program using PyTorch
# for defining tensors fit a
# two-layer network to random
# data and calculating the loss

import torch


dtype = torch.float
device = torch.device("cpu")
# device = torch.device("cuda:0") Uncomment this to run on GPU

# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10

# Create random input and output data
x = torch.random(N, D_in, device=device, dtype=dtype)
y = torch.random(N, D_out, device=device, dtype=dtype)

# Randomly initialize weights
w1 = torch.random(D_in, H, device=device, dtype=dtype)
w2 = torch.random(H, D_out, device=device, dtype=dtype)

learning_rate = 1e-6
for t in range(500):
    # Forward pass: compute predicted y
    h = x.mm(w1)
    h_relu = h.clamp(min=0)
    y_pred = h_relu.mm(w2)

    # Compute and print loss
    loss = (y_pred - y).pow(2).sum().item()
    print(t, loss)

    # Backprop to compute gradients of w1 and w2 with respect to loss
    grad_y_pred = 2.0 * (y_pred - y)
    grad_w2 = h_relu.t().mm(grad_y_pred)
    grad_h_relu = grad_y_pred.mm(w2.t())
    grad_h = grad_h_relu.clone()
    grad_h[h < 0] = 0
    grad_w1 = x.t().mm(grad_h)

    # Update weights using gradient descent
    w1 -= learning_rate * grad_w1
    w2 -= learning_rate * grad_w2

Output: 
 

0 47168344.0
1 46385584.0
2 43153576.0
...
...
...
497 3.987660602433607e-05
498 3.945609932998195e-05
499 3.897604619851336e-05

For more details refer to the documentation. 

Pandas 

Pandas is a popular Python library for data analysis. It is not directly related to Machine Learning. As we know that the dataset must be prepared before training. In this case, Pandas comes handy as it was developed specifically for data extraction and preparation. It provides high-level data structures and wide variety tools for data analysis. It provides many inbuilt methods for grouping, combining and filtering data.

Python3
# Python program using Pandas for 
# arranging a given set of data 
# into a  table

# importing pandas as pd
import pandas as pd

data = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],
       "capital": ["Brasilia", "Moscow", "New Delhi", "Beijing", "Pretoria"],
       "area": [8.516, 17.10, 3.286, 9.597, 1.221],
       "population": [200.4, 143.5, 1252, 1357, 52.98] }

data_table = pd.DataFrame(data)
print(data_table)

Output: 

For more details refer to Pandas.    

Matplotlib
 

matplotlibLogo


Matplotlib is a very popular Python library for data visualization. Like Pandas, it is not directly related to Machine Learning. It particularly comes in handy when a programmer wants to visualize the patterns in the data. It is a 2D plotting library used for creating 2D graphs and plots. A module named pyplot makes it easy for programmers for plotting as it provides features to control line styles, font properties, formatting axes, etc. It provides various kinds of graphs and plots for data visualization, viz., histogram, error charts, bar chats, etc, 
 

Python3
#  Python program using Matplotlib 
# for forming a linear plot

# importing the necessary packages and modules
import matplotlib.pyplot as plt
import numpy as np

# Prepare the data
x = np.linspace(0, 10, 100)

# Plot the data
plt.plot(x, x, label ='linear')

# Add a legend
plt.legend()

# Show the plot
plt.show()

Output: 
 

linear_plot


For more details refer to documentation.



Previous Article
Next Article

Similar Reads

Getting started with Machine Learning || Machine Learning Roadmap
Machine Learning (ML) represents a branch of artificial intelligence (AI) focused on enabling systems to learn from data, uncover patterns, and autonomously make decisions. In today's era dominated by data, ML is transforming industries ranging from healthcare to finance, offering robust tools for predictive analytics, automation, and informed deci
11 min read
Top 10 Javascript Libraries for Machine Learning and Data Science
JavaScript is the programming language of the web which makes it pretty important! However, it has mostly been used as a scripting language in web development without much association with Machine Learning or Data Science as compared to R and Python. That's because R and Python are specifically suited to Data Science or ML with a large collection o
6 min read
Top 5 Programming Languages and their Libraries for Machine Learning in 2020
If you are a newbie in machine learning you may have thought that what programming language should I learn? Nowadays different people are working with different programming languages but among these many popular high-level programming languages, which one is the best for machine learning? Machine Learning is one of the fastest-growing fields which
6 min read
Java libraries for machine learning
Java, known for its robustness and performance, is a powerful choice for implementing machine learning (ML) solutions. Although Python is widely recognized for its dominance in the ML field, Java offers a variety of libraries that are well-suited for different machine learning tasks. Table of Content Overview of Java Machine Learning LibrariesWeka:
5 min read
C++ Libraries for Machine Learning
Machine learning (ML) has significantly transformed various industries by enabling systems to learn from data and make predictions. While Python is often the go-to language for ML due to its extensive libraries and ease of use, C++ is increasingly gaining attention for ML applications. C++ offers superior performance and fine-grained control over s
5 min read
Support vector machine in Machine Learning
In this article, we are going to discuss the support vector machine in machine learning. We will also cover the advantages and disadvantages and application for the same. Let's discuss them one by one. Support Vector Machines : Support vector machine is a supervised learning system and is used for classification and regression problems. Support vec
9 min read
Azure Virtual Machine for Machine Learning
Prerequisites: About Microsoft Azure, Cloud Based Services Some of the Machine Learning and Deep Learning algorithms may require high computation power which may not be supported by your local machine or laptop. In that case, creating a Virtual Machine on a cloud platform can provide you the expected computation power. We can have a system with hig
4 min read
Machine Learning Model with Teachable Machine
Teachable Machine is a web-based tool developed by Google that allows users to train their own machine learning models without any coding experience. It uses a web camera to gather images or videos, and then uses those images to train a machine learning model. The user can then use the model to classify new images or videos. The process of creating
7 min read
Artificial intelligence vs Machine Learning vs Deep Learning
Nowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are related to each other but not the same. Let's see
4 min read
Need of Data Structures and Algorithms for Deep Learning and Machine Learning
Deep Learning is a field that is heavily based on Mathematics and you need to have a good understanding of Data Structures and Algorithms to solve the mathematical problems optimally. Data Structures and Algorithms can be used to determine how a problem is represented internally or how the actual storage pattern works & what is happening under
6 min read
Machine Learning - Learning VS Designing
In this article, we will learn about Learning and Designing and what are the main differences between them. In Machine learning, the term learning refers to any process by which a system improves performance by using experience and past data. It is kind of an iterative process and every time the system gets improved though one may not see a drastic
3 min read
Passive and Active learning in Machine Learning
Machine learning is a subfield of artificial intelligence that deals with the creation of algorithms that can learn and improve themselves without explicit programming. One of the most critical factors that contribute to the success of a machine learning model is the quality and quantity of data used to train it. Passive learning and active learnin
3 min read
Automated Machine Learning for Supervised Learning using R
Automated Machine Learning (AutoML) is an approach that aims to automate various stages of the machine learning process, making it easier for users with limited machine learning expertise to build high-performing models. AutoML is particularly useful in supervised learning, where you have labeled data and want to create models that can make predict
8 min read
Meta-Learning in Machine Learning
Traditional machine learning requires a huge dataset that is specific to a particular task and wishes to train a model for regression or classification purposes using these datasets. That’s radically far from how humans take advantage of their past experiences to learn quickly a new task from only a handset of examples. What is Meta Learning?Meta-l
13 min read
Continual Learning in Machine Learning
As we know Machine Learning (ML) is a subfield of artificial intelligence that specializes in growing algorithms that learn from statistics and make predictions or choices without being explicitly programmed. It has revolutionized many industries by permitting computer systems to understand styles, make tips, and perform tasks that were soon consid
10 min read
Few-shot learning in Machine Learning
What is a Few-shot learning?Few-shot learning is a type of meta-learning process. It is a process in which a model possesses the capability to autonomously acquire knowledge and improve its performance through self-learning. It is a process like teaching the model to recognize things or do tasks, but instead of overwhelming it with a lot of example
8 min read
What Is Meta-Learning in Machine Learning in R
In traditional machine learning, models are typically trained on a specific dataset for a specific task, and their performance is optimized for that particular task. However, in R Programming Language the focus is on building models that can leverage prior knowledge or experience to quickly adapt to new tasks with minimal additional training data.
7 min read
Types of Federated Learning in Machine Learning
Federated Learning is a powerful technique that allow a single machine to learn from many different source and converting the data into small pieces sending them to different Federated Learning (FL) is a decentralized of the machine learning paradigm that can enables to model training across various devices while preserving your data the data priva
5 min read
Machine Learning-based Recommendation Systems for E-learning
In today's digital age, e-learning platforms are transforming education by giving students unprecedented access to a wide range of courses and resources. Machine learning-based recommendation systems have emerged as critical tools for effectively navigating this vast amount of content. The article delves into the role of recommendation systems in e
9 min read
Understanding PAC Learning: Theoretical Foundations and Practical Applications in Machine Learning
In the vast landscape of machine learning, understanding how algorithms learn from data is crucial. Probably Approximately Correct (PAC) learning stands as a cornerstone theory, offering insights into the fundamental question of how much data is needed for learning algorithms to reliably generalize to unseen instances. PAC learning provides a theor
8 min read
One Shot Learning in Machine Learning
One-shot learning is a machine learning paradigm aiming to recognize objects or patterns from a limited number of training examples, often just a single instance. Traditional machine learning models typically require large amounts of labeled data for high performance. Still, one-shot learning seeks to overcome this limitation by enabling models to
7 min read
Difference Between Artificial Intelligence vs Machine Learning vs Deep Learning
Artificial Intelligence is basically the mechanism to incorporate human intelligence into machines through a set of rules(algorithm). AI is a combination of two words: "Artificial" meaning something made by humans or non-natural things and "Intelligence" meaning the ability to understand or think accordingly. Another definition could be that "AI is
14 min read
Difference Between Machine Learning and Deep Learning
If you are interested in building your career in the IT industry then you must have come across the term Data Science which is a booming field in terms of technologies and job availability as well. In this article, we will explore the Difference between Machine Learning and Deep Learning, two major fields within Data Science. Understanding these di
8 min read
AI vs. Machine Learning vs. Deep Learning vs. Neural Networks
Artificial Intelligence (AI), Machine Learning (ML), Deep Learning (DL), and Neural Networks (NN) are terms often used interchangeably. However, they represent different layers of complexity and specialization in the field of intelligent systems. This article will clarify the Difference between AI vs. machine learning vs. deep learning vs. neural n
6 min read
Why is Python the Best-Suited Programming Language for Machine Learning?
Machine Learning is the hottest trend in modern times. According to Forbes, Machine learning patents grew at a 34% rate between 2013 and 2017 and this is only set to increase in the future. And Python is the primary programming language used for much of the research and development in Machine Learning. So much so that Python is the top programming
4 min read
Best Python Web Scraping Libraries in 2024
Python offers several powerful libraries for web scraping, each with its strengths and suitability for different tasks. Whether you're scraping data for research, monitoring, or automation, choosing the right library can significantly affect your productivity and the efficiency of your code. This article explores the Top Python web scraping librari
6 min read
Best Data Science and Machine Learning Platforms in 2024
Data science and Machine learning are two of the current trending technologies. These fields of computer science are evolving rapidly and to stay updated and work in these fields, you need to know about the platforms they work on. There are more than hundreds of platforms for data science and machine learning with new tools and platforms coming eac
11 min read
Best Machine Learning Books for Beginners & Experts [2024]
Alan Turing stated, "What we want is a machine that can learn from experience." And this concept is a reality today in the form of Machine Learning! Generally speaking, Machine Learning involves studying computer algorithms and statistical models for a specific task using patterns and inference instead of explicit instructions. And there is no doub
10 min read
10 Best Databases for Machine Learning and AI [2024]
Machine learning and Artificial Intelligence are the two trending fields in the IT industries that involve a lot of technologies. Hence, databases are the main things which are used in Machine learning and Artificial Intelligence and they serve as a basic foundation for these trending technologies. They also developed their predictive and decision-
7 min read
10 Best Language for Machine Learning
Finding the best programming language for machine learning (ML) is crucial in the ever-changing world of technology and data science. In this article we will look at the Top Programming Languages designed for ML projects, discussing their benefits, available libraries/frameworks, and specific applications. Learning about the distinctive characteris
10 min read