<gh_stars>1-10
# AUTOGENERATED! DO NOT EDIT! File to edit: 01_nn_utils.ipynb (unless otherwise specified).

__all__ = ['mean_from_cluster', 'fig2img', 'c_imshow', 'Flatten', 'conv3x3', 'get_proto_accuracy', 'get_accuracy']

# Cell
# export

import io

import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
from PIL import Image


def mean_from_cluster(z, labels):
    predicted_labels = labels.unsqueeze(1).long().clone()
    predicted_labels = predicted_labels.view(predicted_labels.size(0), 1).expand(-1, z.size(1))
    unique_labels, labels_count = predicted_labels.cpu().unique(dim=0, return_counts=True)
    unique_labels, labels_count = unique_labels.type_as(predicted_labels), labels_count.type_as(predicted_labels)
    res = torch.zeros_like(unique_labels, dtype=torch.float).scatter_add_(0, predicted_labels.long(), z)
    res = res / labels_count.float().unsqueeze(1)
    res = res.detach()
    return res


def fig2img(fig):
    """
    Convert a Matplotlib figure to a PIL Image and return it
    Returns Image as RGBA
    """
    buf = io.BytesIO()
    fig.savefig(buf)
    buf.seek(0)
    img = Image.open(buf)
    return img


# Cell
def c_imshow(img):
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()


# Cell

class Flatten(nn.Module):
    def __init__(self):
        super(Flatten, self).__init__()

    def forward(self, x):
        return x.view(x.shape[0], -1)


# Cell

def conv3x3(in_channels, out_channels, return_indices=False, **kwargs):
    return nn.Sequential(
        nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, **kwargs),
        nn.BatchNorm2d(out_channels),
        nn.ReLU(),
        nn.MaxPool2d(2) if return_indices == False else nn.MaxPool2d(2, return_indices=True)
    )


# Cell

def get_proto_accuracy(prototypes, embeddings, targets):
    """Compute the accuracy of the prototypical network on the test/query points.
    Parameters
    ----------
    prototypes : `torch.FloatTensor` instance
        A tensor containing the prototypes for each class. This tensor has shape
        `(meta_batch_size, num_classes, embedding_size)`.
    embeddings : `torch.FloatTensor` instance
        A tensor containing the embeddings of the query points. This tensor has
        shape `(meta_batch_size, num_examples, embedding_size)`.
    targets : `torch.LongTensor` instance
        A tensor containing the targets of the query points. This tensor has
        shape `(meta_batch_size, num_examples)`.
    Returns
    -------
    accuracy : `torch.FloatTensor` instance
        Mean accuracy on the query points.
    """
    sq_distances = torch.sum((prototypes.unsqueeze(1)
                              - embeddings.unsqueeze(2)) ** 2, dim=-1)
    _, predictions = torch.min(sq_distances, dim=-1)
    return torch.mean(predictions.eq(targets).float())


# Cell
def get_accuracy(logits, targets):
    """Compute the accuracy (after adaptation) of MAML on the test/query points
    Parameters
    ----------
    logits : `torch.FloatTensor` instance
        Outputs/logits of the model on the query points. This tensor has shape
        `(num_examples, num_classes)`.
    targets : `torch.LongTensor` instance
        A tensor containing the targets of the query points. This tensor has
        shape `(num_examples,)`.
    Returns
    -------
    accuracy : `torch.FloatTensor` instance
        Mean accuracy on the query points
    """
    _, predictions = torch.max(logits, dim=-1)
    return torch.mean(predictions.eq(targets).float())

# AUTOGENERATED! DO NOT EDIT! File to edit: 01_nn_utils.ipynb (unless otherwise specified).

__all__ = ['mean_from_cluster', 'fig2img', 'c_imshow', 'Flatten', 'conv3x3', 'get_proto_accuracy', 'get_accuracy']

# Cell
# export

import io

import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
from PIL import Image


def mean_from_cluster(z, labels):
    predicted_labels = labels.unsqueeze(1).long().clone()
    predicted_labels = predicted_labels.view(predicted_labels.size(0), 1).expand(-1, z.size(1))
    unique_labels, labels_count = predicted_labels.cpu().unique(dim=0, return_counts=True)
    unique_labels, labels_count = unique_labels.type_as(predicted_labels), labels_count.type_as(predicted_labels)
    res = torch.zeros_like(unique_labels, dtype=torch.float).scatter_add_(0, predicted_labels.long(), z)
    res = res / labels_count.float().unsqueeze(1)
    res = res.detach()
    return res


def fig2img(fig):
    """
    Convert a Matplotlib figure to a PIL Image and return it
    Returns Image as RGBA
    """
    buf = io.BytesIO()
    fig.savefig(buf)
    buf.seek(0)
    img = Image.open(buf)
    return img


# Cell
def c_imshow(img):
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()


# Cell

class Flatten(nn.Module):
    def __init__(self):
        super(Flatten, self).__init__()

    def forward(self, x):
        return x.view(x.shape[0], -1)


# Cell

def conv3x3(in_channels, out_channels, return_indices=False, **kwargs):
    return nn.Sequential(
        nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, **kwargs),
        nn.BatchNorm2d(out_channels),
        nn.ReLU(),
        nn.MaxPool2d(2) if return_indices == False else nn.MaxPool2d(2, return_indices=True)
    )


# Cell

def get_proto_accuracy(prototypes, embeddings, targets):
    """Compute the accuracy of the prototypical network on the test/query points.
    Parameters
    ----------
    prototypes : `torch.FloatTensor` instance
        A tensor containing the prototypes for each class. This tensor has shape
        `(meta_batch_size, num_classes, embedding_size)`.
    embeddings : `torch.FloatTensor` instance
        A tensor containing the embeddings of the query points. This tensor has
        shape `(meta_batch_size, num_examples, embedding_size)`.
    targets : `torch.LongTensor` instance
        A tensor containing the targets of the query points. This tensor has
        shape `(meta_batch_size, num_examples)`.
    Returns
    -------
    accuracy : `torch.FloatTensor` instance
        Mean accuracy on the query points.
    """
    sq_distances = torch.sum((prototypes.unsqueeze(1)
                              - embeddings.unsqueeze(2)) ** 2, dim=-1)
    _, predictions = torch.min(sq_distances, dim=-1)
    return torch.mean(predictions.eq(targets).float())


# Cell
def get_accuracy(logits, targets):
    """Compute the accuracy (after adaptation) of MAML on the test/query points
    Parameters
    ----------
    logits : `torch.FloatTensor` instance
        Outputs/logits of the model on the query points. This tensor has shape
        `(num_examples, num_classes)`.
    targets : `torch.LongTensor` instance
        A tensor containing the targets of the query points. This tensor has
        shape `(num_examples,)`.
    Returns
    -------
    accuracy : `torch.FloatTensor` instance
        Mean accuracy on the query points
    """
    _, predictions = torch.max(logits, dim=-1)
    return torch.mean(predictions.eq(targets).float())
# AUTOGENERATED! DO NOT EDIT! File to edit: 01_nn_utils.ipynb (unless otherwise specified). # Cell # export Convert a Matplotlib figure to a PIL Image and return it     Returns Image as RGBA # Cell # Cell # Cell # Cell Compute the accuracy of the prototypical network on the test/query points.     Parameters     ----------     prototypes : `torch.FloatTensor` instance         A tensor containing the prototypes for each class. This tensor has shape         `(meta_batch_size, num_classes, embedding_size)`.     embeddings : `torch.FloatTensor` instance         A tensor containing the embeddings of the query points. This tensor has         shape `(meta_batch_size, num_examples, embedding_size)`.     targets : `torch.LongTensor` instance         A tensor containing the targets of the query points. This tensor has         shape `(meta_batch_size, num_examples)`.     Returns     -------     accuracy : `torch.FloatTensor` instance         Mean accuracy on the query points. # Cell Compute the accuracy (after adaptation) of MAML on the test/query points     Parameters     ----------     logits : `torch.FloatTensor` instance         Outputs/logits of the model on the query points. This tensor has shape         `(num_examples, num_classes)`.     targets : `torch.LongTensor` instance         A tensor containing the targets of the query points. This tensor has         shape `(num_examples,)`.     Returns     -------     accuracy : `torch.FloatTensor` instance         Mean accuracy on the query points