KEMBAR78
AI Numpy | PDF | Computer Programming | Computing
0% found this document useful (0 votes)
34 views29 pages

AI Numpy

NumPy is a fundamental library for Python that provides efficient multi-dimensional array objects and mathematical functions for numerical computing, making it essential for data analysis, machine learning, and scientific computing. It is faster than traditional Python lists due to its contiguous memory storage and optimized operations, and it offers features like broadcasting, vectorization, and support for linear algebra. NumPy is widely used in various applications including finance, image processing, and data visualization, and can be easily installed and utilized in Python environments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views29 pages

AI Numpy

NumPy is a fundamental library for Python that provides efficient multi-dimensional array objects and mathematical functions for numerical computing, making it essential for data analysis, machine learning, and scientific computing. It is faster than traditional Python lists due to its contiguous memory storage and optimized operations, and it offers features like broadcasting, vectorization, and support for linear algebra. NumPy is widely used in various applications including finance, image processing, and data visualization, and can be easily installed and utilized in Python environments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

GETTING STARTED WITH NUMPY FOR

ARTIFICIAL INTELLIGENCE
BY - HARSH SHIVHARE
WHAT IS NUMPY ?
• NumPy(Numerical Python) is a fundamental library for Python numerical computing. It
provides efficient multi-dimensional array objects and various mathematical functions for
handling large datasets making it a critical tool for professionals in fields that require heavy
computation.
• NumPy, short for Numerical Python, is an open-source Python library. It supports multi-
dimensional arrays (matrices) and provides a wide range of mathematical functions for array
operations. It is used in scientific computing, and in areas like data analysis, machine
learning, etc.
• NumPy is a Python library used for working with arrays.It also has functions for working in
domain of linear algebra, fourier transform, and matrices.
• NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use
it freely. NumPy stands for Numerical Python.
WHY TO USE NUMPY ?
• The following are the key reasons to use numpy :
• NumPy provides various math functions for calculations like addition, algebra, and data
analysis.
• NumPy provides various objects representing arrays and multi-dimensional arrays which can
be used to handle large data such as images, sounds, etc.
• NumPy also works with other libraries like SciPy (for scientific computing), Pandas (for data
analysis), and scikit-learn (for machine learning).
• NumPy is fast and reliable, which makes it a great choice for numerical computing in
Python.
• In Python we have lists that serve the purpose of arrays, but they are slow to process. NumPy
aims to provide an array object that is up to 50x faster than traditional Python lists. The array
object in NumPy is called ndarray it provides a lot of supporting functions that make working
with ndarray very easy.
• Arrays are very frequently used in data science, where speed and resources are very
important.
WHY TO USE NUMPY ?
• These are some reasons that explains why to use numerical python more
WHY IS NUMPY FASTER THAN LISTS
• NumPy arrays are stored at one continuous place in memory unlike lists, so processes can
access and manipulate them very efficiently. This behavior is called locality of reference in
computer science. This is the main reason why NumPy is faster than lists. Also it is optimized
to work with latest CPU architectures.
• NumPy arrays are stored in a single, contiguous block of memory with all elements of the
same data type (homogeneous). This allows low-level optimizations and CPU-level
vectorized instructions, unlike Python lists which store references to objects scattered in
memory.
• Python lists require frequent type and pointer checks during iteration, as they can hold
mixed types. NumPy arrays skip this by enforcing a single data type, enabling direct, low-
level computations without per-element type resolution.
• In Python, a list is a built-in data structure that can hold elements of varying data types.
However, the flexibility of lists comes at the cost of memory efficiency. Python's NumPy
library supports optimized numerical array and matrix operations.
WHY IS NUMPY FASTER THAN LISTS
WHY IS NUMPY FASTER THAN LISTS
KEY FEATURES OF NUMPY
• NumPy has various features that make it popular over lists such as :
• N-Dimensional Arrays : NumPy's core feature is ndarray a powerful N-dimensional array
object that supports homogeneous data types.
• Arrays with High Performance: Arrays are stored in contiguous memory locations,
enabling faster computations than Python lists.
• Broadcasting : This allows element-wise computations between arrays of different shapes. It
simplifies operations on arrays of various shapes by automatically aligning their dimensions
without creating new data.
• Vectorization : Eliminates the need for explicit Python loops by applying operations
directly on entire arrays.
• Linear algebra: NumPy contains routines for linear algebra operations, such as matrix
multiplication, decompositions, and determinants.
KEY FEATURES OF NUMPY
• The diagram represents the importance key features of numerical python that is NumPy.
APPLICATIONS OF NUMPY
• The following are some common application areas where NumPy is extensively used:
• Data Analysis: In Data analysis, while handling data, we can create data (in the form of array
objects), filter the data, and perform various operations such as mean, finding the standard
deviations, etc.
• Machine Learning & AI: Popular machine learning tools like Tensorflow and pytorch use
numpy to manage input data and process the output values.
• Array Manipulation: NumPy allows you to create, resize, slice, index, stack, split, and
combine arrays.
• Finance & Economics: NumPy is used for financial analysis, including portfolio
optimization, risk assessment, time series analysis, and statistical modelling.
• Image & Signal Processing: NumPy helps process and analyze images and signals for
various applications.
• Data Visualization: NumPy independently does not create visualizations, but it works with
libraries like Matplotlib and seaborn to generate charts.
INSTALLING NUMPY IN PYTHON
• To begin using NumPy, you need to install it first. This can be done through pip command :
• If you have python and pip installed on your system then installation is very easy and one
more thing in colab notebook and in jupyter notebook everything is pre-installed.
• So in jupyter notebook you don’t have to install it.
• For checking if numpy is there just type ‘import numpy’ if it works it is there otherwise not.
We can import numpy as ‘import numpy as np’ where np is alias name.
• For checking the version of numpy type :

• OPERATIONS USING NUMPY :


NUMPY ARRAYS
• The most important object defined in NumPy is an N-dimensional array type called ndarray.
It describes a collection of items of the same type, which can be accessed using a zero-based
index. Each item in an ndarray takes the same size of block in the memory and is represented
by a data-type object called dtype. Any item extracted from an ndarray object (by slicing) is
represented by a Python object of one of the array scalar types.
• Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a
tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the
array. A tuple of integers giving the size of the array along each dimension is known as shape
of the array.
• An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by
using square brackets and can be initialized by using nested Python Lists.
NUMPY ARRAYS
• NumPy is used to work with arrays. The array object in NumPy is called ndarray. We can create a
NumPy ndarray object by using the array() function. Elements in Numpy arrays are accessed by using
square brackets and can be initialized by using nested Python Lists.
• Arrays in Numpy can be created by multiple ways, with various number of Ranks, defining the size of
the Array. Arrays can also be created with the use of various data types such as lists, tuples, etc. An
instance of ndarray class can be constructed by different array creation routines. The basic ndarray is
created using the array() function in NumPy.
• The numpy.array() function creates an ndarray from any object exposing the array interface or from
any method that returns an array. To create a ndarray we can pass a list or tuple and create array using
the array() function.
ATTRIBUTES OF NDARRAY
• Understanding the attributes of an ndarray is important while working with NumPy effectively. Here
are the key attributes:
• ndarray.shape() : Returns a tuple representing the shape (dimensions) of the array.
• ndarray.ndim() : Returns the number of dimensions (axes) of the array.
• ndarray.size(): Returns the total number of elements in the array.
• ndarray.dtype():Provides the data type of the array elements.
• ndarray.itemsize():Returns the size in bytes of each element.
ARRAY OPERATIONS
• NumPy allows us to perform operations on entire arrays which enables efficient computation without the
need for explicit loops. These operations include:
• Element Wise Operations : These are straightforward and allow us to perform arithmetic operations on each
element of the array directly.
• Matrix Operations(Dot Product): It allow us to multiply two arrays or matrices and get a single value or
another matrix.
• Broadcasting : This feature enables us to perform operations on arrays of different shapes. NumPy
automatically adjusts the smaller array to match the shape of the larger one for the operation.
• Reshaping and Flattening : Change the shape of an array while keeping the data same. Convert multi-
dimensional arrays into one-dimensional arrays.
MULTI-DIMENSIONAL ARRAYS
• 0D Array : 0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
• 1D Array : An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array. These
are the most common and basic arrays.
• 2D Array : An array that has 1-D arrays as its elements is called a 2-D array. These are often used to
represent matrix or 2nd order tensors.
• 3D Array : An array that has 2-D arrays (matrices) as its elements is called 3-D array. These are often
used to represent a 3rd order tensor.
• Numpy array defines the ndim attribute the returns the result as an integer that tells us how many
dimension array has. Array can have any no. of dimension.
ACCESS ARRAY
• In a numpy array, indexing or accessing the array index can be done in multiple ways. To print a range
of an array, slicing is done. Slicing of an array is defining a range in a new array which is used to print
a range of elements from the original array. Since, sliced array holds a range of elements of the original
array, modifying content with the help of sliced array modifies the original array content.
• Array indexing is the same as accessing an array element. You can access an array element by referring
to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index
0, and the second has index 1 etc.
NUMPY ARRAY SLICING
• Slicing in python means taking elements from one given index to another given index. We pass slice
instead of index like this:[start:end]. We can also define the step, like this: [start:end:stop]
• Slicing is the way to extract a subset of data from a NumPy array. It can be performed on one or more
dimensions of a NumPy array. We can define which part of the array to be sliced by specifying the start
and end index values using [start : end] along with the array name.
CREATING ARRAY WITH DIFFERENT WAYS
• These are the following ways of creating an array in numpy using different ways other than array() function :
• numpy.fromiter(): The fromiter() function create a new one-dimensional array from an iterable object.
• numpy.arange() : This is an inbuilt numpy function that returns evenly spaced values with in a given interval.
• numpy.linspace(): This function returns evenly spaced numbers over a specified between two limits.
• numpy.empty() : This function create a new array of datatype and given shape without initializing the values.
• numpy.ones() : This function is used to get a new array of given shape and type filled with ones (1).
NUMPY.ARANGE()
• numpy.arange() function creates an array of evenly spaced values within a given interval. It is similar to
Python's built-in range() function but returns a NumPy array instead of a list.
• start (optional): The starting value of the sequence. Default is 0.
• stop (required): The endpoint of the sequence, exclusive.
• step (optional): The spacing between consecutive values. Default is 1.
• dtype (optional): The desired data type of the output array.
NUMPY.ZEROES()
• numpy.zeros() function creates a new array of specified shapes and types, filled with zeros. It is
beneficial when you need a placeholder array to initialize variables or store intermediate results. We can
create 1D array using numpy.zeros().
NUMPY.LINSPACE()
• linspace() function in NumPy returns an array of evenly spaced numbers over a specified
range. Unlike the range() function in Python that generates numbers with a specific step size.
linspace() allows you to specify the total number of points you want in the array, and NumPy
will calculate the spacing between the numbers automatically.
NUMPY DATA TYPES
• NumPy supports a much greater variety of numerical types than Python does. The following table
shows different scalar data types defined in NumPy. NumPy has some extra data types, and refer to
data types with one character, like i for integers, u for unsigned integers and etc. The NumPy array
object has a property called dtype that returns the datatype of the array.
CONVERTING DATATYPE ON EXISTING ARRAY
• The best way to change the data type of an existing array, is to make a copy of the array with
the astype() method. The astype() function creates a copy of the array, and allows you to specify the
data type as a parameter. The data type can be specified using a string, like ‘f’ for float, ‘i’ for
integer and etc.
NUMPY COPY AND VIEW
• The main difference between a copy and a view of an array is that the copy is a new array, and the view
is just a view of the original array. The copy owns the data and any changes made to the copy will not
affect original array, and any changes made to the original array will not affect the copy. The view does
not own the data and any changes made to the view will affect the original array, and any changes made
to the original array will affect the view.
• As mentioned above, copies owns the data, and views does not own the data. Every NumPy array has
the attribute base that returns none if the array owns the data. Otherwise, the base refers to the original
object.
NUMPY ARRAY SHAPE
• The shape of an array is the number of elements in each dimension. NumPy arrays have an
attribute called shape that returns a tuple with each index having the number of corresponding
elements.
RESHAPING NUMPY ARRAY
• By reshaping a NumPy array, we mean to change its shape, i.e., modifying the number of elements
along each dimension while keeping the total number of elements the same. In other words, the product
of the dimensions in the new shape must equal the product of the dimensions in the original shape.
Reshaping means changing the shape of an array. By reshaping we can add or remove dimensions or
change number of elements in each dimension.
• We can reshape a 1-D array to a 2-D array in NumPy using the reshape() function. This is used to
organize linear data into a matrix form.
NUMPY ARRAY ITERATING
• Iterating over an array in NumPy refers to the process of accessing each element in the array one by
one in a systematic manner. This is typically done using loops. Iteration is used to perform operations
on each element, such as calculations, modifications, or checks. Iterating means going through
elements one by one. As we deal with multi-dimensional arrays in numpy, we can do this using basic
for loop.
• Iterating using nditer() – It is a helping function that can be used from very basic to very advanced
iterations. It solves some basic issues which we face in iteration
NUMPY ARRAY JOIN
• Joining means putting contents of two or more arrays in a single array. In SQL we join tables based on
a key, whereas in NumPy we join arrays by axes. We pass a sequence of arrays that we want to join to
the concatenate() function, along with the axis. If axis is not explicitly passed, it is taken as 0.
• We can also join arrays by stacking. Stacking is same as concatenation, the only difference is that
stacking is done along a new axis. We can concatenate two 1-D arrays along the second axis which
would result in putting them one over the other, ie. stacking. We pass a sequence of arrays that we want
to join to the stack() ,method along with the axis. If axis is not explicitly passed it is taken as 0.
• NumPy provides a helper function hstack() to stack along rows and also provides vstack() to stack
along columns and dstack() to stack along heights.

You might also like