且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Keras 计算预测不确定性?

更新时间:2023-02-06 19:50:01

如果您想实施 dropout 方法来测量不确定性,您应该执行以下操作:

If you want to implement dropout approach to measure uncertainty you should do the following:

  1. 实现在测试期间也应用dropout的函数:

import keras.backend as K
f = K.function([model.layers[0].input, K.learning_phase()],
               [model.layers[-1].output])

  • 将此函数用作不确定性预测器,例如方式如下:

  • Use this function as uncertainty predictor e.g. in a following manner:

    def predict_with_uncertainty(f, x, n_iter=10):
        result = numpy.zeros((n_iter,) + x.shape)
    
        for iter in range(n_iter):
            result[iter] = f(x, 1)
    
        prediction = result.mean(axis=0)
        uncertainty = result.var(axis=0)
        return prediction, uncertainty
    

  • 当然,您可以使用任何不同的函数来计算不确定性.

    Of course you may use any different function to compute uncertainty.