IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 人工智能 -> [个人向笔记]pytorch 入门笔记 -> 正文阅读

[人工智能][个人向笔记]pytorch 入门笔记

这篇博客总结了以下教程的最后一节:
https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html

一般套路是先定义一个模型类,取名为Net或Model之类。
然后net = Net().

模型类

代码例子:

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120) # why 5: 32,28,14,10,5
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = torch.flatten(x, 1) # flatten all dimensions except batch
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


net = Net()

步骤:

  • 先用一个类定义模型。
  • 至少两个方法:__init__和forward。
  • init: 先要super一下。
  • init: 然后定义每一层(卷积层、池化层、全连接层)。通常用现成的torch.nn的函数完成,输入网络结构参数
  • forward: 利用上文定义的卷积和全连接,以及torch.nn.functional的函数,如maxpool,relu等。
  • forward: 输入是x,每一步都用x,return也是x

PyTorch 中,nn 与 nn.functional 有什么区别?

  • 功能和运行效率基本一样,调用方法不同。
  • nn不需要自己定义和管理weight。官方推荐:
  • 具有学习参数的(例如,conv2d, linear, batch_norm)采用nn.Xxx方式
  • 没有学习参数的(例如,maxpool, loss func, activation func)等根据个人选择使用nn.functional.xxx或者nn.Xxx方式。
  • 但关于dropout,该知乎用户强烈推荐使用nn.Xxx方式

常用方法:

https://pytorch.org/docs/stable/nn.html
https://pytorch.org/docs/stable/nn.functional.html
https://pytorch.org/docs/stable/generated/torch.flatten.html

torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None)
#常用参数就前三个。

torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)


torch.nn.functional.max_pool2d(input,kernal_size)

torch.nn.functional.relu(input, inplace=False) → Tensor

torch.flatten(input, start_dim=0, end_dim=-1) → Tensor

训练

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
for epoch in range(2):  # loop over the dataset multiple times
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # get the inputs; data is a list of [inputs, labels]
        inputs, labels = data
        # zero the parameter gradients
        optimizer.zero_grad()
        # forward + backward + optimize
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward() # calculate grad to determine how to update the parameters
        optimizer.step() # update the parameters

        # print statistics
        running_loss += loss.item()
        if i % 2000 == 1999:    # print every 2000 mini-batches
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)

步骤:

  • 定义一个优化器
  • 定义loss函数
  • for循环,外层是每个epoch
  • for循环,内层是每个minibatch,
  • 在准备好输入和标签数据后,训练需要的是如下代码:
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward() # calculate grad to determine how to update the parameters
optimizer.step() # update the parameters
  • 如果需要打印loss,可以参考完整代码。里面每2000个minibatches就打印这两千个batch的平均loss.

模型的保存和读取

各有一个函数:

torch.save(net.state_dict(),PATH) #保存模型

net = Net()
net.load_state_dict(torch.load(PATH)) # 读取模型

测试单个样本

outputs = net(images) # 直接用net(input)即可得到softmax值
_, predicted = torch.max(outputs, 1) # 取最大,得到预测标签

print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
                              for j in range(4)))

测试整个测试集

步骤:
-用一个with torch.no_grad():包住后面的内容,因为不需要计算梯度。

  • 遍历整个测试集,每个都用net()计算一遍,统计总数和正确预测的个数。
correct = 0
total = 0
# since we're not training, we don't need to calculate the gradients for our outputs
with torch.no_grad():
    for data in testloader:
        images, labels = data
        # calculate outputs by running images through the network
        outputs = net(images)
        # the class with the highest energy is what we choose as prediction
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))

使用GPU

# 定义设备
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)

net.to(device) # 网络转到设备

inputs, labels = data[0].to(device), data[1].to(device) # 数据转到设备

使用多个GPU

在上面的使用的那个GPU操作后:

if torch.cuda.device_count() > 1:
  print("Let's use", torch.cuda.device_count(), "GPUs!")
  model = nn.DataParallel(model)

model.to(device)

完整代码

#!/usr/bin/env python3.6.5
# -*- coding: UTF-8 -*-
"""
@Author: YuQiao
@Date: 2020/12/22 20:26
@File: TrainingAClassifier.py
"""

'''
For this tutorial, we will use the CIFAR10 dataset. 
It has the classes: 
‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’, ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’. 
The images in CIFAR-10 are of size 3x32x32, 
i.e. 3-channel color images of 32x32 pixels in size.
'''
import torch
import torchvision
import torchvision.transforms as transforms

transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                        download=True, transform=transform)
##
print("trainset")
print(trainset)
##
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
                                          shuffle=True, num_workers=2)
print("trainloader")
print(trainloader)
##
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
                                       download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
                                         shuffle=False, num_workers=2)

classes = ('plane', 'car', 'bird', 'cat',
           'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
##

import matplotlib.pyplot as plt
import numpy as np

# functions to show an image


def imshow(img):
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()


# get some random training images
dataiter = iter(trainloader)
images, labels = dataiter.next()

# show images
imshow(torchvision.utils.make_grid(images))
# print labels
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))
##
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120) # why 5: 32,28,14,10,5
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5) # n_samples, data of an sample
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


net = Net()

##
import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)


##
# Qiao's test cell
for i, data in enumerate(trainloader, 0): # the second parameter means the initial value of i
    # get the inputs; data is a list of [inputs, labels]
    inputs, labels = data
print("data",data)
print("inputs", inputs.shape)
print("labels", labels.shape)
##
print(labels)
# inputs torch.Size([4, 3, 32, 32])
# labels torch.Size([4])

# print(len(testloader))
# inputs, labels = testloader[0]
# print(inputs.size)
# print(labels.size)
##
for epoch in range(2):  # loop over the dataset multiple times
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # get the inputs; data is a list of [inputs, labels]
        inputs, labels = data
        # zero the parameter gradients
        optimizer.zero_grad()
        # forward + backward + optimize
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward() # calculate grad to determine how to update the parameters
        optimizer.step() # update the parameters

        # print statistics
        running_loss += loss.item()
        if i % 2000 == 1999:    # print every 2000 mini-batches
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')

##
#Let’s quickly save our trained model:
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)

##
dataiter = iter(testloader)
images, labels = dataiter.next()

# print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))

##
net = Net()
net.load_state_dict(torch.load(PATH))
##
outputs = net(images)
##
_, predicted = torch.max(outputs, 1)

print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
                              for j in range(4)))
##
# Let us look at how the network performs on the whole dataset.
correct = 0
total = 0
with torch.no_grad():
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))

##
# what are the classes that performed well, and the classes that did not perform well:
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs, 1)
        c = (predicted == labels).squeeze()
        for i in range(4):
            label = labels[i]
            class_correct[label] += c[i].item()
            class_total[label] += 1


for i in range(10):
    print('Accuracy of %5s : %2d %%' % (
        classes[i], 100 * class_correct[i] / class_total[i]))
##


  人工智能 最新文章
2022吴恩达机器学习课程——第二课(神经网
第十五章 规则学习
FixMatch: Simplifying Semi-Supervised Le
数据挖掘Java——Kmeans算法的实现
大脑皮层的分割方法
【翻译】GPT-3是如何工作的
论文笔记:TEACHTEXT: CrossModal Generaliz
python从零学(六)
详解Python 3.x 导入(import)
【答读者问27】backtrader不支持最新版本的
上一篇文章      下一篇文章      查看所有文章
加:2021-09-14 13:20:36  更:2021-09-14 13:22:34 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/21 23:39:41-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码