반응형

This post is based on the pytorch toturial documentation. The address is below

tutorials.pytorch.kr/

My laptop is able to be typed only English,

So, this post is only English.

 

First of all, import print_function and torch

 

from __future__ import print_function

import torch

 

1) Define a tensor variables of pytorch

x = torch.empty(5,3) # empty tensor

x = torch.rand(5,3) # random tensor from 0 to 1

x = torch.zeros(5,3, dtype=torch.long) # zero tensor, the data type is 'long'

x = torch.tensor([5.5, 3]) # directly generate tensor with element values

 

2) Get the size of a pytorch tensor

x.size()

 

3) Plus and minus pytorch tensors

x = torch.randn_like(x,dtype=torch.float)

y = torch.rand(5,3)

print(x+y) # plus tensors with the mathematical representation

print(torch.add(x,y)) # plus tensor with a torch function

result = torch.empty(5,3)

print(torch.add(x,y,out=result)) # plus tensor with a torch function and save as a output variable

z = torch.zeros(5,3)

print(z.add_(x)) # plus tensor with a member function

 

4) Get some element of the tensor

print(x[:,1])

 

5) Transfer from/to the numpy array

a = torch.ones(5)

b = a.numpy() # to numpy

import numpy

a  np.ones(5)

b = torch.from_numpy(a) # from numpy

numpy.add(a,1,out=a)

print(a)

print(b)

 

6) Change the device object (CPU/GPU)

 

 

728x90

+ Recent posts