Matrix¶
In NumPy, a matrix is a specialized 2D array that retains its two-dimensional nature through operations. It has specific operators for matrix math, such as matrix multiplication and matrix inversion.
- Creation: A matrix in NumPy can be created using the
numpy.matrix
class, which is a subclass ofnumpy.ndarray
. Matrices can be created from a string of data or any array-like object.A = np.matrix('1 2; 3 4') B = np.matrix([[1, 2], [3, 4]])
- Operations:
- Matrix Multiplication:
*
- Inversion:
.I
- Transpose:
.T
- Matrix Multiplication:
Create Matrix¶
In [1]:
Copied!
import numpy as np
import numpy as np
In [5]:
Copied!
print(np.mat("5 6;7 8"))
print(type(np.mat("5 6;7 8")))
print(np.mat([[5,6],[7,8]]))
print(type(np.mat([[5,6],[7,8]])))
print(np.array([[5,6],[7,8]]))
print(type(np.array([[5,6],[7,8]])))
print(np.mat("5 6;7 8"))
print(type(np.mat("5 6;7 8")))
print(np.mat([[5,6],[7,8]]))
print(type(np.mat([[5,6],[7,8]])))
print(np.array([[5,6],[7,8]]))
print(type(np.array([[5,6],[7,8]])))
[[5 6] [7 8]] <class 'numpy.matrix'> [[5 6] [7 8]] <class 'numpy.matrix'> [[5 6] [7 8]] <class 'numpy.ndarray'>
In [7]:
Copied!
np.mat(np.zeros((3,3)))
np.mat(np.zeros((3,3)))
Out[7]:
matrix([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])
In [8]:
Copied!
np.matrix(np.ones((2,4)))
np.matrix(np.ones((2,4)))
Out[8]:
matrix([[1., 1., 1., 1.], [1., 1., 1., 1.]])
In [9]:
Copied!
np.matrix(np.random.randn(3,3))
np.matrix(np.random.randn(3,3))
Out[9]:
matrix([[ 0.20541112, 1.06524902, -0.3571914 ], [ 0.01174502, 0.86889312, -0.08787096], [ 0.37034351, -1.33600316, -0.16127082]])
In [10]:
Copied!
np.matrix(np.random.randint(1,8,size = (3,3)))
np.matrix(np.random.randint(1,8,size = (3,3)))
Out[10]:
matrix([[7, 2, 6], [2, 7, 3], [1, 5, 4]])
In [12]:
Copied!
np.eye(3,3)
np.eye(3,3)
Out[12]:
array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
In [13]:
Copied!
np.diag([1,2,3])
np.diag([1,2,3])
Out[13]:
array([[1, 0, 0], [0, 2, 0], [0, 0, 3]])
Operation in Matrix¶
In [22]:
Copied!
d1 = np.mat(np.arange(6).reshape((3,2)))
d2 = np.mat([1,2])
print(d1)
print(d2)
d1 + d2, d1 - d2
d1 = np.mat(np.arange(6).reshape((3,2)))
d2 = np.mat([1,2])
print(d1)
print(d2)
d1 + d2, d1 - d2
[[0 1] [2 3] [4 5]] [[1 2]]
Out[22]:
(matrix([[1, 3], [3, 5], [5, 7]]), matrix([[-1, -1], [ 1, 1], [ 3, 3]]))
In [23]:
Copied!
d1 / d2
d1 / d2
Out[23]:
matrix([[0. , 0.5], [2. , 1.5], [4. , 2.5]])
In [19]:
Copied!
d1 * d2.T
d1 * d2.T
Out[19]:
matrix([[ 2], [ 8], [14]])
In [27]:
Copied!
print(d1)
print(d2)
np.multiply(d1,d2)
print(d1)
print(d2)
np.multiply(d1,d2)
[[0 1] [2 3] [4 5]] [[1 2]]
Out[27]:
matrix([[ 0, 2], [ 2, 6], [ 4, 10]])
In [24]:
Copied!
### List multiplication and dot product
n1 = np.array([[1,2],[5,6],[9,10]])
n2 = np.array([1,2])
print(n1*n2)
print(n1.dot(n2))
### List multiplication and dot product
n1 = np.array([[1,2],[5,6],[9,10]])
n2 = np.array([1,2])
print(n1*n2)
print(n1.dot(n2))
[[ 1 4] [ 5 12] [ 9 20]] [ 5 17 29]
In [28]:
Copied!
print(d1)
print(d1.I)
print(d1)
print(d1.I)
[[0 1] [2 3] [4 5]] [[-1.08333333 -0.33333333 0.41666667] [ 0.83333333 0.33333333 -0.16666667]]
Common function in NumPy¶
add()
,subtract()
,multiply()
,divide()
abs()
,sqrt()
,square()
log()
,log10()
,log2()
reciprocal()
power()
,mod()
,exp()
around()
,ceil()
,floor()
sin()
,cos()
,tan()
modf()
: It takes an input array and returns two arrays - the first one containing the fractional part and the second one containing the integral part of the elements in the input array.arr = np.array([3.5, -2.3, 7.9]) fractional_part, integral_part = np.modf(arr)
sign()
: For each element in the input array,sign
returns 1 if the element is positive, 0 if it's zero, and -1 if it's negative.arr = np.array([-1, 0, 1, 2]) sign_arr = np.sign(arr)
In [32]:
Copied!
d2 = np.array([1.,2.])
print(d2)
print(np.reciprocal(d2))
d2 = np.array([1.,2.])
print(d2)
print(np.reciprocal(d2))
[1. 2.] [1. 0.5]
In [33]:
Copied!
np.power(d2,np.array([1,2]))
np.power(d2,np.array([1,2]))
Out[33]:
array([1., 4.])
In [34]:
Copied!
np.mod(d2,np.array([1,1]))
np.mod(d2,np.array([1,1]))
Out[34]:
array([0., 0.])
In [35]:
Copied!
n = np.array([1.55,68.23,157.65,-15.3,-5.8])
print(n)
print(np.around(n,decimals=-1))
n = np.array([1.55,68.23,157.65,-15.3,-5.8])
print(n)
print(np.around(n,decimals=-1))
[ 1.55 68.23 157.65 -15.3 -5.8 ] [ 0. 70. 160. -20. -10.]
In [36]:
Copied!
arr = np.array([3.5, -2.3, 7.9])
fractional_part, integral_part = np.modf(arr)
fractional_part, integral_part
arr = np.array([3.5, -2.3, 7.9])
fractional_part, integral_part = np.modf(arr)
fractional_part, integral_part
Out[36]:
(array([ 0.5, -0.3, 0.9]), array([ 3., -2., 7.]))
In [37]:
Copied!
arr = np.array([-1, 0, 1, 2])
sign_arr = np.sign(arr)
sign_arr
arr = np.array([-1, 0, 1, 2])
sign_arr = np.sign(arr)
sign_arr
Out[37]:
array([-1, 0, 1, 1])
Statistical function in NumPy¶
sum()
cumsum()
,cumprod()
mean()
,min()
,max()
,median()
,var()
,std()
average()
: is used to compute the weighted average of elements in an array.- Basic Usage:
data = np.array([1, 2, 3, 4, 5]) avg = np.average(data)
- Weighted Average:
weights = np.array([1, 2, 3, 4, 5]) weighted_avg = np.average(data, weights=weights)
- Axis Argument:
data_2d = np.array([[1, 2], [3, 4]]) avg_col = np.average(data_2d, axis=0) # Average across columns avg_row = np.average(data_2d, axis=1) # Average across rows
In [39]:
Copied!
n = np.array([[1,2,3],[4,5,6],[7,8,9]])
n.sum(axis=0),n.sum(axis=1)
n = np.array([[1,2,3],[4,5,6],[7,8,9]])
n.sum(axis=0),n.sum(axis=1)
Out[39]:
(array([12, 15, 18]), array([ 6, 15, 24]))
In [43]:
Copied!
print(n.cumprod(axis=1))
print(n.cumprod(axis=0))
print(n.cumprod(axis=1))
print(n.cumprod(axis=0))
[[ 1 2 6] [ 4 20 120] [ 7 56 504]] [[ 1 2 3] [ 4 10 18] [ 28 80 162]]
Sort in NumPy¶
sort()
argsort()
: is used to sort an array or data along a specific axis, returning the indices that would sort the array.x = np.array([3, 1, 2]) indices = np.argsort(x)
Here, indices will be
[1, 2, 0]
, indicating the sorted order of elements inx
.lexsort()
: is used for indirect lexicographical sorting based on multiple keys.a = np.array([1, 2, 1, 2]) b = np.array([0, 0, 1, 1]) indices = np.lexsort((b, a))
In this example, the array is first sorted by
a
, then byb
. So, indices will be[0, 2, 1, 3]
.
In [47]:
Copied!
n = np.array([[4,7,3],[2,8,5],[9,1,6]])
np.sort(n)
n = np.array([[4,7,3],[2,8,5],[9,1,6]])
np.sort(n)
Out[47]:
array([[3, 4, 7], [2, 5, 8], [1, 6, 9]])
In [48]:
Copied!
np.argsort(n)
np.argsort(n)
Out[48]:
array([[2, 0, 1], [0, 2, 1], [1, 2, 0]], dtype=int64)
In [55]:
Copied!
math = np.array([101,109,115,108,118,118])
en = np.array([117,105,98,108,98,109])
total = np.array([621,623,620,620,615,615])
sort_total = np.lexsort((en,math,total))
print(sort_total)
math = np.array([101,109,115,108,118,118])
en = np.array([117,105,98,108,98,109])
total = np.array([621,623,620,620,615,615])
sort_total = np.lexsort((en,math,total))
print(sort_total)
[4 5 3 2 0 1]
In [56]:
Copied!
lst = [[total[i],math[i],en[i]] for i in sort_total]
lst
lst = [[total[i],math[i],en[i]] for i in sort_total]
lst
Out[56]:
[[615, 118, 98], [615, 118, 109], [620, 108, 108], [620, 115, 98], [621, 101, 117], [623, 109, 105]]
Transfer Graph to Gray Scale(Example)¶
$$ Gray = R * 0.299 + G * 0.587 + B * 0.114 $$
In [57]:
Copied!
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
In [60]:
Copied!
n1 = plt.imread("Data/Pink_flower.jpg")
plt.imshow(n1)
n1 = plt.imread("Data/Pink_flower.jpg")
plt.imshow(n1)
Out[60]:
<matplotlib.image.AxesImage at 0x1bcb6f77610>
In [62]:
Copied!
n1.shape
n1.shape
Out[62]:
(1623, 1699, 3)
In [64]:
Copied!
para_lst = np.array([0.299,0.587,0.144])
gray_img = np.dot(n1,para_lst)
plt.imshow(gray_img)
para_lst = np.array([0.299,0.587,0.144])
gray_img = np.dot(n1,para_lst)
plt.imshow(gray_img)
Out[64]:
<matplotlib.image.AxesImage at 0x1bcb8db6b50>