Introduction To PyTorch Lecture 4 - Forsiden

1y ago
6 Views
2 Downloads
2.03 MB
84 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Alexia Money
Transcription

IN5400 Machine learning for image analysis, 2020 springLecture 4:Introduction to PyTorchDavid Völgyesdavid.volgyes@ieee.orgFebruary 5, 2020XPage 1 / 84

IN5400 Machine learning for image analysis, 2020 springAbout todayYou will get an introduction to PyTorch.PyTorch is a widely used deep learning framework, especially in academia.PyTorch version 1.0-1.4Remark:There is a new PyTorch release in every 2-3 months.5 releases since last yearmost likely at least two new will be released during the semesterWe use PyTorch version 1.x,but the syntax did not change in between 1.0 - 1.4 significantly.Some tutorials use Python 2. Stick to Python 3.6 .XPage 2 / 84

IN5400 Machine learning for image analysis, 2020 springOutlineDeep learning frameworksPyTorchtorch.tensorComputational graphAutomatic differentiation (torch.autograd)Data loading and preprocessing (torch.utils)Useful functions (torch.nn.functional)Creating the model (torch.nn)Optimizers (torch.optim)Save/load modelsMiscellaneousXPage 3 / 84

IN5400 Machine learning for image analysis, 2020 springA simplified workflow in supervised learningcreating datasetcreating a neural network (model)defining a loss functionloading samples (data loader)predicting with the modelcomparison of the prediction and the target (loss)backpropagation: calculating gradients from the errorupdating the model (optimizer)checking the loss: if it is low enough, stop trainingXPage 4 / 84

IN5400 Machine learning for image analysis, 2020 springReadingsHighly recommended (by the end of the semester):Pytorch tutorials: https://pytorch.org/tutorials/Deep Learning with PyTorch: A 60 Minute Blitzhttps://pytorch.org/tutorials/beginner/deep learning 60min blitz.htmlPytorch cheat sheet: lBroadcasting: .htmlOverwhelming, but good additional source for anything:Awesome PyTorch list: t is a collection of hundred of links, including tutorials, research papers, libraries, etc.Note:Don’t get confused. A lot of the available code online is written in an older version ofPyTorch (mostly in 0.3-0.4).XPage 5 / 84

IN5400 Machine learning for image analysis, 2020 springProgressDeep learning frameworksPyTorchtorch.tensorComputational graphAutomatic differentiation (torch.autograd)Data loading and preprocessing (torch.utils)Useful functions (torch.nn.functional)Creating the model (torch.nn)Optimizers (torch.optim)Save/load modelsMiscellaneousXPage 6 / 84

IN5400 Machine learning for image analysis, 2020 springWhy do we need Deep learning frameworks?Speed:Fast GPU/CPU implementation of matrix multiplication, convolutions andbackpropagationAutomatic differentiations:Pre-implementation of the most common functions and their gradients.Reuse:Easy to reuse other people’s modelsLess error prone:The more code you write yourself, the more errorsXPage 7 / 84

IN5400 Machine learning for image analysis, 2020 springDeep learning frameworksDeep learning frameworks does a lot of the complicated computation, remember lastweek.XPage 8 / 84

IN5400 Machine learning for image analysis, 2020 springMajor frameworkspytorch (developed by Facebook)Tensorflow (developed by Google)Caffe (developed by Facebook)MXNetMS Cognitive Toolkit (CNTK)ChainerRemark: all of them are open source.XPage 9 / 84

IN5400 Machine learning for image analysis, 2020 ep-learning-framework-power-scores-2018-Page 10 / 84

IN5400 Machine learning for image analysis, 2020 springPopularity, late 2019Industry is still dominated by Tensorflow / KerasBut 70-75% of the academic papers are in PyTorch(last year: 20%)Major projects change to PyTorch, e.g. OpenAIXPage 11 / 84

IN5400 Machine learning for image analysis, 2020 springWhy PyTorchPython APICan use CPU, GPU (CUDA only)Supports common platforms:Windows, iOS, LinuxPyTorch is a thin framework which lets you work closely with programming the neuralnetworkFocus on the machine learn part not the framework itselfPythonic control flowFlexibleCleaner and more intuitive codeEasy to debugPython debuggerWith PyTorch we can use the python debuggerIt does not run all in a C environment abstracted wayXPage 12 / 84

IN5400 Machine learning for image analysis, 2020 springInstalling PyTorchconda create -n IN5400 python 3.8 PyTorch torchvision cudatoolkit 10.1 jupyter ipython matplotlib scikit-learn -c PyTorch#XPage 13 / 84

IN5400 Machine learning for image analysis, 2020 springInstalling PyTorchWithout CUDA:conda create -n IN5400 python 3.8 PyTorch torchvision cpuonly jupyter ipython matplotlib scikit-learn -c PyTorchInstallation ly/Older versions/Remember: during the semester probably there will be at least two new releases!XPage 14 / 84

IN5400 Machine learning for image analysis, 2020 springChecking PyTorch installation import numpy as np import torch import sys import matplotlib print(f'Python version: {sys.version}')Python version: 3.8.1 packaged by conda-forge (default, Jan 29 2020, 14:55:04) [GCC 7.3.0] print(f'Numpy version: {np.version.version}')Numpy version: 1.17.5 print(f'PyTorch version: {torch.version. version }')PyTorch version: 1.4.0 print(f'Matplotlib version: {matplotlib. version }')Matplotlib version: 3.1.2 print(f'GPU present: {torch.cuda.is available()}')GPU present: FalseXPage 15 / 84

IN5400 Machine learning for image analysis, 2020 springPyTorch packagesXPage 16 / 84

IN5400 Machine learning for image analysis, 2020 springProgressDeep learning frameworksPyTorchtorch.tensorComputational graphAutomatic differentiation (torch.autograd)Data loading and preprocessing (torch.utils)Useful functions (torch.nn.functional)Creating the model (torch.nn)Optimizers (torch.optim)Save/load modelsMiscellaneousXPage 17 / 84

IN5400 Machine learning for image analysis, 2020 springtorch.Tensor classPyTorch ’s tensors are very similar to NumPy’s ndarraysbut they have a device, 'cpu', 'cuda', or 'cuda:X'they might require gradients t torch.tensor([1,2,3], device 'cpu',.requires grad False,dtype torch.float32) print(t.dtype)torch.float32 print(t.device)cpu print(t.requires grad)False t2 t.to(torch.device('cuda')) t3 t.cuda() # or you can use shorthand t4 t.cpu()See: https://pytorch.org/docs/stable/tensors.htmlXPage 18 / 84

IN5400 Machine learning for image analysis, 2020 springPytorch data types:Data type32-bit floating point64-bit floating point16-bit floating point8-bit integer (unsigned)8-bit integer (signed)16-bit integer (signed)32-bit integer (signed)64-bit integer (signed)Booleandtypetorch.float32 or torch.floattorch.float64 or torch.doubletorch.float16 or torch.halftorch.uint8torch.int8torch.int16 or torch.shorttorch.int32 or torch.inttorch.int64 or torch.longtorch.boolCPU sorGPU nversion in numpy and in PyTorch:new array old array.astype(np.int8) # numpy arraynew tensor old tensor.to(torch.int8) # torch tensorRemarks: Almost always torch.float32 or torch.int64 are used.Half does not work on CPUs and on many GPUs (hardware limitation).See: https://pytorch.org/docs/stable/tensors.htmlXPage 19 / 84

IN5400 Machine learning for image analysis, 2020 springNumpy-PyTorch functionsCreating arrays / tensor:eye: creating diagonal matrix / tensorzeros: creating tensor filled with zerosones: creating tensor filled with oneslinspace: creating linearly increasing valuesarange: linearly increasing integersFor instance: torch.eye(3, dtype torch.double)tensor([[1., 0., 0.],[0., 1., 0.],[0., 0., 1.]], dtype torch.float64) torch.arange(6)tensor([0, 1, 2, 3, 4, 5])XPage 20 / 84

IN5400 Machine learning for image analysis, 2020 springPyTorch functions, dimensionalityx.size()#* return tuple-like object of dimensions, old codesx.shape# return tuple-like object of dimensions, numpy stylex.ndim# number of dimensions, also known as .dim()x.view(a,b,.)#* reshapes x into size (a,b,.)x.view(-1,a)#* reshapes x into size (b,a) for some bx.reshape(a,b,.)# equivalent with .view()x.transpose(a,b)# swaps dimensions a and bx.permute(*dims)# permutes dimensions; missing in numpyx.unsqueeze(dim)# tensor with added axis; missing in numpyx.unsqueeze(dim 2)# (a,b,c) tensor - (a,b,1,c) tensor; missing in numpytorch.cat(tensor seq, dim 0) # concatenates tensors along dim# For instance: t torch.arange(6)tensor([0, 1, 2, 3, 4, 5]) t.reshape(2,3) # same as t.view(2,3 or t.view(2,-1)tensor([[0, 1, 2],[3, 4, 5]]) t.reshape(2,3).unsqueeze(1)tensor([[[0, 1, 2]],[[3, 4, 5]]]) t.reshape(2,3).unsqueeze(1).shapetorch.Size([2, 1, 3])XPage 21 / 84

IN5400 Machine learning for image analysis, 2020 springIndexingStandard numpy indexing works: t torch.arange(12).reshape(3,4)tensor([[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11]]) t[1,1:3]tensor([5, 6]) t[:,:] 0 # fill everything with 0, a.k.a. t.fill (0)tensor([[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]])XPage 22 / 84

IN5400 Machine learning for image analysis, 2020 springBroadcasting semanticsIf two tensors x, y are "broadcastable", the resulting tensor size is calculated as follows:If the number of dimensions of x and y are not equal, prepend 1 to the dimensions ofthe tensor with fewer dimensions to make them equal length.Then, for each dimension size, the resulting dimension size is the max of the sizes of xand y along that dimension.See: .htmlXPage 23 / 84

IN5400 Machine learning for image analysis, 2020 springBroadcasting semantics example# can line up trailing dimensions to make reading easier x torch.empty(5,1,4,1) y torch.empty( 3,1,1) (x y).size()torch.Size([5, 3, 4, 1])# but not necessary: x torch.empty(1) y torch.empty(3,1,7) (x y).size()torch.Size([3, 1, 7]) x torch.empty(5,2,4,1) y torch.empty(3,1,1) (x y).size()RuntimeError: The size of tensor a (2) must matchthe size of tensor b (3) at non-singleton dimension 1Be very careful, e.g. when you calculate loss!XPage 24 / 84

IN5400 Machine learning for image analysis, 2020 springMemory: Sharing vs CopyingSome operations share underlying memory, some create new tensors.Copy Data:torch.Tensor()torch.tensor()torch.clone()type castingShare Datatorch.as tensor()torch.from numpy()torch.view()torch.reshape()Most shape changing operators keep data.XPage 25 / 84

IN5400 Machine learning for image analysis, 2020 springMemory: Sharing vs CopyingHow to test it?create a tensorcopy/clone/view itmodify an elementcompare the elements a np.arange(6)# [0,1,2,3,4,5] t torch.from numpy(a) t[2] 11 ttensor([ 0, 1, 11, 3, 4, 5]) aarray([ 0, 1, 11, 3, 4, 5]) # Changed the underlying numpy array too! b a.copy() p t.clone() t[0] 7# a,t change, b, p remain intact.XPage 26 / 84

IN5400 Machine learning for image analysis, 2020 springCreating instances of torch.Tensor without data torch.eye(2)tensor([[1., 0.],[0., 1.]]) torch.zeros(2,2)tensor([[0., 0.],[0., 0.]]) torch.ones(2,2)tensor([[1., 1.],[1., 1.]]) torch.rand(2,2)tensor([[0.6849, 0.1091],[0.4953, 0.8975]]) torch.empty(2,2) # NEVER USE IT! Creates uninitialized tensor.tensor([[-2.2112e-16, 3.0693e-41],[-3.0981e-16, 3.0693e-41]]) torch.arange(6)tensor([0, 1, 2, 3, 4, 5])XPage 27 / 84

IN5400 Machine learning for image analysis, 2020 springInteracting with numpy import imageioimg imageio.imread('example.png')t torch.from numpy(a)out model(t)result out.numpy()####reading data from diskinput from numpy arrayprocessingconverting back to numpy# tuples, lists, arrays, etc. can be converted automatically: t2 torch.tensor(.)Remarks:arrays / tensors must be on the same device.only detached arrays can be converted to numpy (see later)if data types are not the same, casting might be needed (v1.1 or older)E.g. adding an integer and a float tensor together.XPage 28 / 84

IN5400 Machine learning for image analysis, 2020 springTorch.tensor functionalityCommon tensor operations:reshapemax/minshape/sizeetcArithmetic operationsAbs / round / sqrt / pow /etctorch.tensor’s support broadcastingIn-place operationsXPage 29 / 84

IN5400 Machine learning for image analysis, 2020 springTorch.tensor summaryVery similar to numpy (indexing, main functions)Every tensor has a device, a type, and a required grad attributeConversion and/or device transfer might be needed.In-place operations end in underscore, e.g. .fill ()Some operations create new tensors, some share data.Careful with the broadcasting semantics.Remark: not just tensors are similar to ndarrays,but torch functions are also similar to numpy functions.XPage 30 / 84

IN5400 Machine learning for image analysis, 2020 springProgressDeep learning frameworksPyTorchtorch.tensorComputational graph (reminder from last week)Automatic differentiation (torch.autograd)Data loading and preprocessing (torch.utils)Useful functions (torch.nn.functional)Creating the model (torch.nn)Optimizers (torch.optim)Save/load modelsMiscellaneousXPage 31 / 84

IN5400 Machine learning for image analysis, 2020 springWhat is a computational graph?XPage 32 / 84

IN5400 Machine learning for image analysis, 2020 springForward propagationXPage 33 / 84

IN5400 Machine learning for image analysis, 2020 springBackward propagationWhat if we want to get the derivative of f with respect to the x1?XPage 34 / 84

IN5400 Machine learning for image analysis, 2020 springProgressDeep learning frameworksPyTorchtorch.tensorComputational graphAutomatic differentiation ( torch.autograd )Data loading and preprocessing (torch.utils)Useful functions (torch.nn.functional)Creating the model (torch.nn)Optimizers (torch.optim)Save/load modelsMiscellaneousXPage 35 / 84

IN5400 Machine learning for image analysis, 2020 springAutogradAutograd - Automatic differentiation for all operations on TensorsStatic computational graph (TensorFlow 1.0)Dynamic computational graph (PyTorch)The backward graph is defined by the forward run!XPage 36 / 84

IN5400 Machine learning for image analysis, 2020 springExample 1 (autograd) import torch from torch import autograd x1 torch.tensor(2, requires grad True, dtype torch.float32) x2 torch.tensor(3, requires grad True, dtype torch.float32) x3 torch.tensor(1, requires grad True, dtype torch.float32) x4 torch.tensor(4, requires grad True, dtype torch.float32) # Forward propagation z1 x1 * x2 z2 x3 * x4 f z1 z2 df dx grad(outputs f, inputs [x1, x2, x3, x4]) df dx(tensor(3.), tensor(2.), tensor(4.), tensor(1.))XPage 37 / 84

IN5400 Machine learning for image analysis, 2020 springExample 1 (autograd) df dx grad(outputs f, inputs [x1, x2, x3, x4]) df dx(tensor(3.), tensor(2.), tensor(4.), tensor(1.))XPage 38 / 84

IN5400 Machine learning for image analysis, 2020 springLeaf tensorA «leaf tensor» is a tensor you created directly, not as the result of an operation. x torch.tensor(2) # x is a leaf tensor y x 1# y is not a leaf tensorRemember the computation graph:x1, x2, x3, x4 are the leaf tensors.XPage 39 / 84

IN5400 Machine learning for image analysis, 2020 springAutogradThe need for specifying all tensors is inconvenient. import torch from torch import autograd x1 torch.tensor(2, requires grad True, dtype torch.float32) x2 torch.tensor(3, requires grad True, dtype torch.float32) x3 torch.tensor(1, requires grad True, dtype torch.float32) x4 torch.tensor(4, requires grad True, dtype torch.float32) # Forward propagation z1 x1 * x2 z2 x3 * x4 f z1 z2 # df dx grad(outputs f, inputs [x1, x2, x3, x4]) # inconvenient f.backward()# that is better! print(f" f's derivative w.r.t. x1 is {x.grad}")tensor(3.)Chain rule is applied back to all the leaf tensors with requires grad Trueattribute.XPage 40 / 84

IN5400 Machine learning for image analysis, 2020 springXPage 41 / 84

IN5400 Machine learning for image analysis, 2020 springContext managers, decoratorsWe can locally disable/enable gradient calculation withtorch.no grad()torch.enable grad()or using the @torch.no grad @torch.enable grad decorators x torch.tensor([1], requires grad True) with torch.no grad():. y x * 2 y.requires gradFalse with torch.no grad():. with torch.enable grad():.y x * 2 y.requires gradTrueNote: Use «torch.no grad()» during inferenceXPage 42 / 84

IN5400 Machine learning for image analysis, 2020 springAutograd in depth (optional)https://www.youtube.com/watch?v d.htmlXPage 43 / 84

IN5400 Machine learning for image analysis, 2020 springExample 2 - Solving a linear problemGenerating data: a ref -1.5b ref 8noise 0.2 * np.random.randn(50)x np.linspace(1, 4, 50)y a ref * x b ref noiseDefining loss function: def MSE loss(prediction, target):.return (prediction-target).pow(2).mean()XPage 44 / 84

IN5400 Machine learning for image analysis, 2020 springExample 2 - Solving a linear problemData as torch tensors and the unknown variables:xx torch.tensor(x, dtype torch.float32)yy torch.tensor(y, dtype torch.float32)a torch.tensors(0, requires grad True, dtype torch.float32)b torch.tensors(5, requires grad True, dtype torch.float32)XPage 45 / 84

IN5400 Machine learning for image analysis, 2020 springExample 2 - Solving a linear problemTraining loop:number of epochs 1000learning rate 0.01for iteration in range(number of epochs):y pred a * xx bloss MSE loss(y pred, yy)loss.backward()with torch.no grad():a a - learning rate * a.gradb b - learning rate * b.grada.requires grad Trueb.requires grad Trueprint(a)print(b)XPage 46 / 84

IN5400 Machine learning for image analysis, 2020 springExample 2 - Solving a linear problemResult:tensor(-1.5061, requires grad True)tensor(8.0354, requires grad True)XPage 47 / 84

IN5400 Machine learning for image analysis, 2020 springOther useful torch.tensor functionsIf you want to detach a tensor from the graph, you can use « detach() »If you want to get a python number from a tensor, you can use « item() »But if you just take an element, it still will be part of the computational graph! x torch.tensor([2.5,3.5], requires grad True)tensor([2.5000, 3.5000], requires grad True) x.detach()tensor([2.5000, 3.5000]) x[0]# still part of the graph!tensor(2.5000, grad fn SelectBackward ) x[0].item()2.5 # a frequent line when you go back to numpy: x.detach().cpu().numpy()array([2.5, 3.5], dtype float32)XPage 48 / 84

IN5400 Machine learning for image analysis, 2020 springRemember our example workflowcreating datasetcreating a neural network (model)defining a loss functionloading samples (data loader)predicting with the modelcomparison of the prediction and the target (loss)backpropagation: calculating gradients from the errorupdating the model (optimizer)checking the loss: if low enough, stop trainingXPage 49 / 84

IN5400 Machine learning for image analysis, 2020 springProgressDeep learning frameworksPyTorchtorch.tensorComputational graphAutomatic differentiation (torch.autograd)Data loading and preprocessing ( torch.utils )Useful functions (torch.nn.functional)Creating the model (torch.nn)Optimizers (torch.optim)Save/load modelsMiscellaneousXPage 50 / 84

IN5400 Machine learning for image analysis, 2020 springData loading and preprocessingThe «torch.utils.data» package have two useful classes for loading and ils.data.DataLoaderFor more information visit:https://pytorch.org/tutorials/beginner/data loading tutorial.htmlXPage 51 / 84

IN5400 Machine learning for image analysis, 2020 springtorch.utils.data.DatasetTypical structure of the Dataset classimport torchclass ExampleDataset(torch.utils.data.Dataset):def init (self,params, *args,**kwargs):super(). init (*args,**kwargs)# do initalization based on the params,# e.g. load images, etc.self.data .def getitem (self, idx):# return sample indexed with 'idx'# must be tensor or dictionary of tensors!self.data[idx]def len (self):# return the number of samplesreturn self.data.shape[0]XPage 52 / 84

IN5400 Machine learning for image analysis, 2020 springtorch.utils.data.Dataset: regressionimport torchclass def init (self,N 50, m -3, b 2, *args,**kwargs):# N: number of samples, e.g. 50# m: slope# b: offsetsuper(). init (*args,**kwargs)self.x torch.rand(N)self.noise torch.rand(N)*0.2self.m mself.b bdef getitem (self, idx):y self.x[idx] * self.m self.b self.noise[idx]return {'input': self.x[idx], 'target': y}def len (self):return len(self.x)XPage 53 / 84

IN5400 Machine learning for image analysis, 2020 springtorch.utils.data.Dataset: imagesimport torchimport imageioclass ImageDataset(torch.utils.data.Dataset):def init (self, root, N, *args,**kwargs):super(). init (*args,**kwargs)self.input, self.target [], []for i in range(N):t imageio.imread(f'{root}/train {i}.png')t torch.from numpy(t).permute(2,0,1)l imageio.imread(f'target {i}.png')l torch.from rget.append(l)def getitem (self, idx):return {'input': self.input[idx], 'target': self.target[idx]}def len (self):return len(self.input)XPage 54 / 84

IN5400 Machine learning for image analysis, 2020 springtorch.utils.data.Datasetimport torchimport ImageDatasetdatapath 'data directory'myImageDataset ImageDataset(dataPath, 50)# iterating through the samplesfor sample in myImageDataset:input sample['input'].cpu() # or .cuda()target sample['target'].cpu() # or .to(device).Never ever use .cuda() in the dataset or data loaders!XPage 55 / 84

IN5400 Machine learning for image analysis, 2020 springtorch.utils.data.DataLoaderimport torchimport ImageDatasetdatapath 'data directory'myImageDataset ImageDataset(dataPath, 50)# iterating through the samplestrain loader DataLoader(dataset myImageDataset, batch size 32,shuffle False, num workers 2)for sample in train loader:.«DataLoader» is used to:Batching the datasetShuffling the datasetUtilizing multiple CPU cores/ threadsXPage 56 / 84

IN5400 Machine learning for image analysis, 2020 springData augmentetion(forward reference, not for today)modifying the dataset for better training(more robust, etc.)data set can have a a transform parameterDetails here:https://pytorch.org/tutorials/beginner/data loading tutorial.htmlXPage 57 / 84

IN5400 Machine learning for image analysis, 2020 springData augmentetion(forward reference, not for today)import torchimport imageioclass ImageDataset(torch.utils.data.Dataset):def init (self, root, N, transform None, *args,**kwargs):super(). init (*args,**kwargs)self.transform transform.def getitem (self, idx):sample {'input': self.input[idx], 'target': self.target[idx]}if self.transform:sample self.transform(sample)return sampledef len (self):return len(self.input)XPage 58 / 84

IN5400 Machine learning for image analysis, 2020 springData augmentetion(forward reference, not for today)class ImageDataset(torch.utils.data.Dataset):def init (self, root, N, transform None, *args,**kwargs):super(). init (*args,**kwargs)self.transform transform.def getitem (self, idx):sample {'input': self.input[idx], 'target': self.target[idx]}if self.transform:sample self.transform(sample)return sampledef len (self):return len(self.input)XPage 59 / 84

IN5400 Machine learning for image analysis, 2020 springData transformations(forward reference, not for today)import torchvision.transforms as Tcomposed 4),T.ToTensor()]).dataset Mydataset(., transform composed)# another version, needs different datasetdataset Mydataset(., transform {'input' : composed,'target' : None} )XPage 60 / 84

IN5400 Machine learning for image analysis, 2020 springProgressDeep learning frameworksPyTorchtorch.tensorComputational graphAutomatic differentiation (torch.autograd)Data loading and preprocessing (torch.utils)Useful functions ( torch.nn.functional )Creating the model (torch.nn)Optimizers (torch.optim)Save/load modelsMiscellaneousXPage 61 / 84

IN5400 Machine learning for image analysis, 2020 springtorch.nn.functionalThe «torch.nn.functional» package is the functional interface for Pytorch features.Most feature exist both as a function and as a class.Structural parts, or objects with internal state usually used as objectsStateless or simple expressions are usually used in functional form.Activation functions, losses, convolutions, etc. It is a huge module.import torchimport torch.nn as nnimport torch.nn.functional as Fx torch.rand(2,2)y F.relu(x)relu nn.ReLU() # creating the object firstz relu(x)# then using ity z# they should be the same# Similarly:mseloss nn.MSELoss()F.mseloss(.) mseloss(.)XPage 62 / 84

IN5400 Machine learning for image analysis, 2020 springProgressDeep learning frameworksPyTorchtorch.tensorComputational graphAutomatic differentiation (torch.autograd)Data loading and preprocessing (torch.utils)Useful functions (torch.nn.functional)Creating the model ( torch.nn )Optimizers (torch.optim)Save/load modelsMiscellaneousXPage 63 / 84

IN5400 Machine learning for image analysis, 2020 springCreating the modelA model is of a nn.Module class type. A model can contain other models. E.g. we cancreate the class “Model” based on the stacking nn.Modules of type nn.Linear()The nn.Module’s weights as called “Parameters”, and are similar to tensors with“requires grad True”.A nn.Module consists of an initialization of the Parameters and a forward function.class Model(nn.Module):def init (self):super(). init ()# structure definition and initializationdef forward(self, x):# actual forward propagationresult processing(x)return resultXPage 64 / 84

IN5400 Machine learning for image analysis, 2020 springCreating the modelclass Model(nn.Module):def init (self):super(). init ()# let's assume 28x28 input images,self.fc1 nn.Linear(in features self.fc2 nn.Linear(in features self.fc3 nn.Linear(in features e.g. MNIST characters28 * 28, out features 128, bias True)128, out features 64, bias True)64, out features 10, bias True)def forward(self, x):x F.relu(self.fc1(x))x F.relu(self.fc2(x))x self.fc3(x)return xXPage 65 / 84

IN5400 Machine learning for image analysis, 2020 springCreating the model, alternative wayclass Model2(nn.Module):def init (self):super(). init ()# let's assume 28x28 input images,self.fc1 nn.Linear(in features self.activation1 nn.ReLU()self.fc2 nn.Linear(in features self.activation2 nn.ReLU()self.fc3 nn.Linear(in features self.activation3 nn.ReLU()e.g. MNIST characters28 * 28, out features 128, bias True)128, out features 64, bias True)64, out features 10, bias True)def forward(self, x):x self.activation1(self.fc1(x))x self.activation2(self.fc2(x))x self.activation3(self.fc3(x))return xWhat is the difference?XPage 66 / 84

IN5400 Machine learning for image analysis, 2020 springnn.Module’s member functionsAccess information of a model: model Model() model.eval() # see below list(model.children())[Linear(in features 784, out features 128, bias True),Linear(in features 128, out features 64, bias True),Linear(in features 64, out features 10, bias True)]Children: the parameters and modules / layers defined in the constructor.Parts defined in the forward method will not be listed.Forward is called many times, expensive objects should not be recreated.Some layers as e.g. "dropout" and "batch norm" should operate differently during trainingand evaluation of the model. We can set the model in different state by the .train() and.eval() functions.XPage 67 / 84

IN5400 Machine learning for image analysis, 2020 springModel parameters for key, value in model.state dict().items():.print(f'layer {key:10s} feature shape {value.shape}')layerlayerlayerlayerlayerlayer bias peshapeshapeshapeshape torch.Size([128, 784])torch.Size([128])torch.Size([64, 128])torch.Size([64])torch.Size([10, 64])torch.Size([10])The .state dict() contains all the trainable parameters of the model,this is used for optimization and saving/restoring the model. (See later.)XPage 68 / 84

IN5400 Machine learning for image analysis, 2020 springAdvanced examples(Not part of the mandatory curriculum for today)Naive implementation of ReLU:class ReLU(nn.Module):def init (self):super(). init ()def forward(self, x):x x.clone()x[x 0] 0# implements max(x,0)return xYou can implement any activation function, any transformation,and autograd tracks everything.XPage 69 / 84

IN5400 Machine learning for image analysis, 2020 springAdvanced examples, part 2(Not part of the mandatory curriculum for today)Skip connections and residual connections:class SkipResBlock(nn.Module):def init (self):super(). init ()self.convolution nn.ConvX(.)self.convolution2 nn.ConvX(.)def forward(self, x):y self.convolution(x) x # residual blocky F.relu(y)z torch.cat(y,x, dim .) # skip connectionz self.convolut

Some tutorials use Python 2. Stick to Python 3.6 . IN5400 Machine learning for image analysis, 2020 spring . import numpy as np import torch import sys import matplotlib . 32-bit floating point torch.float32 or torch.float torch.FloatTensor torch.cuda.FloatTensor

Related Documents:

Introduction of Chemical Reaction Engineering Introduction about Chemical Engineering 0:31:15 0:31:09. Lecture 14 Lecture 15 Lecture 16 Lecture 17 Lecture 18 Lecture 19 Lecture 20 Lecture 21 Lecture 22 Lecture 23 Lecture 24 Lecture 25 Lecture 26 Lecture 27 Lecture 28 Lecture

Please follow the hands-on tutorial Chapter 5.2: PyTorch ROCm. Demo: Training a LSTM network on PyTorch 20. . level Machine learning frameworks on ROCm based systems High-level framework such as TensorFlow and PyTorch

Lecture 1: A Beginner's Guide Lecture 2: Introduction to Programming Lecture 3: Introduction to C, structure of C programming Lecture 4: Elements of C Lecture 5: Variables, Statements, Expressions Lecture 6: Input-Output in C Lecture 7: Formatted Input-Output Lecture 8: Operators Lecture 9: Operators continued

Lecture 1: Introduction and Orientation. Lecture 2: Overview of Electronic Materials . Lecture 3: Free electron Fermi gas . Lecture 4: Energy bands . Lecture 5: Carrier Concentration in Semiconductors . Lecture 6: Shallow dopants and Deep -level traps . Lecture 7: Silicon Materials . Lecture 8: Oxidation. Lecture

TOEFL Listening Lecture 35 184 TOEFL Listening Lecture 36 189 TOEFL Listening Lecture 37 194 TOEFL Listening Lecture 38 199 TOEFL Listening Lecture 39 204 TOEFL Listening Lecture 40 209 TOEFL Listening Lecture 41 214 TOEFL Listening Lecture 42 219 TOEFL Listening Lecture 43 225 COPYRIGHT 2016

Partial Di erential Equations MSO-203-B T. Muthukumar tmk@iitk.ac.in November 14, 2019 T. Muthukumar tmk@iitk.ac.in Partial Di erential EquationsMSO-203-B November 14, 2019 1/193 1 First Week Lecture One Lecture Two Lecture Three Lecture Four 2 Second Week Lecture Five Lecture Six 3 Third Week Lecture Seven Lecture Eight 4 Fourth Week Lecture .

Introduction to Quantum Field Theory for Mathematicians Lecture notes for Math 273, Stanford, Fall 2018 Sourav Chatterjee (Based on a forthcoming textbook by Michel Talagrand) Contents Lecture 1. Introduction 1 Lecture 2. The postulates of quantum mechanics 5 Lecture 3. Position and momentum operators 9 Lecture 4. Time evolution 13 Lecture 5. Many particle states 19 Lecture 6. Bosonic Fock .

HW2 is pure Python (numpy) but expects you to do (multivariate) calculus so you really understand the basics HW3 introduces PyTorch HW4 and HW5 use PyTorchon a GPU (Microsoft Azure) Libraries like PyTorch, Tensorflow(and Chainer, MXNet, CNTK, Keras, etc.)