I have 4 arrays (all the same length) which I am trying to stack together to create a new array, with each of the 4 arrays being a row.
My first thought was this:
B = -np.array([[x1[i]],[x2[j]],[y1[i]],[y2[j]]])
However the shape of that is (4,1,20).
To get the 2D output I expected I resorted to this:
B = -np.vstack((np.vstack((np.vstack(([x1[i]],[x2[j]])),[y1[i]])),[y2[j]]))
Where the shape is (4,20).
Is there a better way to do this? And why would the first method not work?
Edit
For clarity, the shapes of x1[i], x2[j], y1[i], y2[j] are all (20,).
The problem is with the extra brackets:
B = -np.array([[x1[i]],[x2[j]],[y1[i]],[y2[j]]]) # (4,1,20)
B = -np.array([x1[i],x2[j],y1[i],y2[j]]) # (4,20)
[[x1[i]] is (1,20) in shape.
In [26]: np.array([np.ones((20,)),np.zeros((20,))]).shape
Out[26]: (2, 20)
vstack works, but np.array does just as well. It's concatenate that needs the extra brackets
In [27]: np.vstack([np.ones((20,)),np.zeros((20,))]).shape
Out[27]: (2, 20)
In [28]: np.concatenate([np.ones((20,)),np.zeros((20,))]).shape
Out[28]: (40,)
In [29]: np.concatenate([[np.ones((20,))],[np.zeros((20,))]]).shape
vstack doesn't need the extra dimensions because it first passes the arrays through [atleast_2d(_m) for _m in tup]
np.vstack takes a sequence of equal-length arrays to stack, one on top of the other, as long as they have compatible shapes. So in your case, a tuple of the one-dimensional arrays would do:
np.vstack((x1[i], x2[j], y1[i], y2[j]))
would do what you want. If this statement is part of a loop building many such 4x20 arrays, however, that may be a different matter.
Related
I'm having some trouble understanding the rules for array broadcasting in Numpy.
Obviously, if you perform element-wise multiplication on two arrays of the same dimensions and shape, everything is fine. Also, if you multiply a multi-dimensional array by a scalar it works. This I understand.
But if you have two N-dimensional arrays of different shapes, it's unclear to me exactly what the broadcasting rules are. This documentation/tutorial explains that: In order to broadcast, the size of the trailing axes for both arrays in an operation must either be the same size or one of them must be one.
Okay, so I assume by trailing axis they are referring to the N in a M x N array. So, that means if I attempt to multiply two 2D arrays (matrices) with equal number of columns, it should work? Except it doesn't...
>>> from numpy import *
>>> A = array([[1,2],[3,4]])
>>> B = array([[2,3],[4,6],[6,9],[8,12]])
>>> print(A)
[[1 2]
[3 4]]
>>> print(B)
[[ 2 3]
[ 4 6]
[ 6 9]
[ 8 12]]
>>>
>>> A * B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
Since both A and B have two columns, I would have thought this would work. So, I'm probably misunderstanding something here about the term "trailing axis", and how it applies to N-dimensional arrays.
Can someone explain why my example doesn't work, and what is meant by "trailing axis"?
Well, the meaning of trailing axes is explained on the linked documentation page.
If you have two arrays with different dimensions number, say one 1x2x3 and other 2x3, then you compare only the trailing common dimensions, in this case 2x3. But if both your arrays are two-dimensional, then their corresponding sizes have to be either equal or one of them has to be 1. Dimensions along which the array has size 1 are called singular, and the array can be broadcasted along them.
In your case you have a 2x2 and 4x2 and 4 != 2 and neither 4 or 2 equals 1, so this doesn't work.
From http://cs231n.github.io/python-numpy-tutorial/#numpy-broadcasting:
Broadcasting two arrays together follows these rules:
If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.
The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.
The arrays can be broadcast together if they are compatible in all dimensions.
After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.
In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension
If this explanation does not make sense, try reading the explanation from the documentation or this explanation.
we should consider two points about broadcasting. first: what is possible. second: how much of the possible things is done by numpy.
I know it might look a bit confusing, but I will make it clear by some example.
lets start from the zero level.
suppose we have two matrices. first matrix has three dimensions (named A) and the second has five (named B). numpy tries to match last/trailing dimensions. so numpy does not care about the first two dimensions of B. then numpy compares those trailing dimensions with each other. and if and only if they be equal or one of them be 1, numpy says "O.K. you two match". and if it these conditions don't satisfy, numpy would "sorry...its not my job!".
But I know that you may say comparison was better to be done in way that can handle when they are devisable(4 and 2 / 9 and 3). you might say it could be replicated/broadcasted by a whole number(2/3 in out example). and i am agree with you. and this is the reason I started my discussion with a distinction between what is possible and what is the capability of numpy.
I'm new to Numpy library from Python and I'm not sure what I'm doing wrong here, could you help me please with this?
So, I initialize my ndarray like this.
A = np.array([])
And then I'm training to append into this array A a new array X which has a shape like (1000,32,32) if has any importance.
np.insert(A, X)
The problem here is that if I'm checking the ndarray A after that it's empty, even though the ndarray X has elements inside.
Could you explain me what exactly I'm doing wrong please?
Make sure to write back to A if you use np.append, as in A = np.append(A,X) -- the top-level numpy functions like np.insert and np.append are usually immutable, so even though it gives you a value back, it's your job to store it. np.array likes to flatten the np.ndarray if you use append, so honestly, I think you just want a regular list for A, and that append method is mutable, so no need to write it back.
>>> A = []
>>> X = np.ndarray((1000,32,32))
>>> A.append(X)
>>> print(A)
[array([[[1.43351171e-316, 4.32573840e-317, 4.58492919e-320, ...,
1.14551501e-259, 6.01347002e-154, 1.39804329e-076],
[1.39803697e-076, 1.39804328e-076, 1.39642638e-076, ...,
1.18295070e-076, 7.06474122e-096, 6.01347002e-154],
[1.39804328e-076, 1.39642638e-076, 1.39804065e-076, ...,
1.05118732e-153, 6.01334510e-154, 3.24245662e-086],
...
In [10]: A = np.array([])
In [11]: A.shape
Out[11]: (0,)
In [13]: np.concatenate([A, np.ones((2,3))])
---------------------------------------------------------------------------
...
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)
So one first things you need to learn about numpy arrays is that they have shape, and a number of dimensions. Hopefully that error message is clear.
Concatenate with another 1d array does work:
In [14]: np.concatenate([A, np.arange(3)])
Out[14]: array([0., 1., 2.])
But that is just np.arange(3). The concatenate does nothing for us. OK, you might imagine starting a loop like this. But don't. This is not efficient.
You could easily concatenate a list of arrays, as long as the dimensions obey the rules specified in the docs. Those rules are logical, as long as you take the dimensions of the arrays seriously.
In [15]: X = np.ones((1000,32,32))
In [16]: np.concatenate([X,X,X], axis=1).shape
Out[16]: (1000, 96, 32)
suppose i have 2 numpy arrays as follows:
init = 100
a = np.append(init, np.zeros(5))
b = np.random.randn(5)
so a is of shape (6,) and b is of shape(5,). i would like to add (or perform some other operation, e.g. exponentiation) these together to obtain a new numpy array of shape (6,) whose first value of a (100) is the same and the remaining values are added together (in this case this will just look like appending 100 to b, but that is because it is a toy example initialized with zeroes. attempting to add as is, will produce:
a+b
ValueError: operands could not be broadcast together with shapes (6,) (5,)
is there a one-liner way to use broadcasting, or newaxis here to trick numpy into treating them as compatible shapes?
the desired output:
array([ 100. , 1.93947328, 0.12075821, 1.65319123,
-0.29222052, -1.04465838])
You mean you want to do something like this
np.append(a[0:1], a[1:,] + b)
What do you want your desired output to be? The answer I've provided performs this brodcast add excluding row 1 from a
Not a one-liner but two short lines:
c = a.copy()
c[1:] += b
I am trying to recursively define a numpy array of N dimensions. After researching for several hours, I have came across a couple of ways this might work (np.append and np.concatenate), however neither of these has given me the desired output. I've been getting either:
[-0.6778734 -0.73517866 -0.73517866 0.6778734 ] (1-d array) or
[array([-0.6778734 , -0.73517866]), array([-0.73517866, 0.6778734 ])] (a list of arrays)
My Input:
[(1.2840277121727839, array([-0.6778734, -0.73517866])),
(0.049083398938327472, array([-0.73517866, 0.6778734 ]))]
Desired output:
array([-0.6778734, -0.73517866], [-0.73517866, 0.6778734])
Is it possible to create a numpy array from arrays, because converting them to lists and back to arrays seems computationally inefficient?
Thanks in advance!
Your input is a list of tuples, each tuple consisting of a number and an array. For some reason you want to throw away the number, and just combine the arrays into a larger array - is that right?
In [1067]: x=[(1.2840277121727839, np.array([-0.6778734, -0.73517866])),
(0.049083398938327472, np.array([-0.73517866, 0.6778734 ]))]
In [1068]: x
Out[1068]:
[(1.2840277121727839, array([-0.6778734 , -0.73517866])),
(0.04908339893832747, array([-0.73517866, 0.6778734 ]))]
A list comprehension does a nice job of extracting the desired elements for the tuples:
In [1069]: [y[1] for y in x]
Out[1069]: [array([-0.6778734 , -0.73517866]), array([-0.73517866, 0.6778734 ])]
and vstack is great for combining arrays into a larger one.
In [1070]: np.vstack([y[1] for y in x])
Out[1070]:
array([[-0.6778734 , -0.73517866],
[-0.73517866, 0.6778734 ]])
vstack is just concatenate with an added step that ensures the inputs are 2d.
np.array([y[1] for y in x]) also works, since you are adding a dimension.
I'm assuming that array([-0.6778734, -0.73517866], [-0.73517866, 0.6778734]) has a typo - that it is missing a set of []. The 2nd parameter to np.array is the dtype, not another list.
Note that both np.array and np.concatentate take a list. It can be list of lists, or list of arrays. It doesn't make much difference. And at this stage don't worry about computational efficiency. Any time you combine the data from 2 or more arrays there will be copying. Arrays have a fixed size, and can't 'grow' without making a new copy.
In [1074]: np.concatenate([y[1] for y in x]).reshape(2,2)
Out[1074]:
array([[-0.6778734 , -0.73517866],
[-0.73517866, 0.6778734 ]])
Lists are effectively 1d, so np.concatenate joins them on that dimension, producing a 4 element 1d array. reshape corrects that. vstack makes them both (1,2) and does a concatenate on the 1st dimension.
Another expression that joins the arrays on a new dimension:
np.concatenate([y[1][None,...] for y in x], axis=0)
The [None,...] adds a new dimension at the start.
Try this:
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])
print(repr(np.vstack((a, b))))
Gives:
array([[1, 2],
[3, 4]])
You can form the desired 2D array given a list input_data of the form
input_data = [(1.2840277121727839, np.array([-0.6778734, -0.73517866])),
(0.049083398938327472, np.array([-0.73517866, 0.6778734 ]))]
via
nparr = np.array(list(row[1] for row in input_data))
For example, I want a 2 row matrix, with a first row of length 1, and second row of length 2. I could do,
list1 = np.array([1])
list2 = np.array([2,3])
matrix = []
matrix.append(list1)
matrix.append(list2)
matrix = np.array(matrix)
I wonder if I could declare a matrix of this shape directly in the beginning of a program without going through the above procedure?
A matrix is by definition a rectangular array of numbers. NumPy does not support arrays that do not have a rectangular shape. Currently, what your code produces is an array, containing a list (matrix), containing two more arrays.
array([array([1]), array([2, 3])], dtype=object)
I don't really see what the purpose of this shape could be, and would advise you simply use nested lists for whatever you are doing with this shape. Should you have found some use for this structure with NumPy however, you can produce it much more idiomatically like this:
>>> np.array([list1,list2])
array([array([1]), array([2, 3])], dtype=object)