【问题标题】:How to shape a Pandas DataFrame for LSTM如何为 LSTM 塑造 Pandas DataFrame
【发布时间】:2021-01-05 17:20:54
【问题描述】:

我正在尝试将pandas DataFrame 正确地塑造成与Keras 的方法timeseries_dataset_from_array() 兼容的格式。主要问题在于数据集中的大量特征,这意味着要使用 for 循环:

x_reshaped = [tf.reshape(x_train.iloc[:-seq_length, column].values, (-1, 1))
              for column in range(len(x_train.columns))] 

当我跑步时:

tf.keras.preprocessing.timeseries_dataset_from_array(x_reshaped, y_reshaped,
                                                          sequence_length=seq_length,
                                                          batch_size=bs)

我收到此错误消息AttributeError: 'list' object has no attribute 'shape',因为x_reshaped 被视为向量的列表,而不是矩阵。

我也试过用tf.TensorArray()创建训练矩阵,但是没用。

【问题讨论】:

    标签: python pandas tensorflow keras tf.keras


    【解决方案1】:

    我不会称其为高维数据,因为 Pandas DataFrame 通常具有一维数据。您不需要重塑操作或 for 循环。您可以将 DataFrame 直接传递给 Keras 函数:

    import pandas as pd
    import tensorflow as tf
    
    df = pd.DataFrame({'features1':    [0., 1., 2., 3., 4.],
                       'features2':    [4., 3., 2., 1., 0.],
                       'predictions':  [5., 6., 7., 8., 9.]})
    
       features1  features2  predictions
    0        0.0        4.0          5.0
    1        1.0        3.0          6.0
    2        2.0        2.0          7.0
    3        3.0        1.0          8.0
    4        4.0        0.0          9.0
    

    在 Keras 函数中传递列:

    ds = tf.keras.preprocessing.timeseries_dataset_from_array(
         data=df[['features1', 'features2']],
         targets=df['predictions'],
         sequence_length=3)
    
    x, y = next(iter(ds))
    
    print(x.shape)
    
    TensorShape([3, 3, 2])
    

    看起来像这样:

    <tf.Tensor: shape=(3, 3, 2), dtype=float64, numpy=
    array([[[0., 4.],
            [1., 3.],
            [2., 2.]],
           [[1., 3.],
            [2., 2.],
            [3., 1.]],
           [[2., 2.],
            [3., 1.],
            [4., 0.]]])>
    

    现在它有了时间步长维度,可以将其传递到 LSTM 层中。

    lstm_layer = tf.keras.layers.LSTM(1)
    
    lstm_layer(x)
    
    <tf.Tensor: shape=(3, 1), dtype=float32, numpy=
    array([[0.11129456],
           [0.14443444],
           [0.18482907]], dtype=float32)>
    

    【讨论】:

      猜你喜欢
      • 2019-06-18
      • 2021-09-30
      • 2021-06-14
      • 2022-01-11
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多