1
model.fit(x,y, epochs=10000, batch_size=1)

上面的代码工作正常。当我使用函数向模型中提供数据时,出现了问题。

model.fit(GData(), epochs=10000, batch_size=1)

per_sample_losses = loss_fn.call(targets[i], outs[i])
IndexError: list index out of range

GData() 函数如下所示:

def GData():
  return (x,y)

x 是一个尺寸为 (2, 63, 85)
的 numpy 数组 y 是一个尺寸为 (2, 63, 41000) 的 numpy 数组

这是整个代码:

import os
import tensorflow as tf
import numpy as np

def MSE( y_true, y_pred):
    error = tf.math.reduce_mean(tf.math.square(y_true-y_pred))
    return error

data = np.load("Data.npz")
x = data['x'] # (2,63,   85)
y = data['y'] # (2,63,41000)

frame = x.shape[1]
InSize = x.shape[2]
OutSize = y.shape[2]

def GData():
    return (x,y)


model = tf.keras.Sequential()
model.add(tf.keras.layers.GRU(1000, return_sequences=True, input_shape=(frame,InSize)))
model.add(tf.keras.layers.Dense(OutSize))

model.compile(optimizer='adam',
              loss=MSE)#'mean_squared_error')
model.fit(GData(), epochs=10000, batch_size=1)
4

1 回答 1

1

首先,您的函数GData实际上不是生成器,因为它返回一个值而不是产生一个值。无论如何,我们应该看看您可以在此处fit()找到的方法及其文档。由此,我们看到前两个参数是 x 和 y。更进一步,我们看到 x 仅限于几种类型。即,生成器、numpy 数组、tf.data.Datasets 和其他一些。文档中需要注意的重要一点是,如果 x 是生成器,则它必须是. 我假设这就是你要找的。如果是这种情况,您将需要修改您的函数,使其实际上是一个生成器。这可以这样做fit()A generator or keras.utils.Sequence returning (inputs, targets)GData

batch_size = 1
EPOCHS = 10000
def GData():
    for _ in range(EPOCHS): # Iterate through epochs. Note that this can be changed to be while True so that the generator yields indefinitely. The model will stop training after the amount of epochs you specify in the fit method.
        for i in range(0, len(x), batch_size): # Iterate through batches
            yield (x[i:batch_size], y[i:batch_size]) # Yield batches for training

然后,您必须在fit()调用中指定每个 epoch 的步数,以便您的模型知道何时在每个 epoch 停止。

model.fit(GData(), epochs=EPOCHS, steps_per_epoch=x.shape[0]//batch_size)
于 2020-06-14T07:49:44.407 回答