如何确定CNN Keras中密集层的输入大小?

时间:2019-04-02 14:29:17

标签: python tensorflow keras deep-learning

我尝试使用keras构建人脸识别模型。我有带有主题和特征名称的图像(我知道,对于深度学习来说并不多,但是很快我会得到更多)

但是当我尝试拟合数据时,出现此错误:

  

ValueError:检查目标时出错:预期density_2具有2维,但数组的形状为(3,243,320,3)

我尝试将损失函数从sparse_categorical_crossentropy更改为categorical_crossentropy

使用keras的“ to_categorical”功能使用一键编码标签

但是它不起作用

这是我用图像和标签填充列表的方式

###### fill with images
for i in range(0,num_classes):
k=0
for j in range(len(features)):
    k+=1
    if(i < 10):
        sub = "subject0"+str(i)+"."+features[j]+".png"
    else:
        sub = "subject"+str(i)+"."+features[j]+".png"
    imgfile = Image.open(sub)
    img = np.array(imgfile)
    #print(img.shape)
    #print(type(img))
    if(k != 3):
        train.append(img)
        train_labels.append(i)
    else :
        test.append(img)
        test_labels.append(i)

########## train 
train = np.asarray(train)
train_labels = np.asarray(train_labels)

########## test 
test = np.asarray(test)
test_labels = np.asarray(test_labels)

我的课数目前为3! (一堂课是一门学科)

以下是图像的重塑和规格化。

# Reshape  243x320 pixels, 1 channel (B/W)
train = train.reshape(train.shape[0], img_rows, img_cols, 1)
# Reshape  243x320 pixels, 1 channel (B/W)
test = test.reshape(test.shape[0], img_rows, img_cols, 1)

# Normalize pixel values: [0-255] --> [0.0-1.0]
train, test = train / 255.0, test / 255.0

# One-hot encode labels
test = to_categorical(test, num_classes)
test_labels = to_categorical(test_labels, num_classes)

我建立了一个简单的CNN模型

######### build cnn models

model = Sequential()
model.add(Conv2D(32, kernel_size=(5, 5), padding='same', activation='relu', input_shape=(img_rows,img_cols,1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))


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

batch_size = 128
epochs = 10

model.fit(train, test, validation_data=(train_labels, test_labels), batch_size=batch_size, epochs=epochs)

我认为问题是我模型中某一层的输出。我已经尝试过移动展平,但是它没有用。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

test = to_categorical(test, num_classes)应该是train_labels = ...,而您的model.fit(...)呼叫应该是model.fit(train, train_labels)

这些是我能找到的最明显的错误。