Views
No views yet
1import torch
2from transformers import AutoModelForQuestionAnswering, AutoTokenizer
3
4# Load model and tokenizer
5model = AutoModelForQuestionAnswering.from_pretrained("real-jiakai/bert-base-chinese-finetuned-cmrc2018")
6tokenizer = AutoTokenizer.from_pretrained("real-jiakai/bert-base-chinese-finetuned-cmrc2018")
7
8# Prepare inputs
9question = "长城有多长?"
10context = "长城是中国古代的伟大建筑工程,全长超过2万公里,横跨中国北部多个省份。"
11
12# Tokenize inputs
13inputs = tokenizer(
14 question,
15 context,
16 return_tensors="pt",
17 max_length=384,
18 truncation=True
19)
20
21# Get answer
22outputs = model(**inputs)
23answer_start = torch.argmax(outputs.start_logits)
24answer_end = torch.argmax(outputs.end_logits) + 1
25answer = tokenizer.decode(inputs["input_ids"][0][answer_start:answer_end])
26print("Answer:", answer)1@inproceedings{cui-emnlp2019-cmrc2018,
2 title = "A Span-Extraction Dataset for {C}hinese Machine Reading Comprehension",
3 author = "Cui, Yiming and
4 Liu, Ting and
5 Che, Wanxiang and
6 Xiao, Li and
7 Chen, Zhipeng and
8 Ma, Wentao and
9 Wang, Shijin and
10 Hu, Guoping",
11 booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP)",
12 month = nov,
13 year = "2019",
14 address = "Hong Kong, China",
15 publisher = "Association for Computational Linguistics",
16 url = "https://www.aclweb.org/anthology/D19-1600",
17 doi = "10.18653/v1/D19-1600",
18 pages = "5886--5891",
19}