首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Spacy文本分类:获取错误消息"'float‘object is not iterable“

Spacy文本分类:获取错误消息"'float‘object is not iterable“
EN

Stack Overflow用户
提问于 2019-01-24 19:59:45
回答 1查看 920关注 0票数 1

我使用spaCy进行文本分类项目。我非常关注spaCy代码示例。唯一重要的区别是我在示例中使用了两个类别,而不是一个类别。我不明白哪里出了问题,因为我检查了一下,我加载的数据的格式与原始示例中的格式相同。下面是相关代码(完整代码如下):

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
def load_data(limit=0, split=0.8):
    """Load the patents data."""
    # Partition off part of the train data for evaluation
    temp=pd.read_csv(excel + 'patents_text_class.csv',header = None)
    new_cols = ['id' , 'class' , 'patent_text']
    temp.columns = new_cols
    print(temp)
    train_data = list(zip(temp["patent_text"], temp["class"]))
    random.shuffle(train_data)
    train_data = train_data[-limit:]
    texts, labels = zip(*train_data)
    cats = [{"A01D": bool(y) , "A01B": operator.not_(bool(y))} for y in labels]
    split = int(len(train_data) * split)
    return (texts[:split], cats[:split]), (texts[split:], cats[split:])

这是日志:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Loaded model 'en_core_web_lg'
Loading patents data...
            id  class                                        patent_text
0         1317      0  Improvement n revolving harrows <div itemprop=...
1         2476      1  Machine for cutting meat and other substances ...
2         2650      0  Improvement in cultivators fob vines <div item...
3         3311      0  Improvement in plows <div itemprop="content" h...
4         4544      0  Improvement in plow-clevises <div itemprop="co...
5         7277      1  Improvement in machines for raking and loading...
6         8721      0  Improvement in shovel-plows <div itemprop="con...
7         8844      0  Improvement in gang-plows <div itemprop="conte...
8         9069      0  Improvement in potato-diggers and stone-gather...
9        10624      0  Improvement in rotary cultivators <div itempro...
10       12057      0  Improvement in hoes <div itemprop="content" ht...
[70000 rows x 3 columns]
Using 10000 examples (8000 training, 2000 evaluation)
Training the model...
LOSS      P       R       F  
Traceback (most recent call last):
  File "process/task_classification.py", line 150, in <module>
    plac.call(main)
  File "/anaconda/lib/python3.6/site-packages/plac_core.py", line 328, in call
    cmd, result = parser.consume(arglist)
  File "/anaconda/lib/python3.6/site-packages/plac_core.py", line 207, in consume
    return cmd, self.func(*(args + varargs + extraopts), **kwargs)
  File "process/task_classification.py", line 78, in main
    losses=losses)
  File "/anaconda/lib/python3.6/site-packages/spacy/language.py", line 405, in update
    gold = GoldParse(doc, **gold)
  File "gold.pyx", line 409, in spacy.gold.GoldParse.__init__
TypeError: 'float' object is not iterable

你知道为什么我会得到这个错误吗?

供参考的完整代码:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#!/usr/bin/env python
# coding: utf8
"""Train a convolutional neural network text classifier on the
IMDB dataset, using the TextCategorizer component. The dataset will be loaded
automatically via Thinc's built-in dataset loader. The model is added to
spacy.pipeline, and predictions are available via `doc.cats`. For more details,
see the documentation:
* Training: https://spacy.io/usage/training
Compatible with: spaCy v2.0.0+
"""
from __future__ import unicode_literals, print_function
import plac
import random
from pathlib import Path
import thinc.extra.datasets
import os
import pandas as pd
import operator
import spacy
from spacy.util import minibatch, compounding

root = 'path/to/folder'
output = root + 'output/'
process = root + 'process/'
excel = root + 'excel/'

@plac.annotations(
    model=("Model name. Defaults to blank 'en' model.", "option", "m", str),
    output_dir=("Optional output directory", "option", "o", Path),
    n_texts=("Number of texts to train from", "option", "t", int),
    n_iter=("Number of training iterations", "option", "n", int))
def main(model='en_core_web_lg', output_dir=output, n_iter=5, n_texts=10000):
    if output_dir is not None:
        output_dir = Path(output_dir)
        if not output_dir.exists():
            output_dir.mkdir()

    if model is not None:
        nlp = spacy.load(model)  # load existing spaCy model
        print("Loaded model '%s'" % model)
    else:
        nlp = spacy.blank('en')  # create blank Language class
        print("Created blank 'en' model")

    # add the text classifier to the pipeline if it doesn't exist
    # nlp.create_pipe works for built-ins that are registered with spaCy
    if 'textcat' not in nlp.pipe_names:
        textcat = nlp.create_pipe('textcat')
        nlp.add_pipe(textcat, last=True)
    # otherwise, get it, so we can add labels to it
    else:
        textcat = nlp.get_pipe('textcat')

    # add label to text classifier
    textcat.add_label("A01B")
    textcat.add_label("A01D")
    # load the patents dataset
    print("Loading patents data...")
    (train_texts, train_cats), (dev_texts, dev_cats) = load_data(limit=n_texts)
    print("Using {} examples ({} training, {} evaluation)"
          .format(n_texts, len(train_texts), len(dev_texts)))
    train_data = list(zip(train_texts,
                          [{'cats': cats} for cats in train_cats]))

    # get names of other pipes to disable them during training
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'textcat']
    with nlp.disable_pipes(*other_pipes):  # only train textcat
        optimizer = nlp.begin_training()
        print("Training the model...")
        print('{:^5}\t{:^5}\t{:^5}\t{:^5}'.format('LOSS', 'P', 'R', 'F'))
        for i in range(n_iter):
            losses = {}
            # batch up the examples using spaCy's minibatch
            batches = minibatch(train_data, size=compounding(4., 32., 1.001))
            for batch in batches:
                texts, annotations = zip(*batch)
                nlp.update(texts, annotations, sgd=optimizer, drop=0.2,
                           losses=losses)
            with textcat.model.use_params(optimizer.averages):
                # evaluate on the dev data split off in load_data()
                scores = evaluate(nlp.tokenizer, textcat, dev_texts, dev_cats)
            print('{0:.3f}\t{1:.3f}\t{2:.3f}\t{3:.3f}'  # print a simple table
                  .format(losses['textcat'], scores['textcat_p'],
                          scores['textcat_r'], scores['textcat_f']))

    # test the trained model
    test_text = "Harvesting"
    doc = nlp(test_text)
    print(test_text, doc.cats)

    test_text = "Plowing"
    doc = nlp(test_text)
    print(test_text, doc.cats)

    if output_dir is not None:
        with nlp.use_params(optimizer.averages):
            nlp.to_disk(output_dir)
        print("Saved model to", output_dir)

        # test the saved model
        print("Loading from", output_dir)
        nlp2 = spacy.load(output_dir)
        doc2 = nlp2(test_text)
        print(test_text, doc2.cats)


def load_data(limit=0, split=0.8):
    """Load the patents data."""
    # Partition off part of the train data for evaluation
    temp=pd.read_csv(excel + 'patents_text_class.csv',header = None)
    new_cols = ['id' , 'class' , 'patent_text']
    temp.columns = new_cols
    train_data = list(zip(temp["patent_text"], temp["class"]))
    random.shuffle(train_data)
    train_data = train_data[-limit:]
    texts, labels = zip(*train_data)
    cats = [{"A01D": bool(y) , "A01B": operator.not_(bool(y))} for y in labels]
    split = int(len(train_data) * split)
    return (texts[:split], cats[:split]), (texts[split:], cats[split:])


def evaluate(tokenizer, textcat, texts, cats):
    docs = (tokenizer(text) for text in texts)
    tp = 0.0   # True positives
    fp = 1e-8  # False positives
    fn = 1e-8  # False negatives
    tn = 0.0   # True negatives
    for i, doc in enumerate(textcat.pipe(docs)):
        gold = cats[i]
        print(i)
        for label, score in doc.cats.items():
            if label not in gold:
                continue
            if score >= 0.5 and gold[label] >= 0.5:
                tp += 1.
            elif score >= 0.5 and gold[label] < 0.5:
                fp += 1.
            elif score < 0.5 and gold[label] < 0.5:
                tn += 1
            elif score < 0.5 and gold[label] >= 0.5:
                fn += 1
    precision = tp / (tp + fp)
    recall = tp / (tp + fn)
    f_score = 2 * (precision * recall) / (precision + recall)
    return {'textcat_p': precision, 'textcat_r': recall, 'textcat_f': f_score}


if __name__ == '__main__':
    plac.call(main)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-24 21:58:43

根据文档,Language.update的第一个参数接受一批unicodeDoc的。Probalby texts包含一些NaN值,其类型为float。相关代码:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
batches = minibatch(train_data, size=compounding(4., 32., 1.001))
for batch in batches:
    texts, annotations = zip(*batch)  # check texts for NaN
    nlp.update(texts, annotations, sgd=optimizer, drop=0.2,
               losses=losses)

spacy尝试迭代浮点数( NaN ),它会导致

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
...
TypeError: 'float' object is not iterable

因此,您可以删除所有NaN值或将其替换为空字符串。

此外,这种错误对于NLP (而不仅仅是NLP)任务来说是非常常见的。总是检查NaN的文本数据并替换它们,特别是当您收到类似的错误信息时。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54354431

复制
相关文章
TypeError: cannot unpack non-iterable NoneType object
解决方法:报错的原因是函数返回值得数量不一致,查看函数返回值数量和调用函数时接收返回值的数量是不是一致,修改一致即可
狼啸风云
2020/09/17
5.3K0
scipy读取不了imread_type object is not iterable
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
全栈程序员站长
2022/11/04
3630
盘点JavaScript中的Iterable object(可迭代对象)
可迭代(Iterable) 对象是数组的泛化。这个概念是说任何对象都可以被定制为可在 for..of 循环中使用的对象。
前端进阶者
2021/09/10
1.7K0
盘点JavaScript中的Iterable object(可迭代对象)
[Kaggle] Spam/Ham Email Classification 垃圾邮件分类(spacy)
练习地址:https://www.kaggle.com/c/ds100fa19 相关博文: [Kaggle] Spam/Ham Email Classification 垃圾邮件分类(RNN/GRU/LSTM) [Kaggle] Spam/Ham Email Classification 垃圾邮件分类(BERT)
Michael阿明
2021/02/19
9800
[Kaggle] Spam/Ham Email Classification 垃圾邮件分类(spacy)
【Kaggle微课程】Natural Language Processing - 2.Text Classification
learn from https://www.kaggle.com/learn/natural-language-processing
Michael阿明
2021/02/19
5580
【Kaggle微课程】Natural Language Processing - 2.Text Classification
Expected object of scalar type Float but got scalar type Double for argument
在pytorch中float32为float类型,而float64则为double类型,注意tensor的数据类型。
狼啸风云
2020/12/01
1.7K0
Expected object of scalar type Float but got scalar type Double for argument
机器学习-文本分类(2)-新闻文本分类
参考:https://mp.weixin.qq.com/s/6vkz18Xw4USZ3fldd_wf5g
西西嘛呦
2020/08/26
9710
机器学习-文本分类(2)-新闻文本分类
【文本分类】基于双层序列的文本分类模型
导语 PaddlePaddle提供了丰富的运算单元,帮助大家以模块化的方式构建起千变万化的深度学习模型来解决不同的应用问题。这里,我们针对常见的机器学习任务,提供了不同的神经网络模型供大家学习和使用。本周推文目录如下: 周一:【点击率预估】 Wide&deep 点击率预估模型 周二:【文本分类】 基于DNN/CNN的情感分类 周三:【文本分类】 基于双层序列的文本分类模型 周四:【排序学习】 基于Pairwise和Listwise的排序学习 周五:【结构化语义模型】 深度结构化语义模型 文本分类是自然语言
用户1386409
2018/03/15
1.3K0
【文本分类】基于双层序列的文本分类模型
获取Object对象的length
所有JS程序猿(甚至不止JS)都知道,数组(Array)是有length的,通过length属性,可以很方便的获取数组的长度。可以说,只要使用到了数组,就必会使用到其length属性。 而Object对象是没有length属性或方法的,它确实没有存在的必要,因为人们只会在乎该对象能提供什么样的方法,而没有必要知道它到底有多少方法。的确,这确实不是一个普遍性的需求, 因此ECMAScript中也不会为自己增加额外的负担。 我之前一直没有考虑过这个问题,我们通过CGI获取数据,对于一条一条的数据,后台将其做成数
李文杨
2018/03/14
2.2K0
NLP文本分类
其实最近挺纠结的,有一点点焦虑,因为自己一直都期望往自然语言处理的方向发展,梦想成为一名NLP算法工程师,也正是我喜欢的事,而不是为了生存而工作。我觉得这也是我这辈子为数不多的剩下的可以自己去追求自己喜欢的东西的机会了。然而现实很残酷,大部分的公司算法工程师一般都是名牌大学,硕士起招,如同一个跨不过的门槛,让人望而却步,即使我觉得可能这个方向以后的路并不如其他的唾手可得的路轻松,但我的心中却一直有一股信念让我义无反顾,不管怎样,梦还是要有的,万一实现了呢~
UM_CC
2022/09/22
4670
NLP文本分类
TextCNN(文本分类)
(2)词转成向量(word2vec,Glove,bert,nn.embedding)
全栈程序员站长
2022/09/15
5720
TextCNN(文本分类)
新闻文本分类
一个很粗糙的新闻文本分类项目,解决中国软件杯第九届新闻文本分类算法的问题,记录了项目的思路及问题解决方法
客怎眠qvq
2022/11/01
1.2K0
新闻文本分类
Django 错误:TypeError at / 'bool' object is not callable
使用 Django自带的 auth 用户验证功能,编写函数,使用 is_authenticated 检查用户是否登录,结果报错:
希希里之海
2018/08/02
8640
BERT文本分类
本文使用的是RoBERTa-wwm-ext,模型导入方式参见https://github.com/ymcui/Chinese-BERT-wwm。由于做了全词遮罩(Whole Word Masking),效果相较于裸的BERT会有所提升。
luxuantao
2021/02/24
1.9K0
textRNN/textCNN文本分类
textRNN指的是利用RNN循环神经网络解决文本分类问题,文本分类是自然语言处理的一个基本任务,试图推断出给定文本(句子、文档等)的标签或标签集合。
大数据技术与机器学习
2019/12/05
2.3K0
大话文本分类
概述 文本分类是自然语言处理的重要应用,也可以说是最基础的应用。常见的文本分类应用有:新闻文本分类、信息检索、情感分析、意图判断等。本文主要针对文本分类的方法进行简单总结。 01 — 传统机器学习方法 分类问题一般的步骤可以分为特征提取、模型构建、算法寻优、交叉验证等。对于文本而言,如何进行特征提取是一个很重要也很有挑战性的问题。文本的特征是什么,如何量化为数学表达呢。 最开始的文本分类是基于规则的,特征就是关键词,例如足球在体育类出现的次数多,就将含有足球这一关键词的文本氛围体育。后来为了便于计算,通过
CodeInHand
2018/03/26
1.6K0
大话文本分类
长文本分类
在NLP领域中,文本分类舆情分析等任务相较于文本抽取,和摘要等任务更容易获得大量标注数据。因此在文本分类领域中深度学习相较于传统方法更容易获得比较好的效果。 文本分类领域比较重要的的深度学习模型主要有FastText,TextCNN,HAN,DPCNN。
故事尾音
2019/12/18
1.6K0
文本分类算法之–贝叶斯文本分类算法[通俗易懂]
例如文档:Good good study Day day up可以用一个文本特征向量来表示,x=(Good, good, study, Day, day , up)。在文本分类中,假设我们有一个文档d∈X,类别c又称为标签。我们把一堆打了标签的文档集合<d,c>作为训练样本,<d,c>∈X×C。例如:<d,c>={Beijing joins the World Trade Organization, China}对于这个只有一句话的文档,我们把它归类到 China,即打上china标签。
全栈程序员站长
2022/09/05
6600
GolVe向量化做文本分类向量化文本分类
第一种是常规方法的one-hot-encoding的方法,常见的比如tf-idf生成的0-1的稀疏矩阵来代表原文本:
sladesal
2018/10/08
1.7K0
GolVe向量化做文本分类向量化文本分类
文本分类(六):使用fastText对文本进行分类--小插曲
http://blog.csdn.net/lxg0807/article/details/52960072
bear_fish
2018/09/19
1.6K0

相似问题

必需的Java/Scala : Iterable[_ <:Float],找到: Iterable[Float]

115

Spacy文本分类分数

221

出现错误"TypeError:'NoneType‘object is not iterable“

117

基于spaCy的文本分类

13

Flask错误处理:"Response object is not iterable“

23
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文