【问题标题】:Tensorflow/keras error: ValueError: Error when checking input: expected lstm_input to have 3 dimensions, but got array with shape (4012, 42)Tensorflow/keras 错误:ValueError:检查输入时出错:预期 lstm_input 具有 3 维,但得到的数组具有形状(4012、42)
【发布时间】:2020-07-19 22:18:07
【问题描述】:

我有一个 pandas 数据帧,它是由一个名为 x_train 的 train_test_split 制作的,它有 4012 行数据帧中的所有值都是整数或浮点数(训练/测试拆分后)和 42 列(训练/测试拆分后)。 我正在尝试使用 LSTM 单元训练递归神经网络,但是当模型尝试输入数据帧时,我的程序一直给我一个错误。我尝试过重塑数据框,但这也不起作用,但也许我做错了。如果您知道如何修复它和/或知道如何使我的模型更有效,请告诉我。

这是我的代码:

df = pd.read_csv("data.csv")

x = df.loc[:, df.columns != 'result']
y = df.loc[:, df.columns == 'result']

y = y.astype(int)

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, shuffle = False)

model = Sequential()

model.add(LSTM(128, input_shape = (4012, 42), activation = 'relu', return_sequences = True)) #This is the line where the error happens.
model.add(Dropout(0.2))

model.add(LSTM(128, activation = 'relu'))
model.add(Dropout(0.2))

model.add(Dense(32, activation = 'relu'))
model.add(Dropout(0.2))

model.add(Dense(2, activation = 'softmax'))

opt = tf.keras.optimizers.Adam(lr = 10e-3, decay=1e-5)

model.compile(loss = 'sparse_categorical_crossentropy', optimizer = opt, metrics = ['accuracy'])

model.fit(x_train, y_train, epochs = 5, validation_data = (x_test, y_test))

我得到的错误:

ValueError: 检查输入时出错:预期 lstm_input 有 3 个维度,但得到的数组的形状为 (4012, 42)

请有人帮帮我。

【问题讨论】:

    标签: python pandas tensorflow keras lstm


    【解决方案1】:

    问题是您试图为模型提供二维数组,但它需要 3 维数组。 而不是重塑Dataframe将其转换为数组,然后根据下面的修改代码进行重塑。

    df = pd.read_csv("data.csv")
    
    x = df.loc[:, df.columns != 'result']
    y = df.loc[:, df.columns == 'result']
    
    y = y.astype(int)
    
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, shuffle = False)
    x_train = x_train.values.reshape((1, x_train.shape[0], x_train.shape[1]))
    x_test = x_test.values.reshape((1, x_test.shape[0], x_test.shape[1]))
    
    
    
    y_train = y_train.values.reshape((1, y_train.shape[0], y_train.shape[1]))
    y_test = y_test.values.reshape((1, y_test.shape[0], y_test.shape[1]))
    

    【讨论】:

      猜你喜欢
      • 2020-04-05
      • 2020-09-01
      • 2018-08-03
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      相关资源
      最近更新 更多