PyTorch의 텐서(tensor) 연산을 위한 핵심 모듈


(자료 : https://wikidocs.net/233963)
import torch
scalar = torch.tensor(3.14)
print(scalar.shape) # torch.Size([])
print(scalar.dim()) # 0
vector = torch.tensor([1, 2, 3, 4])
print(vector.shape) # torch.Size([4])
print(vector.dim()) # 1
matrix = torch.tensor([[1, 2, 3],
[4, 5, 6]])
print(matrix.shape) # torch.Size([2, 3])
print(matrix.dim()) # 2
tensor_3d = torch.randn(2, 3, 4) # (배치, 높이, 너비)
print(tensor_3d.shape) # torch.Size([2, 3, 4])
v1 = torch.tensor([1.0, 2.0, 3.0])
v2 = torch.tensor([4.0, 5.0, 6.0])
# 내적 (dot product)
dot = torch.dot(v1, v2) # 1*4 + 2*5 + 3*6 = 32
# 원소별 곱셈
elementwise = v1 * v2 # [4, 10, 18]
A = torch.tensor([[1.0, 2.0],
[3.0, 4.0]])
B = torch.tensor([[5.0, 6.0],
[7.0, 8.0]])
# 행렬 곱셈
C = torch.mm(A, B)
# 또는 C = A @ B
# 전치 (transpose)
A_T = A.T
이러한 구조를 통해 딥러닝에서 효율적인 수치 계산과 자동 미분이 가능함