【问题标题】:How can I load this data into a LSTM?如何将这些数据加载到 LSTM 中?
【发布时间】:2020-02-15 17:13:10
【问题描述】:

分类问题: 数据分为两个文件夹。 CSV 仅包含数据。 我的示例模型的代码是:

model = Sequential()
model.add(CuDNNLSTM(3, input_shape=(None, 3), return_sequences=False))
model.add(Dropout(0.1))
model.add(Dense(1, activation='softmax'))

问题 1: 是否可以替代 keras 生成器来控制加载哪些文件?
问题 2: 除了批量大小为 1 之外,还有什么其他方法可以使可变时间步长成为可能吗? 问题 3: 这是否是 LSTM 接受可变时间步长的正确代码?如果没有,请提出更好的方法。

input_shape=(None, 3)

【问题讨论】:

    标签: python tensorflow keras classification lstm


    【解决方案1】:

    问题 1 和 2

    案例1,你的数据适合你的记忆

    只需将数据加载到数组中并填充数据:

    import pandas as pd
    import numpy as np
    import os
    from keras.preprocessing.sequence import pad_sequences
    
    #your class folders - choose the correct names
    folder0 = "class0"
    folder1 = "class1"
    
    #x and y initially as lists
    fileContents = []
    fileClasses = []
    
    #list of files in each dir
    files0 = os.listdir(folder0)
    files1 = os.listdir(folder1)
    
    #load data for class 0
    for f in files0:
        f = folder0 + "/" + f
        if '.csv' in f:
            frame = pd.read_csv(f) #use header=None if you don't have headers in the files
            fileContents.append(frame.values)
            fileClasses.append(0) #append the correct class
            print(frame.values)
    
    #load data for class 1
    for f in files1:
        f = folder1 + "/" + f
        if '.csv' in f:
            frame = pd.read_csv(f)
            fileContents.append(frame.values)
            fileClasses.append(1) #append the correct class
            print(frame.values)
    
    #pad the sequences so they all have the same length and transform into numpy
    #choose best value for you, I chose 0 for example
    paddedSequences = pad_sequences(fileContents, padding='post', value=0) 
    
    x_train = np.array(paddedSequences)
    y_train = np.array(fileClasses)
    
    

    稍后,您将需要在模型中使用 Masking(0) 层来忽略您用于填充的 0 值。

    情况2,你的数据不适合你的记忆

    创建 Python 生成器或 keras.utils.Sequence 以与 model.fit_generator() 一起使用。

    加载数据的原理和案例一完全一样,但是你会分小批做。

    这也是按长度分隔文件并输出相似长度的批次的好机会(这意味着减少无用的填充)

    有很多答案和教程解释了如何创建这两个选项。比如 Keras 文档教 Sequence: https://keras.io/utils/

    问题 3

    完全正确。

    【讨论】:

    • 感谢您的回答!感谢您的详细解释。代码和你关于批量大小、生成器等的提示让我清楚地了解了 Keras 的输入。
    猜你喜欢
    • 1970-01-01
    • 2012-11-09
    • 2020-12-30
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多