保存变量以供以后在Python中使用

时间:2017-03-28 08:24:23

标签: python

我试图在神经网络上学习,我写了第一个程序。我希望不要浪费所有花在训练网上的时间,方法是将调整后的参数保存在文件中,然后加载它(一小时,一天或一年)。 这是Network类的结构构造函数,我想保存它的可靠性:

def __init__(self, sizes):
    self.num_layers = len(sizes)
    self.sizes = sizes
    self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
    self.weights = [np.random.randn(y, x)
             for x, y in zip(sizes[:-1], sizes[1:])]
    return

这是我尝试保存并加载它,

def save(net, name = "noname"):
    with open("{0}_nn_sizes.nn".format(name),"w") as s:
        s.write(str(net.sizes))
    with open("{0}_nn_weights.nn".format(name),"w") as w:
        w.write(str(net.weights))
    with open("{0}_nn_biases.nn".format(name),"w") as b:
        b.write(str(net.biases))
    return

def load(name = "noname"):
    with open("{0}_nn_sizes.nn".format(name),"w") as s:
        net=nn.Network(list(s)) """ERROR HERE"""
    with open("{0}_nn_weights.nn".format(name),"w") as w:
        net.weights = list(w)
    with open("{0}_nn_biases.nn".format(name),"w") as b:
        net.biases = list(b)
    return net

在指向的地方发生io.UnsupportedOperation: not readable错误后,发生了灾难性的失败。

实际上我很确定即使这种做法也不好,所以我很乐意接受任何有关如何解决问题的建议或暗示。

1 个答案:

答案 0 :(得分:0)

感谢LaundroMat的提示,我在以下代码中找到了一个使用pickle库的工作解决方案

import pickle

def save(net, name = "noname"):
    with open("{0}.nn".format(name),"wb") as save_file:
        pickle.dump(net,save_file)

def load(name = "noname"):
    with open("{0}.nn".format(name),"rb") as load_file:
        return pickle.load(load_file)

但是,任何评论仍然很感激。