我正在尝试使用Keras训练一个CNN模型来分类两类数据。我的数据集不平衡,我希望能够平衡数据。我不知道能否在model.fit_generator
中使用class_weight
。我想知道如果在model.fit_generator
中使用class_weight="balanced"
会怎么样
主要代码:
def generate_arrays_for_training(indexPat, paths, start=0, end=100): while True: from_=int(len(paths)/100*start) to_=int(len(paths)/100*end) for i in range(from_, int(to_)): f=paths[i] x = np.load(PathSpectogramFolder+f) x = np.expand_dims(x, axis=0) if('P' in f): y = np.repeat([[0,1]],x.shape[0], axis=0) else: y =np.repeat([[1,0]],x.shape[0], axis=0) yield(x,y) history=model.fit_generator(generate_arrays_for_training(indexPat, filesPath, end=75), validation_data=generate_arrays_for_training(indexPat, filesPath, start=75), steps_per_epoch=int((len(filesPath)-int(len(filesPath)/100*25))), validation_steps=int((len(filesPath)-int(len(filesPath)/100*75))), verbose=2, epochs=15, max_queue_size=2, shuffle=True, callbacks=[callback])
回答:
如果你不想改变数据生成过程,你可以在你的fit generator中使用class_weight
。你可以使用字典来设置你的class_weight
,并通过微调来观察效果。例如,当不使用class_weight
时,如果class0有50个样本,class1有100个样本,那么损失函数会均匀计算损失。这意味着class1会成为一个问题。但是,当你设置:
class_weight = {0:2 , 1:1}
这意味着损失函数现在会对class 0赋予两倍的权重。因此,对代表性不足的数据进行错误分类的惩罚将比以前增加两倍。这样,模型就可以处理不平衡的数据了。
如果你使用class_weight='balanced'
,模型可以自动进行这种设置。但我的建议是,创建一个像class_weight = {0:a1 , 1:a2}
这样的字典,并尝试不同的a1和a2值,这样你可以了解其中的差异。
此外,你也可以使用欠采样方法来处理不平衡数据,而不使用class_weight
。为此,请查看自助法方法。