使用Keras的密集错误

时间:2017-06-13 16:36:37

标签: python image machine-learning keras

我收到的错误似乎是Keras初学者的常见问题。我试图将彩色图像分类为'某事'或'not_something'并运行基本模型,这样我就可以调整超参数以更好地理解它们的作用。

如果有人可以解释为什么我在model.fit中专门得到我的错误然后解释我应该关注/寻找一般意义上的维度(在火车和测试集中)我想要它。我不确定如果二元分类器为2,Dense(单位)是否应为1,你能解释一下吗?

错误:

```

ValueError: Error when checking target: expected dense_18 to have 4 dimensions, but got array with shape (584, 1)

```

代码:

```

from identify_mounds import *
from PIL import Image
import numpy as np
np.random.seed(6)
import os
import subprocess
from collections import defaultdict
import pickle
from scipy.misc import imread
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils


def train_nomound_mound(dic):
    X = []
    y = []
    X_ = []

    for im in dic:
        X.extend(dic[im]['img_lst'])
        y.extend(dic[im]['label'])

    for im in X:
        arr = imread(im)
        X_.append(arr)

    X_ = (np.array(X_).reshape(779, 4, 16, 16)/255).astype('float32')
    y = np.array(y).astype('float32')

    X_train, X_test, y_train, y_test = train_test_split(X_, y, stratify = y)

    #Demensions: X_train: (584, 4, 16, 16), y_train: (584,), X_test:  (195, 4, 16, 16), y_test: (195,) 

    model = Sequential()

    batch_size = 128
    nb_epoch = 12

    nb_filters = 32
    kernel_size = (3, 3)
    input_shape = (4, 16, 16)
    pool_size = (2, 2)

    model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], activation='relu', input_shape=input_shape))
    model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], activation='relu'))
    # model.add(MaxPooling2D(pool_size=pool_size))
    model.add(Dropout(0.25))


    model.add(Dense(32, activation='relu'))
    model.add(Dropout(.50))
    model.add(Dense(1, activation='relu'))

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

    model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1, validation_data=(X_test, y_test))
    score = model.evaluate(X_test, y_test, verbose=0)
    print('Test score:', score[0])
    print('Test accuracy:', score[1])

```

1 个答案:

答案 0 :(得分:0)

当使用binary_crossentropy损失时,具有单个神经元的致密层是合适的。 categorical_crossentropy丢失需要单热编码和与最终输出层中的类别相同数量的神经元。来自Keras loss documentation

  

注意:使用categorical_crossentropy损失时,您的目标   应该是分类格式(例如,如果你有10个类,那么   每个样本的目标应该是10维向量   all-zeros期望在对应于类的索引处为1   样本)。

Keras MNIST MLP example简明扼要地阐述了to_categorical函数的单热编码。