Redes Neuronales Utilidades#

En esta carpeta se encuentran una serie de utilidades necesarias para los cuadernos sobre Redes Neuronales (RNN)

Utilidad que dibuja las curvas de nivel que determina el valor y en la region X#

Hide code cell content
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt

def plot_decision_regions(X, y, classifier, test_idx=None,
    resolution=0.02):
    # Se define el generador de marcadores y el mapa de colores
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    #cmap = ListedColormap(colors[:len(np.unique(y))])
    cmap = ListedColormap(colors)
    # Se imprime la superficie de decisión
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
    np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    # contourf describe las curvas de nivel de una función sobre la malla
    plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())
    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],
            alpha=0.8, c=colors[idx],
            marker=markers[idx], label=cl,
            facecolor='black')
    # highlight test samples
    if test_idx:
        # plot all samples
        X_test, y_test = X[test_idx, :], y[test_idx]
        plt.scatter(X_test[:, 0], X_test[:, 1],
            c='', facecolor='black', alpha=1.0,
            linewidth=1, marker='o',
            s=100, label='test set')

Las funciones contour y contourf#

La función contour(X, Y, Z) tiene los siguientes parámetros de entrada

  • X : Matriz 2D con los valores X de los puntos de una malla creada con numpy.meshgrid()

  • Y : Matriz 2D con los valores Y de los puntos de una malla creada con numpy.meshgrid()

  • Z : Matriz 2D con el valor de la función

Contour dibuja la curva de nivel. Contourf dibuja la curva de nivel rellenada con color

Se dibujan las curvas de nivel del paraboloide elíptico \(y=x^2+y^2\) y del paraboloide hiperbólico \(y=x^2-y^2\)

## Curvas de nivel de la función 
import matplotlib.pyplot as plt
import numpy as np
A=np.array([-3,-2,-1,0,1,2,3])
B=A
A,B=np.meshgrid(A,B)
fig = plt.figure()
#plt.contour(A,B,A**2+B**2)  # Paraboloide elíptico. Curvas de nivel estándar
#plt.contour(A,B,A**2-B**2)  # Paraboloide hiperbólico. Curvas de nivel estándar
#plt.contourf(A,B,A**2+B**2)  # Paraboloide elíptico. Curvas de nivel con contorno relleno de color
#plt.contourf(A,B,A**2-B**2)  # Paraboloide hiperbólico. Curvas de nivel con contorno relleno de color
#plt.show()
<Figure size 640x480 with 0 Axes>

Función para imprimir una cifra manuscrita y su predicción#

Hide code cell content
import matplotlib.pyplot as plt
import numpy as np

def plotCifra(matImag, probs):
    ##ps = probs.data.numpy().squeeze()
    fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2)
    ax1.imshow(matImag.reshape(28, 28))
    ax1.axis('off')
    ax2.barh(np.arange(10), probs)
    ax2.set_aspect(0.1)
    ax2.set_yticks(np.arange(10))
    ax2.set_yticklabels(np.arange(10))
    ax2.set_title('Probabilidad')
    ax2.set_xlim(0, 1.1)

    plt.tight_layout()
Hide code cell content
import matplotlib.pyplot as plt

def plotCifra_old(matImag, probs):
    fig1, ax1 = plt.subplots()
    img = matImag.reshape(28, 28)
    ax1.imshow(img, cmap='Greys')
    ax1.set_xticks([])
    ax1.set_yticks([])
    plt.tight_layout()
    plt.show()

    fig, ax = plt.subplots()
    # Example data
    cifras = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
    y_pos = np.arange(len(cifras))
    ax.barh(y_pos, probs, align='center')
    ax.set_yticks(y_pos)
    ax.set_yticklabels(cifras)
    ax.invert_yaxis()  # labels read top-to-bottom
    ax.set_xlabel('Probabilidad')
    ax.set_title('Predicción de cifra manuscrita')
    plt.show()

Utilidades para pruebas con pytorch#

Hide code cell content
import matplotlib.pyplot as plt
import numpy as np
from torch import nn, optim
from torch.autograd import Variable


def test_network(net, trainloader):

    criterion = nn.MSELoss()
    optimizer = optim.Adam(net.parameters(), lr=0.001)

    dataiter = iter(trainloader)
    images, labels = dataiter.next()

    # Create Variables for the inputs and targets
    inputs = Variable(images)
    targets = Variable(images)

    # Clear the gradients from all Variables
    optimizer.zero_grad()

    # Forward pass, then backward pass, then update weights
    output = net.forward(inputs)
    loss = criterion(output, targets)
    loss.backward()
    optimizer.step()

    return True


def imshow(image, ax=None, title=None, normalize=True):
    """Imshow for Tensor."""
    if ax is None:
        fig, ax = plt.subplots()
    image = image.numpy().transpose((1, 2, 0))

    if normalize:
        mean = np.array([0.485, 0.456, 0.406])
        std = np.array([0.229, 0.224, 0.225])
        image = std * image + mean
        image = np.clip(image, 0, 1)

    ax.imshow(image)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.tick_params(axis='both', length=0)
    ax.set_xticklabels('')
    ax.set_yticklabels('')

    return ax


def view_recon(img, recon):
    ''' Function for displaying an image (as a PyTorch Tensor) and its
        reconstruction also a PyTorch Tensor
    '''

    fig, axes = plt.subplots(ncols=2, sharex=True, sharey=True)
    axes[0].imshow(img.numpy().squeeze())
    axes[1].imshow(recon.data.numpy().squeeze())
    for ax in axes:
        ax.axis('off')
        ax.set_adjustable('box-forced')
        
def view_classify(img, ps, version="MNIST"):
    ''' Function for viewing an image and it's predicted classes.
    '''
    ps = ps.data.numpy().squeeze()

    fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2)
    ax1.imshow(img.resize_(1, 28, 28).numpy().squeeze())
    ax1.axis('off')
    ax2.barh(np.arange(10), ps)
    ax2.set_aspect(0.1)
    ax2.set_yticks(np.arange(10))
    if version == "MNIST":
        ax2.set_yticklabels(np.arange(10))
    elif version == "Fashion":
        ax2.set_yticklabels(['Camiseta/top',
                            'Pantalones',
                            'Jersey',
                            'Vestido',
                            'Abrigo',
                            'Sandalia',
                            'Camisa',
                            'Deportivas',
                            'Maleta',
                            'Bota'], size='small');
    ax2.set_title('Probabilidad')
    ax2.set_xlim(0, 1.1)

    plt.tight_layout()
print("load done!")
load done!