尝试直接使用训练好的参数,进行预测
使用 Lcqmc 数据集的测试集作为我们的预测数据
加载预测数据
test_ds = load_dataset("lcqmc", splits=["test"])
生成预测数据
predict_data_loader =paddle.io.DataLoader(
dataset=test_ds.map(trans_func),
batch_sampler=batch_sampler,
collate_fn=batchify_fn,
return_list=True)
定义预测模型
pretrained_model = paddlenlp.transformers.ErnieGramModel.from_pretrained('ernie-gram-zh')
model = PointwiseMatching(pretrained_model)
加载已训练好的模型参数
state_dict = paddle.load("test/ernie_gram_zh_pointwise_matching_model/model_20000/model_state.pdparams")
model.set_dict(state_dict)
定义预测函数
def predict(model, data_loader):
batch_probs = []
# 预测阶段打开 eval 模式,模型中的 dropout 等操作会关掉
model.eval()
with paddle.no_grad():
for batch_data in data_loader:
input_ids, token_type_ids = batch_data
input_ids = paddle.to_tensor(input_ids)
token_type_ids = paddle.to_tensor(token_type_ids)
# 获取每个样本的预测概率: [batch_size, 2] 的矩阵
batch_prob = model(
input_ids=input_ids, token_type_ids=token_type_ids).numpy()
batch_probs.append(batch_prob)
if(batch_probs.__len__()==10):
batch_probs = np.concatenate(batch_probs, axis=0)
return batch_probs
# 执行预测函数
y_probs = predict(model, predict_data_loader)
# 根据预测概率获取预测 label
y_preds = np.argmax(y_probs, axis=1)
预测函数里的batch_probs存放前向计算的结果,为了方便观看处理后的数据,我设定了batch_probs的大小为10就返回结果
# 按照千言文本相似度竞赛的提交格式将预测结果存储在 lcqmc.tsv 中,用来后续提交
with open("lcqmc.tsv", 'w', encoding="utf-8") as f:
f.write("index\tprediction\n")
for idx, y_pred in enumerate(y_preds):
f.write("{}\t{}\n".format(idx, y_pred))
text_pair = test_ds[idx]
text_pair["label"] = y_pred
print(text_pair)
可见,在不需要微调的情况下,预训练这种模式使得任务完成地特别简单。