简体   繁体   中英

Keras LSTM input error: Failed to convert NumPy array to Tensor

I have a dataset, where each sample is a variable number of timesteps, and within each timestep there are exact 5 floats. I want to train an RNN/LSTM that predicts a single value:

sample_1 = [[1.0, 2.0, 3.0, 4.0, 5.0], [5.0, 4.0, 3.0, 2.0, 1.0].....]

train_x = [sample_1, sample_2.....] train_y = [123.0, 456.0.....]

My Sequential Keras LSTM model looks as follows:

model = Sequential()
model.add(LSTM(units=4, dropout=0.5))
model.add(Dense(units=4, activation='relu'))
model.add(Dense(1))
model.compile(loss='mean_absolute_error',
              optimizer=Adam())

and to train:

_ = model.fit(
    train_x,
    train_y,
    validation_data=(validation_x, validation_y),
    shuffle=True,
    batch_size=16,
    epochs=10,
    verbose=2)

But, I Immediately get the following error:

"ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list)."

Is there anything explicitly wrong with my model setup? Is it ok for me to simply be using a nested list of lists as the input examples?

As error message suggest convert your input data to tensor

Working sample code

import numpy as np
sample_1 = [[1.0, 2.0, 3.0, 4.0, 5.0], [5.0, 4.0, 3.0, 2.0, 1.0]]
sample_2 = [[6.0, 7.0, 8.0, 9.0, 10.0], [10.0, 9.0, 8.0, 7.0, 6.0]]
sample1 = tf.convert_to_tensor(sample_1, dtype=tf.float32)
sample2 = tf.convert_to_tensor(sample_2, dtype=tf.float32)

train_x = [sample1, sample2] 
train_y = [123.0, 456.0]

train_x = np.asarray(train_x)
train_y = np.asarray(train_y)
from tensorflow.keras import Sequential
model = Sequential()
model.add(tf.keras.layers.LSTM(units=4, dropout=0.5))
model.add(tf.keras.layers.Dense(units=4, activation='relu'))
model.add(tf.keras.layers.Dense(1))
model.compile(loss='mean_absolute_error',
              optimizer=tf.keras.optimizers.Adam())

model = model.fit(train_x,train_y,batch_size=16,epochs=2,verbose=2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM