Python 如何在一维序列上训练我的LSTM?

Python 如何在一维序列上训练我的LSTM?,python,keras,Python,Keras,我正在尝试使用以前编码为向量的句子来训练LSTM。我想做的是使用LSTM层将问题映射到答案 现在,我使用X_列表[0]获取LSTM的输入形状。形状,但是Keras希望X_列表是三维的 这是我的密码: questions = [question.ljust(maxLenQs) for question in question] question_ngram = n_gram.ngramStrings(questions,2) print("Finished getting the ngrams."

我正在尝试使用以前编码为向量的句子来训练LSTM。我想做的是使用LSTM层将问题映射到答案

现在,我使用
X_列表[0]获取LSTM的输入形状。形状
,但是Keras希望
X_列表
是三维的

这是我的密码:

questions = [question.ljust(maxLenQs) for question in question]
question_ngram = n_gram.ngramStrings(questions,2)
print("Finished getting the ngrams.")
X_list = np.array(question_ngram)
print("Type of X_list: " + str(X_list.dtype))
maxLenAs = max([len(answer) for answer in answers])
Y_list = [answer.ljust(maxLenAs) for answer in answers]
Y_list = [answer.split(" ") for answer in Y_list]
vocabulary = set()
print("Beginning one-hot encoding.")
from keras.preprocessing import text
Y_list = np.array([text.one_hot(answer,len(vocabulary)) for answer in answers])
print("Finished one-hot encoding.")
# Expected number of dimensions: 2
# import sklearn.preprocessing
assertionMessage = "Assertion failed: X_list: " + str(len(X_list)) + " Y_list " + str(len(Y_list))
assert len(X_list) > 0, assertionMessage
print("Building neural network")
# Define our neural network.
from keras.models import Sequential
from keras.layers import Dense,LSTM,Dropout
from keras.callbacks import ModelCheckpoint
model = Sequential()
# Train our model.
# Each X represents columns (is our X this word/that word?) 
# Each X includes one word from the answer (or None if we're talking about the first word)
# Train our model.
# Each X represents columns (is our X this word/that word?) 
# Each X includes one word from the answer (or None if we're talking about the first word)
dimensions = 100
print("Loaded model")
model.add(LSTM(100,input_shape=X_list[0].shape,return_sequences=True))
print("X list shape: ",X_list.shape)

您可以将数据更改为三维

例如,如果您有形状
(10003250)
的数据,即您有1000个大小为3250的1D数组样本。您可以重塑为
(1000,13250)
,并在其中训练您的模型。可以使用numpy调整数据大小

import numpy as np
data = np.resize(data,(data.shape[0],1,data.shape[1]))

所以,令人困惑的是,我调整了X_列表的大小,现在我有了一个三维形状。但是,Keras现在抱怨我的输入是4维的。您是否更改了第一层中的输入形状参数。如果不将其设置为
input\u shape=X\u list.shape[1://code>好的,是的-但是您的代码似乎已经解决了ValueError。