加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

分类 – NLTK perceptron tagger“TypeError:’LazySubsequence

发布时间:2020-12-20 11:54:26 所属栏目:Python 来源:网络整理
导读:我想尝试在 Python 3.5的nltk包中使用PerceptronTagger但是我收到错误TypeError:’LazySubsequence’对象不支持项目赋值 我想用来自棕色语料库的数据和通用标签来训练它. 这是我遇到问题时运行的代码. import nltk,mathtagged_sentences = nltk.corpus.brow
我想尝试在 Python 3.5的nltk包中使用PerceptronTagger但是我收到错误TypeError:’LazySubsequence’对象不支持项目赋值

我想用来自棕色语料库的数据和通用标签来训练它.

这是我遇到问题时运行的代码.

import nltk,math
tagged_sentences = nltk.corpus.brown.tagged_sents(categories='news',tagset='universal')
i = math.floor(len(tagged_sentences)*0.2)
testing_sentences = tagged_sentences[0:i]
training_sentences = tagged_sentences[i:]
perceptron_tagger = nltk.tag.perceptron.PerceptronTagger(load=False)
perceptron_tagger.train(training_sentences)

它无法正确训练,并提供以下堆栈跟踪.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-61332d63d2c3> in <module>()
      1 perceptron_tagger = nltk.tag.perceptron.PerceptronTagger(load=False)
----> 2 perceptron_tagger.train(training_sentences)

/home/nathan/anaconda3/lib/python3.5/site-packages/nltk/tag/perceptron.py in train(self,sentences,save_loc,nr_iter)
    192                     c += guess == tags[i]
    193                     n += 1
--> 194             random.shuffle(sentences)
    195             logging.info("Iter {0}: {1}/{2}={3}".format(iter_,c,n,_pc(c,n)))
    196         self.model.average_weights()

/home/nathan/anaconda3/lib/python3.5/random.py in shuffle(self,x,random)
    270                 # pick an element in x[:i+1] with which to exchange x[i]
    271                 j = randbelow(i+1)
--> 272                 x[i],x[j] = x[j],x[i]
    273         else:
    274             _int = int

TypeError: 'LazySubsequence' object does not support item assignment

它似乎来自随机模块中的shuffle函数,但这看起来并不合适.

还有其他可能导致问题的原因吗?
有人有这个问题吗?

我正在使用Anaconda Python 3.5在Ubuntu 16.04.1上运行它. nltk版本是3.2.1

解决方法

NLTK有很多自定义的“懒惰”类型,它们可以简化大量数据的修改,例如带注释的语料库.它们在许多方面表现得像标准列表,元组,词汇等,但避免不必要地占用太多内存.

其中一个例子是LazySubsequence,它是切片表达式tagged_sentences [i:]的结果.如果tagged_sentences是正常列表,则将数据划分为测试/培训将创建数据的完整副本.相反,这个LazySubsequence是对原始序列的部分视图.

虽然这对内存的好处可能是一件好事,但这里的问题是这个视图是只读的.
显然,PerceptronTagger希望将其输入数据原位洗牌,这是不允许的 – 因此是例外.

一个快速(但可能不是最优雅)的解决方案是为标记器提供数据的副本:

perceptron_tagger.train(tuple(training_sentences))

您可能必须对测试数据执行相同的操作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读