0% found this document useful (0 votes)
2 views61 pages

NumPy Arrays

This document provides an overview of NumPy arrays, covering their creation, indexing, slicing, reshaping, and the importance of vectorized operations for efficient numerical computing. It highlights the advantages of NumPy over Python lists, such as speed and memory efficiency, and introduces concepts like broadcasting and matrix operations essential for AI applications. Additionally, it discusses the NumPy Random Module for generating random numbers and its applications in AI workflows.

Uploaded by

mahmoudhaplas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views61 pages

NumPy Arrays

This document provides an overview of NumPy arrays, covering their creation, indexing, slicing, reshaping, and the importance of vectorized operations for efficient numerical computing. It highlights the advantages of NumPy over Python lists, such as speed and memory efficiency, and introduces concepts like broadcasting and matrix operations essential for AI applications. Additionally, it discusses the NumPy Random Module for generating random numbers and its applications in AI workflows.

Uploaded by

mahmoudhaplas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NumPy Arrays:

Indexing, Slicing & Reshape


Today's Topic

In this session, we will learn the basics of working with NumPy arrays.
By the end of this lesson, you will be able to:

Understand what a NumPy Array is. Extract parts of arrays using Slicing.

Create 1D and 2D arrays. Change array shape using Reshape.

Access array elements using Indexing. Understand why arrays are important for AI and ML.
Why Do We Need NumPy Arrays?

Python Lists are great for general programming. However, AI applications usually work with Thousands of numbers, Millions of pixels,
and Large datasets.

Feature Python List NumPy Array

Purpose General purpose Numerical computing

Speed Slower Faster

Memory More memory Less memory

Operations Limited mathematical operations Built-in mathematical operations


What is a NumPy Array?

A NumPy Array is a collection of values stored in one object.


Think of an array as a table of numbers.

All elements usually have the same data type.

Data is stored efficiently in memory.

Mathematical operations are much faster.


Creating a NumPy Array

Before using an array, we must import NumPy. Then we create an array using [Link]().

SYNTAX
Explanation

np is a short name for NumPy.

array() converts a Python list into a NumPy Array.

The variable now stores an array instead of a list.


OUTPUT
Activity: Predict the output if we create: [Link]([3, 6,
9])
1D vs 2D Arrays

1D Array 2D Array
Represents a single sequence of values. Represents rows and columns.

Like a list. One direction. One index. Like a table. Rows and columns. Row and column indexes.
Understanding Array Indexing

Indexing means accessing one element from an array. NumPy


starts counting from 0.

Index 0 1 2 3

Value 15 20 35 40

First element → index 0

Last element → index length - 1


Negative Indexing

NumPy also supports negative indexes. Negative indexes start from the end.

How it works Why is this useful?


Index: -1 (Last), -2 (Second to last), etc. Sometimes we only need the last value without knowing
the array length.
Indexing in 2D Arrays

For 2D arrays, we need two indexes. Rows are selected first,


then columns.
What is Slicing?

start : stop Indexing returns one element. Slicing returns multiple elements.
It allows us to extract part of an array.

The stop position is not included.

Start is included.

Stop is excluded.
More Slicing Examples

From Start Till End From End

Output: [10 20 30] Output: [30 40 50 60] Output: [40 50 60]

Activity: Predict the output of arr[1:5] given [10 20 30 40 50 60]


Slicing 2D Arrays

Slicing also works with rows and columns. Selecting specific


features from a dataset is often done using slicing.

Explanation: : means all rows. 1: means columns starting


from column 1.
What is Reshape?

The Concept Why is this useful?

Sometimes we need to change the layout of data. The Many AI algorithms expect data in a specific shape.
values stay the same. Only the arrangement changes. Reshape helps prepare the data for training or

[1 2 3 4 5 6] prediction.

[[1 2 3] [4 5 6]]
Using reshape()
Syntax

Important Rule

Example The total number of elements must remain the


same.

6 elements 2 × 3 = 6
Output
When Does reshape() Fail?
Calculate New Shape
Reshape only works if the new shape contains the same number of elements. Otherwise, NumPy generates an error. Invalid Check
Check if row * col
5 * 3 = 15 (Error!)
matches total

Count Elements Valid Check

Start with total 3 * 4 = 12 (Success)


elements (e.g. 12)

Always check the total number of elements before reshaping.


Using -1 in reshape()
Sometimes we do not know one dimension. NumPy can calculate it
automatically using -1.

If the array has 12 elements, NumPy calculates: 3 × 4 = 12. Result is (3,4).


From Image to NumPy Array
Computer Vision models never "see" images. They only process arrays of
numbers.

Pixel Brightness: Each number (e.g. 10, 25, 40) represents the brightness of
one pixel.
From Arrays to Fast Computation
So far, we learned how to:

Create arrays

Access data using Indexing

Extract data using Slicing

Change array shape using Reshape

The next question is:

How can we perform calculations on arrays efficiently?

NumPy provides two powerful features:

Vectorized Operations
Broadcasting
Why Not Use Python Loops?
In Python, we often use loops to process lists.
Example idea:

Read one value.

Perform a calculation.

Move to the next value.

Repeat until the end.


This works, but it becomes slow for large datasets. Imagine
processing:
10 numbers → Fast
10,000 numbers → Slower
10 million numbers → Very slow
NumPy avoids this problem by performing operations on the
entire array at once.
What are Vectorized Operations?
A Vectorized Operation means applying one operation to every element in an array at the same time.

Instead of repeating the same calculation using a loop, NumPy performs it internally.

Why is it useful? Example Idea


Less code Instead of adding 5 to each value one by one,

Easier to read NumPy can add 5 to the whole array in one statement.
Faster execution

Optimized for numerical computing


Adding a Number to an Array
NumPy can apply arithmetic operations directly to every
element.

Example
Explanation

Each element receives the same operation.

10 + 5 = 15

20 + 5 = 25

30 + 5 = 35

Output Key Note

No loop is needed.
Other Arithmetic Operations
Vectorized operations work with many arithmetic operators.

Operation Example

Addition arr + 5

Subtraction arr - 2

Multiplication arr * 3

Division arr / 2

Power arr ** 2

Example
Output
arr = [Link]([2,4,6])
arr * 2 [4 8 12]
The calculation happens element by element: 1 + 10, 2 + 20, 3 + 30

Operations Between Two Arrays


NumPy can also perform operations between arrays.

Example

Output

Important Rule

Both arrays should have compatible shapes.

Explanatio
Common Mathematical Functions
NumPy provides many useful mathematical functions.

Function Description

[Link]() Square root

[Link]() Absolute value

[Link]() Largest value

[Link]() Smallest value

[Link]() Sum of all values

[Link]() Average

arr = [Link]([2,4,6])
[Link](arr) Output: 4.0
What is Broadcasting?

Broadcasting is one of NumPy's most powerful features. It allows NumPy to perform operations on arrays with different shapes
whenever possible.

Instead of copying data many times, NumPy automatically expands one array to match the other during the calculation.

Less memory usage Faster calculations Cleaner code

Key Note: Broadcasting does not always create a larger array in memory.
Broadcasting with a
Single Number
When we write arr + 5, NumPy behaves as if the value 5
becomes [5 5 5] before performing the calculation.

Example

Output

Important: NumPy performs this efficiently without


actually creating another array.
Broadcasting Between Arrays
Consider these arrays

NumPy automatically treats the second array as

Result

Explanation: The smaller array is expanded automatically. This is


called Broadcasting.
Broadcasting in 2D Arrays
Broadcasting is also useful with tables (2D arrays).

Example
Original array

Add [1 2]
Result

Explanation: The smaller array is applied to every row.


When Broadcasting Cannot Work
Broadcasting only works when array shapes are compatible.

Compatible Not Compatible

Shape (2,3) and (3,) Shape (2,3) and (4,)

NumPy cannot determine how the values should match.


Checking an Array Shape

The shape attribute tells us the dimensions of an array.


Explanation
Example
2 rows

3 columns

Why is this important?

Knowing the shape helps us understand whether


Output broadcasting and other operations will work correctly.
Vectorization vs Python Loop

Feature Python Loop NumPy Vectorization

Code Amount More code Less code

Speed Slower Faster

Iteration Manual iteration Automatic

Best For General programming Numerical computing

Which should we use?

For AI and Machine Learning, NumPy Vectorization is the


preferred approach.
Real AI Example
Imagine we have exam scores stored as a NumPy array.
Activity

Think-Pair-Share:

Can you think of another real-life situation where the


The teacher decides to give every student 5 bonus marks.
same calculation needs to be applied to thousands of
Without NumPy: Update every score one by one. values at once?
With NumPy: scores + 5

Result
Introduction to Matrix Operations
Until now, we have worked with arrays.

When an array has rows and columns, it is often


called a Matrix.

A matrix is one of the most important data structures


in AI.

Why do we need Matrix Operations?


Many AI tasks involve: Organizing datasets, Transforming data,
Performing mathematical calculations, Training Machine Learning
models, Running Neural Networks

AI Connection: Every layer in a Neural Network


performs matrix operations on the input data.
What is a Matrix?

A matrix is a rectangular arrangement of numbers.

Example

Explanation: This matrix contains 2 rows, 3 columns,


and 6 total elements.

Matrix Shape: Written as (rows, columns). For this


example: (2, 3)

Key Note: Every 2D NumPy array can be treated as a


matrix.
Creating a Matrix in NumPy

Each inner list represents one row.

NumPy automatically organizes the data into rows and columns.

AI Connection: Many datasets are loaded into NumPy as matrices before training Machine Learning models.
Matrix Shape and Dimensions

Attribute Description Example Expected Output

shape Number of rows and columns [Link] (2, 3)

ndim Number of dimensions [Link] 2

size Total number of elements [Link] 6

Why is this important? Understanding the structure of data helps avoid errors during calculations.
Element-wise Matrix Operations

When two matrices have the same shape, NumPy


performs calculations element by element.

Explanation: Each value is added to the value in the


same position.

Key Note: Both matrices should have compatible


shapes.
Element-wise Multiplication

Important Note

This is not Matrix Multiplication.

Explanation: Each element is multiplied by the element in the Students often confuse these
same position. two operations.
Matrix Multiplication

Matrix Multiplication combines rows from the first


matrix with columns from the second matrix.

NumPy uses: @ or [Link]()

Example

Why is it important? It combines information from


different matrices to produce new results.

AI Connection: Every Neural Network layer uses


Matrix Multiplication to calculate outputs.
Understanding Matrix Multiplication

Matrix A Result

Matrix B

How is 19 calculated?

First row of A × First column of B: (1 × 5) + (2 × 7) = 19


The same idea is repeated for every position in the result matrix.

Key Note: Matrix Multiplication is different from element-wise multiplication.


When Can We Multiply Two Matrices?

Matrix Multiplication follows one important rule:

The number of columns in the first matrix must


equal the number of rows in the second matrix.

Matrix A Matrix B Can Multiply?

(2,3) (3,4) ✅ Yes

(2,3) (2,4) ❌ No

(4,2) (2,5) ✅ Yes

Why? This rule ensures that every row has a matching column
during multiplication.
Matrix Transpose
Transpose changes rows into columns.

NumPy uses: matrix.T

Original

Transpose

Why is this useful? Transpose is commonly used


before Matrix Multiplication and in many
Machine Learning algorithms.
Finding Matrix Statistics
NumPy can quickly calculate useful statistics.

Function Description

[Link]() Total sum

[Link]() Average

[Link]() Largest value

[Link]() Smallest value

AI Connection: These statistics help us understand datasets before training Machine Learning models.
Operations Along Rows and Columns

Sometimes we want calculations for each row or


each column. NumPy uses the axis parameter.

Why is this useful? Many AI preprocessing tasks


calculate statistics separately for rows or columns.
Matrix Operations in AI

Matrix Operations appear in almost every AI


application:
Machine Learning datasets & Image processing

Neural Networks & Computer Vision

Embeddings & Recommendation systems

Large Language Models (LLMs)

Key
Takeaway:
Introduction to the NumPy Random Module
In many AI applications, we need to generate
random numbers.
NumPy provides the Random Module for this
purpose. It helps us:

Create random values

Generate sample datasets

Shuffle data

Randomly select values

Initialize Machine Learning models

AI Connection: Random numbers are commonly used to initialize Neural Network weights and split datasets into
training and testing sets.
Importing the Random Module

The Random Module is part of NumPy. There is no need to install anything extra.

Then use [Link] to access its functions.

Key Note: All random functions begin with: [Link]


Generating a Random Number

We can generate one random integer using randint().

Syntax Explanation:

Start value is included.

Example End value is excluded.

Every execution may produce a different


Possible Output: 7
result.

Activity: Predict three possible outputs before running the code.


Generating Multiple Random Numbers
We can generate several random values at once.

Possible Output: [3 8 1 9 5]

Explanation AI Connection

Numbers are generated automatically. The size Useful for creating small sample datasets
parameter controls how many values are during experimentation.
created.
Generating Random Arrays

We can also generate random values in a matrix.

Possible Output:
[[15 72 43]
[98 21 60]]

Why is this useful? It allows us to quickly create


data for testing our programs.
Generating Random Decimal Numbers

Sometimes we need decimal numbers instead of integers. NumPy provides the random() function.

Possible Output: [0.21 0.84 0.36 0.59 0.14]

AI Connection
Explanation
Random decimal values are commonly used
Values are between 0 and 1. The output
when initializing Machine Learning
changes every time the code runs.
parameters.
Choosing Random Values

Instead of generating new numbers, we can randomly choose values from an existing array.

Possible Output: Blue

Student Selection Question Generation Test Sampling


Shuffling Data
Sometimes the order of data should be
changed randomly. NumPy provides the
shuffle() function.

Possible Output: [4 1 5 2 3]

AI Connection: Before training a Machine


Learning model, datasets are often shuffled to
reduce learning bias.
Using a Random Seed
Normally, random results change every time we run the program. Sometimes we want the same random
values every time.

42
Running this code again will produce the same output.
Common Random Functions

Function Purpose

randint() Random integers

random() Random decimal values

choice() Select random values

shuffle() Shuffle an array

seed() Make random results repeatable

Key Note: These functions cover most of the random operations beginners will need when working with
NumPy and AI.
Key Takeaway: Although the values are random, using them correctly helps build more reliable and unbiased AI systems.

Random Module in AI

The Random Module is used in many AI workflows.


Examples include:

Creating sample datasets

Shuffling training data

Selecting random samples

Initializing Neural Network weights

Simulating experiments

Testing algorithms

Dataset Shuffle Data Split Data Train Model Evaluate Results


Lesson Summary

1. NumPy Arrays 5. Broadcasting

NumPy vs Python Lists, Creating 1D/2D arrays. Compatible shapes, Scalars, Arrays.

2. Accessing Data 6. Matrix Operations

Indexing, Negative Indexing, Slicing (1D/2D). Multiplication (@), Transpose, Statistics.

3. Reshaping Data 7. NumPy Random Module

Understanding shapes, reshape(), -1 usage. randint(), random(), choice(), shuffle(), seed().

4. Vectorized Operations

Operations on entire arrays, Math functions.


Knowledge Check (Quiz)

Q1. Converts list to NumPy array? Q5. Broadcasting allows?


B. [Link]() B. Automatically work with compatible shapes.

Q2. Output of arr[-2] on [10,20,30,40]? Q6. Matrix Multiplication operator?


B. 30 C. @

Q3. Slice returns [20,30,40]? Q7. Shuffles array order?


A. arr[1:4] C. [Link]fle()

Q4. Correct about Vectorized Operations?


C. Apply operation to whole array efficiently.
Looking Ahead...
In the Next Session: Probability and Statistics for ML

What is Probability?

Random Variables & Distributions

Mean, Median, and Mode

Variance & Standard Deviation

Normal Distribution

Sampling Concepts

Why is this important? Every Machine Learning algorithm makes decisions based on probability and
statistics.
Thank You
Thank you for your attention and participation.

Keep practicing the NumPy examples in the Jupyter Notebook before the next session.

Prepared by: Yahya Elkholy

You might also like