a = torch.tensor([[1,2],[3,4]], dtype=torch.float32)
print("shape:", a.shape, a.size()) #전체 shape
print("축별 크기:", a.shape[0], a.size(0)) # 측별 size
print("type:", a.type(), a.dtype)
print('차원크기:', a.dim(), a.ndim)
print('원소개수:', a.numel())
print("device:", a.device) # 이 값이 cpu에 의해 처리될 수 있는 (ram) 영역에 있다는 뜻
#Float, Double(32, 64bit 실수)/Int, Long(32, 64 bit 정수) type Tensor
b = torch.FloatTensor([1,3,7]) #float32
print(b.dtype)
c = torch.IntTensor([10,20,30]) # int64
print(c.dtype)
d = torch.DoubleTensor([1, 2, 3]) # torch.tensor([], dtype = torch.float64) 와 동일
print(d.dtype)
e = torch.LongTensor([10, 20, 30, 40]) # torch.tensor([], dtype = torch.int64)와 동일
print(e.dtype)
torch.arange(10) # 0~ 10-1
torch.arange(0, 1, 0.1) # 0~1, 증감: 0.1
torch.arange(10, 1, -1) # (reverse-역순) 10~1+1: 증감: -1
torch.linspace(0, 10, 5) # 0~ 10 등분한 값 5개
torch.linspace(0, 1, 11) # 0~1, 등분한 값 10개
device
파라미터를 이용해 설정tensor.to(device)
를 이용해 설정torch.cuda.is_available()
- nvida gpu 사용가능 여부torch.backends.mps.is_available()
- M1 사용가능 여부tensor.clone(): tensor를 복제
import torch
a = torch.tensor([[10,20],[10,20]])
print(a.shape)
a1, a2 = a[None, :], a.unsqueeze(dim=0)
print(a1.shape, a2.shape)
a3, a4 = a[:, :, None], a.unsqueeze(dim=-1)
print(a3.shape, a4.shape)
a5, a6 = a3[:,None,:,:], a3.unsqueeze(dim=1)
print(a5.shape, a6.shape)
# numpy에도 이 문법이 있음
t = torch.rand(3, 1, 3, 1)
print(t.shape)
r1 = t.squeeze() #축을 명시하지 않모두 제거
print(r1.shape)
r2 = t.squeeze(dim=1) # 특정 axis 제거
print(r2.shape)
r3 = t.squeeze(dim=[1,3]) # 여러 axis의 dummy 축 제거
print(r3.shape)
torch.cat([tensorA, tensorB, ...], dim=0)
tensor.transpose(axis1, axis2)
tensor.permute(axis1, axis2, axis3, ..)
import torch
a = torch.arange(10).reshape(2,5)
b = torch.arange(10,20).reshape(2,5)
c = torch.arange(50, 55)
print(a)
print(b)
print(c)
y = x + torch.randn((3,3))
# print(y)
print(torch.round(y)) # 반올림
print(torch.round(y, decimals=2)) # 소수점 둘째자리 이하에서 반올림
print(torch.floor(y)) # 내림
print(torch.ceil(y)) # 올림
@
연산자 또는 torch.matmul(tensor1, tensor2)
함수 이용import torch
x = torch.FloatTensor([[1, 2],
[3, 4],
[5, 6]
])
y = torch.FloatTensor([[1, 2],
[1, 2],
])
x.size(), y.shape
z1 = x @ y
z2 = torch.matmul(x, y)
print(z1.shape, z2.shape)
print(z1)
print(z2)
# Batch 행렬곱(Batch matrix muliplication) - bmm()
# x, y가 가지는 3개의 2차원 배열 간에 행렬곱을 처리
import torch
x = torch.FloatTensor(3,4,2)
y = torch.FloatTensor(3,2,5)
z = torch.bmm(x, y)
z.shape
print(torch.inf > 10, torch.inf < 10)
print(-torch.inf < 10, -torch.inf > 10)
print(torch.log(torch.tensor(-1))) # nan
print(torch.isnan(torch.tensor([1,2,torch.nan,3,4]))) # nan 여부 확인
print(torch.isinf(torch.tensor([1,2,3,4,torch.inf]))) # inf 여부 확인
requires_grad=True
로 설정되 있어야 함. (default: False)x = torch.tensor([1.], requires_grad=True)
# x = torch.tensor([1.])
# x.requires_grad = True
print(x)
print(x.requires_grad)