Come scrivere un enorme array NumPy 2D in un buffer

Oct 24 2020

Ho un enorme array numpy 2D (dtype = bool) e un buffer e vorrei scrivere questo array 2D nel buffer. Attualmente, faccio quanto segue,

# Python version 3.7.7, NumPy version 1.18.5
# shape in the dummy_array is just an example, sometimes will be bigger
dummy_array = np.array(np.empty((599066148, 213), dtype='bool'), dtype='bool')

# Pyarrow plasma store buffer
buf = client.create(object_id, dummy_array.nbytes)

# Get a NumPy view of the buffer
array = np.frombuffer(buf, dtype="bool").reshape(dummy_array.shape)

# Write the data or the NumPy array to the buffer
array[:] = dummy_array

Il problema è che questo richiede almeno 3 minuti. La dimensione di dummy_arraysolito è da 100 a 200 GB e talvolta anche di più. Non sono riuscito a capire come farlo usando memoryviewe np.ctypeslib.as_array(buf, shape=dummy_array.shape)come menzionato in questa domanda per un array 2D (ho provato, ma non ha funzionato). Qualsiasi suggerimento per farlo in un modo migliore o più veloce sarebbe fantastico perché lo farò almeno poche centinaia di volte, quindi, risparmiare anche da 30 a 60 secondi per iterazione risparmierebbe ore.

Risposte

forgetso Nov 20 2020 at 16:59

Non è possibile assegnare una slice memoryview multidimensionale.

NotImplementedError: memoryview slice assignments are currently restricted to ndim = 1

Quindi potresti dover rimodellare il tuo array in modo che sia unidimensionale prima di copiarlo in una memoryview.

>>> dummy_array = np.array(np.empty((2, 213), dtype='bool'), dtype='bool').reshape(2*213)
>>> mem = memoryview(dummy_array)
>>> mem[0]
True
>>> np.frombuffer(mem, dtype="bool").reshape(dummy_array.shape)
array([ True,  True,  True,  True,  True,  True, False, False,  True,

Se provi a utilizzare il multidimensionale, otterrai questo errore.

>>> dummy_array = np.array(np.empty((2, 213), dtype='bool'), dtype='bool')
>>> mem = memoryview(dummy_array)
>>> mem[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NotImplementedError: multi-dimensional sub-views are not implemented

Non posso dirti se questo sarà più veloce del tuo altro metodo, ma potrebbe darti alcune idee su come far funzionare la versione memoryview.