import jieba
# 假設你有兩篇繁體中文文章
text1 = "天才喜歡唱歌"
text2 = "白痴討厭舞蹈"
# 中文斷詞
tokens1 = list(jieba.cut(text1))
tokens2 = list(jieba.cut(text2))
from transformers import BertTokenizer, BertModel
import torch
import numpy as np
from itertools import product
tokenizer = BertTokenizer.from_pretrained("bert-base-chinese")
model = BertModel.from_pretrained("bert-base-chinese")
def get_word_embedding(word):
inputs = tokenizer(word, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
return outputs.last_hidden_state[0][1:-1].mean(dim=0).numpy()
from scipy.spatial.distance import cosine
diff_scores = {}
common_words = product(set(tokens1),set(tokens2))
print(common_words)
for w1,w2 in common_words:
score = cosine(get_word_embedding(w1), get_word_embedding(w2)) # 越大表示語意差越遠
diff_scores[(w1,w2)] = score
# 按語意差異由大到小排序
diff_sorted = sorted(diff_scores.items(), key=lambda x: x[1], reverse=True)
for word, score in diff_sorted[:10]:
print(f"{word}: 差異程度 {score:.4f}")
但結果唔啱心水:
('唱歌', '討厭'): 差異程度 0.3314
('天才', '討厭'): 差異程度 0.3216
('唱歌', '白痴'): 差異程度 0.3207
('喜歡', '舞蹈'): 差異程度 0.2817
('天才', '舞蹈'): 差異程度 0.2780
('喜歡', '白痴'): 差異程度 0.2451
('唱歌', '舞蹈'): 差異程度 0.2434
('天才', '白痴'): 差異程度 0.2344
('喜歡', '討厭'): 差異程度 0.1249
錯在那裡?謝謝