Tensor

pppanghyun·2022년 7월 12일
0

Pytorch 기본

목록 보기
1/21

텐서 만들기

Pytorch 프레임워크를 사용해서 GPU 연산을 수행하기 위해서는 데이터를 텐서(Tensor) 형태로 만들어야 함. (Type은 다르지만 Numpy 배열과 유사함)

1. 기본적인 텐서 만드는 법

# 라이브러리 불러오기
import torch # Pytorch를 사용하기 위한 기본 라이브러리.
import numpy as np # Numpy를 사용하기 위한 기본 라이브러리. 

1. # 5x4 빈 행렬 생성 (이전에 메모리에 기억된 데이터가 나옴)
x = torch.empty(5,4) 
print(x)

#result
tensor([[1.6426e-35, 0.0000e+00, 7.0065e-44, 7.0065e-44],
        [6.3058e-44, 6.7262e-44, 7.7071e-44, 6.3058e-44],
        [6.8664e-44, 7.0065e-44, 1.1771e-43, 6.8664e-44],
        [7.4269e-44, 8.1275e-44, 7.0065e-44, 7.4269e-44],
        [8.1275e-44, 7.0065e-44, 7.9874e-44, 6.4460e-44]])
        
# 1로 채워진 (3x3) tensor 생성
torch.ones(3,3)

#result
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])
        
# 0으로 채워진 (1x2) tensor 생성
torch.zeros(2)

#result
tensor([0., 0.])

# torch.rand(4,5) # 4x5 랜덤 행렬

tensor([[0.8771, 0.7499, 0.4172, 0.9811, 0.0622],
        [0.4599, 0.5590, 0.3096, 0.6131, 0.6815],
        [0.9466, 0.0214, 0.8590, 0.8170, 0.7559],
        [0.7735, 0.1855, 0.6351, 0.5584, 0.2366]])

2. 리스트, 넘파이 형태의 데이터를 텐서를 만드는 방법

data = [4,5] # 리스트 생성
r = np.array([4,5,6,7]) # 넘파이 배열 생성

# 1. 리스트 to Tensor
torch.tensor(data) # 리스트를 텐서로 
type(torch.tensor(data)) 

#result
torch.Tensor

# 넘파이 to Tensor
torch.tensor(r) #넘파이 배열을 텐서로
type(torch.tensor(r))

#result
torch.Tensor

3. 텐서의 크기와 타입 확인하는 법

x.size()[1] # 텐서의 크기를 확인
x.shape # 텐서의 크기를 확인
type(x) # 텐서뿐만 아니라 데이터 형태 반환

4. 텐서의 덧셈

x = torch.rand(2,2) # 2x2 랜덤 행렬
y = torch.rand(2,2) # 2x2 랜덤 행렬
print(x)
print(y)

#result 
tensor([[0.2600, 0.0782],
        [0.8999, 0.1646]])
tensor([[0.0476, 0.4163],
        [0.8533, 0.9434]])
        
x+y # 두 텐서의 합1
torch.add(x,y) # 두 텐서의 합2
y.add(x) # 두 텐서의 합의3 (y에 x를 더한다는 의미다

#result
tensor([[0.3076, 0.4945],
        [1.7533, 1.1080]])

* y.add_는 y에 x를 더한 값을 y에 대체.(inplace 방식)
print("원래 y: ", y)
y.add_(x)
print("y=y+x: ",y)

#result
원래 y:  tensor([[0.0476, 0.4163],
        [0.8533, 0.9434]])
y=y+x:  tensor([[0.3076, 0.4945],
        [1.7533, 1.1080]]) # inplace 된 것

5. 텐서의 크기 변환

x = torch.rand(8,8) # 8x8 랜덤 행렬
print(x.size())

#result
torch.Size([8, 8])

a = x.view(64) # 크기를 바꿔주는 view 8x8 -> 64
print(a.size())

#result
torch.Size([64])

b = x.view(-1,4,4) # -1은 원래 크기가 되게 하는 값 8x8 -> -1x4x4 즉, 4x4x4이다.
print(b.size()) 

torch.Size([4, 4, 4])

(-1은 원래 크기가 되게 하는 값이 자동으로 지정되기 때문에 한 번만 사용 가능)

6. 텐서에서 넘파이

x = torch.rand(3,3)
y = x.numpy() # .numpy()로 매우 간단하게 넘파이 배열로 만들 수 있다.
print(y)
type(y)

#result
[[0.6187619  0.41163927 0.32872796]
 [0.01589459 0.56967413 0.85498124]
 [0.8282429  0.2654531  0.10821968]]
 
 numpy.ndarray

7. 단일 텐서에서 값으로 뽑아내기 .item()

x = torch.ones(1)
print(x)
print(x.item())

#result
tensor([1.])
1.0
profile
pppanghyun

0개의 댓글