본문 바로가기

내가 보려고 만든 Pytorch

내가 공부하려 만든 Pytorch8(Type Casting ~ In-place Operation)

Type Casting

텐서에는 자료형이라는 것이 있습니다. 각 데이터형별로 정의되어져 있는데, 예를 들어 32비트의 부동 소수점은 torch.FloatTensor를, 64비트의 부호 있는 정수는 torch.LongTensor를 사용합니다. GPU 연산을 위한 자료형도 있습니다. 예를 들어 torch.cuda.FloatTensor가 그 예입니다. 그리고 이 자료형을 변환하는 것을 타입 캐스팅이라고 합니다.

 

예제

lt = torch.LongTensor([1, 2, 3, 4])
print(lt)
print(lt.float())

tensor([1, 2, 3, 4])
tensor([1., 2., 3., 4.])
bt = torch.ByteTensor([True, False, False, True])
print(bt)
print(bt.long())
print(bt.float())


tensor([1, 0, 0, 1], dtype=torch.uint8)
tensor([1, 0, 0, 1])
tensor([1., 0., 0., 1.])

 

Concatenate(cat)

두 텐서를 연결하는 방법

연결 방법은 한 가지만 있는 것이 아닙니다. torch.cat은 어느 차원을 늘릴 것인지를 인자로 줄 수 있습니다. 예를 들어 dim=0은 첫번째 차원을 늘리라는 의미를 담고있습니다.

 

1. 텐서 생성

x = torch.FloatTensor([[1, 2], [3, 4]])
y = torch.FloatTensor([[5, 6], [7, 8]])
print(x)
print(y)

tensor([[1., 2.],
        [3., 4.]])
tensor([[5., 6.],
        [7., 8.]])

2. cat(dim = 0)

z0 = torch.cat([x,y],dim=0)
print(z0)
print(z0.shape)
print(z0.dim())

tensor([[1., 2.],
        [3., 4.],
        [5., 6.],
        [7., 8.]])
torch.Size([4, 2])
2

3. cat(dim = 1)

z1 = torch.cat([x,y],dim=1)
print(z1)
print(z1.shape)
print(z1.dim())

tensor([[1., 2., 5., 6.],
        [3., 4., 7., 8.]])
torch.Size([2, 4])
2

 

 

Stacking

연결(concatenate)을 하는 또 다른 방법으로 스택킹(Stacking)이 있습니다. 스택킹은 영어로 쌓는다는 의미입니다. 때로는 연결을 하는 것보다 스택킹이 더 편리할 때가 있는데, 이는 스택킹이 많은 연산을 포함하고 있기 때문입니다.

 

1. 텐서 생성

x = torch.FloatTensor([1, 4])
y = torch.FloatTensor([2, 5])
z = torch.FloatTensor([3, 6])
print(x.shape)
print(y)
print(z)

torch.Size([2])
tensor([2., 5.])
tensor([3., 6.])

2. stack 사용(dim 사용 가능)

print(torch.stack([x,y,z]))
print(torch.cat([x.unsqueeze(0), y.unsqueeze(0), z.unsqueeze(0)], dim=0))

tensor([[1., 4.],
        [2., 5.],
        [3., 6.]])
        
tensor([[1., 4.],
        [2., 5.],
        [3., 6.]])
print(torch.stack([x, y, z], dim=1))

tensor([[1., 2., 3.],
        [4., 5., 6.]])

 

In-place Operation

덮어쓰기 연산

x = torch.FloatTensor([[1, 2], [3, 4]])
print(x.mul(2.)) # 곱하기 2를 수행한 결과를 출력
print(x) # 기존의 값 출력

tensor([[2., 4.],
        [6., 8.]])
tensor([[1., 2.],
        [3., 4.]])

x의 텐서 값이 바뀌는 것을 알 수 있다.

print(x.mul_(2.))  # 곱하기 2를 수행한 결과를 변수 x에 값을 저장하면서 결과를 출력
print(x) # 기존의 값 출력


tensor([[2., 4.],
        [6., 8.]])
tensor([[2., 4.],
        [6., 8.]])

 

출처 : https://wikidocs.net/52846