最后一层神经网络出错

时间:2017-08-14 16:28:33

标签: python-3.x tensorflow neural-network keras

#10-Fold split
seed = 7
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)
np.random.seed(seed)
cvscores = []

    act = 'relu'
    for train, test in kfold.split(X, Y):

        model = Sequential()

        model.add(Dense(43, input_shape=(8,)))
        model.add(Activation(act))

        model.add(Dense(500))
        model.add(Activation(act))
    #model.add(Dropout(0.4))

        model.add(Dense(1000))
        model.add(Activation(act))
    #model.add(Dropout(0.4))

        model.add(Dense(1500))
        model.add(Activation(act))
    #model.add(Dropout(0.4))


        model.add(Dense(2))
        model.add(Activation('softmax'))

        model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
        hist = model.fit(X[train], Y[train],
                    epochs=500,
                    shuffle=True,
                    batch_size=100,
                    validation_data=(X[test], Y[test]), verbose=2)
    #model.summary()

当我致电 model.fit时报告以下错误:

  

ValueError:检查目标时出错:预期activation_5有形状(None,2)但是有形状的数组(3869,1)

我正在使用 keras TensorFlow 后端。如有需要,请询问任何进一步的说明。

2 个答案:

答案 0 :(得分:0)

试试这个:

#10-Fold split
seed = 7
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)
np.random.seed(seed)
cvscores = []

    act = 'relu'
    for train, test in kfold.split(X, Y):

        model = Sequential()

        model.add(Dense(43, input_shape=(8,)))
        model.add(Activation(act))

        model.add(Dense(500))
        model.add(Activation(act))
    #model.add(Dropout(0.4))

        model.add(Dense(1000))
        model.add(Activation(act))
    #model.add(Dropout(0.4))

        model.add(Dense(1500))
        model.add(Activation(act))
    #model.add(Dropout(0.4))


        model.add(Dense(1))
        model.add(Activation('softmax'))

        model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
        hist = model.fit(X[train], Y[train],
                    epochs=500,
                    shuffle=True,
                    batch_size=100,
                    validation_data=(X[test], Y[test]), verbose=2)
    #model.summary()

答案 1 :(得分:0)

当我们使用这个陈述

时,问题就解决了
y = to_categorical(Y[:])