Can cPickle save reshaped numpy object reference?

2019-07-18 19:38发布

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 of array a. If we change the first element of a:a[0] = 10, b[0, 0] will also change to 10. I use cPickle to save this array, however, when I load the dump. a and b become different array. I want to know whether there are any method to make b still the reference of a?

2条回答
爷、活的狠高调
2楼-- · 2019-07-18 20:26

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

查看更多
放荡不羁爱自由
3楼-- · 2019-07-18 20:43

You can use __getstate__ and __setstate__ to control the pickle:

import numpy as np

class A:
    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
查看更多
登录 后发表回答