ValueError:检查输入时出错:预期密集_输入有2个维度,但得到了形状为(1,1,15)的数组

2024-04-29 05:33:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试建立一个定制的健身房环境,这样我就可以在Keras网络中使用它。但当我尝试去适应de神经网络时,有一个问题正在发生在我身上

ValueError: Error when checking input: expected dense_6_input to have 2 dimensions, but got array with shape (1, 1, 15)

我对这个问题的理解是,状态(网络接收的输入)被构造成一个三维数组,但我不知道为什么

下面是我在定义环境的类中的init方法:

def __init__ (self):
    self.action_space = Discrete (4)
    self.observation_space = Box(low=0, high=100, shape=(15,))
    self.state = np.array([1,2,0,3,2,0,4,0,0,1,3,0,0,0,0], dtype=float)
    #self.state = state
    self.length = 15
    self.index = 0

之后,我初始化了两个保存状态和动作形状的变量,这样我们就可以定义模型了

states = env.observation_space.shape
actions = env.action_space.n

def build_model(states, actions):
model = Sequential()    
model.add(Dense(24, activation='relu', input_shape=states))
model.add(Dense(24, activation='relu'))
model.add(Dense(actions, activation='linear'))
return model

模型摘要:

图层(类型)输出形状参数#
致密(致密)(无,24)384
密集型_7(密集型)(无,24)600
密集型_8(密集型)(无,4)100

出现错误之前的最后一步是在构建代理时。之后,我们调用fit方法并出现问题

def build_agent(model, actions):
   policy = BoltzmannQPolicy()
   memory = SequentialMemory(limit=50000, window_length=1)
   dqn = DQNAgent(model=model, memory=memory, policy=policy, 
              nb_actions=actions, nb_steps_warmup=10, target_model_update=1e-2)
   return dqn

dqn = build_agent(model, actions)
dqn.compile(Adam(lr=1e-3), metrics=['mae'])
dqn.fit(env, nb_steps=50000, visualize=False, verbose=1)

我试图将第一层的输入形状更改为(1,1,15),但似乎不起作用。问题可能与环境(观测空间)的定义有关,或者与环境如何向网络提供信息有关。我不知道

我希望你能帮助我。如果您需要更多信息来处理错误,请告诉我

非常感谢你


Tags: self网络actionsinputmodel定义环境def
1条回答
网友
1楼 · 发布于 2024-04-29 05:33:27

在您的情况下,输入形状应为(1,15)。这是因为实际输入形状增加了在shape中指定的额外维度,因为keras以批处理输入,批大小是第一个参数

错误消息告诉您形状(1,1,15)的输入正在传递给模型(即批次1和输入形状(1,15),因此ndims=3),但您只有ndims=2。尽管只传递(15,)作为输入形状,但请注意ndims=2。这是因为Keras正在为批次添加额外维度

因此,为了解决这个问题,将shape=(1,15)设置为(1,1,15),这是Keras所期望的

相关问题 更多 >