【数据集分析】TACRED关系抽取数据集分析(三)—— Relation Distribution

目录

【数据集分析】TACRED关系抽取数据集分析(一)—— 理解单条实例
【数据集分析】TACRED关系抽取数据集分析(二)—— 统计类别和实例数
【数据集分析】TACRED关系抽取数据集分析(三)—— Relation Distribution
【数据集分析】TACRED关系抽取数据集分析(四)—— train set 和 valid set中是否有重复数据

第二节,获得了三个子集的描述:类别数和实例数。

本节介绍绘制数据集的Relation分布图:
在这里插入图片描述

图中横坐标是不同的Relation,纵坐标是每个Relation的Instances数。

1. 查看数据分布

查看数据分布主要包括三步:

  1. 获取数据集的每条数据(json格式)
  2. 建立一个词频dict,格式为:
    {"class name 1": count1, "class name 2":count2, ...}
  3. 使用matplotlib进行图像绘制

2. 代码

import matplotlib as mpl
import matplotlib.pyplot as plt

def plot_relation_distribution(dataset_path):
    # 1. 获取 Train Set 的数据
    rel_fre_dict = {}
    with open(dataset_path, 'r', encoding = 'utf-8') as f:
        # 2. 建立词频表
        for line in f.readlines():
            line = json.loads(line) # loads(字符串), load(文件名字)
            if line['relation'] not in rel_fre_dict.keys():
                rel_fre_dict[line['relation']] = 1
            else:
                rel_fre_dict[line['relation']] += 1

    # print("train set中的Relation个数:",len(train_rel_fre_dict))

    # 3. 绘图
    x = []
    y = []
    width = []
    sorted_rel_fre_dict = sorted(rel_fre_dict.items(), key=lambda kv: (-kv[1])) # 按值排序
    for i in sorted_rel_fre_dict:
        x.append(i[0])
        y.append(i[1])
        width.append(0.35)
    plt.figure(figsize = [40, 10])
    plt.bar(x,y,width, align='center', alpha=0.5, clip_on = True)
    plt.ylim([0, 4000]) # 限制y轴数据的取值范围
    plt.xlabel("relation name")
    plt.ylabel("# of relation")
    plt.title(str(dataset_path)+' relation number statistic')
    plt.tick_params(axis='x', colors='red', length=13, width=3, rotation=90)
    plt.savefig(str(dataset_path)+'.png')

plot_relation_distribution(train_path)
plot_relation_distribution(valid_path)
plot_relation_distribution(test_path)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
关系抽取是自然语言处理中的一个重要任务,它的目标是从文本中提取实体之间的关系。以下是一个使用Python进行中文关系抽取的示例代码: 1. 安装相关依赖库 ```python pip install pyltp pip install gensim pip install numpy pip install pandas ``` 2. 下载LTP模型和Word2Vec模型 LTP模型可以从官网下载,Word2Vec模型可以从[中文维基百科语料库](https://dumps.wikimedia.org/zhwiki/latest/zhwiki-latest-pages-articles.xml.bz2)中训练得到。 3. 加载模型和数据 ```python import os import numpy as np import pandas as pd import jieba import jieba.posseg as pseg from pyltp import SentenceSplitter, Segmentor, Postagger, Parser from gensim.models import KeyedVectors # 加载LTP模型 LTP_DATA_DIR = 'ltp_data_v3.4.0' cws_model_path = os.path.join(LTP_DATA_DIR, 'cws.model') pos_model_path = os.path.join(LTP_DATA_DIR, 'pos.model') par_model_path = os.path.join(LTP_DATA_DIR, 'parser.model') segmentor = Segmentor() segmentor.load(cws_model_path) postagger = Postagger() postagger.load(pos_model_path) parser = Parser() parser.load(par_model_path) # 加载Word2Vec模型 word2vec_model_path = 'zhwiki_word2vec_300.bin' word2vec = KeyedVectors.load_word2vec_format(word2vec_model_path, binary=True) # 加载数据 data = pd.read_csv('data.csv') ``` 4. 对文本进行分句和分词,提取实体和关系 ```python # 分句 sentences = SentenceSplitter.split(data['text']) # 实体和关系提取 entities = [] relations = [] for sentence in sentences: words = segmentor.segment(sentence) postags = postagger.postag(words) arcs = parser.parse(words, postags) # 提取实体 for i in range(len(words)): if postags[i] == 'nh': entity = words[i] for j in range(i+1, len(words)): if arcs[j].head == i+1 and postags[j] == 'ni': entity += words[j] else: break entities.append(entity) # 提取关系 for i in range(len(words)): if postags[i] == 'v': relation = words[i] for j in range(len(words)): if arcs[j].head == i+1 and postags[j] == 'nh': relation += words[j] else: break relations.append(relation) # 去重 entities = list(set(entities)) relations = list(set(relations)) ``` 5. 计算实体和关系的相似度 ```python # 计算相似度 def similarity(a, b): if a in word2vec.vocab and b in word2vec.vocab: return word2vec.similarity(a, b) else: return 0 # 构建相似度矩阵 entity_matrix = np.zeros((len(entities), len(entities))) for i in range(len(entities)): for j in range(i+1, len(entities)): entity_matrix[i][j] = similarity(entities[i], entities[j]) entity_matrix[j][i] = entity_matrix[i][j] relation_matrix = np.zeros((len(relations), len(relations))) for i in range(len(relations)): for j in range(i+1, len(relations)): relation_matrix[i][j] = similarity(relations[i], relations[j]) relation_matrix[j][i] = relation_matrix[i][j] ``` 6. 输出结果 ```python # 输出结果 print('实体:') for entity in entities: print(entity) print('关系:') for relation in relations: print(relation) ``` 以上是一个简单的中文关系抽取示例,具体实现还需要根据具体场景进行调整和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值