Problems in np.reshape arrays - arrays

I have a problem when np.reshape an array.
I have a list roi_x with a total size of 120 elements, each of which is a np.array of float of different sizes:
len(roi_x)
Out: 120
for i in range(len(roi_x)):
print(len(roi_x[i]))`
625
3125
6250
625
3125
6250
... # and so on
I want to reshape it, but I get an error (even though I get the reshaped array):
roi_x = np.reshape(roi_x, (20,6))
VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
result = getattr(asarray(obj), method)(*args, **kwds)
After a bit of research, I adjusted my code as suggested and I don't get the error anymore and I am happy with the outcome:
roi_x = np.array(roi_x, dtype=object) # I added dtype=object
roi_x.shape
Out: (120,) # I get just the first dimension
roi_x = np.reshape(roi_x, (20,6))
roi_x.shape
Out: (20, 6)
However, when I try to do the same with another array roi_x of different size:
len(roi_x)
Out: 192
for i in range(len(roi_x)):
print(len(roi_x[i]))`
625
625
625
625
625
625
... # in this case, all with the same size
And I try to reshape it following the same procedure (but with a different shape):
roi_x = np.array(roi_x, dtype=object)
roi_x.shape
Out: (192, 625) # it is already a different outcome compared to before, there is a 2nd dimension
roi_x = np.reshape(roi_x, (48,4)) # 48*4=192 so it should be ok
I get the following error:
ValueError: cannot reshape array of size 120000 into shape (48,4)
I can't figure out what I am doing different between my two examples.
Any ideas?
I had a look at this : Reshaping arrays in an array of arrays
and I tried to reshape each item, but I get an error:
roi_x = [i.reshape(48, 4) for i in roi_x]
ValueError: cannot reshape array of size 625 into shape (48,4)
Thank you in advance!

Related

Size of outputs in OpenMDAO

Is it possible to have lists or arrays passed as outputs of components in openMDAO?
Since my problem relies on 6x6 matrices to solve an equation of motion in 6 degrees of freedom, I would like to be able to do the following:
M = np.ones([6, 6])
outputs['M'] = M
However, that results in an error:
ValueError: cannot reshape array of size 36 into shape (1,)
Is there any way to avoid passing each of 36 values seperately?
Yes, you can declare an output of any size or shape in your component's setup method by doing the following:
self.add_output('M', shape=(6, 6))
or
self.add_output('M', val=np.ones((6, 6)))

How to calculate the mean by index of N elements in an array in R

I have a generic array of 15 elements. Each element in this array is a 159 by 159 matrix.
Now, I want to calculate the mean of of each index across 15 elements and store the result in a new 159 by 159 matrix, which has the new index resulting from the mean of the same index position over 15 elements of the original array.
This is a nested array if I am allowed to say so. This is also an EigenFace problem on an open source site that I found interesting. So, long story short, this array is a collection of 15 people, and each person has 11 images taken with 11 facial emotions such as wink, happy, sad, etc. So it is an array of 15 elements, each element is also an array of 11 rows and thousands of columns of pixels to portray the facial expression of that person.
For instance, the new index [1,1] of the new matrix is obtained by taking the mean of [1,1] indexes from 15 elements/matrices in the original array.
I would like to avoid using the for loop and hope that there is a built-in function which I can utilize.
Any tips would be greatly appreciated!
You could use Reduce():
data <- list(matrix(1:16, 4), matrix(1:16, 4))
result <- Reduce('+', data)
result <- result * 1/length(data)

Making an array of images in numpy python 2.7

I want to have an array of images. For example, I would have a 4x1 array, (called imslice below) where each element is a nxnx3 image.
I want to do this to to do matrix operations on my imslice matrix like it was a normal matrix. For example, multiply it by a regular 2x2 matrix (called V.) When I try an do this right now, I am getting an array with 5 dimensions and when I try and multiply it by my V matrix I am getting the error that the dimensions don't agree (even though mathematically it's fine because the inner dimensions agree.)
Code:
imslice = np.array(([imslice1q, imslice2q, imslice3q, imslice4q]))
print imslice.shape
V = mh.gen_vmonde(4, 2, 1)
V.shape
C = np.dot(np.transpose(V), imslice)
------------------------------------------- ValueError Traceback (most recent call
last)
in ()
6 V.shape
7
----> 8 np.dot(np.transpose(V), imslice)
9
ValueError: shapes (6,4) and (4,178,178,3) not aligned: 4 (dim 1) !=
178 (dim 2)
Both np.dot and np.matmul treat more-than-two-dimensional arrays as stacks of matrices, so the last and last but one dimensions have to match.
A simple workaround in your case would be transposing:
np.dot(imslice.T, V).T
If you need something more flexible, there is np.einsum:
np.einsum('ji,jklm', V, imslice)

Reshaping an outputted 1 dimensional numpy array into a 2/3 dimensional array

So I'm using an image's pixel data, applying some calculations to it, which gives me a resulting array whose shape is unknown until the calculations are done to it.
I'm having trouble reshaping the outputted array into a 2-dimensional or 3-dimensional array
Here is an example
from PIL import Image
img = Image.open('C:\Users\Amit\Desktop\sample_pic.jpeg').convert("RGB")
pixels =np.array(img)
print(pixels.shape) # (477L, 887L, 3L) PIL seems to switch height and width because original dimensions are 877 x 477
flat = pixels.flatten()
print (flat.shape) # (1269297L,)
filter1= np.array([1,1,0])
pixels2 = np.array([])
for i in range(0, len(flat),2):
pixels2 =np.append(pixels2,np.sum((flat[i:i+3] * filter1)))
The loop at the end is just doing some calculations to the flattened array, and outputting a new array whose shape I don't know till the output
print pixels2.shape
#(634649L,)
So I'm trying to reshape the outputted array into dimensions fit for a picture.
I tried the code
pixels2.reshape(800,-1)
but I got the error
pixels2.reshape(800,-1)
ValueError: total size of new array must be unchanged
same with
pixels.reshape(800,-1,3)
ValueError: total size of new array must be unchanged
I was hoping that adding the (-1) would automatically find the appropriate second dimension but that doesn't seem to be the case. I'm not bound to the number 800 as one of the dimensions but I'm looking for the first two dimensions to be above 300 so (300+, 300+, 3)
Thanks.
Update:
adding one more element to the pixels2 array, makes it a (634650L,) array which is divisible by 3. ( I found it by trial and error)
But finding the other two dimensions involves a lot of trial and error as well it seems. (800, -1, 3) doesn't work.

How to convert a cell array of 2D matrices into a multidimensional array in MATLAB

In MATLAB, I have a defined cell array C of
size(C) = 1 by 150
Each matrix T of this cell C is of size
size(C{i}) = 8 by 16
I am wondering if there is a way to define a new multidimension (3D) matrix M that is of size 8 by 16 by 150
That is when I write the command size(M) I get 8 by 16 by 150
Thank you! Looking forward for your answers
If I'm understanding your problem correctly, you have a cell array of 150 cells, and each cell element is 8 x 16, and you wish to stack all of these matrices together in the third dimension so you have a 3D matrix of size 8 x 16 x 150.
It's a simple as:
M = cat(3, C{:});
This syntax may look strange, but it's very valid. The command cat performs concatenation of matrices where the first parameter is the dimension you want to concatenate to... so in your case, that's the third dimension, and the parameters after are the matrices you want to concatenate to make the final matrix.
Doing C{:} creates what is known as a comma-separated list. This is equivalent to typing out the following syntax in MATLAB:
C{1}, C{2}, C{3}, ..., C{150}
Therefore, by doing cat(3, C{:});, what you're really doing is:
cat(3, C{1}, C{2}, C{3}, ..., C{150});
As such, you're taking all of the 150 cells and concatenating them all together in the third dimension. However, instead of having to type out 150 individual cell entries, that is encapsulated by creating a comma-separated list via C{:}.

Resources