Keras输出概率而不是类

时间:2018-12-19 10:51:05

标签: python machine-learning keras neural-network classification

我正在尝试为Keras中的多类分类实现一个简单的神经网络。代码是:

model = Sequential()
model.add(Dense(512, input_dim = 55 , kernel_regularizer=l2(0.00001), 
activation = 'relu'))
model.add(Dense(8, activation = 'softmax'))

model.compile(loss = 'categorical_crossentropy' , optimizer = 'adam' , metrics = ['accuracy'] )

model.fit(X_train, dummy_y, epochs = 20, batch_size = 30, class_weight=class_weights)

我有55个特征,我想预测8个类别之一(0、1、2、3、4、5、6、7)。我也像这样编码y_train

encoder = LabelEncoder()
encoder.fit(y_train)
encoded_Y = encoder.transform(y_train)
# convert integers to dummy variables (i.e. one hot encoded)
dummy_y = np_utils.to_categorical(encoded_Y)

但是,当我使用predict()时,输出是每个类别的概率的数组:

array([[3.3881092e-01, 2.6201099e-06, 1.9504215e-03, ..., 7.0641324e-02,
    4.4026113e-01, 1.2641836e-02],
   [2.3457911e-02, 5.5409328e-04, 2.8759112e-05, ..., 2.1585675e-03,
    5.5625242e-01, 1.0208529e-01],
   [4.6981460e-01, 2.0882198e-05, 1.4895502e-01, ..., 1.3179567e-01,
    2.2908358e-01, 1.4160757e-03],
   ...

我应该如何修改网络才能以最高的概率输出课程?像这样:

[[0,5,7,3,2,0,0,.....]]

1 个答案:

答案 0 :(得分:0)

您可以简单地使用public class MainActivity extends AppCompatActivity { TextView helloText; RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); helloText = findViewById(R.id.hello_world_salute); recyclerView = findViewById(R.id.stock_updates_recycler_view); } 方法:

predict_classes

您看到的作为preds_classes = model.predict_classes(X_test) 方法输出的那些数字是每个类别的概率或置信度得分。因此,作为替代解决方案,您可以获取最大分数的索引,该索引对应于预测的类别:

predict