解释代码 with open("result/ner_predict.utf8", "r", encoding="utf-8") as f: data = f.read() data = [i.split(" ") for i in data.split("\n") if i] print(data) y1 = [i for _, i, _ in data] y2 = [i for _, _, i in data] label = set(list(y1)) acc = accuracy_score(y1, y2) precision = precision_score(y1, y2, average='micro') recall = recall_score(y1, y2, average='micro') f1score = f1_score(y1, y2, average='micro') mcc = matthews_corrcoef(y1, y2) print('accuracy_score is :', acc) print('precision_score is : ', precision) print('recall_score is : ', recall) print('f1_score is : ', f1score) print('matthews_corrcoef is : ', mcc) label = list(set(y1)) matrixs = pd.DataFrame(confusion_matrix(y1, y2, labels=label), index=label, columns=label) del matrixs['O'] matrixs = matrixs[matrixs.index != 'O'] print(matrixs) sns.heatmap(matrixs, cmap="Wistia") # plt.show() plt.savefig("matrixs.png", dpi=300)

时间: 2024-04-28 15:21:28 浏览: 10
这段代码主要是对 NER(命名实体识别)的预测结果进行评估和可视化。下面是代码的具体解释: 1. `with open("result/ner_predict.utf8", "r", encoding="utf-8") as f:`:打开 NER 预测结果文件 ner_predict.utf8,并使用 utf-8 编码方式读取文件内容,使用 with 语句可以确保文件读取完毕后自动关闭文件。 2. `data = f.read()`:读取文件内容并赋值给变量 data。 3. `data = [i.split(" ") for i in data.split("\n") if i]`:根据换行符对 data 进行分割,得到多行文本,然后对每一行文本使用空格进行分割,得到一个二维列表。 4. `y1 = [i for _, i, _ in data]` 和 `y2 = [i for _, _, i in data]`:从二维列表中分别提取出第二列和第三列的值,分别赋值给 y1 和 y2。 5. `label = set(list(y1))`:将 y1 转换成集合类型,得到命名实体类型,赋值给变量 label。 6. `acc = accuracy_score(y1, y2)`、`precision = precision_score(y1, y2, average='micro')`、`recall = recall_score(y1, y2, average='micro')`、`f1score = f1_score(y1, y2, average='micro')` 和 `mcc = matthews_corrcoef(y1, y2)`:使用 sklearn 库中的函数计算各种评估指标,包括准确率、精确率、召回率、f1 分数和 Matthews 相关系数。 7. `print`:输出各种评估指标的值。 8. `label = list(set(y1))`:将 y1 转换成列表类型,得到命名实体类型,赋值给变量 label。 9. `matrixs = pd.DataFrame(confusion_matrix(y1, y2, labels=label), index=label, columns=label)`:使用 pandas 库中的 DataFrame 函数构建混淆矩阵,其中 confusion_matrix 函数可以计算出混淆矩阵,labels 参数用于指定行和列的标签。 10. `del matrixs['O']` 和 `matrixs = matrixs[matrixs.index != 'O']`:将矩阵中的 O 类别删除,并将矩阵中行标签为 O 的行删除,因为 O 类别通常表示无命名实体。 11. `print(matrixs)`:打印出处理后的混淆矩阵。 12. `sns.heatmap(matrixs, cmap="Wistia")`:使用 seaborn 库中的 heatmap 函数将混淆矩阵以热力图的形式进行可视化,cmap 参数指定使用的颜色映射。 13. `plt.savefig("matrixs.png", dpi=300)`:将热力图保存为图片文件。

相关推荐

from transformers import pipeline, BertTokenizer, BertModel import numpy as np import torch import jieba tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') model = BertModel.from_pretrained('bert-base-chinese') ner_pipeline = pipeline('ner', model='bert-base-chinese') with open('output/weibo1.txt', 'r', encoding='utf-8') as f: data = f.readlines() def cosine_similarity(v1, v2): return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)) def get_word_embedding(word): input_ids = tokenizer.encode(word, add_special_tokens=True) inputs = torch.tensor([input_ids]) outputs = model(inputs)[0][0][1:-1] word_embedding = np.mean(outputs.detach().numpy(), axis=0) return word_embedding def get_privacy_word(seed_word, data): privacy_word_list = [] seed_words = jieba.lcut(seed_word) jieba.load_userdict('data/userdict.txt') for line in data: words = jieba.lcut(line.strip()) ner_results = ner_pipeline(''.join(words)) for seed_word in seed_words: seed_word_embedding = get_word_embedding(seed_word) for ner_result in ner_results: if ner_result['word'] == seed_word and ner_result['entity'] == 'O': continue if ner_result['entity'] != seed_word: continue word = ner_result['word'] if len(word) < 3: continue word_embedding = get_word_embedding(word) similarity = cosine_similarity(seed_word_embedding, word_embedding) print(similarity, word) if similarity >= 0.6: privacy_word_list.append(word) privacy_word_set = set(privacy_word_list) return privacy_word_set 上述代码运行之后,结果为空集合,哪里出问题了,帮我修改一下

/home/chenxingyue/anaconda3/envs/py39/bin/python /home/chenxingyue/codes/caopengfei/CMeKG_tools/test4.py Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions. Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions. Traceback (most recent call last): File "/home/chenxingyue/codes/caopengfei/CMeKG_tools/test4.py", line 9, in <module> my_pred=medical_ner() File "/home/chenxingyue/codes/caopengfei/CMeKG_tools/medical_ner.py", line 21, in __init__ self.model = BERT_LSTM_CRF('/home/chenxingyue/codes/caopengfei/medical_ner', tagset_size, 768, 200, 2, File "/home/chenxingyue/codes/caopengfei/CMeKG_tools/model_ner/bert_lstm_crf.py", line 16, in __init__ self.word_embeds = BertModel.from_pretrained(bert_config,from_tf=True) File "/home/chenxingyue/anaconda3/envs/py39/lib/python3.9/site-packages/transformers/modeling_utils.py", line 2612, in from_pretrained model, loading_info = load_tf2_checkpoint_in_pytorch_model( File "/home/chenxingyue/anaconda3/envs/py39/lib/python3.9/site-packages/transformers/modeling_tf_pytorch_utils.py", line 390, in load_tf2_checkpoint_in_pytorch_model import tensorflow as tf # noqa: F401 ModuleNotFoundError: No module named 'tensorflow' 这个报错可以是需要把tensorflow安装到本地吗?还是Linux

最新推荐

recommend-type

新建文本文档.txt

新建文本文档
recommend-type

开源Git gui工具Fork

开源Git gui工具Fork,CSDN能找到教程,但是资料不多,推荐用Tortoise
recommend-type

yolov5在华为昇腾atlas上加速推理

该资源为yolov5在华为昇腾atlas上使用Ascend310芯片加速推理,属于c++后端开发,适合C++开发者在华为昇腾盒子上移植深度学习算法的博主们。 资源是demo形式,包含完整的一套代码,还有转好的离线模型文件和跑出的测试结果图片。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

HSV转为RGB的计算公式

HSV (Hue, Saturation, Value) 和 RGB (Red, Green, Blue) 是两种表示颜色的方式。下面是将 HSV 转换为 RGB 的计算公式: 1. 将 HSV 中的 S 和 V 值除以 100,得到范围在 0~1 之间的值。 2. 计算色相 H 在 RGB 中的值。如果 H 的范围在 0~60 或者 300~360 之间,则 R = V,G = (H/60)×V,B = 0。如果 H 的范围在 60~120 之间,则 R = ((120-H)/60)×V,G = V,B = 0。如果 H 的范围在 120~180 之间,则 R = 0,G = V,B =
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

MATLAB柱状图在数据分析中的作用:从可视化到洞察

![MATLAB柱状图在数据分析中的作用:从可视化到洞察](https://img-blog.csdnimg.cn/img_convert/1a36558cefc0339f7836cca7680c0aef.png) # 1. MATLAB柱状图概述** 柱状图是一种广泛用于数据可视化的图表类型,它使用垂直条形来表示数据中不同类别或组别的值。在MATLAB中,柱状图通过`bar`函数创建,该函数接受数据向量或矩阵作为输入,并生成相应的高度条形。 柱状图的优点在于其简单性和易于理解性。它们可以快速有效地传达数据分布和组别之间的比较。此外,MATLAB提供了广泛的定制选项,允许用户调整条形颜色、