Paddlepaddle如何只加载指定变量?
Created by: jayxio
请问paddlepaddle如何加载指定变量?比如,如果我用如下程序训练了一个CNN
def mnist_cnn_model(img):
"""
Mnist cnn model
Args:
img(Varaible): the input image to be recognized
Returns:
Variable: the label prediction
"""
conv_pool_1 = fluid.nets.simple_img_conv_pool(
input=img,
num_filters=20,
filter_size=5,
pool_size=2,
pool_stride=2,
act='relu')
conv_pool_2 = fluid.nets.simple_img_conv_pool(
input=conv_pool_1,
num_filters=50,
filter_size=5,
pool_size=2,
pool_stride=2,
act='relu')
fc = fluid.layers.fc(input=conv_pool_2, size=50, act='relu')
logits = fluid.layers.fc(input=fc, size=10, act=None)
softmax = fluid.layers.softmax(input=logits)
return softmax, logits
然后用:
fluid.io.save_params(
exe, dirname='./mnist', main_program=fluid.default_main_program())
保存了这个default的program里面的所有变量。之后,当我又新建另一个program中,并向计算图添加了新的变量,比如我这里使用了create_parameter
在self._loss_cw
中:
with fluid.program_guard(main_program=attack_main_program, startup_program=attack_startup_program):
img_0_1_placehold = fluid.layers.data(name='img_data_scaled',shape=[1,28,28],dtype="float32")
target_placehold = fluid.layers.data(name='target',shape=[10],dtype="float32")
shape_placehold = fluid.layers.data(name="shape", shape=[1], dtype="float32")
#k_placehold = fluid.layers.data(name='k',shape=[1],dtype="float32")
c_placehold = fluid.layers.data(name='c',shape=[1],dtype="float32")
# get fluid.layer object from prebuilt program
#img_placehold_from_prebuilt_program = attack_main_program.block(0).var(self.model._input_name)
#softmax_from_prebuilt_program = attack_main_program.block(0).var(self.model._softmax_name)
#logits_from_prebuilt_program = attack_main_program.block(0).var(self.model._predict_name)
t0,t1,t2,t3,t4 = self._loss_cw(img_0_1_placehold,
target_placehold,
shape_placehold,
c_placehold)#,
#img_placehold_from_prebuilt_program,
#softmax_from_prebuilt_program,
#logits_from_prebuilt_program)
# Adam optimizer as suggested in paper
optimizer = fluid.optimizer.Adam(learning_rate=learning_rate)
optimizer.minimize(t2,parameter_list=['parameter'])
如何调用在'./mnist'
之前已保存的数据,并正确的只加载在mnist_cnn_model
函数所创建的变量上?
我想到的解决思路如下:
fluid.io.load_params(executor=exe, dirname=param_path,
main_program=prog)
但是这个API默认直接加载在对应program的所有变量上。但在TensorFlow里面可以通过:
saver = tf.train.Saver(tf.contrib.framework.get_variables()[1:-4])#[0:-1][1:-4]
saver.restore(self.sess,self.weights_file)
来选取想要加载的变量的。 请求大神指点!