图像数据处理 pytorch

2023-11-01

# -*- coding: utf-8 -*-
"""
Transfer Learning Tutorial
==========================
**Author**: `Sasank Chilamkurthy <https://chsasank.github.io>`_

In this tutorial, you will learn how to train your network using
transfer learning. You can read more about the transfer learning at `cs231n
notes <http://cs231n.github.io/transfer-learning/>`__

Quoting these notes,

    In practice, very few people train an entire Convolutional Network
    from scratch (with random initialization), because it is relatively
    rare to have a dataset of sufficient size. Instead, it is common to
    pretrain a ConvNet on a very large dataset (e.g. ImageNet, which
    contains 1.2 million images with 1000 categories), and then use the
    ConvNet either as an initialization or a fixed feature extractor for
    the task of interest.

These two major transfer learning scenarios look as follows:

-  **Finetuning the convnet**: Instead of random initializaion, we
   initialize the network with a pretrained network, like the one that is
   trained on imagenet 1000 dataset. Rest of the training looks as
   usual.
-  **ConvNet as fixed feature extractor**: Here, we will freeze the weights
   for all of the network except that of the final fully connected
   layer. This last fully connected layer is replaced with a new one
   with random weights and only this layer is trained.

"""
# License: BSD
# Author: Sasank Chilamkurthy

from __future__ import print_function, division

import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import matplotlib.pyplot as plt
import time
import os
import copy

plt.ion()   # interactive mode

######################################################################
# Load Data
# ---------
#
# We will use torchvision and torch.utils.data packages for loading the
# data.
#
# The problem we're going to solve today is to train a model to classify
# **ants** and **bees**. We have about 120 training images each for ants and bees.
# There are 75 validation images for each class. Usually, this is a very
# small dataset to generalize upon, if trained from scratch. Since we
# are using transfer learning, we should be able to generalize reasonably
# well.
#
# This dataset is a very small subset of imagenet.
#
# .. Note ::
#    Download the data from
#    `here <https://download.pytorch.org/tutorial/hymenoptera_data.zip>`_
#    and extract it to the current directory.

# Data augmentation and normalization for training
# Just normalization for validation
data_transforms = {
    'train': transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'val': transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
}

data_dir = 'data'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
                                          data_transforms[x])
                  for x in ['train', 'val']}
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,
                                             shuffle=True, num_workers=4)
              for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classes
#device = torch.device("cpu")
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

######################################################################
# Visualize a few images
# ^^^^^^^^^^^^^^^^^^^^^^
# Let's visualize a few training images so as to understand the data
# augmentations.

def imshow(inp, title=None):
    """Imshow for Tensor."""
    inp = inp.numpy().transpose((1, 2, 0))
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    inp = std * inp + mean
    inp = np.clip(inp, 0, 1)
    #plt.imshow(inp)
    if title is not None:
        plt.title(title)
    plt.pause(0.001)  # pause a bit so that plots are updated

# Get a batch of training data
inputs, classes = next(iter(dataloaders['train']))

# Make a grid from batch
out = torchvision.utils.make_grid(inputs)

#imshow(out, title=[class_names[x] for x in classes])


######################################################################
# Training the model
# ------------------
#
# Now, let's write a general function to train a model. Here, we will
# illustrate:
#
# -  Scheduling the learning rate
# -  Saving the best model
#
# In the following, parameter ``scheduler`` is an LR scheduler object from
# ``torch.optim.lr_scheduler``.


def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
    #ariterion为nn.CrossEntropyLoss()
    since = time.time()

    best_model_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0

    for epoch in range(num_epochs):
        print('Epoch {}/{}'.format(epoch, num_epochs - 1))
        print('-' * 10)

        # Each epoch has a training and validation phase
        for phase in ['train', 'val']:
            if phase == 'train':
                scheduler.step()
                model.train()  # Set model to training mode
            else:
                model.eval()   # Set model to evaluate mode

            running_loss = 0.0
            running_corrects = 0

            # Iterate over data.
            for inputs, labels in dataloaders[phase]:
                inputs = inputs.to(device)
                labels = labels.to(device)

                # zero the parameter gradients
                optimizer.zero_grad()

                # forward
                # track history if only in train
                with torch.set_grad_enabled(phase == 'train'):
                    outputs = model(inputs)
                    _, preds = torch.max(outputs, 1)
                    loss = criterion(outputs, labels)

                    # backward + optimize only if in training phase
                    if phase == 'train':
                        loss.backward()
                        optimizer.step()

                # statistics
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)

            epoch_loss = running_loss / dataset_sizes[phase]
            epoch_acc = running_corrects.double() / dataset_sizes[phase]

            print('{} Loss: {:.4f} Acc: {:.4f}'.format(
                phase, epoch_loss, epoch_acc))

            # deep copy the model update to get the best acc
            if phase == 'val' and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_model_wts = copy.deepcopy(model.state_dict())

        print()

    time_elapsed = time.time() - since
    print('Training complete in {:.0f}m {:.0f}s'.format(
        time_elapsed // 60, time_elapsed % 60))
    print('Best val Acc: {:4f}'.format(best_acc))

    # load best model weights
    model.load_state_dict(best_model_wts)
    return model


######################################################################
# Visualizing the model predictions
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Generic function to display predictions for a few images
#

def visualize_model(model, num_images=6):
    was_training = model.training
    model.eval()
    images_so_far = 0
    fig = plt.figure()

    with torch.no_grad():
        for i, (inputs, labels) in enumerate(dataloaders['val']):
            inputs = inputs.to(device)
            labels = labels.to(device)

            outputs = model(inputs)
            _, preds = torch.max(outputs, 1)

            for j in range(inputs.size()[0]):
                images_so_far += 1
                ax = plt.subplot(num_images//2, 2, images_so_far)
                ax.axis('off')
                ax.set_title('predicted: {}'.format(class_names[preds[j]]))
                #imshow(inputs.cpu().data[j])

                if images_so_far == num_images:
                    model.train(mode=was_training)
                    return
        model.train(mode=was_training)

######################################################################
# Finetuning the convnet
# ----------------------
#
# Load a pretrained model and reset final fully connected layer.
#

model_ft = models.resnet18(pretrained=True)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 2)

model_ft = model_ft.to(device)

criterion = nn.CrossEntropyLoss()

# Observe that all parameters are being optimized
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)

# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)

######################################################################
# Train and evaluate
# ^^^^^^^^^^^^^^^^^^
#
# It should take around 15-25 min on CPU. On GPU though, it takes less than a
# minute.
#

model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,
                       num_epochs=25)

######################################################################
#

#visualize_model(model_ft)


######################################################################
# ConvNet as fixed feature extractor
# ----------------------------------
#
# Here, we need to freeze all the network except the final layer. We need
# to set ``requires_grad == False`` to freeze the parameters so that the
# gradients are not computed in ``backward()``.
#
# You can read more about this in the documentation
# `here <http://pytorch.org/docs/notes/autograd.html#excluding-subgraphs-from-backward>`__.
#

model_conv = torchvision.models.resnet18(pretrained=True)
for param in model_conv.parameters():
    param.requires_grad = False

# Parameters of newly constructed modules have requires_grad=True by default
num_ftrs = model_conv.fc.in_features
model_conv.fc = nn.Linear(num_ftrs, 2)

model_conv = model_conv.to(device)

criterion = nn.CrossEntropyLoss()

# Observe that only parameters of final layer are being optimized as
# opoosed to before.
optimizer_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)

# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)


######################################################################
# Train and evaluate
# ^^^^^^^^^^^^^^^^^^
#
# On CPU this will take about half the time compared to previous scenario.
# This is expected as gradients don't need to be computed for most of the
# network. However, forward does need to be computed.
#

model_conv = train_model(model_conv, criterion, optimizer_conv,
                         exp_lr_scheduler, num_epochs=25)

######################################################################
#

visualize_model(model_conv)

plt.ioff()
plt.show()

文章完全参考别人,可见代码中,万分感谢,再次感谢!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

图像数据处理 pytorch 的相关文章

随机推荐

  • kettle增量抽取

    通过时间去增量抽取 数据源 1 新建trans转换 设置变量 step1 mysql输入 不勾选 允许建议转换 勾选中文可能会乱码 step2 设置变量 2 新建trans转换 根据变量抽取数据 step1 获取变量 step2 表输入 s
  • uni-app和web-view页面相互传参

    在uni app中 可以通过uni navigateTo和uni redirectTo等方法跳转到其他页面 并且可以通过url参数进行页面间的参数传递 而在web view页面中 可以通过url的query参数进行参数传递 下面是一个示例
  • 什么是springboot

    Spring Boot是由Pivotal团队提供的全新框架 其设计目的是用来简化Spring应用的创建 运行 调试 部署等 使用Spring Boot可以做到专注于Spring应用的开发 而无需过多关注XML的配置 Spring Boot使
  • csdn 代码样式 代码高亮 代码风格

    刚玩csdn 结果发现博客帮助里没有教这个 就写了一下 希望可以帮到一些和我一样的新手 在文章的富文本内 选择源代码后 在源代码中编辑即可 修改下文中的class可以进行多种样式风格的支持 如html c javascript java c
  • 在ubuntu 20.04中安装mmSegmentation

    注 此教程是博主的学习笔记 基于pycharm软件进行学习 如有问题可以在评论区进行评论 目录 一 在pycharm中创建object segmentation虚拟环境 二 mmSegmentation配置与安装 一 mmSegmentat
  • 腾讯云16核服务器配置大全_CVM和轻量服务器汇总

    腾讯云16核CPU服务器有哪些配置可以选择 可以选择标准型S6 标准型SA3 计算型C6或标准型S5等 目前标准型S5云服务器有优惠活动 性价比高 计算型C6云服务器16核性能更高 轻量16核32G28M带宽优惠价3468元15个月 腾讯云
  • 组合式API- 1-Setup

    参数 使用 setup 函数时 它将接受两个参数 props context 第一个参数 Props setup 函数中的第一个参数是 props 正如在一个标准组件中所期望的那样 setup 函数中的 props 是响应式的 当传入新的
  • Keil转到Eclipse遇到的几个问题

    ARM下Keil转到Eclipse后的几个问题 Keil转战到Eclipse下 首先 Eclipse的交叉工具链的环境要进行设置 其次 在Keil中的Scatter file在Eclipse下要重新编写 最后 Eclipse的调试环境要进行
  • SQL7 查找年龄大于24岁的用户信息

    描述 题目 现在运营想要针对24岁以上的用户开展分析 请你取出满足条件的设备ID 性别 年龄 学校 用户信息表 user profile id device id gender age university province 1 2138
  • 网络通信TCP/UDP

    目录 1 TCP 通信 cs 模型 socket 函数 bind 函数 listen 函数 connect 函数 accept 函数 recv 函数 send 函数 close 函数 出现的问题解决 2 UDP 通信 sendto 函数 r
  • 10 个基本的 Python 编码约定

    10 个基本的 Python 编码约定 1 使用描述性变量名 2 遵循 PEP 8 标准 3 使用文档字符串记录函数 4 避免全局变量 5 DRY Don t Repeat Yourself 不要重复自己 6 使用列表表达式 7 使用异常进
  • 串口与普通IO口的区别

    General Purpose Input Output 通用输入 输出 简称为GPIO 或总线扩展器 人们利用工业标准I2C SMBus或SPI接口简化了I O口的扩展 当微控制器或芯片组没有足够的I O端口 或当系统需要采用远端串行通信
  • Linux SVN 搭建(YUM)安装

    原文地址 http www centoscn com CentosServer ftp 2014 0202 2409 html 安装说明 系统环境 CentOS 6 2 安装方式 yum install 源码安装容易产生版本兼容的问题 安装
  • 正则验证

    一 校验数字的表达式 数字 0 9 n位的数字 d 2 至少n位的数字 d n m n位的数字 d m n 零和非零开头的数字 0 1 9 0 9 非零开头的最多带两位小数的数字 1 9 0 9 0 9 1 2 带1 2位小数的正数或负数
  • 遍历dataframe中的某列,找出含有空格的元素

    工作上需要处理一个数据 把一个较大数据中的姓名列和账号列全部遍历一遍 然后看是否数据里面含有空格 一开始想法是用for循环 一行一行遍历df数据 这个方法效率太慢 搜索一下 有个博主发现了一个map函数 太厉害了 我直接用了 准备先贴我的代
  • IDEA中POM 项目parent中的dependencyManagement中的依赖版本号报红

    现象 IDEA中作为管理依赖的parent项目的pom文件中 在dependencyManagement中的dependency 如果指定的版本在本地仓库不存在 并且在子项目中也未引用的时候 会报红 疑惑 只是引用了很常见的依赖 并且版本官
  • 如何编写一个含有抄底信号的副图指标

    如果你作为通达信软件源代码的程序维护员 如何编写一个含有抄底提示的副图指标 请看下面的的示例教程 python语言 python 导入所需的库 import talib 计算移动平均线 def moving average data per
  • 【哈佛积极心理学笔记】第6讲 乐观主义

    第6讲 乐观主义 How can we create consciously and subconsciously a positive environment where we actually can take out the most
  • 小白学习一周 Linux命令

    文件系统管理相关命令 clear 清屏 pwd 打印当前工作目录 tmp 打开文件夹 cd 改变当前工作目录 mkdir 创建一个新文件夹 mkdir 在根目录下创建一个新文件夹 mkdir p 套娃创建文件夹 rmdir 删除当前目录下的
  • 图像数据处理 pytorch

    coding utf 8 Transfer Learning Tutorial Author Sasank Chilamkurthy