Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving List of Numpy 2D arrays using numpy.save (the arrays together are jagged)

I have a large image dataset. When I use the images, I have several components--a mirrored image, a regular image, an eigenvector matrix and an eigenvalue vector.

I would like to store it like:

training_sunsets_data = [cropped_training_sunsets,
                         mirrored_training_sunsets,
                         rgb_cov_eigvec_training_sunsets,
                         rgb_cov_eigval_training_sunsets]

np.save('training_sunsets_data',training_sunsets_data)

And as I was writing this I was testing it (because I was sure it would fail), and the strangest thing happened when I did this: it worked.

Further, when I loaded it back up into the code, it was type ndarray, but it is a jagged array.


How is this possible if numpy does not allow jagged multidimensional arrays? Did I just find a backdoor way to create a jagged array in numpy?

like image 643
Chris Avatar asked Apr 22 '16 23:04

Chris


People also ask

Can Numpy arrays be jagged?

NumPy does not support jagged arrays natively.

How do I save a list as a Numpy array?

import numpy as np # b is some list, then ... a = np. array(b). reshape(lengthDim0, lengthDim1); gives you a as an array of list b in the shape given in reshape.

How do I save Numpy array to Numpy?

You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.


2 Answers

After testing on my machine:

  import numpy as np
  np.save('testnp.npy', [[2,3,4],[1,2]])
  np.load('testnp.npy')
  #   array([[2, 3, 4], [1, 2]], dtype=object)

As shown in the example code, the loaded object is of type ndarray, but its data type is object. That means, np.save store an array of python objects, which can be anything. According to the documentation, it seems to use python pickle to pack those objects.

So you didn't find a backdoor, it behaves just as expected.

like image 95
gdlmx Avatar answered Oct 22 '22 15:10

gdlmx


np.savez() would work in your situation. save each as a variable.

like image 22
Dan Erez Avatar answered Oct 22 '22 13:10

Dan Erez