ankane/mitie

PHP 的命名实体识别

v0.2.0 2024-07-01 00:43 UTC

This package is auto-updated.

Last update: 2024-09-09 08:38:27 UTC


README

MITIE - 命名实体识别、二元关系检测和文本分类 - 用于 PHP

  • 在文本中找到人、组织和地点
  • 检测实体之间的关系,如 PERSON 出生在 LOCATION

Build Status

安装

运行

composer require ankane/mitie

将脚本添加到 composer.json 以下载共享库

    "scripts": {
        "post-install-cmd": "Mitie\\Vendor::check",
        "post-update-cmd": "Mitie\\Vendor::check"
    }

运行

composer install

并下载您语言的预训练模型

入门

命名实体识别

加载 NER 模型

$model = new Mitie\NER('ner_model.dat');

创建文档

$doc = $model->doc('Nat works at GitHub in San Francisco');

获取实体

$doc->entities();

这会返回

[
    ['text' => 'Nat',           'tag' => 'PERSON',       'score' => 0.3112371212688382, 'offset' => 0],
    ['text' => 'GitHub',        'tag' => 'ORGANIZATION', 'score' => 0.5660115198329334, 'offset' => 13],
    ['text' => 'San Francisco', 'tag' => 'LOCATION',     'score' => 1.3890524313885309, 'offset' => 23]
]

获取标记

$doc->tokens();

获取标记及其偏移量

$doc->tokensWithOffset();

获取模型的所有标签

$model->tags();

训练

将 NER 模型加载到训练器中

$trainer = new Mitie\NERTrainer('total_word_feature_extractor.dat');

创建训练实例

$tokens = ['You', 'can', 'do', 'machine', 'learning', 'in', 'PHP', '!'];
$instance = new Mitie\NERTrainingInstance($tokens);
$instance->addEntity(3, 4, 'topic');    // machine learning
$instance->addEntity(6, 6, 'language'); // PHP

将训练实例添加到训练器

$trainer->add($instance);

训练模型

$model = $trainer->train();

保存模型

$model->saveToDisk('ner_model.dat');

二元关系检测

检测两个实体之间的关系,如

  • PERSON 出生在 LOCATION
  • ORGANIZATION 成立于 LOCATION
  • FILMPERSON 导演

有 21 个英语检测器。您可以在模型下载中的 binary_relations 目录中找到它们。

加载检测器

$detector = new Mitie\BinaryRelationDetector('rel_classifier_organization.organization.place_founded.svm');

并创建文档

$doc = $model->doc('Shopify was founded in Ottawa');

获取关系

$detector->relations($doc);

这会返回

[['first' => 'Shopify', 'second' => 'Ottawa', 'score' => 0.17649169745814464]]

训练

将 NER 模型加载到训练器中

$trainer = new Mitie\BinaryRelationTrainer($model);

向训练器添加正例和反例

$tokens = ['Shopify', 'was', 'founded', 'in', 'Ottawa'];
$trainer->addPositiveBinaryRelation($tokens, [0, 0], [4, 4]);
$trainer->addNegativeBinaryRelation($tokens, [4, 4], [0, 0]);

训练检测器

$detector = $trainer->train();

保存检测器

$detector->saveToDisk('binary_relation_detector.svm');

文本分类

将模型加载到训练器

$trainer = new Mitie\TextCategorizerTrainer('total_word_feature_extractor.dat');

向训练器添加标记文本

$trainer->add('This is super cool', 'positive');

训练模型

$model = $trainer->train();

保存模型

$model->saveToDisk('text_categorization_model.dat');

加载保存的模型

$model = new Mitie\TextCategorizer('text_categorization_model.dat');

分类文本

$model->categorize('What a super nice day');

历史记录

查看 变更日志

贡献

鼓励每个人帮助改进这个项目。以下是一些您可以提供帮助的方式

开始开发

git clone https://github.com/ankane/mitie-php.git
cd mitie-php
composer install
composer test