ValueError:检查输入时出错:预期density_1_input具有2维

时间:2019-06-04 03:57:28

标签: keras

我尝试了以下示例:

from keras.models import Sequential  
from keras.layers import *  
import numpy as np

x_train = np.random.random((30,50,50,3))
y_train = np.random.randint(2, size=(30,1))

model = Sequential()    

#start from the first hidden layer, since the input is not         actually a layer   
#but inform the shape of the input, with 3 elements.    
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1    with input

#further layers:    
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer

model.compile(loss='binary_crossentropy',
           optimizer='adam',
           metrics=['accuracy'])

model.fit(x_train, y_train,
       epochs=20,
       batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)

我收到此错误:

ValueError:检查输入时出错:预期density_1_input具有2维,但数组的形状为(30,50,50,3)。

因此,我将input_shape更改如下:

from keras.models import Sequential  
from keras.layers import *  
import numpy as np

x_train = np.random.random((30,50,50,3))
y_train = np.random.randint(2, size=(30,1))

model = Sequential()    

#start from the first hidden layer, since the input is not         actually a layer   
#but inform the shape of the input, with 3 elements.    
model.add(Dense(units=4,input_shape=(50,50,3))) #hidden layer 1    with input

#further layers:    
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer

model.compile(loss='binary_crossentropy',
           optimizer='adam',
           metrics=['accuracy'])

model.fit(x_train, y_train,
       epochs=20,
       batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)

但是现在我收到此错误:

ValueError:检查目标时出错:预期density_2具有4维,但数组的形状为(30,1)

关于我在做什么错的任何想法吗?

1 个答案:

答案 0 :(得分:1)

问题在于最后一个密集层的输出形状。您可以使用 model.summary()来查看每个图层的输出形状。

  

您的输出形状为(None,50,50,1),但要与您的y_train匹配   形状应该为(None,1)。

所以我建议您在最后一个致密层之前添加一个 flattern层。请参考此link来了解喀拉拉邦的terntern层。

这是您的模型代码的外观

model.add(Dense(units=4,input_shape=(50,50,3),name="d1")) #hidden layer 1    with input  
model.add(Dense(units=4,name="d2")) #hidden layer 2
model.add(Flatten())
model.add(Dense(units=1,name="d3")) #output layer

model.compile(loss='binary_crossentropy',
           optimizer='adam',
           metrics=['accuracy'])

model.summary()

为您的图层添加更多的使用名称,您将很容易理解问题所在。祝您好运;-)