Showing posts with label NumPy. Show all posts
Showing posts with label NumPy. Show all posts

Tuesday, April 23, 2024

What does np.meshgrid() do?

The np.meshgrid() function in NumPy is used to generate a two-dimensional grid of coordinates from one-dimensional arrays representing coordinates along each axis. Here's a more detailed explanation:

Purpose:

  • It takes two (or more in higher dimensions) one-dimensional arrays and creates two (or more) new two-dimensional arrays (meshes).
  • Each element in the output meshes corresponds to a combination of elements from the original input arrays.

How it Works:

  1. Input Arrays:

    • It requires two one-dimensional arrays (x and y) representing the coordinates along two axes (usually X and Y).
    • These arrays define the range of values for each dimension in the grid.
  2. Output Meshes:

    • It returns two new two-dimensional arrays (XX and YY) with the same shape.
    • Each element in XX represents the X-coordinate for a specific point in the grid.
    • Each element in YY represents the Y-coordinate for the corresponding point in the grid.
  3. Repeating Values:

    • To create all possible combinations, np.meshgrid() repeats the values from one array along rows or columns of the other array.
    • Imagine placing a copy of the X-axis values across every row of the Y-axis values to get all X, Y combinations.

Example:

Python
import numpy as np

# Define one-dimensional arrays
x = np.linspace(-2, 2, 7)  # 7 values between -2 and 2
y = np.linspace(-1, 1, 5)  # 5 values between -1 and 1

# Create mesh grids
X, Y = np.meshgrid(x, y)

# Print the shapes of the grids
print("X:", X.shape)
print("Y:", Y.shape)

# X will have the shape (5, 7) and Y will also have the shape (5, 7)
# Each element in X will be a value from the x array
# Each element in Y will be a value from the y array

Applications:

  • np.meshgrid() is commonly used to evaluate functions over grids in two or more dimensions.
  • It's a helpful tool for creating data for visualization tasks, especially when working with surfaces or 3D plots.
  • It can be used in various scientific computing applications where evaluating a function over a grid is necessary.
Tags: Technology,Python,Interview Preparation,NumPy,

Interview Problem on NumPy meshgrid() function and vstack() function - Create this array of numbers using Python code

""" 
Can you create an array like the two shown below using Python code:

[[-2. -1.]
 [-1. -1.]
 [ 0. -1.]
 [ 1. -1.]
 [ 2. -1.]
 [-2.  0.]
 [-1.  0.]
 [ 0.  0.]
 [ 1.  0.]
 [ 2.  0.]
 [-2.  1.]
 [-1.  1.]
 [ 0.  1.]
 [ 1.  1.]
 [ 2.  1.]]

OR 

May be this array:

[[-2. -1.]
 [ 0. -1.]
 [ 2. -1.]
 [-2.  0.]
 [ 0.  0.]
 [ 2.  0.]
 [-2.  1.]
 [ 0.  1.]
 [ 2.  1.]]

"""


import numpy as np

# Define one-dimensional arrays
x = np.linspace(-2, 2, 5)  # 5 values between -2 and 2
y = np.linspace(-1, 1, 3)  # 3 values between -1 and 1

# Create mesh grids
X, Y = np.meshgrid(x, y) 

# Print the shapes of the grids
print("X:", X.shape)
print("Y:", Y.shape)

# X will have the shape (5, 3) and Y will also have the shape (5, 3)
# Each element in X will be a value from the x array. X values change along the columns.
# Each element in Y will be a value from the y array. Y values change along the rows.

print(X)
print(Y)

Xgrid = np.vstack((X.flatten(), Y.flatten())).T
print(Xgrid)


# In order to get the second output, we need to change the input:

# Define one-dimensional arrays
x = np.linspace(-2, 2, 3)  # 3 values between -2 and 2
y = np.linspace(-1, 1, 3)  # 3 values between -1 and 1

# Rest of the code would remain the same.

Side Note

You may be wondering where this might be used. The answer is that it can be used in creating dummy data that is 2 Dimensional (excluding the target values) in Machine Learning projects.
Tags: Technology,Python,NumPy,Interview Preparation,

Tuesday, September 7, 2021

Functions in NumPy



The lists of NumPy functions are not exhaustive:

Unary
Binary
Commonly Used NumPy.LinAlg Functions
Tags: Technology,Python,NumPy,

Indexing in NumPy



Boolean Indexing
Tags: Technology,Python,NumPy,

Factorial, NumPy and DocTest



Script: s1.py

import numpy as np
import doctest 

def factorial(n):
    """
    Test for the factorial of 3 that should pass.
    >>> factorial(3)
    6

    Test for the factorial of 0 that should fail.
    >>> factorial(0)
    1
    """
    return np.arange(1, n+1).cumprod()[-1]

doctest.testmod() 

OUTPUT:


(base) CMD>python s1.py
**********************************************************************
File "s1.py", line 11, in __main__.factorial
Failed example:
    factorial(0)
Exception raised:
    Traceback (most recent call last):
        File "E:\programfiles\Anaconda3\lib\doctest.py", line 1329, in __run
        compileflags, 1), test.globs)
        File "<doctest __main__.factorial[1]>", line 1, in <module>
        factorial(0)
        File "s1.py", line 14, in factorial
        return np.arange(1, n+1).cumprod()[-1]
    IndexError: index -1 is out of bounds for axis 0 with size 0
**********************************************************************
1 items had failures:
    1 of   2 in __main__.factorial
***Test Failed*** 1 failures. 


(base) CMD>python s1.py -v
Trying:
    factorial(3)
Expecting:
    6
ok
Trying:
    factorial(0)
Expecting:
    1
**********************************************************************
File "s1.py", line 11, in __main__.factorial
Failed example:
    factorial(0)
Exception raised:
    Traceback (most recent call last):
        File "E:\programfiles\Anaconda3\lib\doctest.py", line 1329, in __run
        compileflags, 1), test.globs)
        File "<doctest __main__.factorial[1]>", line 1, in <module>
        factorial(0)
        File "s1.py", line 14, in factorial
        return np.arange(1, n+1).cumprod()[-1]
    IndexError: index -1 is out of bounds for axis 0 with size 0
1 items had no tests:
    __main__
**********************************************************************
1 items had failures:
    1 of   2 in __main__.factorial
2 tests in 2 items.
1 passed and 1 failed.
***Test Failed*** 1 failures.


Code with two functions

import numpy as np import doctest def factorial(n): """ Test for the factorial of 3 that should pass. >>> factorial(3) 6 Test for the factorial of 0 that should fail. >>> factorial(0) 1 """ return np.arange(1, n+1).cumprod()[-1] def isEven(n): """ Test that would pass >>> isEven(10) True Test that would fail >>> isEven(9) True Test that would pass >>> isEven(9) False """ rtn = n % 2 return rtn == 0 doctest.testmod() Output (base) CMD>python script.py ********************************************************************** File "script.py", line 11, in __main__.factorial Failed example: factorial(0) Exception raised: Traceback (most recent call last): File "E:\programfiles\Anaconda3\lib\doctest.py", line 1329, in __run compileflags, 1), test.globs) File "<doctest __main__.factorial[1]>", line 1, in <module> factorial(0) File "script.py", line 14, in factorial return np.arange(1, n+1).cumprod()[-1] IndexError: index -1 is out of bounds for axis 0 with size 0 ********************************************************************** File "script.py", line 24, in __main__.isEven Failed example: isEven(9) Expected: True Got: False ********************************************************************** 2 items had failures: 1 of 2 in __main__.factorial 1 of 3 in __main__.isEven ***Test Failed*** 2 failures.
Tags: Technology,Python,Machine Learning,NumPy

Friday, September 3, 2021

Two Types of Matrix Multiplication Using NumPy



How are two matrices multiplied according to the math rules: Khan Academy

(base) C:\Users\ashish>python
Python 3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> a = [[1, -1], [1, 2]]
>>> b = [[3], [4]]

>>> a * b
Traceback (most recent call last):
  File "[stdin]", line 1, in [module]
TypeError: can't multiply sequence by non-int of type 'list'

>>> a = np.array(a)
>>> b = np.array(b)

>>> a
array([[ 1, -1],
       [ 1,  2]])

>>> b
array([[3],
       [4]])

>>> np.matmul(a,b)
array([[-1],
       [11]])

>>> np.matmul(b, a)
Traceback (most recent call last):
  File "[stdin]", line 1, in [module]
ValueError: shapes (2,1) and (2,2) not aligned: 1 (dim 1) != 2 (dim 0)

>>> a.dot(b)
array([[-1],
       [11]])

>>> np.dot(a, b)
array([[-1],
       [11]])

>>> a.b
Traceback (most recent call last):
  File "[stdin]", line 1, in [module]
AttributeError: 'numpy.ndarray' object has no attribute 'b'

>>> np.dot(b, a)
Traceback (most recent call last):
  File "[stdin]", line 1, in [module]
ValueError: shapes (2,1) and (2,2) not aligned: 1 (dim 1) != 2 (dim 0)

# How about an element to element multiplication?
# Note: this is not how math books do it

>>> np.multiply(a, b)
array([[ 3, -3],
       [ 4,  8]])

>>> np.multiply(b, a)
array([[ 3, -3],
       [ 4,  8]])

>>> a*b
array([[ 3, -3],
       [ 4,  8]])

>>> a = [[1, 1], [2, 2]]
>>> b = [[0, 0], [1, 1]]
>>> a = np.array(a)
>>> b = np.array(b)
>>> a*b
array([[0, 0],
       [2, 2]])

>>> a = [[0, 1], [2, 3]]
>>> a = np.array(a)
>>> b = [[5, 10], [15, 20]]
>>> b = np.array(b)
>>> a*b
array([[ 0, 10],
       [30, 60]])
>>>

Ref: docs.scipy.org

Tags: Technology,Python,NumPy

Using NumPy's 'random' package (randint and shuffle)



randint

>>> np.random.randint(4) 0 >>> np.random.randint(4) 3 >>> np.random.randint(4) 2 >>> np.random.randint(4) 0

shuffle

>>>arr = np.arange(10) >>>np.random.shuffle(arr) >>>arr [1 7 5 2 9 4 3 6 0 8] # random - - - >>> import numpy as np >>> arr = [0, 1, 2, 3] >>> np.random.shuffle(arr) >>> arr [1, 0, 2, 3] >>> np.random.shuffle(arr) >>> arr [0, 1, 3, 2] >>> Tags: Technology,Python,NumPy

Dot Product using Python, NumPy, Matplotlib



Dot product / Inner product / Scalar product

Algebraic Definition
Geometric Definition
Python Code
from matplotlib.pyplot import plot point1 = [0, 0] point2 = [3, 0] x_values = [point1[0], point2[0]] y_values = [point1[1], point2[1]] plot(x_values, y_values, 'b-') # format: Blue dashes point1 = [0, 0] point2 = [3, 3] x_values = [point1[0], point2[0]] y_values = [point1[1], point2[1]] plot(x_values, y_values, color='red', marker='o')
import numpy as np a = np.array([3, 0]) b = np.array([3, 3]) c = np.array([1, 1]) print("a, b, c:", a, b, c, end = "\n\n") print("a.dot(b):", a.dot(b)) print("b.dot(a):", b.dot(a), end = "\n\n") print("np.dot(a, b):", np.dot(a, b)) print("sum(a*b):", sum(a*b), end = "\n\n") print("np.dot(b, c):", np.dot(b, c)) print("sum(b*c):", sum(b*c), end = "\n\n") theta = np.pi / 4 print("theta = np.pi / 4") print("np.linalg.norm(a) * np.linalg.norm(b) * np.cos(theta):", np.linalg.norm(a) * np.linalg.norm(b) * np.cos(theta)) a, b, c: [3 0] [3 3] [1 1] a.dot(b): 9 b.dot(a): 9 np.dot(a, b): 9 sum(a*b): 9 np.dot(b, c): 6 sum(b*c): 6 theta = np.pi / 4 np.linalg.norm(a) * np.linalg.norm(b) * np.cos(theta): 9.0 Tags: Technology,Python,Data Visualization,Machine Learning,