Kerasでの多クラス分類問題の処理方法

Kerasでの多クラス分類問題の取り扱いでは、通常softmax活性化関数とcategorical_crossentropy損失関数が使用されます。以下は簡単な多クラス分類問題の例です。

from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(64, activation='relu', input_shape=(100,)))
model.add(Dense(64, activation='relu'))
model.add(Dense(10, activation='softmax'))

model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

# 训练模型
model.fit(X_train, y_train, epochs=10, batch_size=32)

# 评估模型
loss, accuracy = model.evaluate(X_test, y_test)
print('Test accuracy:', accuracy)

この例では、2つの隠れ層を持つニューラルネットワークを使用し、最後の層は10クラスを持つsoftmax層です。モデルのトレーニングでは、categorical_crossentropy損失関数とadam最適化アルゴリズムを使用しました。最後に、モデルのテストデータでの正解率を評価しました。

多クラス分類問題を処理する際には、ラベルをワンホットエンコーディングする必要があります。つまり、各カテゴリをカテゴリ数の長さを持つベクトルに変換し、対応するカテゴリの位置に1を、他の位置に0を割り当てます。Kerasでは、to_categorical関数を使用して変換することができます。

from keras.utils import to_categorical

# 将标签进行one-hot编码
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
コメントを残す 0

Your email address will not be published. Required fields are marked *


广告
広告は10秒後に閉じます。
bannerAds