Introduction to NumPy PDF
Document Details
Uploaded by Deleted User
SDU University
2024
Meraryslan Meraliyev
Tags
Summary
This document provides an introduction to the NumPy library for scientific computing in Python. It covers various applications and use cases, including numerical computations, linear algebra, and statistics. The document is part of a course.
Full Transcript
Week 2: Introduction to NumPy Meraryslan Meraliyev SDU University September 20, 2024 Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Intr...
Week 2: Introduction to NumPy Meraryslan Meraliyev SDU University September 20, 2024 Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Introduction to NumPy NumPy stands for ”Numerical Python” and is the core library for numerical computing in Python. It supports multi-dimensional arrays, matrices, and numerous mathematical operations. Learning outcomes: Understand NumPy arrays and operations. Work with array indexing, slicing, and reshaping. Perform mathematical operations on arrays. Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy What are NumPy Arrays? Arrays in NumPy are grid-like data structures for efficiently storing and manipulating large amounts of numerical data. Arrays are superior to Python lists due to better memory efficiency and performance. Operations like matrix multiplications, broadcasting, and element-wise operations can be performed easily on arrays. Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Why Use NumPy? Efficient memory management. Optimized for numerical computations (fast and vectorized operations). Core library for scientific computing, machine learning, and data analysis. Extensively used in mathematics for matrix operations, numerical methods, and statistics. Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Creating Arrays in NumPy Arrays can be created using different functions: ‘np.array()‘: Create arrays from Python lists. ‘np.zeros()‘: Create an array of zeros. ‘np.ones()‘: Create an array of ones. ‘np.arange()‘: Create an array with a range of numbers. ‘np.linspace()‘: Create an array with evenly spaced numbers. Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Creating Arrays Example 1 import numpy as np 2 3 # Creating different types of arrays 4 a = np. array ([1 , 2 , 3 , 4]) 5 b = np. zeros ((2 , 3) ) 6 c = np. ones ((3 , 3) ) 7 d = np. arange (10 , 20) 8 e = np. linspace (0 , 1 , 5) 9 10 print (a , b , c , d , e ) Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Visual Representation of Arrays Visualizing arrays can help understand how data is stored and manipulated. Multi-dimensional arrays (2D, 3D, etc.) represent matrices, Meraryslan Meraliyev SDU University tensors, and more complex structures. Week 2: Introduction to NumPy Understanding Array Attributes NumPy arrays have several important attributes: ‘shape‘: The dimensions of the array (rows, columns). ‘size‘: The total number of elements. ‘dtype‘: The data type of the array elements (e.g., ‘int32‘, ‘float64‘). Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Code Example: Array Attributes 1 arr = np. array ([[1 , 2 , 3] , [4 , 5 , 6]]) 2 3 # Display attributes 4 print ( " Shape : " , arr. shape ) 5 print ( " Size : " , arr. size ) 6 print ( " Data type : " , arr. dtype ) Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Use Case 1: Linear Algebra NumPy is extensively used in linear algebra for operations like: Matrix multiplication. Matrix inversion. Eigenvalue and eigenvector computation. These tools are essential for solving systems of equations, understanding transformations, and modeling. Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Code Example: Matrix Multiplication 1 A = np. array ([[2 , 3] , [5 , 7]]) 2 B = np. array ([[1 , 0] , [0 , 1]]) 3 4 # Matrix multiplication 5 result = np. dot (A , B ) 6 print ( result ) Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Use Case 2: Solving Systems of Equations NumPy can solve linear systems of equations using methods like: ‘np.linalg.solve()‘: Efficiently solving equations of the form ‘Ax = b‘. This is especially useful in mathematical modeling, economics, and physics. Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Code Example: Solving a System of Equations 1 # Solving 2 x + 3 y = 5 and 5 x + 7 y = 11 2 A = np. array ([[2 , 3] , [5 , 7]]) 3 b = np. array ([5 , 11]) 4 5 # Solve for x and y 6 x = np. linalg. solve (A , b ) 7 print ( " Solution for x and y : " , x ) Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Interactive Task: Solve a System of Equations Task: Solve the system of equations: 3x + 4y = 6 7x + 2y = 10 Use ‘np.linalg.solve()‘ to find the values of ‘x‘ and ‘y‘. Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Use Case 3: Eigenvalues and Eigenvectors Eigenvalues and eigenvectors have applications in differential equations, stability analysis, and machine learning. NumPy provides tools to compute eigenvalues and eigenvectors with ‘np.linalg.eig()‘. Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Code Example: Eigenvalues and Eigenvectors 1 A = np. array ([[4 , -2] , [1 , 1]]) 2 3 # Compute eigenvalues and eigenvectors 4 eig_vals , eig_vecs = np. linalg. eig ( A ) 5 6 print ( " Eigenvalues : " , eig_vals ) 7 print ( " Eigenvectors :\ n " , eig_vecs ) Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Visualizing Eigenvectors Eigenvectors represent directions in space that remain unchanged after a transformation (scaling by eigenvalues). Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Use Case 4: Calculus - Numerical Differentiation Numerical differentiation can be used when analytical derivatives are not feasible. NumPy enables numerical approximation using small increments (‘h‘). This is essential in areas like optimization and numerical methods. Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Code Example: Numerical Differentiation 1 # Function : f ( x ) = x ^3 2 def f ( x ) : 3 return x **3 4 5 # Numerical derivative of f ( x ) at x = 2 6 x = 2 7 h = 0.001 # Small step size 8 derivative = ( f ( x + h ) - f ( x ) ) / h 9 print ( " Numerical derivative : " , derivative ) Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Use Case 5: Numerical Integration Numerical integration is often required when analytical integration is challenging or impossible. The trapezoidal rule is one method for approximating the integral of a function. Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Code Example: Trapezoidal Rule 1 # Function : f ( x ) = x ^2 2 def f ( x ) : 3 return x **2 4 5 # Numerical integration from 0 to 3 6 x = np. linspace (0 , 3 , 100) 7 y = f(x) 8 9 # Apply trapezoidal rule 10 integral = np. trapz (y , x ) 11 print ( " Numerical integral : " , integral ) Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Use Case 6: Statistics (Mean, Median, Std) Statistics play a huge role in analyzing data. NumPy provides functions to calculate descriptive statistics: Mean: ‘np.mean()‘ Median: ‘np.median()‘ Standard Deviation: ‘np.std()‘ Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Code Example: Descriptive Statistics 1 data = np. array ([23 , 45 , 67 , 89 , 12 , 34 , 56]) 2 3 mean = np. mean ( data ) 4 median = np. median ( data ) 5 std_dev = np. std ( data ) 6 7 print ( " Mean : " , mean ) 8 print ( " Median : " , median ) 9 print ( " Standard Deviation : " , std_dev ) Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Use Case 7: Random Sampling and Simulations Random sampling is essential in statistics and probability, particularly for simulations and experiments. NumPy provides random sampling functions: ‘np.random.rand()‘: Generate uniform random values. ‘np.random.choice()‘: Randomly sample from an array. Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Code Example: Random Sampling 1 # Generate 5 random numbers between 0 and 1 2 rand_vals = np. random. rand (5) 3 4 # Randomly sample 3 elements from an array 5 arr = np. array ([10 , 20 , 30 , 40 , 50]) 6 samples = np. random. choice ( arr , 3) 7 8 print ( " Random values : " , rand_vals ) 9 print ( " Samples : " , samples ) Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Use Case: Monte Carlo Simulation Monte Carlo methods are powerful tools for numerical simulations. Example: Estimating the value of pi by randomly generating points in a unit square and counting how many fall inside a quarter-circle. Meraryslan Meraliyev SDU University Week 2: Introduction to NumPy Code Example: Monte Carlo Simulation 1 N = 10000 # Number of random points 2 inside_circle = 0 3 4 for _ in range ( N ) : 5 x , y = np. random. rand (2) 6 if x **2 + y **2