【问题标题】:Multiclass Dataset Imbalance多类数据集不平衡
【发布时间】:2020-02-05 19:49:27
【问题描述】:
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf

train_path = 'Skin/Train'
test_path = 'Skin/Test'

train_gen = ImageDataGenerator(rescale=1./255)
train_generator = train_gen.flow_from_directory(train_path,target_size= 
                                         (300,300),batch_size=30,class_mode='categorical')

model = tf.keras.models.Sequential([
# Note the input shape is the desired size of the image 300x300 with 3 bytes color
# This is the first convolution
tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(600, 450, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
# The second convolution
tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
# The third convolution
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
# The fourth convolution
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
# The fifth convolution
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
# Flatten the results to feed into a DNN
tf.keras.layers.Flatten(),
# 512 neuron hidden layer
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(9, activation='softmax')
])

from tensorflow.keras.optimizers import RMSprop

model.compile(loss='categorical_crossentropy',
          optimizer=RMSprop(lr=0.001),
          metrics=['acc'])

history = model.fit_generator(
  train_generator,
  steps_per_epoch=8,  
  epochs=15,
  verbose=2, class_weight = ? )

我在实现准确性方面存在问题,我正在训练一个 9 类数据集,其中 1、4 和 5 类只有 100、96、90 张图像,而其余类的图像超过 500 张。由于权重偏向数量较多的图像,因此我无法获得更高的准确度。我希望在训练期间所有类都被认为是相等的,即 500。如果我可以通过 tensorflow 或任何 keras 函数代码对类进行上采样,将不胜感激。而不是手动对文件夹中的图像进行上采样或下采样。

【问题讨论】:

    标签: keras tensorflow2.0 tensorflow-datasets


    【解决方案1】:

    您可以改为在 fit 方法中使用 class_weight 参数。 对于上采样,您需要大量手动工作,这是不可避免的。

    假设您有一个形状为(anything, 9) 的输出,并且您知道每个类的总数:

    totals = np.array([500,100,500,500,96,90,.......])
    totalMean = totals.mean()
    weights = {i: totalMean / count for i, count in enumerate(totals)}
    
    model.fit(....., class_weight = weights)
    

    【讨论】:

    • 在第 3 行将关闭 ] 更改为 }
    猜你喜欢
    • 2015-01-28
    • 1970-01-01
    • 2019-06-17
    • 2017-11-01
    • 2023-04-03
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2019-11-05
    相关资源
    最近更新 更多