LSTM-训练给定矢量作为输入特征的模型

时间:2019-10-22 10:00:23

标签: python tensorflow keras lstm recurrent-neural-network

我正在LSTM中训练一个模型,以根据输入向量预测单个步骤。这是示例数据:

enter image description here

我的输入是短语序列(向量),我的目标是预测“成本”。词组顺序是向量的原因是因为我在同一日期有多个记录。 我已成功将数据拆分为以下形状:

x_train: (249, 7) y_train: (249,)
x_val: (2, 7) y_val: (2,)

现在,当我将此输入传递给Keras时,会出现以下错误:

ValueError: Failed to convert numpy ndarray to a Tensor (Unable to get element as bytes.).

我已使用以下代码拆分和整形数据:

def multivariate_data(dataset, target, start_index, end_index, history_size,
                      target_size, step, single_step=False):
  data = []
  labels = []

  start_index = start_index + history_size
  if end_index is None:
    end_index = len(dataset) - target_size

  for i in range(start_index, end_index):
    indices = range(i-history_size, i, step)
    data.append(dataset[indices])

    if single_step:
      labels.append(target[i+target_size])
    else:
      labels.append(target[i:i+target_size])

  return np.array(data), np.array(labels)

我已遵循this教程。这是我的代码:

train_data_single = tf.data.Dataset.from_tensor_slices((x_train_single, y_train_single))
train_data_single = train_data_single.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat()

val_data_single = tf.data.Dataset.from_tensor_slices((x_val_single, y_val_single))
val_data_single = val_data_single.batch(BATCH_SIZE).repeat()

single_step_model = tf.keras.models.Sequential()
single_step_model.add(tf.keras.layers.LSTM(32,input_shape=x_train_single.shape[-2:]))
single_step_model.add(tf.keras.layers.Dense(1))
single_step_model.compile(loss='mae', optimizer=tf.train.RMSPropOptimizer(learning_rate=0.001))

如何将numpy nd数组转换为张量?

1 个答案:

答案 0 :(得分:0)

尝试通过填充从短语序列中消除列表。参见https://www.tensorflow.org/guide/keras/masking_and_padding