PyTorch官方教程中文版:PYTORCH之60MIN入门教程代码学习

Pytorch入门

import torch"""
构建非初始化的矩阵
"""x = torch.empty(5,3)
#print(x)"""
构建随机初始化矩阵
"""x = torch.rand(5,3)"""
构造一个矩阵全为 0,而且数据类型是 long
"""x = torch.zeros(5, 3, dtype=torch.long)"""
直接构造一个张量:
"""x = torch.tensor([5.5, 3])"""
创建一个 tensor 基于已经存在的 tensor。
"""x = x.new_ones(5, 3, dtype=torch.double)
x = torch.randn_like(x, dtype=torch.float)
#randn_like->返回与输入大小相同的张量,该张量由正态分布中的随机数填充,平均值为0,方差为1。"""
获取它的维度信息:
"""print(x.size())"""
tensor的加法
"""y = torch.rand(5, 3)
#第一种方法
print(x + y)
#第二种方法
print(torch.add(x, y))
#第三种方法
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
#第四种方法
y.add_(x)   #注意:这是原地加法,y=x+y
#任何在原地(in-place)改变张量的操作都有一个_后缀。例如x.copy_(y), x.t_()操作将改变x."""
tensor切片
"""print(x[:, 1])  #这里输出的x第二列,如果是第二行就是[1,:]"""
改变一个 tensor 的大小或者形状
"""y = x.view(16)z = x.view(-1, 8)
#注意这个-1,这个-1代表你并不清楚这个tensor修改后的行数或者列数是多少,所以用-1代替,只能存在一个-1"""
获取tensor值(这里可以直接提取使用value)
"""print(x.item())

Pytorch自动微分

import torch"""
创建一个张量,设置 requires_grad=True 来跟踪与它相关的计算(来源)
"""
x = torch.ones(2, 2, requires_grad=True)
print(x)y = x + 2
print(y)
#如果这时打印y,你会发现y有了一个grad_fn也在跟踪计算
print(y.grad_fn)
#打印grad_fn就会得到y的来源z = y * y * 3
out = z.mean()  #mean函数中的参数dim代表在第几维度求平均数。
print(z, out)print(z.requires_grad)
#.requires_grad_( ... ) 会改变张量的 requires_grad 标记。输入的标记默认为 False ,如果没有提供相应的参数。"""
反向传播梯度
"""
#我们现在后向传播,因为输出包含了一个标量,out.backward() 等同于out.backward(torch.tensor(1.))。
out.backward()
print(x.grad)   #out反向传播后,改变的是之前变量的梯度,即x"""
雅可比向量积的例子:
在向量微积分中,雅可比矩阵是一阶偏导数以一定方式排列成的矩阵,其行列式称为雅可比行列式。
"""x = torch.randn(3, requires_grad=True)
y = x * 2
while y.data.norm() < 1000:     #torch.norm是对输入的Tensor求范数y = y * 2
print(y)#现在在这种情况下,y 不再是一个标量。torch.autograd 不能够直接计算整个雅可比,但是如果我们只想要雅可比向量积,只需要简单的传递向量给 backward 作为参数。
v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)
y.backward(v)
print(x.grad)#你可以通过将代码包裹在 with torch.no_grad(),来停止对从跟踪历史中的 .requires_grad=True 的张量自动求导。
with torch.no_grad():print((x ** 2).requires_grad)

Pytorch神经网络

import torch
import torch.nn as nn
import torch.functional as Fclass Net(nn.Module):def __init__(self):super(Net, self).__init__()self.conv1 = nn.Conv2d(1,6,5)#Conv2d(in_channels, out_channels, kernel_size, stride=1,padding=0, dilation=1, groups=1,bias=True, padding_mode=‘zeros’)self.conv2 = nn.Conv2d(6,16,5)self.fc1 = nn.Linear(16 * 5 * 5, 120)self.fc2 = nn.Linear(120, 84)self.fc3 = nn.Linear(84, 10)def forward(self,x):x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))x = F.max_pool2d(F.relu(self.conv2(x)), 2)x = x.view(-1, self.num_flat_features(x))x = F.relu(self.fc1(x))x = F.relu(self.fc2(x))x = self.fc3(x)return xdef num_flat_features(self, x):size = x.size()[1:]num_features = 1for s in size:num_features *= sreturn num_featuresnet = Net()
#print(net)"""
一个模型可训练的参数可以通过调用 net.parameters() 返回:
"""
# params = list(net.parameters())
# print(len(params))
# print(params[0].size())
"""
让我们尝试随机生成一个 32x32 的输入。注意:期望的输入维度是 32x32
"""
input = torch.randn(1, 1, 32, 32)
#这一步会错误,我也不知道为什么:AttributeError: module 'torch.functional' has no attribute 'max_pool2d'
out = net(input)
print(out)
"""
把所有参数梯度缓存器置零,用随机的梯度来反向传播
"""net.zero_grad()
out.backward(torch.randn(1, 10))"""
一个损失函数需要一对输入:模型输出和目标,然后计算一个值来评估输出距离目标有多远。
有一些不同的损失函数在 nn 包中。一个简单的损失函数就是 nn.MSELoss ,这计算了均方误差。
"""output = net(input)
target = torch.randn(10)
target = target.view(1, -1)  # make it the same shape as output
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
"""
现在,如果你跟随损失到反向传播路径,可以使用它的 .grad_fn 属性,查看计算图
"""
print(loss.grad_fn)"""
为了实现反向传播损失,我们所有需要做的事情仅仅是使用 loss.backward()。你需要清空现存的梯度,要不然帝都将会和现存的梯度累计到一起。
"""# net.zero_grad()
# loss.backward()"""
如果你是用神经网络,你想使用不同的更新规则,类似于 SGD, Nesterov-SGD, Adam, RMSProp, 等。为了让这可行,我们建立了一个小包:torch.optim 实现了所有的方法。使用它非常的简单。
"""
import torch.optim as optim# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)# in your training loop:
optimizer.zero_grad()   # zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()

Pytorch图像分类器

import torch
import torchvision
import torchvision.transforms as transforms"""
下载数据集并将其归一化
torchvision 数据集的输出是范围在[0,1]之间的 PILImage,我们将他们转换成归一化范围为[-1,1]之间的张量 Tensors。
"""transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize(mean = (0.5, 0.5, 0.5), std = (0.5, 0.5, 0.5))])
#(1)transforms.Compose就是将transforms组合在一起;
#(2)transforms.Normalize使用如下公式进行归一化:
# channel=(channel-mean)/std(因为transforms.ToTensor()已经把数据处理成[0,1],那么(x-0.5)/0.5就是[-1.0, 1.0])
# 这样一来,我们的数据中的每个值就变成了[-1,1]的数了。trainset = torchvision.datasets.CIFAR10(root='./data', train=True,download=False, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,shuffle=True, num_workers=2)testset = torchvision.datasets.CIFAR10(root='./data', train=False,download=False, 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 npdef imshow(img):img = img / 2 + 0.5npimg = img.numpy()plt.imshow(np.transpose(npimg, (1, 2, 0)))plt.show()# dataiter = iter(trainloader)
# images, labels = dataiter.next()
# imshow(torchvision.utils.make_grid(images))
# for j in range(4):
#     print(' '.join('%5s' % classes[labels[j]]))"""
之前的神经网络复制过来
"""import torch.nn as nn
import torch.nn.functional as Fclass 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)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)x = F.relu(self.fc1(x))x = F.relu(self.fc2(x))x = self.fc3(x)return xnet = Net()"""
定义一个损失函数和优化器 让我们使用分类交叉熵Cross-Entropy 作损失函数,动量SGD做优化器。
"""import torch.optim as optimif __name__ == '__main__':#<--遇到BUG:The “freeze_support()” line can be omitted if the program is not going to be frozen的解决办法-->criterion = nn.CrossEntropyLoss()optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)"""在数据迭代器上循环传给网络和优化器 输入就可以"""for epoch in range(2):  # loop over the dataset multiple timesrunning_loss = 0.0for i, data in enumerate(trainloader, 0):inputs, labels = dataoptimizer.zero_grad()outputs = net(inputs)loss = criterion(outputs, labels)loss.backward()optimizer.step()running_loss += loss.item()if i % 2000 == 1999:    # print every 2000 mini-batchesprint('[%d, %5d] loss: %.3f' %(epoch + 1, i + 1, running_loss / 2000))running_loss = 0.0print('Finished Training')"""选取测试数据集"""dataiter = iter(testloader)images, labels = dataiter.next()imshow(torchvision.utils.make_grid(images))print('GraoundTruth: ', ' '.join(['%5s' % classes[labels[j]] for j in range(4)]))"""显示预测值"""outputs = net(images)_, predicted = torch.max(outputs, 1)print('Predicted: ', ' '.join(['%5s' % classes[predicted[j]] for j in range(4)]))"""看看网络在整个数据集上的表现    """correct = 0total = 0with torch.no_grad():for data in testloader:images, labels = dataoutputs = 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))"""各类的准确率"""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 = dataoutputs = 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] += 1for i in range(10):print('Accuracy of %5s : %2d %%' % (classes[i], 100 * class_correct[i] / class_total[i]))

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/389429.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Flexbox 最简单的表单

弹性布局(Flexbox)逐渐流行&#xff0c;越来越多的人开始使用&#xff0c;因为它写Css布局真是太简单了一一、<form>元素表单使用<form>元素<form></form>复制代码上面是一个空的表单&#xff0c;根据HTML标准&#xff0c;它是一个块级元素&#xff0c…

CSS中的盒子模型

一.为什么使用CSS 1.有效的传递页面信息 2.使用CSS美化过的页面文本&#xff0c;使页面漂亮、美观&#xff0c;吸引用户 3.可以很好的突出页面的主题内容&#xff0c;使用户第一眼可以看到页面主要内容 4.具有良好的用户体验 二.字体样式属性 1.font-family:英…

jdk重启后步行_向后介绍步行以一种新颖的方式来预测未来

jdk重启后步行“永远不要做出预测&#xff0c;尤其是关于未来的预测。” (KK Steincke) (“Never Make Predictions, Especially About the Future.” (K. K. Steincke)) Does this picture portray a horse or a car? 这张照片描绘的是马还是汽车&#xff1f; How likely is …

PyTorch官方教程中文版:入门强化教程代码学习

PyTorch之数据加载和处理 from __future__ import print_function, division import os import torch import pandas as pd #用于更容易地进行csv解析 from skimage import io, transform #用于图像的IO和变换 import numpy as np import matplotlib.pyplot a…

css3-2 CSS3选择器和文本字体样式

css3-2 CSS3选择器和文本字体样式 一、总结 一句话总结&#xff1a;是要记下来的&#xff0c;记下来可以省很多事。 1、css的基本选择器中的:first-letter和:first-line是什么意思&#xff1f; :first-letter选择第一个单词&#xff0c;:first-line选择第一行 2、css的伪类选…

mongodb仲裁者_真理的仲裁者

mongodb仲裁者Coming out of college with a background in mathematics, I fell upward into the rapidly growing field of data analytics. It wasn’t until years later that I realized the incredible power that comes with the position. As Uncle Ben told Peter Par…

优化 回归_使用回归优化产品价格

优化 回归应用数据科学 (Applied data science) Price and quantity are two fundamental measures that determine the bottom line of every business, and setting the right price is one of the most important decisions a company can make. Under-pricing hurts the co…

Node.js——异步上传文件

前台代码 submit() {var file this.$refs.fileUpload.files[0];var formData new FormData();formData.append("file", file);formData.append("username", this.username);formData.append("password", this.password);axios.post("http…

用 JavaScript 的方式理解递归

原文地址 1. 递归是啥? 递归概念很简单&#xff0c;“自己调用自己”&#xff08;下面以函数为例&#xff09;。 在分析递归之前&#xff0c;需要了解下 JavaScript 中“压栈”&#xff08;call stack&#xff09; 概念。 2. 压栈与出栈 栈是什么&#xff1f;可以理解是在内存…

PyTorch官方教程中文版:Pytorch之图像篇

微调基于 torchvision 0.3的目标检测模型 """ 为数据集编写类 """ import os import numpy as np import torch from PIL import Imageclass PennFudanDataset(object):def __init__(self, root, transforms):self.root rootself.transforms …

大数据数据科学家常用面试题_进行数据科学工作面试

大数据数据科学家常用面试题During my time as a Data Scientist, I had the chance to interview my fair share of candidates for data-related roles. While doing this, I started noticing a pattern: some kinds of (simple) mistakes were overwhelmingly frequent amo…

scrapy模拟模拟点击_模拟大流行

scrapy模拟模拟点击复杂系统 (Complex Systems) In our daily life, we encounter many complex systems where individuals are interacting with each other such as the stock market or rush hour traffic. Finding appropriate models for these complex systems may give…

公司想申请网易企业电子邮箱,怎么样?

不论公司属于哪个行业&#xff0c;选择企业邮箱&#xff0c;交互界面友好度、稳定性、安全性都是选择邮箱所必须考虑的因素。网易企业邮箱邮箱方面已有21年的运营经验&#xff0c;是国内资历最高的电子邮箱&#xff0c;在各个方面都非常成熟完善。 从交互界面友好度来看&#x…

莫烦Matplotlib可视化第二章基本使用代码学习

基本用法 import matplotlib.pyplot as plt import numpy as np""" 2.1基本用法 """ # x np.linspace(-1,1,50) #[-1,1]50个点 # #y 2*x 1 # # y x**2 # plt.plot(x,y) #注意&#xff1a;x,y顺序不能反 # plt.show()"""…

vue.js python_使用Python和Vue.js自动化报告过程

vue.js pythonIf your organization does not have a data visualization solution like Tableau or PowerBI nor means to host a server to deploy open source solutions like Dash then you are probably stuck doing reports with Excel or exporting your notebooks.如果…

plsql中导入csvs_在命令行中使用sql分析csvs

plsql中导入csvsIf you are familiar with coding in SQL, there is a strong chance you do it in PgAdmin, MySQL, BigQuery, SQL Server, etc. But there are times you just want to use your SQL skills for quick analysis on a small/medium sized dataset.如果您熟悉SQ…

第十八篇 Linux环境下常用软件安装和使用指南

提醒&#xff1a;如果之后要安装virtualenvwrapper的话&#xff0c;可以直接跳到安装virtualenvwrapper的方法&#xff0c;而不需要先安装好virtualenv安装virtualenv和生成虚拟环境安装virtualenv&#xff1a;yum -y install python-virtualenv生成虚拟环境&#xff1a;先切换…

莫烦Matplotlib可视化第三章画图种类代码学习

3.1散点图 import matplotlib.pyplot as plt import numpy as npn 1024 X np.random.normal(0,1,n) Y np.random.normal(0,1,n) T np.arctan2(Y,X) #用于计算颜色plt.scatter(X,Y,s75,cT,alpha0.5)#alpha是透明度 #plt.scatter(np.arange(5),np.arange(5)) #一条线的散点…

计算机科学必读书籍_5篇关于数据科学家的产品分类必读文章

计算机科学必读书籍Product categorization/product classification is the organization of products into their respective departments or categories. As well, a large part of the process is the design of the product taxonomy as a whole.产品分类/产品分类是将产品…

es6解决回调地狱问题

本文摘抄自阮一峰老师的 http://es6.ruanyifeng.com/#docs/generator-async 异步 所谓"异步"&#xff0c;简单说就是一个任务不是连续完成的&#xff0c;可以理解成该任务被人为分成两段&#xff0c;先执行第一段&#xff0c;然后转而执行其他任务&#xff0c;等做好…