Why is my unpainted sequence different from when it was pickled?

I am a bit confused about saving the python variable, in my code I use the following code so that the model parameters are saved during some iterations

 with open('W_Hs_Hu_iter'+str(inx)+'.pickle', 'wb') as f:
        pickle.dump((self.W,self.Hs,self.Hu),f)

and after a long iteration I try to load the model with

with open('W_Hs_Hu_iter450.pickle', 'rb') as f:
    W,Hs,Hu= pickle.load(f)
    #W,Hu,Hs= pickle.load(f)

but after I checked this, the sequence of Hs and Hu is wrong? can this happen?

+4
source share
2 answers

I agree with @ peter-wood, it looks correct, also I checked it to make sure.

import pickle

class TestObj(object):
    def __init__(self, one=1, two=2, three=3):
        self.one = one
        self.two = two
        self.three = three

    def save(self):
        with open('D:\\test.pickle', 'wb') as f:
            pickle.dump((self.one,self.two,self.three),f,-1)

    @staticmethod
    def load():
        with open('D:\\test.pickle', 'rb') as f:
            one,two,three = pickle.load(f)
        test_obj = TestObj(one, two, three)
        return test_obj

test_obj = TestObj() #Init with defaults
test_obj.save()
print 'after save: one: %s, two: %s, three: %s' % (test_obj.one,test_obj.two,test_obj.three)
test_obj = test_obj.load()
print 'after load: one: %s, two: %s, three: %s' % (test_obj.one,test_obj.two,test_obj.three)

My best guess is that while saving the values Hsand are Hualready exchanged. Do log \ print before saving.

0

, .

>>> class Foo(object):
...   a = 1
...   b = 2
...   def __init__(self, c,d):
...     self.c = c
...     self.d = d
...   def bar(self):
...     return self.a,self.b,self.c,self.d
... 
>>> f = Foo(3,4)
>>> _f = pickle.dumps(f)
>>> f.c,f.d = f.d,f.c
>>> f.b,f.a = f.a,f.b
>>> f_ = pickle.loads(_f)
>>> f_.bar()
(1, 2, 3, 4)
>>> f.bar()
(2, 1, 4, 3)

, , . , python , , , , -, .

>>> g = Foo(3,4)
>>> _g = pickle.dumps(g)
>>> g.c,g.d = g.d,g.c
>>> Foo.a,Foo.b = Foo.b,Foo.a
>>> g_ = pickle.loads(_g)
>>> g_.bar()
(2, 1, 3, 4)
>>> g.bar()
(2, 1, 4, 3)

, - . , .

>>> Foo.a = []
>>> Foo.zap = lambda self:self.a
>>> Foo.baz = lambda self,x:self.a.append(x)
>>> 
>>> h = Foo(3,4)
>>> h.baz(0)
>>> h.baz(1)
>>> h.zap()
[0, 1]
>>> _h = pickle.dumps(h)
>>> h.baz(2)
>>> h.baz(3)
>>> h_ = pickle.loads(_h)
>>> h_.zap()
[0, 1, 2, 3]

, class, . .

" " (.. ), dill. dill .

>>> import dill
>>> _h = dill.dumps(h)
>>> h.baz(4)
>>> h.baz(5)
>>> h_ = dill.loads(_h)
>>> h_.zap()
[0, 1, 2, 3]
>>> h.zap()
[0, 1, 2, 3, 4, 5]
+2

Source: https://habr.com/ru/post/1610169/


All Articles