Machine Learning

[pytorch] tensor 초기화 및 속성

텐서(Tensors)

텐서는 배열 및 행렬과 비슷한 특수 데이터구조로, Pytorch에서는 텐서를 사용하여 모델 입출력과 파라미터 값을 인코딩해서 사용한다.

Tensor는 numpy의 ndarray와 비슷하며 다른점이 있다면 GPU 기반에서 동작한다는 점이 다르다.

텐서의 initialization(초기화)

텐서를 초기화 하는 방법은 3가지 정도가 있다.

1. 직접 초기화 (데이터 타입은 자동 할당)

data = [[1,2],[3,4]]
x_data = torch.tensor(data)

print(x_data,type(x_data))

---------output----------
tensor([[1, 2],
        [3, 4]]) <class 'torch.Tensor'>

2. ndarray에서 초기화 ( tensor-ndarray bridge)

아래 두가지 방식으로 모두 numpy배열에서 tensor로 생성가능하다

  • torch.from_numpy(ndarray)
  • torch.tensor(ndarray)
data = [[1,2],[3,4]]
nd_arr = np.array(data)
x_data = torch.from_numpy(nd_arr)
print(x_data,type(x_data))
----------output----------
tensor([[1, 2],
        [3, 4]]) <class 'torch.Tensor'>

3. 다른 텐서를 사용해 초기화

다른 텐서를 통해 새로운 텐서를 생성할 수 있고, 이 경우에는 명시적으로 재정의하지 않는 한, 텐서의 속성(shape, datatype)은 생성에 사용한 다른 텐서의 속성을 그대로 유지한다.

x_original_data = torch.tensor([[1,2],[3,4]])
x_ones = torch.ones_like(x_original_data)
print(f'Ones Tensor: \t {x_ones}')

x_rand = torch.rand_like(x_original_data, dtype=torch.float) # 데이터타입 변경
print(f'Rand Tensor: \t {x_rand}')

----------output----------
Ones Tensor: 	 tensor([[1, 1],
        [1, 1]])
Rand Tensor: 	 tensor([[0.0922, 0.1121],
        [0.6457, 0.5841]])

4. 랜덤 값 사용 / 상수 값 사용

shape 차원만 정해주고 텐서를 생성한다.  shape 이란 텐서의 차원을 나타내는 튜플

shape = (2,3)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f'rand tensor:\t{rand_tensor}')
print(f'ones tensor:\t{ones_tensor}')
print(f'zeros tensor:\t{zeros_tensor}')

----------output----------
rand tensor:	tensor([[0.1211, 0.8171, 0.3957],
        [0.9410, 0.5810, 0.3276]])
ones tensor:	tensor([[1., 1., 1.],
        [1., 1., 1.]])
zeros tensor:	tensor([[0., 0., 0.],
        [0., 0., 0.]])

텐서의 attributes(속성)

텐서의 내장된 속성에는 아래 3가지가 있다.

  • shape
  • datatype
  • device
    # tensor 속성
    
    tensor = torch.rand(3,4)
    print(tensor)
    print(tensor.shape)
    print(tensor.dtype)
    print(tensor.device)
    ----------output----------
    tensor([[0.3388, 0.6769, 0.5536, 0.2925],
            [0.8297, 0.9153, 0.8371, 0.9256],
            [0.0756, 0.1835, 0.1438, 0.9926]])
    torch.Size([3, 4])
    torch.float32
    cpu​