【问题标题】:SpaCy - ValueError: operands could not be broadcast together with shapes (1,2) (1,5)SpaCy - ValueError:操作数无法与形状一起广播(1,2)(1,5)
【发布时间】:2019-12-20 18:47:31
【问题描述】:

关于 stackoverflow 上的上一篇文章 Model() got multiple values for argument 'nr_class' - SpaCy multi-classification model (BERT integration) 我的问题已部分解决 我想分享实施解决方案后出现的问题。

如果我去掉 nr_class 参数,我会在这里得到这个错误:

ValueError: operands could not be broadcast together with shapes (1,2) (1,5)

我实际上认为这会发生,因为我没有指定 nr_class 争论。这是正确的吗?

再写一次我的多类模型代码:

nlp = spacy.load('en_pytt_bertbaseuncased_lg')
textcat = nlp.create_pipe(
    'pytt_textcat',
    config={
        "nr_class":5,
        "exclusive_classes": True,
    }
)
nlp.add_pipe(textcat, last = True)

textcat.add_label("class1")
textcat.add_label("class2")
textcat.add_label("class3")
textcat.add_label("class4")
textcat.add_label("class5")

训练的代码如下,基于此处的示例(https://pypi.org/project/spacy-pytorch-transformers/):

def extract_cat(x):
    for key in x.keys():
        if x[key]:
            return key

# get names of other pipes to disable them during training
n_iter = 250 # number of epochs

train_data = list(zip(train_texts, [{"cats": cats} for cats in train_cats]))


dev_cats_single   = [extract_cat(x) for x in dev_cats]
train_cats_single = [extract_cat(x) for x in train_cats]
cats = list(set(train_cats_single))
recall = {}
for c in cats:
    if c is not None: 
        recall['dev_'+c] = []
        recall['train_'+c] = []



optimizer = nlp.resume_training()
batch_sizes = compounding(1.0, round(len(train_texts)/2), 1.001)

for i in range(n_iter):
    random.shuffle(train_data)
    losses = {}
    batches = minibatch(train_data, size=batch_sizes)
    for batch in batches:
        texts, annotations = zip(*batch)
        nlp.update(texts, annotations, sgd=optimizer, drop=0.2, losses=losses)
    print(i, losses)

所以我的数据结构是这样的:

[('TEXT TEXT TEXT',
  {'cats': {'class1': False,
    'class2': False,
    'class3': False,
    'class4': True,
    'class5': False}}), ... ]

【问题讨论】:

  • (1,2) 指的是“恢复”优化器的 2 类,(1,5) 指的是您的问题的 5 类。当我遇到同样的问题时,我可以通过将我的问题简化为 2 类问题来使代码正常工作。当然,这不是解决方案..
  • 我追踪了它,我认为它在几天前已修复:github.com/explosion/spacy-pytorch-transformers/commit/…

标签: python pytorch spacy multiclass-classification


【解决方案1】:

正如@Milla Well 已经评论的那样,可以在here 找到答案(来自@syllogism_ 的github 上的错误修复)

【讨论】:

  • 链接失效:(
猜你喜欢
  • 2014-08-16
  • 2021-03-03
  • 2017-09-09
  • 2012-10-31
  • 2013-04-07
  • 2012-08-05
  • 2018-08-18
  • 2020-06-20
  • 2014-08-24
相关资源
最近更新 更多