1 回答
TA贡献1783条经验 获得超4个赞
对于与 sklearn 一起使用GridSearchCV的多类标签,标签不应进行单热编码。它们应该是包含两个以上离散值的一维或列向量。检查文档以获取表示。
所以我们必须将单热编码目标转换为一维,而这又需要我们将损失函数更改为sparse_categorical_crossentropy
示例代码:
X = np.random.randn(1000, 2048)
y = np.array([i for i in range(100)]*10) # <- 1D array with target labels
def myModel():
model = keras.models.Sequential()
model.add(keras.layers.Dense(100, input_dim=2048, activation='softmax'))
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
model = KerasClassifier(build_fn=myModel)
parameters = { 'epochs': [10, 20, 30],
'batch_size':[1, 2, 3, 4, 5, 6, 7,8] }
grid_search = GridSearchCV(estimator=model,
param_grid=parameters,
scoring='accuracy',
cv=2)
grid_search = grid_search.fit(X, y)
print (grid_search.best_params_)
输出:
Epoch 1/10
500/500 [==============================] - 2s 3ms/step - loss: 5.6664 - accuracy: 0.0100
Epoch 2/10
500/500 [==============================] - 1s 3ms/step - loss: 0.0066 - accuracy: 1.0000
Epoch 3/10
500/500 [==============================] - 1s 3ms/step - loss: 9.9609e-04 - accuracy: 1.0000
------ output truncated ------
{'batch_size': 3, 'epochs': 20}
添加回答
举报