我尝试使用基于新数据构建的keras模型,除了在尝试预测预测时出现输入错误。
这是我的模型代码:
def build_model(max_features, maxlen):
"""Build LSTM model"""
model = Sequential()
model.add(Embedding(max_features, 128, input_length=maxlen))
model.add(LSTM(128))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop')
return model
还有用于预测新数据的输出预测的代码:
LSTM_model = load_model('LSTMmodel.h5')
data = pickle.load(open('traindata.pkl', 'rb'))
#### LSTM ####
"""Run train/test on logistic regression model"""
# Extract data and labels
X = [x[1] for x in data]
labels = [x[0] for x in data]
# Generate a dictionary of valid characters
valid_chars = {x:idx+1 for idx, x in enumerate(set(''.join(X)))}
max_features = len(valid_chars) + 1
maxlen = np.max([len(x) for x in X])
# Convert characters to int and pad
X = [[valid_chars[y] for y in x] for x in X]
X = sequence.pad_sequences(X, maxlen=maxlen)
# Convert labels to 0-1
y = [0 if x == 'benign' else 1 for x in labels]
y_pred = LSTM_model.predict(X)
运行此代码时出现的错误:
ValueError: Error when checking input: expected embedding_1_input to have shape (57,) but got array with shape (36,)
我的错误来自maxlen
,因为对于我的训练数据maxlen=57
和新数据maxlen=36
。
所以我尝试设置预测代码maxlen=57
,但随后出现此错误:
tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[31,53] = 38 is not in [0, 38)
[[Node: embedding_1/embedding_lookup = GatherV2[Taxis=DT_INT32, Tindices=DT_INT32, Tparams=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](embedding_1/embeddings/read, embedding_1/Cast, embedding_1/embedding_lookup/axis)]]
我应该怎么做才能解决这些问题?更改我的嵌入层?
答案 0 :(得分:1)
可以将“嵌入”层的input_length
设置为您将在数据集中看到的最大长度,或者仅使用在maxlen
中构建模型时使用的相同pad_sequences
值。在这种情况下,将填充任何短于maxlen
的序列,并截短任何长于maxlen
的序列。
进一步确保在训练和测试时间中使用的功能相同(即,其编号不应更改)。