首页 > 解决方案 > Class weights for multi-output classification

问题描述

I have a problem where i created a model like this :

from keras.models import Sequential, Model
from keras.layers import Dense,  Dropout, Flatten
from keras.layers import LSTM, Conv1D, Input, MaxPooling1D, GlobalMaxPooling1D
from keras.layers.embeddings import Embedding

posts_input = Input(shape=(None,), dtype='int32', name='posts')
embedded_posts = Embedding(max_nb_words, embedding_vector_length, input_length=max_post_len)(posts_input)

x = Conv1D(128, 5, activation='relu')(embedded_posts)
x = Dropout(0.25)(x)
x = MaxPooling1D(5)(x)
x = Conv1D(256, 5, activation='relu')(x)
x = Conv1D(256, 5, activation='relu')(x)
x = Dropout(0.25)(x)
x = MaxPooling1D(5)(x)
x = Conv1D(256, 5, activation='relu')(x)
x = Conv1D(256, 5, activation='relu')(x)
x = Dropout(0.25)(x)
x = GlobalMaxPooling1D()(x)
x = Dense(128, activation='relu')(x)

Axe1_prediction = Dense(1, activation='sigmoid', name='axe1')(x)
Axe2_prediction = Dense(1, activation='sigmoid', name='axe2')(x)
Axe3_prediction = Dense(1, activation='sigmoid', name='axe3')(x)
Axe4_prediction = Dense(1, activation='sigmoid', name='axe4')(x)

model = Model(posts_input, [Axe1_prediction, Axe2_prediction, Axe3_prediction, Axe4_prediction])

as you can see, this model has 4 outputs.

Then i compile this model like this :

model.compile(optimizer='rmsprop', 
              loss=['binary_crossentropy', 
                    'binary_crossentropy', 
                    'binary_crossentropy', 
                    'binary_crossentropy'],
              metrics=['accuracy'])

For fitting this model, i think i need to set the class weights, so i create these :

from sklearn.preprocessing import LabelEncoder
from sklearn.utils import class_weight

le = LabelEncoder()
y1 = le.fit_transform(df2["Axe1"])
y2 = le.fit_transform(df2["Axe2"])
y3 = le.fit_transform(df2["Axe3"])
y4 = le.fit_transform(df2["Axe4"])

cw1 = class_weight.compute_class_weight('balanced', np.unique(y1), y1)
cw2 = class_weight.compute_class_weight('balanced', np.unique(y2), y2)
cw3 = class_weight.compute_class_weight('balanced', np.unique(y3), y3)
cw4 = class_weight.compute_class_weight('balanced', np.unique(y4), y4)

But finally i don't know how to set this parameters in the fitting :

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]));

Could you help me by showing how i can add the "class_weights =" parameter ?

标签: pythonmachine-learningkerasscikit-learn

解决方案


您必须使用 tensorflow 2.1 或更早版本。在 TF2.1 之后,多输出模型的类权重功能已被删除


推荐阅读