使用Keras的数据集不平衡

hyC*_*ook 4 python machine-learning neural-network keras

我正在使用python和Keras库构建分类ANN。我正在使用3种不同类别的不平衡数据集训练NN。第1类大约是第2类和第3类的7.5倍。作为补救措施,我采纳了这个stackoverflow答案的建议,并按如下方式设置我的类权重:

class_weight = {0 : 1,
                1 : 6.5,
                2: 7.5}
Run Code Online (Sandbox Code Playgroud)

但是,这就是问题所在:人工神经网络正在以相同的速度预测3个班级!

因为数据集,这是没有用不平衡,并预测为各自具有33%的几率是不准确的结果。

问题是:如何处理不平衡的数据集,以使ANN不会每次都预测1类,而且还使得ANN不会以相同的概率预测这些类?

这是我正在使用的代码:

class_weight = {0 : 1,
1 : 6.5,
2: 7.5}

# Making the ANN
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout

classifier = Sequential()


# Adding the input layer and the first hidden layer with dropout
classifier.add(Dense(activation = 'relu',
                     input_dim = 5,
                     units = 3,
                     kernel_initializer = 'uniform'))
#Randomly drops 0.1, 10% of the neurons in the layer.
classifier.add(Dropout(rate= 0.1))

#Adding the second hidden layer
classifier.add(Dense(activation = 'relu',
                     units = 3,
                     kernel_initializer = 'uniform'))
#Randomly drops 0.1, 10% of the neurons in the layer.
classifier.add(Dropout(rate = 0.1)) 

# Adding the output layer
classifier.add(Dense(activation = 'sigmoid',
                     units = 2,
                     kernel_initializer = 'uniform'))

# Compiling the ANN
classifier.compile(optimizer = 'adam',
                   loss = 'binary_crossentropy',
                   metrics = ['accuracy'])

# Fitting the ANN to the training set
classifier.fit(X_train, y_train, batch_size = 100, epochs = 100, class_weight = class_weight)
Run Code Online (Sandbox Code Playgroud)

Dan*_*ola 5

我在您的模型中看到的最明显的问题是,它的结构不适合分类。如果您的样本一次只能属于一个类别,那么您不应将S型激活作为最后一层来忽略这一事实。

理想情况下,分类器的最后一层应输出样本属于某个类的概率,即(在您的情况下)一个数组[a, b, c]where a + b + c == 1.

如果使用S形输出,则[1, 1, 1]可能不是一个输出,尽管不是您想要的。这也是模型无法正确概括的原因:鉴于您没有专门训练模型以偏爱“不平衡”的输出(例如[1, 0, 0]),因此它将无法预测训练期间看到的平均值,并考虑了重新加权。

尝试将最后一层的激活更改为'softmax',将丢失的更改为'catergorical_crossentropy'

# Adding the output layer
classifier.add(Dense(activation='softmax',
                     units=2,
                     kernel_initializer='uniform'))

# Compiling the ANN
classifier.compile(optimizer='adam',
                   loss='categorical_crossentropy',
                   metrics=['accuracy'])
Run Code Online (Sandbox Code Playgroud)

如果这不起作用,请参阅我的其他评论,并使用该信息与我联系,但我非常有信心这是主要问题。
干杯