python - 检查输入时出错:预期 lstm_1_input 有 3 个维度,但得到了形状为 (5, 3) 的数组
问题描述
我的任务是使用 LSTM 从 3 个传感器预测房间占用率(1,2)。有关此数据的示例,请参见下图:
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt
x = np.array([
[31, 3, 5],
[32, 3, 5],
[29, 0, 3],
[31, 3, 4],
[23, 2, 4],
[22, 2, 4],
[23, 1, 4], ])
y = np.array([
[2],
[2],
[1],
[2],
[1],
[1],
[1], ])
x = x.reshape(7, 3, 1)
x_train,x_test,y_train,y_test = train_test_split(x, y,test_size =0.2, random_state = 4)
model=Sequential()
model.add(LSTM((1), activation='softmax', input_shape=x_train.shape,return_sequences=False))
我在这里遇到一个错误:
-------------------------------------------------- ------------------------- ValueError Traceback (last last call last) in ----> 1 model.add(LSTM((1),激活='softmax', input_shape=x_train.shape, return_sequences=False))
~/opt/anaconda3/lib/python3.7/site-packages/keras/engine/sequential.py in add(self, layer) 163 # 并创建将当前层 164 # 连接到我们刚刚创建的输入层的节点。--> 165 layer(x) 166 set_inputs = True 167 else:
~/opt/anaconda3/lib/python3.7/site-packages/keras/layers/recurrent.py in call (self, inputs, initial_state, constants, **kwargs) 530 531 如果 initial_state 为 None 并且 constants 为 None:- -> 532 返回超级(RNN,自我)。call (inputs, **kwargs) 533 534 # 如果指定了
initial_state
orconstants
并且是 Keras~/opt/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py in call (self, inputs, **kwargs) 412 # 在输入不兼容的情况下引发异常 413 # 与 input_spec在层构造函数中指定。--> 414 self.assert_input_compatibility(inputs) 415 416 # 收集输入形状以构建层。
~/opt/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py in assert_input_compatibility(self, inputs) 309 self.name + ': 预期 ndim=' + 310 str(spec.ndim) + ', found ndim=' + --> 311 str(K.ndim(x))) 312 如果 spec.max_ndim 不是 None: 313 ndim = K.ndim(x)
ValueError:输入 0 与层 lstm_1 不兼容:预期 ndim=3,发现 ndim=4
然后由于错误,我无法运行以下几行:
model.compile(loss='binary_crossentropy', optimizer='adam',metrics=['accuracy'])
model.summary()
history = model.fit(x_train, y_train, epochs=20, validation_data=(x_test, y_test))
谁能帮我找出问题?所有的数据都是转换成整数的类别,这样创建模型合理吗?
解决方案
您需要像这样重塑您的输入:
x = x.reshape(x.shape[0], 1, x.shape[1]) # the 1 is the steps
并像这样指定输入形状:
input_shape=(x.shape[1:])
所以使用这些行,它将起作用:
x = x.reshape(7, 1, 3)
model.add(LSTM((1), activation='softmax', input_shape=x_train.shape[1:],
return_sequences=False))
sigmoid
最后,如果你只有两个类,你的激活函数应该是。
推荐阅读
- android - 如何在函数返回结果之前从内部匿名类返回结果?
- r - 在 R 中舍入到最接近的非零小数位的函数(包括负数)
- django - 在此设置中,如何内部连接 Product、ProductAttributes 和 ProductAttributesValue?[Django 模型和视图]
- html - 将包含 & 的 XML 值节点保存到数据库中的正确方法是什么?
- react-native - react-native 为什么我的 state.size 不是函数?
- c# - 只读类变量中报告的 CSRF 问题
- jenkins - Jenkins 2.289.1 升级读取权限
- python - python Dramatiq 等到比赛
- angular - 我正在制作一个简单的应用程序,但我不知道为什么每次上传新帖子时都会调用我的 home 组件的 onInit 函数
- javascript - 是否可以基于边界创建鼠标悬停事件?