본문 바로가기

pytorch

파이토치 텐서 생성

import torch
import numpy as np

np.set_printoptions(precision=3)

a = [1,2,3]
b = np.array([4,5,6], dtype=np.int32)
t_a = torch.tensor(a)
t_b = torch.from_numpy(b)

print(a, b)

텐서의 직접 생성과, 넘파이 배열의 토치 변환 수행

 

텐서의 수학 연산 적용

import torch

torch.manual_seed(1)

t1 = 2 * torch.rand(5, 2) - 1
t2 = torch.normal(mean=0, std = 1, size = (5, 2))

t3 = torch.multiply(t1, t2)

print(t3)

 

텐서의 분리와 연결

import torch

torch.manual_seed(1)

t = torch.rand(6)

print(t)

t_split = torch.chunk(t, 3)

[print(item.numpy()) for item in t_split]

크기를 임의로 지정 가능

t = torch.rand(5)

t_split = torch.split(t, split_size_or_sections=[3,2])
[print(item.numpy()) for item in t_split]

 

텐서의 연결

A = torch.ones(3)
B = torch.zeros(3)
S = torch.stack([A, B], axis=1)
print(S)

>>>
tensor([[1., 0.],
        [1., 0.],
        [1., 0.]])

cat 의 경우 1D 텐서의 연결, 

stack 의 경우 동일한 크기일 시 2D 텐서로 확장 가능