ValueError: `validation_split` 只支持 Tensor 或 NumPy 数组,发现:(keras.preprocessing.sequence.TimeseriesGenerator object)

Jus*_* 51 3 python lstm keras tensorflow

当我尝试在 LSTM 模型中添加 validation_split 时,出现此错误

ValueError: `validation_split` is only supported for Tensors or NumPy arrays, found: (<tensorflow.python.keras.preprocessing.sequence.TimeseriesGenerator object)
Run Code Online (Sandbox Code Playgroud)

这是代码

ValueError: `validation_split` is only supported for Tensors or NumPy arrays, found: (<tensorflow.python.keras.preprocessing.sequence.TimeseriesGenerator object)
Run Code Online (Sandbox Code Playgroud)

我能想到的一个原因是,要使用validation_split需要张量或numpy 数组,如错误中所述,但是,当通过TimeSeriesGenerator传递训练数据时,它会将训练数据的维度更改为 3D 数组
并且由于TimeSeriesGenerator是使用 LSTM 时必须使用,这是否意味着对于 LSTM 我们不能使用 validation_split

unc*_*123 9

y = np.array(y)
Run Code Online (Sandbox Code Playgroud)

这为我解决了这个问题。报错说只支持numpy数组,所以把它转成数组。

  • 这个答案违背了使用tensorflow.datasets的目的。而是按照@pratsbhatt的建议分割数据并使用``model.fit(train_dataset,validation_data=test_dataset)``` (3认同)

Pra*_*att 5

Your first intution is right that you can't use the validation_split when using dataset generator.

You will have to understand how the functioninig of dataset generator happens. The model.fit API does not know how many records or batch your dataset has in its first epoch. As the data is generated or supplied for each batch one at a time to the model for training. So there is no way to for the API to know how many records are initially there and then making a validation set out of it. Due to this reason you cannot use the validation_split when using dataset generator. You can read it in their documentation.

介于 0 和 1 之间的浮点数。要用作验证数据的训练数据的一部分。该模型将把这部分训练数据分开,不会对其进行训练,并将在每个时期结束时评估损失和此数据的任何模型指标。在混洗之前,验证数据是从提供的 x 和 y 数据中的最后一个样本中选择的。当 x 是数据集、生成器或 keras.utils.Sequence 实例时,不支持此参数。

您需要阅读最后两行,他们说数据集生成器不支持它。

您可以做的是使用以下代码来拆分数据集。您可以在此处详细阅读。我只是从下面的链接中写出重要的部分。

# Splitting the dataset for training and testing.
def is_test(x, _):
    return x % 4 == 0


def is_train(x, y):
    return not is_test(x, y)


recover = lambda x, y: y

# Split the dataset for training.
test_dataset = dataset.enumerate() \
    .filter(is_test) \
    .map(recover)

# Split the dataset for testing/validation.
train_dataset = dataset.enumerate() \
    .filter(is_train) \
    .map(recover)
Run Code Online (Sandbox Code Playgroud)

希望我的回答对你有帮助。