比较两个生产级NLP库:运行Spark-NLP和spaCy的管道

本文比较了两个自然语言处理库——Spark-NLP和spaCy,通过构建并运行NLP管道,评估它们在处理文本数据时的性能。在导入测试数据和运行时间方面,两库各有特点。尽管Spark-NLP在处理大量数据时有优势,但对小数据集,两者表现相近,准确度相当。文章强调了根据项目需求选择合适库的重要性。
摘要由CSDN通过智能技术生成

编者注:文中超链接如果不能访问可以点击“阅读原文”访问本文原页面;可以参考2018年5月21-24日伦敦Strata数据会议上的教学辅导课《使用spaCy和Spark NLP进行自然语言理解》。

在本博客系列的第一篇中我介绍了两个自然语言处理库(John Snow Labs的Apache Spark NLP和Explosion AI的spaCy),并用它们训练了分词和词性标注的模型。在本篇中我将继续构建并运行一个自然语言处理(NLP)管道,来把这些训练好的模型应用于新的文本数据。

导入测试数据是一个具有挑战性的步骤,因为我的测试数据是由未格式化的、未进行句子边界界定的文本构成的,是粗糙的和异构的。我要处理一个包含.txt文件的文件夹,并且需要将结果保存为文字标签的格式以便将其与正确的答案进行比较。下面让我们来解决它:

spaCy

start = time.time()

path = “./target/testing/”

files = sorted([path + f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])

prediction = {}

for file in files:

    fo = io.open(file, mode=’r’, encoding=’utf-8′)

    content = []

    for doc in nlp_model(re.sub(“\\s+”, ‘ ‘, fo.read())):

        content.append((doc.text, doc.tag_))

    prediction[file] = content

    fo.close()

    

print (time.time() – start)

另一种并行计算方法是使用generator和spaCy的语言管道。 像下面这样的方式也可以解决数据导入的问题。

spaCy

from spacy.language import Language

import itertools

def genf():

    path = “./target/testing/”

    files = sorted([path + f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])

    for file in files:

        fo = io.open(file, mode=’r’, encoding=’utf-8′)

        t = re.sub(“\\s+”, ‘ ‘, fo.read())

        fo.close()

        yield (file, t)

        

gen1, gen2 = itertools.tee(genf())

files = (file for (file, text) in gen1)

texts = (text for (file, text) in gen2)

start = time.time()

prediction = {}

for file, doc in zip(files, nlp_model.pipe(texts, batch_size=10, n_threads=12)):

    content = []

    for d in doc:

        content.append((d.text, d.tag_))

    prediction[file] = content

print (time.time() – start)

Spark-NLP

var data = spark.read.textFile(“./target/testing”).as[String]

    .map(_.trim()).filter(_.nonEmpty)

    .withColumnRenamed(“value”, “text”)

    .withColumn(“filename”, regexp_replace(input_file_name(), “file://”, “”))

data = data.groupBy(“filename”).agg(concat_ws(” “, collect_list(data(“text”))).as(“text”))

    .repartition(12)

    .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值