【问题标题】:How to use Keras' multi layer perceptron for multi-class classification如何使用 Keras 的多层感知器进行多类分类
【发布时间】:2016-08-23 22:43:55
【问题描述】:

我尝试遵循指令here,其中指出 它使用Reuter dataset

from keras.datasets import reuters

(X_train, y_train), (X_test, y_test) = reuters.load_data(path="reuters.pkl",
                                                         nb_words=None,
                                                         skip_top=0,
                                                         maxlen=None,
                                                         test_split=0.1)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD

model = Sequential()
# Dense(64) is a fully-connected layer with 64 hidden units.
# in the first layer, you must specify the expected input data shape:
# here, 20-dimensional vectors.
model.add(Dense(64, input_dim=20, init='uniform'))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(64, init='uniform'))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(10, init='uniform'))
model.add(Activation('softmax'))

sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
              optimizer=sgd,
              metrics=['accuracy'])

#breaks here
model.fit(X_train, y_train,
          nb_epoch=20,
          batch_size=16)

score = model.evaluate(X_test, y_test, batch_size=16)

但代码在模型拟合时中断。我该如何解决这个问题?

更新:这是我得到的错误。

In [21]: model.fit(X_train, y_train,
   ....:           nb_epoch=20,
   ....:           batch_size=16)
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-21-4b227e56e5a9> in <module>()
      1 model.fit(X_train, y_train,
      2           nb_epoch=20,
----> 3           batch_size=16)

//anaconda/lib/python2.7/site-packages/keras/models.pyc in fit(self, x, y, batch_size, nb_epoch, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, **kwargs)
    400                               shuffle=shuffle,
    401                               class_weight=class_weight,
--> 402                               sample_weight=sample_weight)
    403
    404     def evaluate(self, x, y, batch_size=32, verbose=1,

//anaconda/lib/python2.7/site-packages/keras/engine/training.pyc in fit(self, x, y, batch_size, nb_epoch, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight)
    969                                                            class_weight=class_weight,
    970                                                            check_batch_dim=False,
--> 971                                                            batch_size=batch_size)
    972         # prepare validation data
    973         if validation_data:

//anaconda/lib/python2.7/site-packages/keras/engine/training.pyc in _standardize_user_data(self, x, y, sample_weight, class_weight, check_batch_dim, batch_size)
    909                           in zip(y, sample_weights, class_weights, self.sample_weight_modes)]
    910         check_array_lengths(x, y, sample_weights)
--> 911         check_loss_and_target_compatibility(y, self.loss_functions, self.internal_output_shapes)
    912         if self.stateful and batch_size:
    913             if x[0].shape[0] % batch_size != 0:

//anaconda/lib/python2.7/site-packages/keras/engine/training.pyc in check_loss_and_target_compatibility(targets, losses, output_shapes)
    182             if y.shape[1] == 1:
    183                 raise Exception('You are passing a target array of shape ' + str(y.shape) +
--> 184                                 ' while using as loss `categorical_crossentropy`. '
    185                                 '`categorical_crossentropy` expects '
    186                                 'targets to be binary matrices (1s and 0s) '

Exception: You are passing a target array of shape (10105, 1) while using as loss `categorical_crossentropy`. `categorical_crossentropy` expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:
```
from keras.utils.np_utils import to_categorical
y_binary = to_categorical(y_int)
```

Alternatively, you can use the loss function `sparse_categorical_crossentropy` instead, which does expect integer targets.

【问题讨论】:

    标签: python tensorflow machine-learning keras deep-learning


    【解决方案1】:

    答案与你的目标格式有关……你有两种可能:

    1.可能性:如果你有一维整数编码的目标,你可以使用sparse_categorical_crossentropy作为损失函数

    n_class = 3
    n_features = 100
    n_sample = 1000
    
    X = np.random.randint(0,10, (n_sample,n_features))
    y = np.random.randint(0,n_class, n_sample)
    
    inp = Input((n_features,))
    x = Dense(128, activation='relu')(inp)
    out = Dense(n_class, activation='softmax')(x)
    
    model = Model(inp, out)
    model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
    history = model.fit(X, y, epochs=3)
    

    2。可能性:如果您对目标进行一次热编码以获得 2D 形状(n_samples,n_class),则可以使用 categorical_crossentropy 作为损失

    n_class = 3
    n_features = 100
    n_sample = 1000
    
    X = np.random.randint(0,10, (n_sample,n_features))
    y = pd.get_dummies(np.random.randint(0,n_class, n_sample)).values
    
    inp = Input((n_features,))
    x = Dense(128, activation='relu')(inp)
    out = Dense(n_class, activation='softmax')(x)
    
    model = Model(inp, out)
    model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
    history = model.fit(X, y, epochs=3)
    

    【讨论】:

      【解决方案2】:

      这是 Keras 初学者很常见的错误。与其他深度学习框架不同,Keras 不使用整数标签来进行通常的交叉熵损失,而是需要一个二进制向量(称为“one-hot”),其中向量只是 0 和正确类索引的 1。

      您可以使用以下代码轻松地将标签转换为这种格式:

      from keras.utils.np_utils import to_categorical
      y_train = to_categorical(y_train)
      y_test = to_categorical(y_test)
      

      model.fit 之前。另一种方法是将损失更改为“sparse_categorical_crossentropy”,它确实需要整数标签。

      【讨论】:

      • 谢谢。但我仍然收到相同的错误消息。这是我的full code 合并您的评论。
      猜你喜欢
      • 2013-12-11
      • 2021-07-31
      • 2021-12-25
      • 2021-07-25
      • 2021-02-17
      • 2018-03-27
      • 2020-06-26
      • 2017-09-27
      • 1970-01-01
      相关资源
      最近更新 更多