【发布时间】:2020-01-10 03:19:26
【问题描述】:
我试图让 Keras 处理一个分类问题,该问题有五个分类目标标签(1、2、3、4、5)。由于某种原因,我在使用 StratifiedKFold 时无法使其正常工作。 X 和 y 分别是形状为 (500, 20) 和 (500, ) 的 NumPy 数组。
错误消息是“ValueError: Error when checks target: expected dense_35 to have shape (1,) but got array with shape (5,)”,这让我认为错误肯定出在目标变量。同样值得注意的是,每次尝试运行代码时,“dense_35”中的数字似乎都不同。
random_state = 123
n_splits = 10
cv = StratifiedKFold(n_splits=n_splits,
random_state=random_state, shuffle=False)
def baseline_model():
nn_model = Sequential()
nn_model.add(Dense(units=50, input_dim=X.shape[1], init='normal',
activation= 'relu' ))
nn_model.add(Dense(30, init='normal', activation='relu'))
nn_model.add(Dense(10, init='normal', activation='relu'))
nn_model.add(Dense(1, init='normal', activation='softmax'))
nn_model.compile(optimizer='adam', loss='categorical_crossentropy',
metrics = ['accuracy'])
return nn_model
for train, test in cv.split(X, y):
X_train, X_test = X[train], X[test]
y_train, y_test = y[train], y[test]
np_utils.to_categorical(y_train)
np_utils.to_categorical(y_test)
estimator = KerasClassifier(build_fn=baseline_model,
epochs=200, batch_size=5,
verbose=0)
estimator.fit(X_train, y_train)
y_pred = estimator.predict(X_test)
The numpy array (y), that I am trying to split:
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2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