How to multiply numpy 2D array with numpy 1D array? - python

The two arrays:
a = numpy.array([[2,3,2],[5,6,1]])
b = numpy.array([3,5])
c = a * b
What I want is:
c = [[6,9,6],
[25,30,5]]
But, I am getting this error:
ValueError: operands could not be broadcast together with shapes (2,3) (2)
How to multiply a nD array with 1D array, where len(1D-array) == len(nD array)?

You need to convert array b to a (2, 1) shape array, use None or numpy.newaxis in the index tuple:
import numpy
a = numpy.array([[2,3,2],[5,6,1]])
b = numpy.array([3,5])
c = a * b[:, None]
Here is the document.

Another strategy is to reshape the
second array, so it has the same number of dimensions as the first array:
c = a * b.reshape((b.size, 1))
print(c)
# [[ 6 9 6]
# [25 30 5]]
Alternatively, the shape attribute of the second array can be modified in-place:
b.shape = (b.size, 1)
print(a.shape) # (2, 3)
print(b.shape) # (2, 1)
print(a * b)
# [[ 6 9 6]
# [25 30 5]]

Related

Numpy Matrix Subtraction Different Dimensions

I currently have a 5D numpy array of dimensions 40 x 3 x 3 x 5 x 1000 where the dimensions are labelled by a x b x c x d x e respectively.
I have another 2D numpy array of dimensions 3 x 1000 where the dimensions are labelled by b x e respectively.
I wish to subtract the 5D array from the 2D array.
One way I was thinking of was to expand the 2D into a 5D array (since the 2D array does not change for all combinations of the other 3 dimensions). I am not sure what array method/numpy function I can use to do this.
I tend to start getting lost with nD array manipulations. Thank you for assisting.
In [217]: a,b,c,d,e = 2,3,4,5,6
In [218]: A = np.ones((a,b,c,d,e),int); B = np.ones((b,e),int)
In [219]: A.shape
Out[219]: (2, 3, 4, 5, 6)
In [220]: B.shape
Out[220]: (3, 6)
In [221]: B[None,:,None,None,:].shape # could also use reshape()
Out[221]: (1, 3, 1, 1, 6)
In [222]: C = B[None,:,None,None,:]-A
In [223]: C.shape
Out[223]: (2, 3, 4, 5, 6)
The first None isn't essential; numpy will add it as needed, but as a human it might help to see it.
IIUC, suppose your arrays are a and b:
np.swapaxes(np.swapaxes(a, 1, 3) - b, 1, 3)

Numpy Matrix Multiplication with Vectors

i wanna do a simple matrix multiplication with 2 Vectors: so that A * B.T = 3x3Matrix.
But somehow numpy returns a scalar or vector.
i already tried:
np.dot(a, b.transpose())
np.matmul(a, b.transpose())
a * b.transpose()
But nothins works, it seems like a simple operation to me, but i just cannot solve it
The reason why you are getting a scalar because you are multiplying two 1D vectors in numpy, which produces the inner product of 2 vectors. You need to reshape your vector to the shape (3,1), which turns them into a 2D shape and then you get the expected result upon performing the vector multiplication. Check the snippet below
>>> import numpy as np
>>> A = np.array([1,2,3])
>>> B = np.array([4,5,6])
>>> A.shape
(3,)
>>> B.shape
(3,)
>>> AA = A.reshape(3, 1)
>>> BB = B.reshape(3, 1)
>>> AA.shape
(3, 1)
>>> BB.shape
(3, 1)
>>> np.matmul(AA, np.transpose(BB))
array([[ 4, 5, 6],
[ 8, 10, 12],
[12, 15, 18]])
Using numpy.reshape works for me all the time.
Maybe you're stumbling on it because of your matrix's size.
A should be (3,1) dan B.transpose should be (1,3).
When using numpy.dot, both matrix should have the same inner size. In your case is (1). The inner should be 1 because the inner of AxA_transpose is (3,1)x(1,3). Result will be 3x3 matrix.
Do:
A_ = np.reshape(A,(1,-1)) # array (3,1)
B_ = np.reshape(B,(1,-1))
C = np.dot(A_,B_.T) # T for transpose

Matrix size in Python

a is a 2x2 matrix
b is a 2x1 matrix
c is a 1x2 matrix
But ... what kind of matrices d is?
import numpy as np
a= np.array([[1,2],[3,4]])
b= np.array([[1],[2]])
c= np.array([[1,2]])
d= np.array([1,2])
Variable explorer
The variable d is not a matrix but a row vector.
import numpy as np
a= np.array([[1,2],[3,4]])
b= np.array([[1],[2]])
c= np.array([[1,2]])
d= np.array([1,2])
print(a.shape, b.shape, c.shape, d.shape)
print(a.ndim, b.ndim, c.ndim, d.ndim)
outputs shapes:
(2, 2) (2, 1) (1, 2) (2,)
and dimensions:
2 2 2 1
The number of brackets indicate the number of dimensions, for example:
e = np.array([[[1,2]]])
outputs shape (1, 1, 2) and ndim 3 (so 3 dimensional).
It's a 1-dimensional array with 2 elements in it.
Check the output in the sandbox.

Multidimensional array in numpy

I have an array of shape (5,2) which each row consist of an array of shape (4,3,2) and a float number.
After I slice that array[:,0], I get an array of shape (5,) which each element has shape of (4,3,2), instead of an array of shape (5,4,3,2) (even if I'd use np.array()).
Why?
Edited
Example:
a1 = np.arange(50).reshape(5, 5, 2)
a2 = np.arange(50).reshape(5, 5, 2)
b1 = 15.0
b2 = 25.0
h = []
h.append(np.array([a1, b1]))
h.append(np.array([a2, b2]))
h = np.array(h)[:,0]
np.shape(h) # (2,)
np.shape(h[0]) # (5, 5, 2)
np.shape(h[1]) # (5, 5, 2)
h = np.array(h)
np.shape(h) # (2,) Why not (2, 5, 5, 2)?
You have an array of objects; You can use np.stack to convert it to the shape you need if you are sure all the sub elements have the same shape:
np.stack(a[:,0])
a = np.array([[np.arange(24).reshape(4,3,2), 1.]]*5)
a.shape
# (5, 2)
a[:,0].shape
# (5,)
a[:,0][0].shape
# (4, 3, 2)
np.stack(a[:,0]).shape
# (5, 4, 3, 2)
In [121]: a1.dtype, a1.shape
Out[121]: (dtype('int32'), (5, 5, 2))
In [122]: c1 = np.array([a1,b1])
In [123]: c1.dtype, c1.shape
Out[123]: (dtype('O'), (2,))
Because a1 and b1 are different shaped objects (b1 isn't even an array), an array made from them will have dtype object. And the h made from several continues to be object dtype.
In [124]: h = np.array(h)
In [125]: h.dtype, h.shape
Out[125]: (dtype('O'), (2, 2))
In [126]: h[:,1]
Out[126]: array([15.0, 25.0], dtype=object)
In [127]: h[:,0].dtype
Out[127]: dtype('O')
After the appends, h (as an array) is object dtype. The 2nd column is the b1 and b2 values, the 1st column the a1 and a2.
Some form of concatenate is required to combine those a1 a2 arrays into one. stack does it on a new axis.
In [128]: h[0,0].shape
Out[128]: (5, 5, 2)
In [129]: np.array(h[:,0]).shape # np.array doesn't cross the object boundary
Out[129]: (2,)
In [130]: np.stack(h[:,0]).shape
Out[130]: (2, 5, 5, 2)
In [131]: np.concatenate(h[:,0],0).shape
Out[131]: (10, 5, 2)
Turning the (2,) array into a list, does allow np.array to recombine the elements into a higher dimensional array, just as np.stack does:
In [133]: np.array(list(h[:,0])).shape
Out[133]: (2, 5, 5, 2)
You appear to believe that Numpy can magically divine your intent. As #Barmar explains in the comments, when you slice a shape(5,2) array with [:, 0] you get all rows of the first column of that array. Each element of that slice is a shape(4,3,2) array. Numpy is giving you exactly what you asked for.
If you want to convert that into a shape(5,4,3,2) array you'll need to perform further processing to extract the elements from the shape(4,3,2) arrays.

check if numpy array is multidimensional or not

I want to check if a numpy array is multidimensional or not?
V = [[ -7.94627203e+01 -1.81562235e+02 -3.05418070e+02 -2.38451033e+02][ 9.43740653e+01 1.69312771e+02 1.68545575e+01 -1.44450299e+02][ 5.61599000e+00 8.76135909e+01 1.18959245e+02 -1.44049237e+02]]
How can I do that in numpy?
Use the .ndim property of the ndarray:
>>> a = np.array([[ -7.94627203e+01, -1.81562235e+02, -3.05418070e+02, -2.38451033e+02],[ 9.43740653e+01, 1.69312771e+02, 1.68545575e+01, -1.44450299e+02],[ 5.61599000e+00, 8.76135909e+01, 1.18959245e+02, -1.44049237e+02]])
>>> a.ndim
2
In some cases, you should also add np.squeeze() to make sure there are no "empty" dimensions
>>> a = np.array([[1,2,3]])
>>> a.ndim
2
>>> a = np.squeeze(a)
>>> a .ndim
1
You can use .shape property too, which gives you a tuple containing the length of each dimension. Therefore, to get the dimension using .shape you could aswell call len() on the resulting tuple:
import numpy as np
a = np.array([1,2,3])
b = np.array([[1,2,3]])
c = np.array([[1,2,3],[2,4,6],[3,6,9]])
print("a={}".format(a))
print("a.shape: {}; len(a.shape): {}".format(a.shape, len(a.shape)))
print("b={}".format(b))
print("b.shape: {}; len(b.shape): {}".format(b.shape, len(b.shape)))
print(c)
print("c.shape: {}; len(c.shape): {}".format(c.shape, len(c.shape)))
Output:
a=[1 2 3]
a.shape: (3,); len(a.shape): 1
b=[[1 2 3]]
b.shape: (1, 3); len(b.shape): 2
[[1 2 3]
[2 4 6]
[3 6 9]]
c.shape: (3, 3); len(c.shape): 2

Categories

Resources