Search
 
SCRIPT & CODE EXAMPLE
 

C

mc dropout pytorch

import sys

import numpy as np

import torch
import torch.nn as nn


def enable_dropout(model):
    """ Function to enable the dropout layers during test-time """
    for m in model.modules():
        if m.__class__.__name__.startswith('Dropout'):
            m.train()

def get_monte_carlo_predictions(data_loader,
                                forward_passes,
                                model,
                                n_classes,
                                n_samples):
    """ Function to get the monte-carlo samples and uncertainty estimates
    through multiple forward passes

    Parameters
    ----------
    data_loader : object
        data loader object from the data loader module
    forward_passes : int
        number of monte-carlo samples/forward passes
    model : object
        keras model
    n_classes : int
        number of classes in the dataset
    n_samples : int
        number of samples in the test set
    """

    dropout_predictions = np.empty((0, n_samples, n_classes))
    softmax = nn.Softmax(dim=1)
    for i in range(forward_passes):
        predictions = np.empty((0, n_classes))
        model.eval()
        enable_dropout(model)
        for i, (image, label) in enumerate(data_loader):

            image = image.to(torch.device('cuda'))
            with torch.no_grad():
                output = model(image)
                output = softmax(output) # shape (n_samples, n_classes)
            predictions = np.vstack((predictions, output.cpu().numpy()))

        dropout_predictions = np.vstack((dropout_predictions,
                                         predictions[np.newaxis, :, :]))
        # dropout predictions - shape (forward_passes, n_samples, n_classes)
    
    # Calculating mean across multiple MCD forward passes 
    mean = np.mean(dropout_predictions, axis=0) # shape (n_samples, n_classes)

    # Calculating variance across multiple MCD forward passes 
    variance = np.var(dropout_predictions, axis=0) # shape (n_samples, n_classes)

    epsilon = sys.float_info.min
    # Calculating entropy across multiple MCD forward passes 
    entropy = -np.sum(mean*np.log(mean + epsilon), axis=-1) # shape (n_samples,)

    # Calculating mutual information across multiple MCD forward passes 
    mutual_info = entropy - np.mean(np.sum(-dropout_predictions*np.log(dropout_predictions + epsilon),
                                            axis=-1), axis=0) # shape (n_samples,)
Comment

PREVIOUS NEXT
Code Example
C :: what is the last character of a string in c 
C :: pointer in c 
C :: size of float in c 
C :: c functions 
C :: iterating through a linked list 
C :: *= in c 
C :: ecto where is not nil 
C :: two way communication between child and parent processes in C using pipes 
C :: allintext:christie kiser filetype:log 
C :: 4 byte alignment c code 
C :: Here is a program in C that illustrates the use of fprintf() to write a text file: 
C :: como somar em C 
C :: How to include multiline conditional inside template literal 
C :: onvert a string into 2d string in c 
C :: Battlefield4u.com 
C :: ejemplo c holamundo 
C :: VLOOKUP CHECK #N/A 
C :: synopsis of fork() 
C :: convert char to int ascii in c function 
C :: denomination counter 
C :: timespec c 
C :: reverse string in c 
C :: using tables as arguments in c++/c 
C :: print number in c 
C :: gotoxy not working in dev c++ 
C :: Sampoo C programming 
C :: how to get value of multidimensional array in c 
C :: jframe mittig positionieren 
Dart :: flutter generate random color 
Dart :: sleep in dart 
ADD CONTENT
Topic
Content
Source link
Name
3+5 =