what's the difference between (4,) and (4,1) for the shape in Numpy?
Asked Answered
G

2

5

I have two ndarray A and B, one has the shape (4,) and another (4,1).

When I want to calculate the cosine distance using this, it throws some exceptions that complains the two objects are not aligned

Does anyone have ideas about this? Thanks!

Giblets answered 3/11, 2012 at 18:31 Comment(0)
D
9

One is a 1-dimensional array, the other is a 2-dimensional array.

Example:

>>> import numpy as np
>>> a = np.arange(4).reshape(4,1)
>>> a
array([[0],
       [1],
       [2],
       [3]])
>>> a.ravel()
array([0, 1, 2, 3])
>>> a.squeeze()
array([0, 1, 2, 3])
>>> a[:,0]
array([0, 1, 2, 3])
>>>
>>> a[:,0].shape
(4,)
Damick answered 3/11, 2012 at 18:33 Comment(9)
How can a convert a 4*1 array to a vector with 4-element?Giblets
There's also .squeeze() (docs).Megmega
@Damick Sorry.. the ravel() change the shape of (4,1) to (1,), how can I change the shape from (4,1) to (4,)Giblets
@firegun Perhaps the easiest way to change [ [1], [2], [3], [4] ] to [1, 2, 3, 4] is your_array.TCanescent
@JonClements -- your_array.T gives array([[1, 2, 3, 4]]). Not array([1, 2, 3, 4])Damick
if you have an array x= np.array([[1],[2],[3],[4]]), shape (4,1). You can flatten it so it will have a shape (4,). y = x.flatten(). The shape of y is now (4,)Cushing
@Damick Right you are.... My Python-fu leaves a lot to be desired the last day or so... Maybe it's too much coffee and not enough sleep!Canescent
@AbdulhaqElhouderi -- I think that flatten creates a copy, which seems unnecessary ...Damick
@firegun: no, .ravel() changes the shape of (4,1) to (4,)Vetter
H
0

An ndarray having shape equal to (4,) is a 1-Dimensional NumPy array.
Example,

>>> import numpy as np
>>> array_1 = np.random.randint(0,10,4)
>>> array_1
array([9, 3, 0, 4])
>>> array_1.shape    # shape of array_1
(4,)
>>> array_1.ndim    # number of dimensions in array_1
1

An ndarray having shape equal to (4,1) is a 2-Dimensional NumPy array having 4 rows and 1 column. It is also called a column vector.
Example,

>>> array_2 = np.random.randint(0, 10, (4,1))
>>> array_2
array([[7],
       [0],
       [5],
       [8]])
>>> array_2.shape    # shape of array_2
(4, 1)
>>> array_2.ndim    # number of dimensions in array_2
2

An ndarray having shape equal to (1,4) is a 2-Dimensional NumPy array having 1 row and 4 columns. It is also called a row vector.
Example,

>>> array_3 = np.random.randint(0, 10, (1,4))
>>> array_3
array([[0, 5, 2, 6]])
>>> array_3.shape    # shape of array_3
(1, 4)
>>> array3.ndim    # number of dimensions in array_3
2

As a general rule, the number of [ (opening square brackets) at the beginning of the array or the number of ] (closing square brackets) at the end of the array represents the number of dimensions in the array.
For Example,
[1, 2, 3] is a 1-D array, [[1,2,3], [4,5,6]] is a 2-D array, and so on.

Hillhouse answered 8/6 at 5:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.