【问题标题】:ValueError: Error when checking input: expected dense_1_input to have 2 dimensionsValueError:检查输入时出错:预期的 dense_1_input 有 2 个维度
【发布时间】:2019-06-04 16:09:45
【问题描述】:

我尝试了以下示例:

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:检查输入时出错:预期 dense_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: 检查目标时出错:预期 dense_2 有 4 个维度,但得到的数组形状为 (30, 1)

知道我做错了什么吗?

【问题讨论】:

    标签: keras


    【解决方案1】:

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

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

    所以我建议你在最后一个密集层之前添加一个flattern layer。请参考link 了解keras 中flattern layer 的定义。

    你的模型代码应该是这样的

    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()
    

    为您的图层提供更多使用名称,您将很容易理解问题出在哪里。祝您好运 ;-)

    【讨论】:

      猜你喜欢
      • 2019-11-18
      • 1970-01-01
      • 2020-01-04
      • 2018-07-25
      • 2019-12-17
      • 2020-04-15
      • 2020-05-04
      • 2020-04-05
      • 1970-01-01
      相关资源
      最近更新 更多