python - ValueError : `validation_split` is only supported for Tensors or NumPy arrays, 发现 : (keras. preprocessing.sequence.TimeseriesGenerator 对象)

标签 python tensorflow keras lstm

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

ValueError: `validation_split` is only supported for Tensors or NumPy arrays, found: (<tensorflow.python.keras.preprocessing.sequence.TimeseriesGenerator object)
这是代码
from keras.preprocessing.sequence import TimeseriesGenerator
train_generator = TimeseriesGenerator(df_scaled, df_scaled, length=n_timestamp, batch_size=1)

model.fit(train_generator, epochs=50,verbose=2,callbacks=[tensorboard_callback], validation_split=0.1)

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

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

最佳答案

您的第一直觉是正确的,您不能使用 validation_split使用数据集生成器时。
您必须了解 dataset 的功能如何发电机发生。 model.fit API 不知道您的数据集在其第一个纪元中有多少记录或批次。由于数据是为每个批次一次生成或提供给模型进行训练的。因此,API 无法知道最初有多少记录,然后从中进行验证。由于这个原因,您不能使用 validation_split使用数据集生成器时。您可以在他们的 documentation 中阅读.

Float between 0 and 1. Fraction of the training data to be used as validation data. The model will set apart this fraction of the training data, will not train on it, and will evaluate the loss and any model metrics on this data at the end of each epoch. The validation data is selected from the last samples in the x and y data provided, before shuffling. This argument is not supported when x is a dataset, generator or keras.utils.Sequence instance.


您需要阅读最后两行,他们说数据集生成器不支持它。
您可以做的是使用以下代码来拆分数据集。您可以详细阅读here .我只是从下面的链接中写出重要的部分。
# 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)
希望我的回答对你有帮助。

关于python - ValueError : `validation_split` is only supported for Tensors or NumPy arrays, 发现 : (keras. preprocessing.sequence.TimeseriesGenerator 对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63166479/

相关文章:

python - 如何在python中解析带有国际单词的文件

python - Py安装程序: “ImportError: No module named htmlentitydefs”

python - 如何访问/处理 TensorFlow 数据集中的内容?

tensorflow - 填充张量有什么影响?

python - Keras LocallyConnected1D 层

python如何用零填充numpy数组

python - 无法解析余数 : '{{' from '{{'

tensorflow - 在tf-slim中实现混合精度训练

python - 如何在 tensorflow 中获取张量的数据类型?

python - 如何在 python 中使用 keras 获得概率/置信度作为 CNN 的输出?