预训练网络为什么不能当作中间模块使用?
Created by: aiyouwoqu123
paddlepaddle 1.5.1 在训练过程中,需要加载自己预训练好的模型,来当作当前任务中的一个inference模块,但是出现了以下问题
def inference(img):
adv_program = fluid.Program()
with fluid.program_guard(adv_program,fluid.Program()):
input_layer = fluid.layers.data(name='img', shape=image_shape, dtype='float32')
model = models.__dict__[model_name]()
out_logits = model.net(input=input_layer, class_dim=class_dim)
out = fluid.layers.softmax(out_logits)
place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
exe = fluid.Executor(placel)
exe.run(fluid.default_startup_program())
fluid.io.load_persistables(exe_cl, pretrained_model)
eval_program = adv_program.clone(for_test=False)
fetch_list = [out.name]
result = exe.run(eval_program,
fetch_list=fetch_list,
feed={"img": img})
result = result[0][0]
pred_label = np.argmax(result)
pred_score = result[pred_label]
return pred_label, pred_score
def main():
...
with fluid.program_guard(train_g, startup):
img = fluid.layers.data('image', shape=[3,224,224])
perturbation = Generator(img)
fake_img = fluid.layers.clip(perturbation, -0.3, 0.3) + img
fake_img = fluid.layers.clip(fake_img, 0., 1.)
infer_program = train_g.clone(for_test=True)
p = Discriminator(fake_img)
ones = fluid.layers.fill_constant_batch_size_like(p,shape=[-1,1,24,24],dtype='float32', value=1)
g_cost = fluid.layers.reduce_mean(fluid.layers.square_error_cost(p, ones*0.9))
g_avg_cost = fluid.layers.mean(g_cost)
fluid.layers.reshape(perturbation,[perturbation.shape[0],perturbation.shape[1]*perturbation.shape[2]*perturbation.shape[3]])
C = 0.1
loss_perturb = fluid.layers.mean(fluid.layers.l2_normalize(fluid.layers.reshape(perturbation,[perturbation.shape[0],perturbation.shape[1]*perturbation.shape[2]*perturbation.shape[3]]),axis=1))
pred_label, pred_score = inference(fake_img)
...