【问题标题】:GridSearch for MultiClass KerasClassifier多类 KerasClassifier 的 GridSearch
【发布时间】:2018-03-29 17:37:46
【问题描述】:

我正在尝试使用 Keras 对多类分类进行网格搜索。下面是一段代码:

数据的一些属性如下:

y_
array(['fast', 'immobile', 'immobile', ..., 'slow',
       'immobile', 'slow'],
      dtype='<U17')

y_onehot = pd.get_dummies(y_).values

y_onehot
array([[1, 0, 0],
       [0, 0, 1],
       [0, 0, 1],
    ...
       [0, 1, 0],
       [0, 0, 1],
       [0, 1, 0]], dtype=uint8)

#Do train-test split

y_train.shape
(1904,)

y_train_onehot.shape
(1904, 3)

还有模特……

# Function to create model, required for KerasClassifier
def create_model(optimizer='rmsprop', init='glorot_uniform'):
    # create model
    model = Sequential()
    model.add(Dense(2048, input_dim=X_train.shape[1], kernel_initializer=init, activation='relu'))
    model.add(Dense(512, kernel_initializer=init, activation='relu'))
    model.add(Dense(y_train_onehot.shape[1], kernel_initializer=init, activation='softmax'))
    # Compile model
    model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
    return model

# create model
model = KerasClassifier(build_fn=create_model, verbose=0)

# grid search epochs, batch size and optimizer
optimizers = ['rmsprop', 'adam']
init = ['glorot_uniform', 'normal', 'uniform']
epochs = [50, 100, 150]
batches = [5, 10, 20]

param_grid = dict(optimizer=optimizers, epochs=epochs, batch_size=batches, init=init)
grid = GridSearchCV(estimator=model, param_grid=param_grid, scoring='accuracy')
grid_result = grid.fit(X_train, y_train_onehot)

这是错误:

--> grid_result = grid.fit(X_train, y_train_onehot)
ValueError: Classification metrics can't handle a mix of multilabel-indicator and multiclass targets

代码用于二进制模型,但我希望针对多类数据集对其进行修改。请协助。谢谢!

【问题讨论】:

  • 您能否展示一些您的y_train_onehot 和原始y 的样本?以及将原始 y 转换为 y_onehot 的代码。
  • @VivekKumar,我已经按照你的建议添加了内容。
  • 看起来像一个简单的多类问题。请不要对y_ 进行一次性编码。直接在fit()中使用:grid.fit(X_train, y_train)

标签: keras grid-search hyperparameters multiclass-classification


【解决方案1】:

错误在softmax层。

我认为您的意思是 y_train_onehot.shape[1] 而不是 y_train_onehot[1]

更新 1:这很奇怪,但您的第二个问题似乎是 y_train_onehot,您介意尝试 2 件事吗:

  1. 在 y_train 上尝试不使用 onehot 编码的相同模型。
  2. 如果仅此一项不起作用,请将 loss 更改为 sparse_categorical_crossentropy

还要确保将y_train_onehot.shape[1] 更改为softmax 层中的类数

【讨论】:

  • 我遇到了类似的问题,你能更明确地说明你的尝试吗?恢复为非热编码似乎会产生各种其他也不起作用的问题(例如必须将最后一个 softmax 设置为层到维度 1 等)。谢谢!
猜你喜欢
  • 2018-07-20
  • 2012-12-22
  • 2014-11-19
  • 2019-05-23
  • 1970-01-01
  • 2018-10-20
  • 2021-09-07
  • 2019-06-06
  • 2017-09-17
相关资源
最近更新 更多