Keras多输出二分类模型class_weight参数设置方法咨询
Great question! When working with multi-output Keras models and dealing with class imbalance, you have two straightforward ways to pass class weights—using a dictionary mapped to your output layer names (the most readable and error-resistant option) or a list matching the order of your model outputs. Let's walk through how to implement this for your specific setup:
Step 1: Convert computed class weights to Keras-compatible format
The class_weight.compute_class_weight function returns an array of weights ordered by class labels. Since you're using binary classification (with sigmoid activation), we need to convert these arrays into {class_label: weight} dictionaries that Keras expects:
# Convert each class weight array to a dictionary for binary classification class_weight_axe1 = {0: cw1[0], 1: cw1[1]} class_weight_axe2 = {0: cw2[0], 1: cw2[1]} class_weight_axe3 = {0: cw3[0], 1: cw3[1]} class_weight_axe4 = {0: cw4[0], 1: cw4[1]}
Step 2: Create a combined class weight mapping
Use a dictionary to map each output layer's name (the name parameter you set in Dense(..., name='axe1')) to its corresponding class weight dictionary. This ensures weights are applied to the correct output, even if you reorder outputs later:
total_class_weights = { 'axe1': class_weight_axe1, 'axe2': class_weight_axe2, 'axe3': class_weight_axe3, 'axe4': class_weight_axe4 }
Step 3: Add the class weights to your training call
Pass the total_class_weights dictionary to the class_weight parameter in model.fit():
history = model.fit( X_train, [y1_train, y2_train, y3_train, y4_train], epochs=10, validation_data=(X_val, [y1_val, y2_val, y3_val, y4_val]), class_weight=total_class_weights # Add this parameter )
Alternative: List-based approach (for order-matching fans)
If you prefer, you can pass a list where the order of weight dictionaries exactly matches the order of your model's outputs (Axe1_prediction, Axe2_prediction, etc.):
total_class_weights_list = [class_weight_axe1, class_weight_axe2, class_weight_axe3, class_weight_axe4] history = model.fit( X_train, [y1_train, y2_train, y3_train, y4_train], epochs=10, validation_data=(X_val, [y1_val, y2_val, y3_val, y4_val]), class_weight=total_class_weights_list )
The dictionary method is generally recommended because it avoids bugs if you ever reorder or modify your model's output layers later.
内容的提问来源于stack exchange,提问作者user14884311

