텐서 (Tensor)
- 텐서는 배열 또는 행렬과 매우 유사한 데이터 구조
import torch
import numpy as np
텐서 만들기
- 입력 받은 객체를 텐서 객체로 변경
- 입력 받은 객체의 자료형을 유지
>>> data = [
>>> [1,2,3],
>>> [4,5,6]
>>> ]
>>> x = torch.tensor(data)
>>> x
tensor([[1, 2, 3],
[4, 5, 6]])
>>> type(x)
torch.Tensor
- 텐서의 속성
# int64가 기본값
>>> x.dtype
torch.int64
>>> x.shape
torch.Size([2, 3])
>>> x.size()
torch.Size([2, 3])
>>> x.device
device(type='cpu')
# 64에서 32로 전환
>>> arr = np.array(data,dtype="int32")
>>> torch.tensor(arr)
tensor([[1, 2, 3],
[4, 5, 6]], dtype=torch.int32)
>>> data = [
>>> [1., 2., 3.],
>>> [4., 5., 6.]
>>> ]
>>> arr = np.array(data)
>>> arr
array([[1., 2., 3.],
[4., 5., 6.]])
>>> torch.tensor(arr)
tensor([[1., 2., 3.],
[4., 5., 6.]], dtype=torch.float64)
- Tensor 클래스
- 입력 데이터를 텐서 객체에 반환
- 데이터 타입을 float32 형태로 변경해줌
>>> x = torch.Tensor(arr)
>>> x
tensor([[1., 2., 3.],
[4., 5., 6.]])
>>> x.dtype
torch.float32
- from_numpy 함수
- ndarry를 텐서 객체로 변환
- 원본 ndarray와 메모리를 공유하기 때문에 텐서가 변경되면 원본도 변경된다
>>> arr = np.array(data)
>>> arr
array([[1., 2., 3.],
[4., 5., 6.]])
>>> x = torch.from_numpy(arr)
>>> x
tensor([[1., 2., 3.],
[4., 5., 6.]], dtype=torch.float64)
>>> x[0,0] = 0
>>> arr
array([[0., 2., 3.],
[4., 5., 6.]])
텐서 ndarray로 변경하기
>>> x.numpy()
array([[0., 2., 3.],
[4., 5., 6.]])
>>> np.array(x)
array([[0., 2., 3.],
[4., 5., 6.]])
indexing, slicing, masking
>>> data = [
>>> [1,2,3],
>>> [4,5,6],
>>> [7,8,9]
>>> ]
>>> x = torch.Tensor(data)
>>> x
tensor([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
>>> x[[0,1]]
tensor([[1., 2., 3.],
[4., 5., 6.]])
>>> x[[2,0]]
tensor([[7., 8., 9.],
[1., 2., 3.]])
랜덤한 값을 가지는 텐서 생성
- rand 함수
- 0~1 사이의 값을 랜덤하게 생성
>>> torch.manual_seed(42)
>>> torch.rand(5)
tensor([0.8823, 0.9150, 0.3829, 0.9593, 0.3904])
#2 차원
>>> x = torch.rand([2,3])
>>> x
tensor([[0.1330, 0.7672, 0.6757],
[0.6625, 0.2297, 0.9545]])
#3 차원
>>> x = torch.rand([2,3,4])
>>> x
tensor([[[0.9487, 0.2994, 0.5494, 0.9824],
[0.7265, 0.2333, 0.1539, 0.1180],
[0.8102, 0.1296, 0.8121, 0.0165]],
[[0.8171, 0.3351, 0.2932, 0.6921],
[0.8504, 0.5031, 0.1680, 0.3694],
[0.3453, 0.3983, 0.3679, 0.6136]]])
- rand_like 함수
- 입력 데이터의 shape에 맞춰 0 ~ 1 사이 값을 생성
>>> torch.rand_like(x)
tensor([[0.6099, 0.5643, 0.0594],
[0.7099, 0.4250, 0.2709]])
- torch.randn 함수
- 평균이 0이고 분산이 1인 랜덤한 텐서를 생성
>>> torch.randn(5)
tensor([-1.6172, 0.6904, 0.9998, -2.5733, -0.7208])
>>> x = torch.randn([2,3])
>>> x
tensor([[-0.7698, 0.0366, 0.3688],
[-0.4128, -0.2120, -0.3083]])
>>> torch.randn(100000).mean(), torch.randn(100000).var()
(tensor(-0.0049), tensor(1.0025))
>>> torch.randn_like(x)
tensor([[ 1.0109, -0.6049, 1.0498],
[-0.5017, -0.3310, -1.2828]])
- randint 함수
- 지정한 범위 내에 정수를 지정한 shape만큼 랜덤하게 텐서를 생성
>>> torch.randint(1,10,[3,4])
tensor([[5, 7, 7, 7],
[7, 6, 5, 7],
[9, 3, 7, 8]])
>>> x
tensor([[-0.7698, 0.0366, 0.3688],
[-0.4128, -0.2120, -0.3083]])
>>> torch.randint_like(x,1,10)
tensor([[6., 9., 6.],
[1., 8., 4.]])
지정한 값을 가지는 텐서 생성
- arrange 함수
>>> torch.arange(1,10)
tensor([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> torch.arange(10)
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> torch.arange(0,10,2)
tensor([0, 2, 4, 6, 8])
- ones 함수
>>> torch.ones([2,3])
tensor([[1., 1., 1.],
[1., 1., 1.]])
>>> x
tensor([[-0.7698, 0.0366, 0.3688],
[-0.4128, -0.2120, -0.3083]])
>>> torch.ones_like(x)
tensor([[1., 1., 1.],
[1., 1., 1.]])
- zeros 함수
>>> torch.zeros([2,3])
tensor([[0., 0., 0.],
[0., 0., 0.]])
>>> torch.zeros_like(x)
tensor([[0., 0., 0.],
[0., 0., 0.]])
- full 함수
>>> torch.full([2,3],True)
tensor([[True, True, True],
[True, True, True]])
>>> torch.full_like(x,3.14)
tensor([[3.1400, 3.1400, 3.1400],
[3.1400, 3.1400, 3.1400]])
텐서 장치 이동
>>> device = "cuda" if torch.cuda.is_available() else "cpu" # GPU 사용가능한지 확인
>>> device
'cpu'
>>> x.to(device)
tensor([[-0.7698, 0.0366, 0.3688],
[-0.4128, -0.2120, -0.3083]])
텐서 연산하기
>>> data = [
>>> [1,2,3],
>>> [4,5,6]
>>> ]
>>> x1 = torch.Tensor(data)
>>> x1
tensor([[1., 2., 3.],
[4., 5., 6.]])
>>> data = [
>>> [1,1,1],
>>> [2,2,2]
>>> ]
>>> x2 = torch.Tensor(data)
>>> x2
tensor([[1., 1., 1.],
[2., 2., 2.]])
>>> torch.mul(x1,x2)
tensor([[ 1., 2., 3.],
[ 8., 10., 12.]])
>>> x1 * x2
tensor([[ 1., 2., 3.],
[ 8., 10., 12.]])
>>> torch.sub(x1,x2)
tensor([[0., 1., 2.],
[2., 3., 4.]])
# torch.add
>>> x1 + x2
tensor([[2., 3., 4.],
[6., 7., 8.]])
# torch.div
>>> x1 / x2
tensor([[1.0000, 2.0000, 3.0000],
[2.0000, 2.5000, 3.0000]])
# 브로드 캐스팅!!
>>> x1 * 2
tensor([[ 2., 4., 6.],
[ 8., 10., 12.]])
>>> x1
tensor([[1., 2., 3.],
[4., 5., 6.]])
>>> data = [
>>> [1,1],
>>> [2,2],
>>> [3,3]
>>> ]
>>> x3 = torch.Tensor(data)
>>> x3
tensor([[1., 1.],
[2., 2.],
[3., 3.]])
# 행렬곱
>>> torch.matmul(x1,x3)
tensor([[14., 14.],
[32., 32.]])
>>> x1 @ x3
tensor([[14., 14.],
[32., 32.]])
집계하기
>>> x = x1
>>> x
tensor([[1., 2., 3.],
[4., 5., 6.]])
>>> torch.mean(x)
tensor(3.5000)
>>> torch.mean(x,axis=0)
tensor([2.5000, 3.5000, 4.5000])
>>> torch.mean(x,dim=0)
tensor([2.5000, 3.5000, 4.5000])
dim
차원축
- 2차원에서 dim=0은 아래방향(행방향)쪽
- dim=1은 가로방향(열방향)쪽
# std
>>> torch.std(x)
tensor(1.8708)
>>> torch.std(x, dim = 0)
tensor([2.1213, 2.1213, 2.1213])
# var , sum, min, max
# 귀찮아서 생략
텐서 차원 변경
- view 메서드
- 원소의 순서를 유지하면서 차원을 변경
- 원본 텐서와 메모리를 공유해서 반환된 텐서의 데이터를 변경시, 원본 텐서도 변경된다
>>> x
tensor([[1., 2., 3.],
[4., 5., 6.]])
>>> x_view = x.view(3,2)
>>> x_view
tensor([[1., 2.],
[3., 4.],
[5., 6.]])
>>> x_view[0,0] = 0
>>> x_view
tensor([[0., 2.],
[3., 4.],
[5., 6.]])
>>> x
tensor([[0., 2., 3.],
[4., 5., 6.]])
- reshape 메서드
- view 메서드와 비슷
- 가능한 view 메서드처럼 반환하고, 안되면 copy 해서 반환하기
>>> x
tensor([[0., 2., 3.],
[4., 5., 6.]])
>>> x_reshape = x.reshape(3,2)
>>> x_reshape
tensor([[1., 2.],
[3., 4.],
[5., 6.]])
>>> x_reshape[0,1] = 0
>>> x_reshape
tensor([[0., 2.],
[3., 4.],
[5., 6.]])
>>> x
tensor([[0., 2., 3.],
[4., 5., 6.]])
- 복사하기
>>> x_cp = x.clone()
- transpose 메서드
- 차원 맞바꾸기
- 두개의 차원 가능
>>> x = torch.Tensor(data)
>>> x
tensor([[1., 2., 3.],
[4., 5., 6.]])
>>> x.transpose(0,1)
tensor([[1., 4.],
[2., 5.],
[3., 6.]])
- permute 메서드
- 여러개 차원 맞바꾸기
>>> arr = np.arange(1,25).reshape(2,3,4)
>>> arr.shape
(2, 3, 4)
텐서 합치기
>>> ones_tensor = torch.ones(2,3)
>>> zeros_tensor = torch.zeros(2,3)
>>> torch.cat([ones_tensor,zeros_tensor],dim=0)
tensor([[1., 1., 1.],
[1., 1., 1.],
[0., 0., 0.],
[0., 0., 0.]])
>>> torch.cat([ones_tensor,zeros_tensor],dim=1)
tensor([[1., 1., 1., 0., 0., 0.],
[1., 1., 1., 0., 0., 0.]])