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.pswp.cn/news/389429.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/389429.shtml
英文地址,請注明出處:http://en.pswp.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;等做好…