Keras错误:预期density_input_1具有3个维度 [英] Keras error: expected dense_input_1 to have 3 dimensions

查看:85
本文介绍了Keras错误:预期density_input_1具有3个维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Keras中尝试一个简单的模型,我希望将其作为输入,将5x3大小的矩阵作为输入.在下面的示例中,这是在添加第一个密集层时使用input_shape=(5, 3)指定的.

I am trying out a simple model in Keras, which I want to take as input a matrix of size 5x3. In the below example, this is specified by using input_shape=(5, 3) when adding the first dense layer.

from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import Adam
import numpy as np


model = Sequential()
model.add(Dense(32, input_shape=(5, 3)))
model.add(Activation('relu'))
model.add(Dense(32))
model.add(Activation('relu'))
model.add(Dense(4))


adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
model.compile(loss='mean_squared_error', optimizer=adam)


x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]])


y = model.predict(x)

但是,当我运行代码时,model.predict()函数会出现以下错误:

However, when I run the code, the model.predict() function gives the following error:

ValueError:检查时出错:预期density_input_1具有3维,但数组的形状为(5,3)

ValueError: Error when checking : expected dense_input_1 to have 3 dimensions, but got array with shape (5, 3)

但是我不明白这个错误. x的形状为(5,3),这正是我告诉第一密层期望作为输入的形状.因此为什么期望三个维度?看来这可能与批处理大小有关,但我认为input_shape仅指网络的形状,与批处理大小无关...

But I don't understand the error. The shape of x is (5, 3), and this is exactly what I have told the first dense layer to expect as input. Why is it therefore expecting three dimensions? It seems that this may be something to do with the batch size, but I thought that input_shape is only referring to the shape of the network, and is nothing to do with the batch size...

推荐答案

问题出在这里:

model.add(Dense(32, input_shape=(5, 3)))

应为:

model.add(Dense(32, input_shape=(3,)))

第一个示例维度未包含在input_shape中.也因为它实际上取决于网络拟合期间设置的batch_size.如果要指定,可以尝试:

This first example dimension is not included in input_shape. Also because it's actually dependent on batch_size set during network fitting. If you want to specify you could try:

model.add(Dense(32, batch_input_shape=(5, 3)))

从您的评论中我了解到,在这种情况下,您希望输入的内容为shape=(5,3)

From your comment I understood that you want your input to have shape=(5,3) in this case you need to:

    通过设置
  1. reshape您的x:

x = x.reshape((1, 5, 3))

第一维来自示例.

您需要在某些阶段flatten您的模型.这是因为如果没有它,您将通过网络传递2d输入.我建议您执行以下操作:

You need to flatten your model at some stage. It's because without it you'll be passing a 2d input through your network. I advice you to do the following:

model = Sequential()
model.add(Dense(32, input_shape=(5, 3)))
model.add(Activation('relu'))
model.add(Dense(32))
model.add(Activation('relu'))
model.add(Flatten())
model.add(Dense(4))

这篇关于Keras错误:预期density_input_1具有3个维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆