def infer_net(test_reader, use_gpu, model_path=None): """ Inference function """ if model_path is None: print(str(model_path) + "can not be found") return # set place, executor place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace() exe = fluid.Executor(place) inference_scope = fluid.core.Scope() with fluid.scope_guard(inference_scope): # load the saved model [inference_program, feed_target_names, fetch_targets] = fluid.io.load_inference_model(model_path, exe) for data in test_reader(): # infer a batch pred = exe.run(inference_program, feed=utils.data2tensor(data, place), fetch_list=fetch_targets, return_numpy=True) for i, val in enumerate(data): class3_label, class2_label = utils.get_predict_label( pred[0][i, 1]) pos_prob = pred[0][i, 1] neg_prob = 1 - pos_prob print("predict label: %d, pos_prob: %f, neg_prob: %f" % (class3_label, pos_prob, neg_prob))
def eval_net(test_reader, use_gpu, model_path=None): """ Evaluation function """ if model_path is None: print(str(model_path) + "can not be found") return # set place, executor place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace() exe = fluid.Executor(place) inference_scope = fluid.core.Scope() with fluid.scope_guard(inference_scope): # load the saved model [inference_program, feed_target_names, fetch_targets] = fluid.io.load_inference_model(model_path, exe) # compute 2class and 3class accuracy class2_acc, class3_acc = 0.0, 0.0 total_count, neu_count = 0, 0 for data in test_reader(): # infer a batch pred = exe.run(inference_program, feed=utils.data2tensor(data, place), fetch_list=fetch_targets, return_numpy=True) for i, val in enumerate(data): class3_label, class2_label = utils.get_predict_label( pred[0][i, 1]) true_label = val[1] if class2_label == true_label: class2_acc += 1 if class3_label == true_label: class3_acc += 1 if true_label == 1.0: neu_count += 1 total_count += len(data) class2_acc = class2_acc / (total_count - neu_count) class3_acc = class3_acc / total_count print("[test info] model_path: %s, class2_acc: %f, class3_acc: %f" % (model_path, class2_acc, class3_acc))