Views
No views yet
AimanGh/bert-base-chinese-word-segmentation| Epoch | Training Loss | Validation Loss | Precision | Recall | F1 |
|---|---|---|---|---|---|
| 1 | 0.031600 | 0.024586 | 0.9800 | 0.9787 | 0.9793 |
| 2 | 0.017700 | 0.022133 | 0.9836 | 0.9823 | 0.9829 |
| Metric | Score |
|---|---|
| Precision | 0.9919 |
| Recall | 0.9796 |
| F1 | 0.9857 |
1from transformers import BertTokenizer, BertForTokenClassification
2import torch
3
4
5
6label_list = ["B", "I"]
7label2id = {label: i for i, label in enumerate(label_list)}
8id2label = {i: label for label, i in label2id.items()}
9num_labels = len(label_list)
10
11# Load model and tokenizer
12tokenizer = BertTokenizer.from_pretrained("path")
13model = BertForTokenClassification.from_pretrained("path")
14
15def segment_sentence(sentence, tokenizer, model, id2label):
16 """
17 Segment a single sentence using the fine-tuned model, excluding special tokens.
18 """
19 # Tokenize the input sentence
20 inputs = tokenizer(sentence, return_tensors="pt", is_split_into_words=False)
21 inputs = {key: value.to(device) for key, value in inputs.items()}
22
23 # Get model predictions
24 with torch.no_grad():
25 outputs = model(**inputs)
26
27
28 logits = outputs.logits
29 predictions = torch.argmax(logits, dim=-1).squeeze().tolist()
30 tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"].squeeze().tolist())
31 labels = [id2label[pred] for pred in predictions]
32
33 # remove special tokens
34 filtered_tokens = tokens[1:-1]
35 filtered_labels = labels[1:-1]
36
37 # combine tokens into segmented sentence
38 segmented_sentence = ""
39 for token, label in zip(filtered_tokens, filtered_labels):
40 if token.startswith("##"): # Handle subwords
41 segmented_sentence += token[2:]
42 else:
43 if label == "B" and segmented_sentence: # add a space before a new word
44 segmented_sentence += " "
45 segmented_sentence += token
46
47 return segmented_sentence
48
49
50test_sentence = "芜湖如诗如画,青山环抱,江水悠悠"
51
52segmented_output = segment_sentence(test_sentence, tokenizer, model, id2label)
53print(f"Segmented Sentence: {segmented_output}")
54
55author = { Aiman Ghannami },
title = { bert-base-chinese-word-segmentation (Revision afc647a) },
year = 2026,
url = { https://huggingface.co/AimanGh/bert-base-chinese-word-segmentation },
doi = { 10.57967/hf/8875 },
publisher = { Hugging Face }