Skip to main content
 首页 » 编程设计

python之Keras 多类分类概率总和不为 1

2025年05月04日22jackei

当使用以下 Keras 网络对 9 个类进行训练和分类时:

from keras.models import Model 
from keras.layers import Convolution1D, Input, Dropout, GlobalMaxPooling1D, Dense, merge 
 
input_window3 = Input(shape=(MEANLEN, W2VLEN)) 
input_window4 = Input(shape=(MEANLEN, W2VLEN)) 
 
conv_w3 = Convolution1D(MEANLEN*2, 3, activation='tanh', border_mode='valid')(input_window3) 
drop_w3 = Dropout(0.7)(conv_w3), 
pool_w3 = GlobalMaxPooling1D(name='pool_w3')(drop_w3[0]) 
 
conv_w4 = Convolution1D(MEANLEN, 5, activation='tanh', border_mode='valid')(input_window4) 
 
drop_w4 = Dropout(0.7)(conv_w4), 
pool_w4 = GlobalMaxPooling1D(name='pool_w4')(drop_w4[0]) 
print(conv_w4.shape) 
 
x = merge([pool_w3, pool_w4], mode='concat', concat_axis=1) 
print(x.shape) 
x = Dense(MEANLEN*3, activation='relu')(x) 
drop_dense = Dropout(0.5)(x) 
main_output = Dense(num_categories, activation='sigmoid', name='main_output')(drop_dense) 
model = Model(input=[input_window3, input_window4], output=[main_output]) 
model.compile(optimizer='adam', loss='mse', metrics=['accuracy', f1_score]) 

预测:

result = model.predict([X_test, X_test]) 

返回与这些类似的向量数组:

array([[ 0.08401331,  0.1911521 ,  0.14310306,  0.07138534,  0.19428432, 
         0.15808958,  0.16400988,  0.27708355,  0.09983496], 
       [ 0.02074078,  0.08897329,  0.03244834,  0.00112842,  0.04122255, 
         0.03494435,  0.17535761,  0.55671334,  0.04375785], 
       [ 0.04897207,  0.06169643,  0.00313113,  0.002085  ,  0.00275023, 
         0.00131959,  0.09961601,  0.56414878,  0.02338091]], dtype=float32) 

我假设为类概率的数组中的值总和不为 1。如何获取类概率?

请您参考如下方法:

根据您发布的数组,您有 9 个类别。在这种情况下,您应该将最终激活函数替换为 softmax而不是乙状结肠。此外,如果您还没有这样做,您需要将您的标签转换为 one-hot vector。您可以使用函数 to_categorical 来做到这一点.最后,作为损失函数,你应该使用 categorical_crossentropy loss,而不是mse。提供了使用keras进行分类的教程(使用上面提到的函数)here .