Machine Learning
University of Engineering and Technology
Taxila-Electrical Engineering Department
Name of student: ABDULLAH IBRAHIM
Registration No: 22-EE-73
Section/Group: A1
Date of Experiment:
Marks obtained: …………………………
Remarks: ………………………………….
Instructor’s signature: …………………
Prepared By: Dr. Mamoona Khalid
Machine Learning
University of Engineering and Technology
Taxila-Electrical Engineering Department
LAB # 01: Introduction to Machine Learning and Python Basics
(PLO 4, 5 and 10)
Name of student: ABDULLAH IBRAHIM
Registration No: 22-EE-73
Section/Group: A1
Date of Experiment:
Marks obtained: …………………………
Remarks: ………………………………….
Instructor’s signature: …………………
Prepared By: Dr. Mamoona Khalid
Machine Learning
Objective:
• Understand the basics of machine learning (ML) and its applications in electrical engineering.
• Set up the Python environment and get familiar with basic Python syntax.
Introduction to Machine Learning
Definition: Machine Learning is a subset of artificial intelligence that involves the use of
algorithms to learn patterns from data and make predictions or decisions without being explicitly
programmed.
Types of Machine Learning:
• Supervised Learning: Learning from labeled data (e.g., linear regression).
• Unsupervised Learning: Finding hidden patterns in unlabeled data (e.g., clustering).
• Reinforcement Learning: Learning by interacting with an environment to maximize a reward
(e.g., robotics).
Steps involved: Import data > Clean data > Split the data into training and testing sets > Create a model
> Train the model > Make prediction > Evaluate and improve.
Student notes: Comments on types of ML:
Supervised learning: In supervised learning, the training data you feed to the algorithm includes the
desired solutions, called labels. A typical supervised learning task is classification. The spam filter is a
good example of supervised learning.
Unsupervised learning: In unsupervised learning, as you might guess, the training data is unlabeled. The
System tries to learn without a teacher. Visualization algorithms are also good examples of unsupervised
learning algorithms.
Reinforcement Learning: Reinforcement Learning is a very different beast. The learning system, called
an agent. in this context, can observe the environment, select and perform actions, and get rewards in
return.
Applications in Electrical Engineering:
• Predictive maintenance of electrical equipment.
• Signal processing and noise reduction.
• Power load forecasting.
• Self-driving cars
Prepared By: Dr. Mamoona Khalid
Machine Learning
• Robotics
Task: Write a short paragraph (in your notebook) about how machine learning could be applied to a
specific area of electrical engineering that interests you.
Based on the area of interest machine learning can be applied in the following areas of electrical
engineering
Wireless communication: It can significantly improve the indicating interference, optimizing
transmissions power, enhancing security of networks and antenna management etc.
Mobile networks: ML transform mobile networks as by preventing network congestion congestion
optimizing resource allocation enhance quality of service preventing fraud and security threats as well.
Wi-Fi systems: It can also enhance Wi-Fi network configuration user handle management etc.
Getting Started:
Instructions for Setting Up the Python Environment (Method 1):
• Install Python:
o If Python is not installed on your system, download and install it from [Link].
• Install Jupyter Notebook:
o Open your command prompt or terminal.
o Run the command: pip install jupyterlab.
• Install Required Libraries:
o Install the following libraries by running the commands in your terminal:
“pip install numpy pandas matplotlib scikit-learn”
• Launch Jupyter Notebook:
o In your terminal, navigate to the directory where you want to save your lab files and run: jupyter
notebook.
o This will open the Jupyter Notebook interface in your web browser.
Method 2 (Recommended):
• Recommended compared to the .pip method as you will not need to install all the related libraries
manually. You can write the codes and check their step by step execution.
o Go to [Link]
o Download Anaconda distribution based on your operating system (Windows, Linux, MAC
book etc)
o Download Anaconda for Python (it will download all the required libraries of Jupyter)
o Install Microsoft VS code on your PC/Laptop.
Prepared By: Dr. Mamoona Khalid
Machine Learning
o After installation open the terminal that has been installed.
o Type ~ Jupyter notebook in the terminal. This will start the default server on your machine
and ignore the default messages you see.
o This will take you to the Jupyter dashboard. The link you can see on the top search bar
would be localhost:8888/tree.
o The first tab of this dashboard is home directory which contains the folders from your
system.
o Now create notebook for Python by going into files tab > Desktop > New > Python >. This
will open a new python notebook for you to carry on lab tasks.
o By default, the notebook will be called untitled. You can change the title by clicking it.
o .ipynb jupyter extension for python
o In the notebook write print (“Hello World”) and then click run. You will see the results there
on the same console.
Task:
o Create a new notebook in Jupyter and name it Lab1_Introduction_to_ML.ipynb.
o In the first cell, type and run the following code to ensure everything is working “print ("Hello,
Machine Learning!")”
Basics of Python:
• Variables and Data Types:
o Python variables can store data of different types such as integers, floats, strings, and lists.
• Control Structures:
o Use if, else, and elif for decision making.
o Use for and while loops for iteration.
• Functions:
o Functions are defined using the def keyword. They allow you to write reusable code.
• Numpy Basics:
o numpy is a library for numerical computations.
o You can create arrays, perform mathematical operations, and manipulate data efficiently.
• Pandas Basics:
o pandas is used for data manipulation and analysis. It provides data structures like Series
and DataFrame.
The Requirement includes for machine learning
Prepared By: Dr. Mamoona Khalid
Machine Learning
• Basic knowledge of Python programming language
• Fundamental knowledge of statistics and probability
• Understanding of linear algebra and calculus
Why Python?
o Many data-heavy applications are now developed in Python
o Highly readable, less complexity, fast prototyping
o Easy to offload number crunching to underlying C/Fortran/…
o Easy to install and import many rich libraries
Python Libraries:
There are a lot of reasons why Python is popular among developers and one of them is that it has an
amazingly large collection of libraries that users can work with. In this Python library, we will discuss the
Python Standard library, and the different libraries offered by the Python Programming Language, such as
SciPy, NumPy, Pandas, Matplotlib etc. We know that a module is a file with some Python code, and a
package is a directory for sub packages and modules. A Python library is a reusable chunk of code that you
may want to include in your programs/ projects. Here, a library loosely describes a collection of core
modules. Essentially, then, a library is a collection of modules. A package is a library that can be installed
using a package manager like NumPy.
▪ NumPy: Efficient data structures. Contains definitions for 2 dimensional arrays
▪ SciPy: fast numerical analysis recipes.
▪ Matplotlib: Creates high-quality graphs
▪ scikit-learn: Contains a set of useful machine learning algorithms required to create
machine learning models
▪ TensorFlow: Contains neural network algorithms.
Python Standard Library
The Python Standard Library is a collection of script modules accessible to a Python program to
simplify the programming process and remove the need to rewrite commonly used commands. They
can be used by 'calling/importing' them at the beginning of a script. A list of the Standard Library
modules that are most important: time , sys, csv, math, random, statistics, tkinter.
Implementation of Python Basic Libraries such as Math, NumPy and SciPy
Python Math Library
The math module is a standard module in Python and is always available. To use mathematical
functions under this module, you have to import the module using import math. It gives access tothe
underlying C library functions. This module does not support complex datatypes. The math module
is the complex counterpart.
List of Functions in Python Math Module
Prepared By: Dr. Mamoona Khalid
Machine Learning
Function Description
ceil(x) Returns the smallest integer greater than or equal to x.
copysign(x,y) Returns x with the sign of y
fabs(x) Returns the absolute value of x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
fmod(x, y) Returns the remainder when x is divided by y
frexp(x) Returns the mantissa and exponent of x as the pair(m, e)
fsum(iterable) Returns an accurate floating-point sum of values in the iterable
isfinite(x) Returns True if x is neither an infinity nor a NaN (Not a Number)
isinf(x) Returns True if x is a positive or negative infinity
isnan(x) Returns True if x is a NaN
ldexp(x,i) Returns x*(2**i)
modf(x) Returns the fractional and integer parts of x
trunc(x) Returns the truncated integer value of x
exp(x) Returns e**x
expm1(x) Returns e**x-1
Basic Python Operations:
• In a new cell, write the following code to create variables and perform operations:
o a=5
o b=3
o sum_ab = a + b
o print("Sum:", sum_ab)
• Create a function that takes a list of numbers and returns the average:
o def calculate_average(numbers):
o return sum(numbers) / len(numbers)
o numbers = [10, 20, 30, 40, 50]
o average = calculate_average(numbers)
o print("Average:", average)
Tasks for students:
Program-1
Prepared By: Dr. Mamoona Khalid
Machine Learning
Program-2
Program-3
Program-4
Program-5
Prepared By: Dr. Mamoona Khalid
Machine Learning
Python NumPy Library:
NumPy is an open-source library available in Python that aids in mathematical, scientific,
engineering, and data science programming. NumPy is an incredible library to perform
mathematical and statistical operations. It works perfectly well for multi-dimensional arrays and
matrices multiplication.
For any scientific project, NumPy is the tool to know. It has been built to work with the N-
dimensional array, linear algebra, random number, Fourier transform, etc. It can be integrated to
C/C++and Fortran. NumPy is a programming language that deals with multi-dimensional arrays
and matrices. On top of the arrays and matrices, NumPy supports a large number of mathematical
operations.
NumPy is memory efficient, meaning it can handle the vast amount of data more accessible than
any other library. Besides, NumPy is very convenient to work with, especially for matrix
multiplication and reshaping. On top of that, NumPy is fast. Infact, Tensor Flow and Scikitlearn
use NumPy array to compute the matrix multiplication in the backend.
Numpy Operations:
• Create a numpy array and perform basic operations:
import numpy as np
array = [Link]([1, 2, 3, 4, 5])
print("Array:", array)
print("Array Sum:", [Link](array))
• Arrays in NumPy: NumPy’s main object is the homogeneous multidimensional array. It is a
table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers.
In NumPy dimensions are called axes. The number of axes is rank.
NumPy’s array class is called ndarray. It is also known by the alias array.
We use Python numpy array instead of a list because of the below three reasons (i) Less Memory, (ii) Fast,
and (iii) Convenient.
Numpy Functions
Prepared By: Dr. Mamoona Khalid
Machine Learning
NumPy arrays carry attributes around them. The most important ones are:
o ndim: The number of axes or rank of the array. ndim returns an integer that tells us how many
dimensions the array has shape:
o A tuple containing the length in each dimension size: The total number of elements
Program-6
Program-7
Program-8
Program-9
Arithmetic operations apply element wise
Prepared By: Dr. Mamoona Khalid
Machine Learning
Built-in Methods
Many standard numerical functions are available as methods out of the box:
Python SciPy Library
SciPy is an Open-Source Python-based library, which is used in mathematics, scientific computing,
Engineering, and technical computing. SciPy is also pronounced as"SighPi."
• SciPy contains a variety of sub-packages that help to solve the most common issue related to
Scientific Computation.
• SciPy is the most used Scientific library, only second to GNU Scientific Library for
C/C++or MATLAB’s. Easy to use and understand as well as fast computational power.
• It can operate on an array of NumPy libraries.
• NumPy VS SciPy
NumPy:
• NumPy is written in C and used for mathematical or numerical calculation.
• It is faster than other Python Libraries
• NumPy is the most useful library for Data Science to perform basic calculations.
• NumPy contains nothing but array data type which performs the most basic operation like
sorting, shaping, indexing, etc.
SciPy:
• SciPy is built in top of the NumPy
• SciPy is a fully-feature diversion of Linear Algebra while Numpy contains only a few
features.
• Most new Data Science features are available in Scipy rather than Numpy
Linear Algebra with SciPy
• Linear Algebra of SciPy is an implementation of BLAS and ATLAS LAPACK libraries.
• Performance of Linear Algebra is very fast compared to BLAS and LAPACK.
• Linear algebra routine accepts a two-dimensional array objects and output is also a two-
dimensional array.
• Now let's do some tests with [Link]
Prepared By: Dr. Mamoona Khalid
Machine Learning
Calculating the determinant of a two-dimensional matrix:
Program-10
Eigenvalues and Eigenvector–[Link] ()
• The most common problem in linear algebra is eigenvalues and eigenvectors which can be
easily solved using the eig() function.
• Now let’s find the Eigenvalue of (X) and the corresponding eigenvector of a two-dimensional
square matrix.
Program-11
TASK
Run all the programs and write down your observations.
Student Comments
After deeply analyzing and making all these programs work on Jupiter notebook state that Python
programming in terms of machine learning is very useful tool that helps to train, build and complete
models with respect to their data sets very easily. There are many other things that we learned in this
lab such as import library N for this we accessed different libraries like math which contains built-in
functions. Similarly who used another library numpy to access and from Paris and with these arrays
who used task like ndim(), shape(), size(), arrange(). We learn how to change the default name of
library by using keyboard
Prepared By: Dr. Mamoona Khalid
Machine Learning
At last we used scipy to perform task related to linear algebra and for that we used linolg to soul
equations for eigenvalues and eigenvectors.
Lesson Learnt and Conclusion
In this lab we learned that Python programming importance of machine learning steps to carry out
machine learning and libraries of Python language associated with ML task. These things also serves as
basis of ML understanding. To conclude that we can say that process of machine learning uses Python
interpreter in major areas, so it is very crucial to have knowledge and deep understanding of Python
language if we are to take ourselves at peaks of machine learning expertise
Prepared By: Dr. Mamoona Khalid