如何使用savez保存数组

时间:2017-01-30 13:23:39

标签: python numpy

我遇到了不同的例子。但我无法理解他们。这是我的清单: 在第一个列表中,我保存权重,在第二个相应的键中  存储。

        self.weight_list=[]
        self.keys=[]

例如:

# conv1_1
    with tf.name_scope('conv1_1') as scope:
        kernel = tf.Variable(tf.truncated_normal([3, 3, 3, 64], dtype=tf.float32,
                                                 stddev=1e-1), name='weights')
        conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')
        biases = tf.Variable(tf.constant(0.0, shape=[64], dtype=tf.float32),
                             trainable=True, name='biases')
        out = tf.nn.bias_add(conv, biases)
        self.conv1_1 = tf.nn.relu(out, name=scope)
        self.parameters += [kernel, biases]
    self.keys.append('conv1_1')
    self.weight_list.append(self.parameters)

我不知道如何以npz格式保存这些数组。

我尝试实施此示例How to use `numpy.savez` in a loop for save more than one array?  这是错误。

Traceback (most recent call last):
  File "f.py", line 355, in <module>
    vgg = vgg16(imgs1,imgs2, 'vgg16_weights.npz', sess)
  File "f.py", line 43, in __init__
    self.SaveWeights()
  File "f.py", line 344, in SaveWeights
    exec(str_exec_save)
  File "<string>", line 1, in <module>
NameError: name 'conv1_1' is not defined

以下是我实施它的方式

def SaveWeights(self):

    tmp = file("vgg16_predict.npz",'wb')




        # save the npz file with the variables you selected
    str_exec_save = "np.savez(tmp,"    
    for i in range(len(self.keys)):    
         str_exec_save += "%s = %s," % (self.keys[i],self.keys[i])
         str_exec_save += ")"
         exec(str_exec_save)

    tmp.close

1 个答案:

答案 0 :(得分:1)

这可能有效:

numpy.savez(**dict(zip(self.keys, self.weight_list)))

使用双星号**将dict解包为关键字参数。这在概念上与numpy.savez(conv1_1=self.parameters, conv1_2=..., ...)相同。