티스토리 뷰

PyTorch는 대표적인 딥러닝 프레임워크 중 하나로, 빠른 연산과 GPU 가속을 지원합니다. 여기서는 PyTorch의 핵심 개념인 텐서(Tensor) 생성과 속성, 연산 방법에 대해 정리해보자.

 

 

텐서(tensor)란?

Pytorch의 기본 데이터 구조이다. Numpy의 ndarray와 유사하지만, GPU에서 실행 가능한 점이 큰 차이다.

import torch

 

tensor 생성 방법

1) 데이터로부터 직접 생성

torch.tensor()를 이용하여 직접 데이터를 생성할 수 있다.

x_data = torch.tensor([[1,2,3],[4,5,6]])
print(x_data) #tensor([[1, 2, 3],
                    # [4, 5, 6]])

 

2) Numpy 배열로부터 생성

torch.from_numpy()를 통해 생성된 ndarray를 tensor로 변환하여 생성할 수 있다.

np_array = np.array([[1,2,3],[4,5,6]])
x_np = torch.from_numpy(np_array)
print(x_data) #tensor([[1, 2, 3],
                    # [4, 5, 6]])

 

3) 무작위(random) 또는 상수(constant) 값으로 생성

print(torch.rand(4)) # tensor([0.7584, 0.0069, 0.4242, 0.4079])
print(torch.ones(5)) # tensor([1., 1., 1., 1., 1.])
print(torch.zeros((2,2))) #tensor([[0., 0.],
                                # [0., 0.]])
print(torch.arange(1,10,2)) # tensor([1, 3, 5, 7, 9])
print(torch.linspace(1,10,2)) # tensor([ 1., 10.])

 

4) 다른 텐서를 기반으로 생성

기존 텐서와 동일한 형태(shape)을 유지하며 값을 초기화한다.

print(torch.zeros_like(x_data)) # tensor([[0, 0, 0],
                                        # [0, 0, 0]])
print(torch.rand_like(x_data,dtype=torch.float)) # tensor([[0.1002, 0.6965, 0.7235],
                                                        #  [0.0243, 0.4645, 0.2306]])

 

* _like() 함수들은 기존 텐서의 모양(shape) 은 그대로, 값만 새롭게 채워지는 방식이다.

 

tensor의 속성

텐서의 속성은 텐서의 모양(shape), 자료형(datatype) 및 어느 장치에 저장되는지를 나타낸다.

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

print(x_data.shape)   # torch.Size([2, 3])
print(x_data.dtype)   # torch.int64
print(x_data.ndim)    # 차원 수: 2
print(x_data.numel()) # 전체 원소 수: 6
print(type(x_data))   # <class 'torch.Tensor'>

 

  • shape: 텐서의 구조나 크기를 나타냄
  • dtype: 텐서에 저장된 값들의 데이터 타입
  • ndim: 텐서의 차원 수. 2차원이므로 행렬 형태
  • numel(): 텐서에 포함된 전체 원소(숫자)의 개수
  • type: 파이썬 객체의 타입으로, PyTorch의 Tensor 클래스

 

 

tensor 연산

a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])

print(a + b)        
# 원소별 덧셈: tensor([5, 7, 9])

print(a - b)        
# 원소별 뺄셈: tensor([-3, -3, -3])

print(a * b)        
# 원소별 곱(element-wise multiplication): tensor([4, 10, 18])

print(a @ b)        
# 벡터 내적(dot product): 1*4 + 2*5 + 3*6 = 32

print(a @ a.T)      
# 자기 자신과의 내적 (벡터의 제곱합): 1*1 + 2*2 + 3*3 = 14

print(a.matmul(a.T))  
# 위와 동일한 결과: 14
# matmul()은 일반적으로 2D 이상의 행렬 곱셈에 주로 사용됨

 

 

NumPy ↔ PyTorch 변환

tensor = torch.ones(5)
ndarray = tensor.numpy()
ndarray = np.ones(5)
tensor = torch.from_numpy(n)

'파이썬 > Pytorch' 카테고리의 다른 글

[Pytorch] Dataset과 DataLoader  (2) 2025.08.14
[Pytorch] Tensor 인덱싱(Indexing), 슬라이싱(Slicing)  (1) 2025.08.13
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/04   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
글 보관함