Skip to content Skip to sidebar Skip to footer

Can Cpickle Save Reshaped Numpy Object Reference?

I have a class defined as: class A(): def __init__(): self.a = np.array([0,1,2,3,4,5]) self.b = self.a.reshape((2, 3)) now, b is in fact a reshaped reference o

Solution 1:

You can use __getstate__ and __setstate__ to control the pickle:

import numpy as np

classA:
    def__init__(self):
        self.a = np.array([0,1,2,3,4,5])
        self.b = self.a.reshape((2, 3))

    def__getstate__(self):
        return {"a":self.a, "b":self.b.shape}

    def__setstate__(self, state):
        self.a = state["a"]
        self.b = self.a.reshape(state["b"])

import pickle

x = A()
s = pickle.dumps(x)
y = pickle.loads(s)

y.b.base is y.a

Solution 2:

the latest prerelease of jsonpickle does correctly serialize numpy views; pickle sadly does not.

Post a Comment for "Can Cpickle Save Reshaped Numpy Object Reference?"