본문 바로가기
Python

[PyTorch] 생성 및 초기화, 기본 조작

by ds31x 2025. 3. 13.
728x90
반응형

NumPy에 대한 것은 다음을 참고:

2024.09.09 - [Python] - [NumPy] 생성 및 초기화, 기본 조작 (1)

 

[NumPy] 생성 및 초기화, 기본 조작 (1)

1. ndarray 생성하기 (=tensor생성하기)np.array ( seq [,dtype])list 나 tuple 등의 sequence 객체로부터 ndarray 생성.dtype : data type of element.float64 : default type in the numpy. *uint8 : unsigned int (8bit), the most commonly used for im

ds31x.tistory.com


0. tensor란?

https://dsaint31.tistory.com/891

 

[ML] Tensor: Scalar, Vector, Matrix.

Tensor 종류1. Scalar (0차원 tensor)하나의 숫자로 표현되는 가장 기본적인 형태.크기(magnitude)만을 가지며 방향은 없음.예시: 온도(25°C), 나이(20), 가격(1000원)# 파이썬/NumPy에서의 표현scalar = 5.02. Vector (

dsaint31.tistory.com


1. tensor 생성하기

import torch

torch.tensor( seq [,dtype])
  • listtuple 등의 sequence 객체로부터 ndarray 생성.
  • 또는 NumPy의 ndarray로부터 생성하는 경우도 많음.
  • dtype : data type of element.(keyword argument로 설정)
    • float32 : default type in the PyTorch tensor. 
    • uint8 : unsigned int (8bit), the most commonly used for image processing
    • int8 : signed int (8bit)
    • float64 : float (64bit) NumPy의 기본 dtype
    • int64 : default type in the PyTorch integer tensor.

예제는 다음과 같음.

In [36]: t = (1,2,3,4,5,6)

In [37]: a = torch.tensor(t)

In [38]: print(f"{type(t)=}")
type(t)=<class 'tuple'>

In [39]: print(f"{type(a)=}")
type(a)=<class 'torch.Tensor'>

참고: Primitive Type (or Unboxed Type)

https://dsaint31.tistory.com/456

 

[Programming] Primitive Data Type : C, C++, NumPy, Torch

Primitive Data Type이(Unboxed type)란?C, C++, NumPy, PyTorch, TensorFlow 등에서 사용되는numeric data type들은보통 unboxed type 이라고도 불리는 primitive data type들이다.unboxed type에서는할당된 메모리 bit들이 해당 numeri

dsaint31.tistory.com


2. tensor의 대표적인 attributes

2024.03.15 - [Python] - [DL] Tensor 객체의 attributes: ndim, shape, dtype

 

[DL] Tensor 객체의 attributes: ndim, shape, dtype

Class들Python에서Tensor 를 추상화하는 대표적인 class는 다음과 같음.NumPy의 ndarray: numpy.arrayPyTorch의 tensorTensorflow의 constant대표 Attributes이들의 대표적인 attributes는 다음과 같음.dtype: the datatype of elementn

ds31x.tistory.com


3. 기본 dtype

  • NumPy : float64 , integer의 경우엔 int64
  • PyTorch: float32, integer의 경우엔 int64
  • Tensorflow: float32, integer의 경우엔 int32
In [58]: np.array([]).dtype
Out[58]: dtype('float64')

In [59]: np.array([], dtype=int).dtype
Out[59]: dtype('int64')

In [60]: torch.tensor([]).dtype
Out[60]: torch.float32

In [61]: torch.tensor([],dtype=int).dtype
Out[61]: torch.int64

4. Multi-dimensional Tensor

In [50]: a = torch.tensor([range(i, i+3) for i in [2,4,6]])

In [51]: print(f"{a.ndim=}")
a.ndim=2

In [52]: print(f"{a.shape=}")
a.shape=torch.Size([3, 3])

In [53]: print(f"{a.itemsize=}")
a.itemsize=8

In [54]: print(f"{a.size()=}")
a.size()=torch.Size([3, 3])

In [55]: print(f"{a.dtype=}")
a.dtype=torch.int64

5. tensor를 특정값으로 초기화하여 생성.

zeros, ones, 그리고 full


5.1 zeros: 0으로 초기화하여 생성

In [63]: a = torch.zeros((3,2))

In [64]: print(f"{a.dtype=}")
a.dtype=torch.float32

In [65]: a
Out[65]:
tensor([[0., 0.],
        [0., 0.],
        [0., 0.]])

integer를 사용하는 경우.

In [66]: a = torch.zeros((3,2), dtype=int)

In [67]: print(f"{a.dtype=}")
a.dtype=torch.int64

In [68]: a
Out[68]:
tensor([[0, 0],
        [0, 0],
        [0, 0]])

5.2 ones: 1 로 초기화하여 생성

In [69]: a = torch.ones((3,2))

In [70]: print(f"{a.dtype=}")
a.dtype=torch.float32

In [71]: a
Out[71]:
tensor([[1., 1.],
        [1., 1.],
        [1., 1.]])

5.3 full: 특정값을 가지는 텐서 생성.

In [83]: a = torch.full((3,2),  255.)

In [84]: a
Out[84]:
tensor([[255., 255.],
        [255., 255.],
        [255., 255.]])

참고) fill_: 특정값을 지정하여 초기화 (in-place) 하는 method임.

  • tensor.fill_ 의 경우, 호출한 tensor instance에 특정 상수값으로 채우는 것은 가능함.
  • torch에선 메서드 등에서 _으로 끝날 경우 in-place 로 동작함을 의미.
  • 즉, 새로운 텐서를 생성하지 않고 기존 텐서를 직접 수정하므로 메모리 효율적임.
  • 단, 해당 변경된 instance를 반환함.
In [1]: import torch

In [2]: a = torch.zeros((3,2))

In [3]: a.fill_(400)
Out[3]:
tensor([[400., 400.],
        [400., 400.],
        [400., 400.]])

In [4]: a
Out[4]:
tensor([[400., 400.],
        [400., 400.],
        [400., 400.]])

In [5]: a.dtype
Out[5]: torch.float32

 

2025.03.13 - [Python] - [PyTorch] in-place 연산이란?

 

[PyTorch] in-place 연산이란?

in-place 연산이란?in-place 연산은 원본 데이터 구조를 직접 수정하여 별도의 복사본을 만들지 않는 연산 방식을 가리킴.메모리 효율성이 높지만,원본 데이터가 변경된다는 점을 주의해야 함.주의

ds31x.tistory.com

 


6. 기존의 tensor와 같은 shape를 가진 텐서 생성.

  • 기존의 ndarray 와 같은 shape를 가지는 ndarray생성 (torchtensor도 유사.)
    • zeros_like, ones_like, and full_like
  • tf 의 경우는 다음과 같음.
    • zeors_like, ones_like, and fill

dtype 를 지정하지 않는 경우,
원본 텐서와 같은 dtype를 가짐.


6.1 zeros_like

In [85]: s = torch.tensor([[1,2,3],[4,5,6]])

In [86]: print(f"{s.dtype=},{s.shape=}")
s.dtype=torch.int64,s.shape=torch.Size([2, 3])

In [87]: a = torch.zeros_like(s)

In [88]: print(f"{a.dtype=},{a.shape=}")
a.dtype=torch.int64,a.shape=torch.Size([2, 3])

6.2 ones_like

In [90]: s = torch.tensor([[1,2,3],[4,5,6]])

In [91]: print(f"{s.dtype=},{s.shape=}")
s.dtype=torch.int64,s.shape=torch.Size([2, 3])

In [92]: a = torch.ones_like(s)

In [93]: print(f"{a.dtype=},{a.shape=}")
a.dtype=torch.int64,a.shape=torch.Size([2, 3])

In [94]: a
Out[94]:
tensor([[1, 1, 1],
        [1, 1, 1]])

6.3 full_like

In [95]: s = torch.tensor([[1,2,3],[4,5,6]])

In [96]: print(f"{s.dtype=},{s.shape=}")
s.dtype=torch.int64,s.shape=torch.Size([2, 3])

In [97]: a = torch.full_like(s, 255.)

In [98]: print(f"{a.dtype=},{a.shape=}")
a.dtype=torch.int64,a.shape=torch.Size([2, 3])

In [99]: a
Out[99]:
tensor([[255, 255, 255],
        [255, 255, 255]])

7. 알아두면 유용한 생성 방법

7.1 arange

https://dsaint31.tistory.com/502

 

[Python] range and enumerate

range 란엄밀하게 애기하면, range 는 숫자들의 immutable sequence (=iterable)를 나타내는 built-in type이다.  즉, 흔히 built-in function으로 애기하는 range() 는 사실은 range class의 instance를 생성하는 생성자에

dsaint31.tistory.com

  • range 의 float 버전.
  • dtype 도 지정가능함.
In [102]: range(0,10,1)
Out[102]: range(0, 10)

In [103]: torch.arange(0,10,1)
Out[103]: tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [104]: range(0,1,0.1)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[104], line 1
----> 1 range(0,1,0.1)

TypeError: 'float' object cannot be interpreted as an integer

In [105]: torch.arange(0,1,.1)
Out[105]:
tensor([0.0000, 0.1000, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000, 0.7000, 0.8000,
        0.9000])

7.2 linspace

range 나 arange에서 step을 지정하는 것과 달리, point의 갯수를 지정함.

In [106]: a = torch.linspace(1,5,6)

In [107]: print(f"{a.dtype=},{a.shape=}")
a.dtype=torch.float32,a.shape=torch.Size([6])

In [108]: a
Out[108]: tensor([1.0000, 1.8000, 2.6000, 3.4000, 4.2000, 5.0000])

7.3 Identity Matrix

In [109]: a = torch.eye(3)

In [110]: a
Out[110]:
tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])

7.4 초기화 없이 생성.

In [111]: a = torch.empty((3,3))

In [112]: a
Out[112]:
tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])

8. 난수로 구성된 Tensor

2024.03.29 - [Python] - [DL] Tensor: Random Tensor 만들기 (NumPy, PyTorch)

 

[DL] Tensor: Random Tensor 만들기 (NumPy, PyTorch)

Tensor: Random Tensor 만들기 (NumPy, PyTorch)Random value를 얻는데 이용되는 Probability Distribution에 따라 크게 2가지로 나눌 수 있음.Uniform DistributionNormal Distribution 0. Uniform DistributionRandom Variable이 가질 수

ds31x.tistory.com


9. dtype 나 shape 변경하기

아래를 먼저 읽어서 Tensor에서의 메모리 관리를 이해하고 살펴볼 것.

2024.03.21 - [Python] - [DL] Storage: PyTorch 텐서를 위한 메모리 관리

 

[DL] Storage: PyTorch 텐서를 위한 메모리 관리

Storage는 Tensor 인스턴스의 실제 데이터가 저장되는 1D Numerical Array를 관리함. 여러 Tensor 인스턴스들이 같은 storage를 공유할 수 있음. Storage는 memory에서 contiguous data block를 관리하며, 컴퓨터의 memory

ds31x.tistory.com


2024.03.15 - [Python] - [DL] Tensor: dtype 변경(casting) 및 shape 변경.

 

[DL] Tensor: dtype 변경(casting) 및 shape 변경.

Tensor를 추상화하고 있는 class로는numpy.array: numpy의 ndarraytorch.tensortensorflow.constant: (or tensorflow.Variable)이 있음. 이들은 Python의 sequence types과 달리 일반적으로 다음과 같은 특징을 지님.데이터들이

ds31x.tistory.com

2025.03.13 - [Python] - [PyTorch] flatenning - Tensor's methods

 

[PyTorch] flatenning - Tensor's methods

PyTorch에서 Multi-dimensional tensor 를 1차원(1D)으로 변환을 지원하는 여러 방법(주로 method.)이 있음.단순히 view를 제공하는지 아니면 복사본인지에 대한 이해가 필요함.NumPy의 ndarray의 경우는 다음을

ds31x.tistory.com


10. ndarray 와 tensor간 변환

2024.03.15 - [Python] - [DL] Tensor 간의 변환: NumPy, PyTorch, TensorFlow

 

[DL] Tensor 간의 변환: NumPy, PyTorch, TensorFlow

pytorch와 numpy의 경우, 텐서를 추상화하고 있는 tensor와 ndarray 를 제공하며, 이 둘은 zero-copy interoperability를 가진다고 말할 수 있을 정도로 상호호환이 가능하다. TensorFlow도 numpy와 상당히 연관되어

ds31x.tistory.com

 

 

'Python' 카테고리의 다른 글

[PyTorch] in-place 연산이란?  (0) 2025.03.13
[PyTorch] flattenning - Tensor's methods  (0) 2025.03.13
[Ex] PySide6  (0) 2025.03.11
[Py] dis 모듈 - Python  (1) 2025.03.11
[DL] Tensor 다루기 - PyTorch 중심  (0) 2025.03.07