1 Dimension – Vector
1 2 3 4 5 6 7 8 9 10 |
>>> a = np.array([0, 1, 2, 3]) >>> a array([0, 1, 2, 3]) >>> a.ndim 1 >>> a.shape (4,) >>> len(a) 4 |
2 Dimension – Matrix
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# 2D >>> b = np.array([[0, 1, 2], [3, 4, 5]]) # 2 x 3 array >>> b array([[ 0, 1, 2], [ 3, 4, 5]]) >>> b.ndim 2 >>> b.shape (2, 3) >>> len(b) # returns the size of the first dimension 2 ### 3D >>> c = np.array([[[1], [2]], [[3], [4]]]) >>> c array([[[1], [2]], [[3], [4]]]) >>> c.shape (2, 2, 1) |
Tensor
Google has created a data structure named tensor that is used to deal with n-dimension array
Populate your array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
a = np.arange(10) # 0 .. n-1 >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> b = np.arange(1, 9, 2) # start, end (exlusive), step >>> b array([1, 3, 5, 7]) ## common arrays >>> a = np.ones((3, 3)) # reminder: (3, 3) is a tuple >>> a array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]) >>> b = np.zeros((2, 2)) >>> b array([[ 0., 0.], [ 0., 0.]]) >>> c = np.eye(3) >>> c array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> d = np.diag(np.array([1, 2, 3, 4])) >>> d array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]) >>> a = np.random.rand(4) # uniform in [0, 1] >>> a array([ 0.58597729, 0.86110455, 0.9401114 , 0.54264348]) >>> b = np.random.randn(4) # Gaussian >>> b array([-2.56844807, 0.06798064, -0.36823781, 0.86966886]) >>> np.random.seed(1234) # Setting the random seed |
Connect with us