Skip to main content

Automated Phrase Mining from Massive Text Corpora in Python.

Project description

AutoPhraseX

Python package PyPI version Python

Automated Phrase Mining from Massive Text Corpora in Python.

实现思路参考 shangjingbo1226/AutoPhrase,并不完全一致。

安装

pip install -U autophrasex

基本使用

from autophrasex import *

# 构造autophrase
autophrase = AutoPhrase(
    reader=DefaultCorpusReader(tokenizer=JiebaTokenizer()),
    selector=DefaultPhraseSelector(),
    extractors=[
        NgramsExtractor(N=4), 
        IDFExtractor(), 
        EntropyExtractor()
    ]
)

# 开始挖掘
predictions = autophrase.mine(
    corpus_files=['data/answers.10000.txt'],
    quality_phrase_files='data/wiki_quality.txt',
    callbacks=[
        LoggingCallback(),
        ConstantThresholdScheduler(),
        EarlyStopping(patience=2, min_delta=3)
    ])

# 输出挖掘结果
for pred in predictions:
    print(pred)

高级用法

本项目的各个关键步骤都是可以扩展的,所以大家可以自由实现自己的逻辑。

本项目大体上可以氛围以下几个主要模块:

  • tokenizer分词器模块
  • reader语料读取模块
  • selector高频短语的选择模块
  • extractors特征抽取器,用于抽取分类器所需要的特征
  • callbacks挖掘周期的回调模块

以下是每个模块的高级使用方法。

tokenizer

tokenizer用于文本分词,用户可以继承AbstractTokenizer实现自己的分词器。本库自带JiebaTokenizer

例如,你可以使用baidu/LAC来进行中文分词。你可以这样实现分词器:

# pip install lac

class BaiduLacTokenizer(AbstractTokenizer):

    def __init__(self, custom_vocab_path=None, model_path=None, mode='seg', use_cuda=False, **kwargs):
        self.lac = LAC(model_path=model_path, mode=mode, use_cuda=use_cuda)
        if custom_vocab_path:
            self.lac.load_customization(custom_vocab_path)

    def tokenize(self, text, **kwargs):
        text = self._uniform_text(text, **kwargs)
        results = self.lac.run(text)
        results = [x.strip() for x in results if x.strip()]
        return results

然后在构建reader的使用使用BaiduLacTokenizer:

reader = DefaultCorpusReader(tokenizer=BaiduLacTokenizer())

reader

reader用于读取语料,用户可以继承AbstractCorpusReader实现自己的Reader。本库自带DefaultCorpusReader

因为目前的extractor其实是依赖reader的(具体来说是extractor实现了reader的生命周期回调接口),因此想要重写reader,在有些情况下需要同时更改extractor的实现,此时自定义成本比较大,暂时不推荐重写reader

selector

selector用于选择高频Phrase,用户可以继承AbstractPhraseSelector实现自己的Phrase选择器。本库自带DefaultPhraseSelector

selector可以拥有多个phrase_filter,用于实现Phrase的过滤。关于phrase_filter本库提供了开放的接口,用户可以继承AbstractPhraseFilter实现自己的过滤器。本库自带了默认的过滤器DefaultPhraseFilter,并且在默认情况下使用。

如果你想要禁用默认的过滤器,转而使用自己实现的过滤器,可以在构造selector的时候设置:

# 自定义过滤器
class MyPhraseFilter(AbstractPhraseFilter):

    def apply(self, pair, **kwargs):
        phrase, freq = pair
        # return True to filter this phrase
        if is_verb(phrase):
            return True
        return False

selector = DefaultPhraseSelector(
    phrase_filters=[MyPhraseFilter()], 
    use_default_phrase_filters=False
)

考虑到有些过滤过程,使用按批处理可以显著提升速度(例如使用深度学习模型计算词性),phrase_filter提供了一个batch_apply方法。

举个例子,使用baidu/LAC来计算词性,从而实现Phrase的过滤:

class VerbPhraseFilter(AbstractPhraseFilter):

    def __init__(self, batch_size=100):
        super().__init__()
        self.lac = LAC()
        self.batch_size = batch_size

    def batch_apply(self, batch_pairs, **kwargs):
        predictions = []
        for i in range(0, len(batch_pairs), self.batch_size):
            batch_texts = [x[0] for x in batch_pairs[i: i + self.batch_size]]
            batch_preds = self.lac.run(batch_texts)
            predictions.extend(batch_preds)
        candidates = []
        for i in range(len(predictions)):
            _, pos_tags = predictions[i]
            if any(pos in ['v', 'vn', 'vd'] for pos in pos_tags):
                continue
            candidates.append(batch_pairs[i])
        return candidates

selector = DefaultPhraseSelector(
    phrase_filters=[VerbPhraseFilter()], 
    use_default_phrase_filters=False
)

extractor

extractor用于抽取分类器的特征。特征抽取器会在reader读取语料的时候进行必要信息的统计。因此extractor实现了reader的回调接口,所以在自定义特征抽取器的时候,需要同时继承AbstractCorpusReadCallbackAbstractFeatureExtractor

本库自带了以下几个特征抽取器:

  • NgramExtractorn-gram特征抽取器,可以计算phrase的pmi特征
  • IDFExtractoridf特征抽取器,可以计算phrase的doc_freqidf特征
  • EntropyExtractor特征抽取器,可以计算phrase的左右熵特征

上述自带的特征抽取器,都是基于n-gram统计的,因此都支持ngram的选择,也就是都可以自定义ngram_filter来过滤不需要统计的ngram。本库自带了DefaultNgramFilter,并且默认启用。用户可以实现自己的ngram_filter来灵活选取合适的ngram

举个例子,我需要过滤掉包含标点符号ngram

CHARACTERS = set('!"#$%&\'()*+,-./:;?@[\\]^_`{|}~ \t\n\r\x0b\x0c,。?:“”【】「」')

class MyNgramFilter(AbstractNgramFiter):

    def apply(self, ngram, **kwargs):
        if any(x in CHARACTERS for x in ngram):
            return True
        return False

autophrase = AutoPhrase(
    reader=DefaultCorpusReader(tokenizer=JiebaTokenizer()),
    selector=DefaultPhraseSelector(),
    extractors=[
        NgramsExtractor(N=4, ngram_filters=[MyNgramFilter()]), 
        IDFExtractor(ngram_filters=[MyNgramFilter()]), 
        EntropyExtractor(ngram_filters=[MyNgramFilter()]),
    ]
)
# 开始挖掘
...

用户可以继承AbstractFeatureExtractor实现自己的特征计算。只需要在构建autophrase实例的时候,把这些特征计算器传入即可,不需要做其他任何额外操作。

举个例子,我增加一个phrase是否是unigram的特征:

class UnigramFeatureExtractor(AbstractFeatureExtractorAbstractCorpusReadCallback):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def extract(self, phrase, **kwargs):
        parts = phrase.split(' ')
        features = {
            'is_unigram': 1 if len(parts) == 1 else 0
        }
        return features


autophrase = AutoPhrase(
    reader=DefaultCorpusReader(tokenizer=JiebaTokenizer()),
    selector=DefaultPhraseSelector(),
    extractors=[
        NgramsExtractor(N=N), 
        IDFExtractor(), 
        EntropyExtractor(),
        UnigramFeatureExtractor(),
    ]
)

# 可以开始挖掘了
...

callback

callback回调接口,可以提供phrase挖掘过程中的生命周期监听,并且实现一些稍微复杂的功能,例如EarlyStopping判断阈值Schedule等。

本库自带以下回调:

  • LoggingCallback提供挖掘过程的日志信息打印
  • ConstantThresholdScheduler在训练过程中调整阈值的回调
  • EarlyStopping早停,在指标没有改善的情况下停止训练

用户可以自己继承Callback实现自己的逻辑。

结果示例

以下结果属于本库比较早期的测试效果,目前本库的代码更新比较大,返回结果和下述内容不太一致。仅供参考。

新闻语料上的抽取结果示例:

成品油价格, 0.992766816097071
股份制银行, 0.992766816097071
公务船, 0.992766816097071
中国留学生, 0.992766816097071
贷款基准, 0.992766816097071
欧足联, 0.992766816097071
新局面, 0.992766816097071
淘汰赛, 0.992766816097071
反动派, 0.992766816097071
生命危险, 0.992766816097071
新台阶, 0.992766816097071
知名度, 0.992766816097071
新兴产业, 0.9925660976153782
安全感, 0.9925660976153782
战斗力, 0.9925660976153782
战略性, 0.9925660976153782
私家车, 0.9925660976153782
环球网, 0.9925660976153782
副校长, 0.9925660976153782
流行语, 0.9925660976153782
债务危机, 0.9925660976153782
保险资产, 0.9920376397372204
保险机构, 0.9920376397372204
豪华车, 0.9920376397372204
环境质量, 0.9920376397372204
瑞典队, 0.9919345469537152
交强险, 0.9919345469537152
马卡报, 0.9919345469537152
生产力, 0.9911077251879798

医疗对话语料的抽取示例:

左眉弓, 1.0
支原体, 1.0
mri, 1.0
颈动脉, 0.9854149008885851
结核病, 0.9670815675552518
手术室, 0.9617546444783288
平扫示, 0.9570324222561065
左手拇指, 0.94
双膝关节, 0.94
右手中指, 0.94
拇指末节, 0.94
cm皮肤, 0.94
肝胆脾, 0.94
抗体阳性, 0.94
igm抗体阳性, 0.94
左侧面颊, 0.94
膀胱结石, 0.94
左侧基底节, 0.94
腰椎正侧, 0.94
软组织肿胀, 0.94
手术瘢痕, 0.94
枕顶部, 0.94
左膝关节正侧, 0.94
膝关节正侧位, 0.94
腰椎椎体, 0.94
承德市医院, 0.94
性脑梗塞, 0.94
颈椎dr, 0.94
泌尿系超声, 0.94
双侧阴囊, 0.94
右颞部, 0.94
肺炎支原体, 0.94

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

autophrasex-0.3.1.tar.gz (21.8 kB view details)

Uploaded Source

Built Distribution

autophrasex-0.3.1-py3-none-any.whl (20.3 kB view details)

Uploaded Python 3

File details

Details for the file autophrasex-0.3.1.tar.gz.

File metadata

  • Download URL: autophrasex-0.3.1.tar.gz
  • Upload date:
  • Size: 21.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.0.1 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.60.0 CPython/3.9.5

File hashes

Hashes for autophrasex-0.3.1.tar.gz
Algorithm Hash digest
SHA256 a81ade30142bfe008868a46c61d5fea19220c673276cc0afd39c02c409ed876f
MD5 870c1a49068290dc19e620c8db9d8a39
BLAKE2b-256 5dfca34c2f0959d884b57b829ef61c57ae22cf1c675c9a1196254ccf7b4eaab1

See more details on using hashes here.

File details

Details for the file autophrasex-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: autophrasex-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 20.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.0.1 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.60.0 CPython/3.9.5

File hashes

Hashes for autophrasex-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 17ffd7fa3ab2dc32cf038a981bc667bfbb4b09964426bf84c842961b86cd6f4d
MD5 1cee0e38952fed7e4e97a776ea1d22fc
BLAKE2b-256 34468601caad56fc1bdc9d72e73c3c8f2b9a0d26eb14bd241de445229fbba362

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page