深度学习驱动的字符表示下中文分词算法优化

0 下载量 97 浏览量 更新于2024-08-27 收藏 495KB PDF 举报
本文主要探讨了"基于字符表示学习的中文分词算法探索"这一主题,针对中文自然语言处理中的一个重要环节——中文分词,提出了新的解决方案。传统中文分词方法如最大正向匹配、最大逆向匹配和双向匹配等,虽然在一定程度上依赖词典进行匹配,但难以处理词边界歧义和未登录词的问题。基于此,文章转向了基于字的分词策略,这种方法假设词内部的文本具有高度内聚性,而词语边界与外部文本的联系较弱,通过上下文特征对每个字进行表示,以区分词的结构。 然而,传统的字级特征如一元特征(Unigram)和二元特征(Bigram)在表示字的含义上存在局限性,它们往往难以有效捕捉字的本质信息。此外,词袋模型的使用导致了两个主要问题:一是语义鸿沟,即词袋模型无法直接反映词汇之间的语义关系,例如"麦克风"和"话筒";二是低频词问题,低频词由于在训练中的频率较低,可能导致模型训练不足或过拟合。 为了克服这些挑战,文章引入了深度学习(Deep Learning)的概念,尤其是特征表示学习。深度学习通过多层神经网络自动学习数据的内在表示,这种能力使得模型能够学习到更抽象、丰富的特征表示。在语音和图像处理领域,深度学习已显示出显著的优势。在自然语言处理任务中,如命名实体识别、词性标注和情感分类等,深度学习也展现出良好性能。 然而,在中文分词任务中,尽管深度学习有着巨大的潜力,但尚未得到充分应用。文章指出,如何将深度学习的特征表示学习技术应用于中文字符,构建一个能够自动抽取字的表示特征、有效处理词边界歧义和未登录词的分词模型,是当前研究的一个关键难点。未来的研究方向可能包括开发深度神经网络架构,优化特征提取方法,以及如何将深度学习与传统的统计模型相结合,以提升中文分词的准确性和效率。通过这种方式,有望实现一种更加智能且适应性强的中文分词算法,推动中文NLP技术的发展。

import jieba import torch from sklearn.metrics.pairwise import cosine_similarity from transformers import BertTokenizer, BertModel seed_words = ['姓名'] # 加载微博文本数据 text_data = [] with open("output/weibo1.txt", "r", encoding="utf-8") as f: for line in f: text_data.append(line.strip()) # 加载BERT模型和分词器 tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') model = BertModel.from_pretrained('bert-base-chinese') seed_tokens = ["[CLS]"] + seed_words + ["[SEP]"] seed_token_ids = tokenizer.convert_tokens_to_ids(seed_tokens) seed_segment_ids = [0] * len(seed_token_ids) # 转换为张量,调用BERT模型进行编码 seed_token_tensor = torch.tensor([seed_token_ids]) seed_segment_tensor = torch.tensor([seed_segment_ids]) with torch.no_grad(): seed_outputs = model(seed_token_tensor, seed_segment_tensor) seed_encoded_layers = seed_outputs[0] jieba.load_userdict('data/userdict.txt') # 构建隐私词库 privacy_words = set() for text in text_data: words = jieba.lcut(text.strip()) tokens = ["[CLS]"] + words + ["[SEP]"] token_ids = tokenizer.convert_tokens_to_ids(tokens) segment_ids = [0] * len(token_ids) # 转换为张量,调用BERT模型进行编码 token_tensor = torch.tensor([token_ids]) segment_tensor = torch.tensor([segment_ids]) with torch.no_grad(): outputs = model(token_tensor, segment_tensor) encoded_layers = outputs[0] # 对于每个词,计算它与种子词的相似度 for i in range(1, len(tokens)-1): word = tokens[i] if word in seed_words: continue word_tensor = encoded_layers[0][i].reshape(1, -1) seed_tensors =seed_encoded_layers[0][i].reshape(1, -1) # 计算当前微博词汇与种子词的相似度 sim = cosine_similarity(word_tensor, seed_tensors, dense_output=False)[0].max() print(sim, word) if sim > 0.5 and len(word) > 1: privacy_words.add(word) print(privacy_words) 上述代码运行之后有错误,报错信息为:Traceback (most recent call last): File "E:/PyCharm Community Edition 2020.2.2/Project/WordDict/newsim.py", line 397, in <module> seed_tensors =seed_encoded_layers[0][i].reshape(1, -1) IndexError: index 3 is out of bounds for dimension 0 with size 3. 请帮我修改

2023-05-31 上传

import torch from sklearn.metrics.pairwise import cosine_similarity from transformers import BertTokenizer, BertModel # 加载种子词库 seed_words = [] with open("output/base_words.txt", "r", encoding="utf-8") as f: for line in f: seed_words.append(line.strip()) print(seed_words) # 加载微博文本数据 text_data = [] with open("output/weibo1.txt", "r", encoding="utf-8") as f: for line in f: text_data.append(line.strip()) print(text_data) # 加载BERT模型和分词器 tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') model = BertModel.from_pretrained('bert-base-chinese') # 构建隐私词库 privacy_words = set(seed_words) for text in text_data: # 对文本进行分词,并且添加特殊标记 tokens = ["[CLS]"] + tokenizer.tokenize(text) + ["[SEP]"] token_ids = tokenizer.convert_tokens_to_ids(tokens) segment_ids = [0] * len(token_ids) # 转换为张量,调用BERT模型进行编码 token_tensor = torch.tensor([token_ids]) segment_tensor = torch.tensor([segment_ids]) with torch.no_grad(): outputs = model(token_tensor, segment_tensor) encoded_layers = outputs[0] # 对于每个词,计算它与种子词的相似度 for i in range(1, len(tokens)-1): word = tokens[i] if word in seed_words: continue word_tensor = encoded_layers[0][i].reshape(1, -1) sim = cosine_similarity(encoded_layers[0][1:-1], word_tensor, dense_output=False)[0].max() if sim > 0.5: privacy_words.add(word) # 输出隐私词库 with open("output/privacy_words.txt", "w", encoding="utf-8") as f: for word in privacy_words: f.write(word + "\n") 上述代码中的这两行代码: if sim > 0.5: privacy_words.add(word) 中privacy_words集合写入的词汇不是我想要的,运行之后都是写入privacy_words集合的都是单个字,我需要的是大于等于两个字的中文词汇,并且不包含种子词列表中的词汇,只需要将微博文本数据中与种子词相似度高的词汇写入privacy_words集合中,请帮我正确修改上述代码

2023-05-31 上传

import jieba import torch from sklearn.metrics.pairwise import cosine_similarity from transformers import BertTokenizer, BertModel seed_words = ['姓名'] # with open("output/base_words.txt", "r", encoding="utf-8") as f: # for line in f: # seed_words.append(line.strip()) # print(seed_words) # 加载微博文本数据 text_data = [] with open("output/weibo1.txt", "r", encoding="utf-8") as f: for line in f: text_data.append(line.strip()) # print(text_data) # 加载BERT模型和分词器 tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') model = BertModel.from_pretrained('bert-base-chinese') jieba.load_userdict('data/userdict.txt') # 构建隐私词库 privacy_words = set() for text in text_data: words = jieba.lcut(text.strip()) # 对文本进行分词,并且添加特殊标记 tokens = ["[CLS]"] + words + ["[SEP]"] # print(tokens) # # 对文本进行分词,并且添加特殊标记 # tokens = ["[CLS]"] + tokenizer.tokenize(text) + ["[SEP]"] # print(tokens) token_ids = tokenizer.convert_tokens_to_ids(tokens) # print(token_ids) segment_ids = [0] * len(token_ids) # 转换为张量,调用BERT模型进行编码 token_tensor = torch.tensor([token_ids]) segment_tensor = torch.tensor([segment_ids]) with torch.no_grad(): outputs = model(token_tensor, segment_tensor) encoded_layers = outputs[0] # print(encoded_layers) # 对于每个词,计算它与种子词的相似度 for i in range(1, len(tokens)-1): # print(tokens[i]) word = tokens[i] if word in seed_words: continue word_tensor = encoded_layers[0][i].reshape(1, -1) sim = cosine_similarity(encoded_layers[0][1:-1], word_tensor, dense_output=False)[0].max() if sim > 0.5 and len(word) > 1: privacy_words.add(word) print(privacy_words) # 输出隐私词库 with open("output/privacy_words.txt", "w", encoding="utf-8") as f: for word in privacy_words: f.write(word + "\n") 上述代码使用bert微调来训练自己的微博数据来获取词向量,然后计算与种子词的相似度,输出结果会不会更准确,修改代码帮我实现一下

2023-06-01 上传

import jieba import torch from transformers import BertTokenizer, BertModel, BertConfig # 自定义词汇表路径 vocab_path = "output/user_vocab.txt" count = 0 with open(vocab_path, 'r', encoding='utf-8') as file: for line in file: count += 1 user_vocab = count print(user_vocab) # 种子词 seed_words = ['姓名'] # 加载微博文本数据 text_data = [] with open("output/weibo_data.txt", "r", encoding="utf-8") as f: for line in f: text_data.append(line.strip()) print(text_data) # 加载BERT分词器,并使用自定义词汇表 tokenizer = BertTokenizer.from_pretrained('bert-base-chinese', vocab_file=vocab_path) config = BertConfig.from_pretrained("bert-base-chinese", vocab_size=user_vocab) # 加载BERT模型 model = BertModel.from_pretrained('bert-base-chinese', config=config, ignore_mismatched_sizes=True) seed_tokens = ["[CLS]"] + seed_words + ["[SEP]"] seed_token_ids = tokenizer.convert_tokens_to_ids(seed_tokens) seed_segment_ids = [0] * len(seed_token_ids) # 转换为张量,调用BERT模型进行编码 seed_token_tensor = torch.tensor([seed_token_ids]) seed_segment_tensor = torch.tensor([seed_segment_ids]) model.eval() with torch.no_grad(): seed_outputs = model(seed_token_tensor, seed_segment_tensor) seed_encoded_layers = seed_outputs[0] jieba.load_userdict('data/user_dict.txt') # 构建隐私词库 privacy_words = set() privacy_words_sim = set() for text in text_data: words = jieba.lcut(text.strip()) tokens = ["[CLS]"] + words + ["[SEP]"] token_ids = tokenizer.convert_tokens_to_ids(tokens) segment_ids = [0] * len(token_ids) # 转换为张量,调用BERT模型进行编码 token_tensor = torch.tensor([token_ids]) segment_tensor = torch.tensor([segment_ids]) model.eval() with torch.no_grad(): outputs = model(token_tensor, segment_tensor) encoded_layers = outputs[0] # 对于每个词,计算它与种子词的余弦相似度 for i in range(1, len(tokens) - 1): word = tokens[i] if word in seed_words: continue if len(word) <= 1: continue sim_scores = [] for j in range(len(seed_encoded_layers)): sim_scores.append(torch.cosine_similarity(seed_encoded_layers[j][0], encoded_layers[j][i], dim=0).item()) cos_sim = sum(sim_scores) / len(sim_scores) print(cos_sim, word) if cos_sim >= 0.5: privacy_words.add(word) privacy_words_sim.add((word, cos_sim)) print(privacy_words) # 输出隐私词库 with open("output/privacy_words.txt", "w", encoding="utf-8") as f1: for word in privacy_words: f1.write(word + '\n') with open("output/privacy_words_sim.txt", "w", encoding="utf-8") as f2: for word, cos_sim in privacy_words_sim: f2.write(word + "\t" + str(cos_sim) + "\n") 详细解释上述代码,包括这行代码的作用以及为什么要这样做?

2023-06-08 上传