搭建NER分类器——方法1(投票模型)

1 导入数据并初始化

数据集见评论区

import pandas as pd
import numpy as np

# 导入数据初始化
data = pd.read_csv('ner_dataset.csv', encoding='latin1' )

data = data.fillna(method='ffill')
data.tail(10)

输出

输出

2 预定义数据结构

# 预定义数据结构
words = list(set(data['Word'].values)) # 单词表
print(words[:50]) 

n_words = len(words) # 查看单词总个数
n_words

输出

输出

3 投票模型代码

from sklearn.base import BaseEstimator, TransformerMixin

class MajorityVotingTagger(BaseEstimator, TransformerMixin):
    
    def fit(self, X, y):
        """
        x: list of words
        y: list of tags
        """
        word2cnt = {}
        tags = []
        
        for x, t in zip(X, y):
            if t not in tags:
                tags.append(t)
                
            if x in word2cnt:
                if t in word2cnt[x]:
                    word2cnt[x][t] += 1
                else:
                    word2cnt[x][t] = 1
            else:
                word2cnt[x] = {t: 1}
        
        self.mjvote = {}
        
        for k, d in word2cnt.items(): 
            #  k    :  d,      d
            # Indian: {B_gpe: 4, B_geo:1, ...}
            # 每个单词有哪些实体标签,{单词1:{实体名称1:次数, 实体名称2:次数}, 单词2:{实体名称1:次数, 实体名称2:次数}}
            self.mjvote[k] = max(d, key=d.get) # 取次数最多的实体名称
            
    def predict(self, X, y = None):
        """
        预测内存中的标签, 如果单词是未知的,则预测为O
        """
        return [self.mjvote.get(x, 'O') for x in X]            

4 数据预处理

words = data['Word'].values.tolist()
tags = data['Tag'].values.tolist()
print(words[:10], tags[:10], sep = '\n')

输出

输出

5 模型预测

from sklearn.model_selection import cross_val_predict
from sklearn.metrics import classification_report

# 交叉验证
pred = cross_val_predict(estimator = MajorityVotingTagger(), X = words, y = tags, cv = 5)

# 计算验证报告
report = classification_report(y_pred = pred, y_true = tags)
print(report)

输出

输出

Hugging Face 提供了许多用于命名实体识别(Named Entity Recognition,NER)的预训练模型,其中最受欢迎的是基于 Transformer 的 BERT 和 RoBERTa 模型。下面是使用 Hugging Face 模型进行 NER 的基本步骤: 1. 安装所需的库: ```python !pip install transformers ``` 2. 导入所需的库和模型: ```python from transformers import AutoTokenizer, AutoModelForTokenClassification # 选择适合你任务的预训练模型 model_name = "bert-base-uncased" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForTokenClassification.from_pretrained(model_name) ``` 3. 准备输入文本: ```python text = "Apple Inc. was founded in 1976 and its headquarters is located in Cupertino, California." ``` 4. 对输入文本进行分词和编码: ```python input_ids = tokenizer.encode(text, add_special_tokens=True) ``` 5. 使用模型进行预测: ```python outputs = model(torch.tensor([input_ids])) predictions = torch.argmax(outputs.logits, dim=2)[0] ``` 6. 解码预测结果: ```python predicted_labels = [tokenizer.decode([pred]) for pred in predictions] ``` 在上述代码中,`model_name` 可以根据你的需求选择不同的预训练模型,比如 "bert-base-cased"、"roberta-base" 等。使用 Hugging Face 的模型和工具,你可以更轻松地进行 NER 任务的训练和推理。请注意,以上代码仅演示了基本的 NER 操作,具体的实现可能会根据你的任务和数据集的要求有所不同。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值