'tuple'对象不是迭代器

时间:2019-03-07 01:39:12

标签: python keras

以下代码是我的词嵌入神经网络的切入点:

negative_ratio, n_positive = 1, 10
t = Trainer()
epoch = t.generate_batch(n_positive, negative_ratio=negative_ratio)
model = t.model()
h = model.fit_generator(
    epoch,
    epochs=15,
    steps_per_epoch=negative_ratio,
    verbose=2
)
上面的

epoch是来自生成器的数据,它以以下格式产生(编码的)训练数据:

 [[list([57, 41, 49, 50, 55, 19, 26, 38, 5, 14, 51])
  list([50, 0, 0, 0, 0, 49, 0, 0, 0, 0, 26, 0, 0, 0, 0, 41, 55, 19, 38, 5, 51, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 57, 0, 0, 0, 0, 0, 0, 0])
  1]
 [list([35, 50, 12, 15, 21, 19, 26, 34, 13, 52])
  list([50, 12, 0, 0, 0, 0, 0, 0, 0, 0, 26, 34, 0, 0, 0, 21, 19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 15, 13, 0, 0, 0, 0, 0, 0])
  1]
 [list([20, 28, 41, 56, 2, 1, 51, 23, 22])
  list([28, 0, 0, 22, 0, 0, 0, 0, 0, 0, 2, 23, 0, 0, 0, 41, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 20, 56, 0, 0, 0, 0, 0, 0, 0])
  1]
 [list([30, 20, 9, 12, 15, 19, 34, 5, 52, 51, 22])
  list([12, 0, 0, 22, 0, 0, 0, 9, 0, 0, 34, 0, 0, 0, 0, 19, 5, 51, 0, 0, 0, 0, 0, 0, 0, 0, 30, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 20, 15, 0, 0, 0, 0, 0, 0, 0])
  1]]

尽管如此,Keras一直告诉我,生成器无效:

TypeError: 'tuple' object is not an iterator

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

如错误所示,您正在传递一个元组而不是一个生成器对象。 fit_generator()需要一个生成器对象。在内部,它将在生成器对象上调用next()以获取一批数据。

如果这样做,在元组上执行next(),我将得到相同的错误:

>>> next((1,2))
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    next((1,2))
TypeError: 'tuple' object is not an iterator

>>> sample_generator = ((1,2) for i in range(3))
>>> x,y = next(sample_generator)
>>> x,y
(1, 2)