zoukankan      html  css  js  c++  java
  • Pytorch加载并可视化FashionMNIST指定层(Udacity)

    加载并可视化FashionMNIST


    在这个notebook中,我们要加载并查看 Fashion-MNIST 数据库中的图像。

    任何分类问题的第一步,都是查看你正在使用的数据集。这样你可以了解有关图像和标签格式的一些详细信息,以及对如何定义网络以识别此类图像集中的模式的一些见解。

    PyTorch有一些你可以使用的内置数据集,而FashionMNIST就是其中之一,它已经下载到了这个notebook中的data/目录中,所以我们要做的就是使用FashionMNIST数据集类加载这些图像,并使用DataLoader批量加载数据。

    加载数据

    数据集类和张量

    torch.utils.data.Dataset是一个表示数据集的抽象类,而 FashionMNIST类是这个数据集类的扩展,它可以让我们加载批量的图像/标签数据,并且统一地将变换应用于我们的数据,例如将所有图像转换为用于训练神经网络的张量。张量类似于numpy数组,但也可以在GPU上使用,用来加速计算 。

    下面,让我们看一看如何构建训练数据集。

    # our basic libraries
    import torch
    import torchvision
    
    # data loading and transforming
    from torchvision.datasets import FashionMNIST
    from torch.utils.data import DataLoader
    from torchvision import transforms
    
    # The output of torchvision datasets are PILImage images of range [0, 1]. 
    # We transform them to Tensors for input into a CNN
    
    ## Define a transform to read the data in as a tensor
    data_transform = transforms.ToTensor()
    
    # choose the training and test datasets
    train_data = FashionMNIST(root='./data', train=True,
                                       download=False, transform=data_transform)
    
    # Print out some stats about the training data
    print('Train data, number of images: ', len(train_data))
    

     Train data, number of images: 60000

    数据迭代与批处理

    接下来,我们将要使用的是torch.utils.data.DataLoader,它是一个可以批量处理数据并置乱数据的迭代器。

    在下一个单元格中,我们将数据置乱,并以大小为20的批量加载图像/标签数据。

    # prepare data loaders, set the batch_size
    ## TODO: you can try changing the batch_size to be larger or smaller
    ## when you get to training your network, see how batch_size affects the loss
    batch_size = 20
    
    train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True)
    
    # specify the image classes
    classes = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
    

    将一些训练数据可视化

    这个单元格会遍历该训练数据集,并使用dataiter.next()加载一个随机批次的图像/标签数据。然后,它会在2 x batch_size/2网格中将这批图像和标签可视化。

    import numpy as np
    import matplotlib.pyplot as plt
    
    %matplotlib inline
        
    # obtain one batch of training images
    dataiter = iter(train_loader)
    images, labels = dataiter.next()
    images = images.numpy()
    
    # plot the images in the batch, along with the corresponding labels
    fig = plt.figure(figsize=(25, 4))
    for idx in np.arange(batch_size):
        ax = fig.add_subplot(2, batch_size/2, idx+1, xticks=[], yticks=[])
        ax.imshow(np.squeeze(images[idx]), cmap='gray')
        ax.set_title(classes[labels[idx]])
    

    更详细地查看图像

    该数据集中的每个图像都是28x28像素且已归一化的灰度图像。

    关于归一化的说明

    归一化可以确保在训练CNN的过程中,先后经历前馈与反向传播步骤时,每个图像特征都将落入类似的值范围内,而不是过度激活该网络中的特定层。在前馈步骤期间,该神经网络会接收输入图像并将每个输入像素乘以一些卷积滤波器权重并加上偏差,然后应用一些激活和池化函数。如果没有归一化,反向传播步骤中的计算梯度将会非常大,并且会导致我们的损失增加而不是收敛。

    # select an image by index
    idx = 2
    img = np.squeeze(images[idx])
    
    # display the pixel values in that image
    fig = plt.figure(figsize = (12,12)) 
    ax = fig.add_subplot(111)
    ax.imshow(img, cmap='gray')
    width, height = img.shape
    thresh = img.max()/2.5
    for x in range(width):
        for y in range(height):
            val = round(img[x][y],2) if img[x][y] !=0 else 0
            ax.annotate(str(val), xy=(y,x),
                        horizontalalignment='center',
                        verticalalignment='center',
                        color='white' if img[x][y]<thresh else 'black')
    

     

  • 相关阅读:
    沉淀再出发:在python3中导入自定义的包
    沉淀再出发:java中的equals()辨析
    沉淀再出发:web服务器和应用服务器之间的区别和联系
    沉淀再出发:jetty的架构和本质
    沉淀再出发:dubbo的基本原理和应用实例
    沉淀再出发:OpenStack初探
    沉淀再出发:Spring的架构理解
    沉淀再出发:关于IntelliJ IDEA使用的一些总结
    沉淀再出发:spring boot的理解
    沉淀再出发:Bean,JavaBean,POJO,VO,PO,EJB等名词的异同
  • 原文地址:https://www.cnblogs.com/wangyarui/p/11087918.html
Copyright © 2011-2022 走看看