【发布时间】:2021-05-22 14:56:01
【问题描述】:
我在创建这样的模型时遇到了问题:
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])
如您所见,此模型有 4 个输出。
然后我像这样编译这个模型:
model.compile(optimizer='rmsprop',
loss=['binary_crossentropy',
'binary_crossentropy',
'binary_crossentropy',
'binary_crossentropy'],
metrics=['accuracy'])
为了拟合这个模型,我想我需要设置类权重,所以我创建了这些:
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)
但最后我不知道如何在配件中设置此参数:
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_weights =”参数吗?
【问题讨论】:
-
而不是模型中的多个输出,我相信您可以使用具有 4 个输出的密集层,并对其应用 sigmoid 激活。然后像往常一样使用二元交叉熵。
-
是的,我知道,但使用这种模型的想法是项目的限制
标签: python machine-learning keras scikit-learn