Post

[PyTorch] 1. PyTorch Fundamentals and Setup

Introduction to Machine Learning (SWE4003)

[PyTorch] 1. PyTorch Fundamentals and Setup

이 포스팅 시리즈는 2026년 1학기 어수경교수님의 기계학습개론 수업 내용 및 「apxml-Pytorch」1을 바탕으로 정리한 글입니다.


파이토치 (PyTorch)

PyTorch는 Meta AI가 개발한 오픈소스 머신러닝 라이브러리이다.
딥러닝 모델 구축을 위한 완벽한 기능을 갖춘 프레임 워크이며 GPU support, 자동 미분등의 이유로 자주 사용된다.

환경설정

import torch
import numpy as np #나중에 사용

print(f"PyTorch Version: {torch.__version__}") # 파이썬 버전을 출력

# if-else문으로 cuda(GPU) 지원이 가능한 지 확인
if torch.cuda.is_available():
    device = torch.device("cuda")
else:
    device = torch.device("cpu")

print(f"Default device: {device}") 
1
2
3
결과>>
PyTorch Version: 2.10.0+cpu  
Default device: cpu

텐서 소개

텐서는 PyTorch에서 핵심적인 데이터 구조이다.

  • scalar: 67과 같은 단일 숫자는 0차원 텐서 또는 랭크 0 텐서이다.
  • vector: 1차원 숫자 목록 또는 배열로 [1, 2, 3]은 1차원 텐서 또는 랭크 1 텐서이다.
  • matrix: 2차원 숫자 [[1, 2], [3, 4]]는 2차원 텐서 또는 랭크 2 텐서이다.
  • 이를 확장하면 3차원, 4차원.. 으로도 가능하다.

텐서 생성하기

이제 다양한 방법으로 텐서를 만들어보자.

1. 파이썬 리스트로부터: 중첩된 파이썬 리스트를 사용해서 2×3 텐서를 만들어라

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

print("Tensor from list:")
print(tensor_from_list)
print(f"Shape: {tensor_from_list.shape}")
print(f"Data type: {tensor_from_list.dtype}")
1
2
3
4
5
6
결과>>
Tensor from list:  
tensor([[1, 2],  
        [3, 4]])  
Data type: torch.int64  
Shape: torch.Size([2, 2])  

2. 동일한 텐서를 만들되 데이터 타입을 명시적으로 32비트 부동소수점으로 설정해라.

tensor_float = torch.tensor(data, dtype=torch.float32) # 숫자 타입을 float32로 지정

print("\nTensor with float32 dtype:")
print(tensor_float)
print(f"Shape: {tensor_float.shape}")
print(f"Data type: {tensor_float.dtype}")
1
2
3
4
5
6
결과>>
Tensor with float32 dtype:  
tensor([[1., 2., 3.],  
        [4., 5., 6.]])  
Shape: torch.Size([2, 3])  
Data type: torch.float32   

3. 팩토리 함수 사용: 특정한 형태(shape)와 초기값을 가진 텐서를 생성하라

zeros_tensor = torch.zeros(3,4)

ones_tensor_int = torch.ones(2,2, dtype=torch.int32)

range_tensor = torch.arange(5)

rand_tensor = torch.rand(2,3)

print("\nZeros Tensor (3x4):")
print(zeros_tensor)
print("\nOnes Tensor (2x2, 32-bit int):")
print(ones_tensor_int)
print("\nRange Tensor (0 to 4):")
print(range_tensor)
print("\nRandom Tensor (2x3):")
print(rand_tensor)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
결과>>
Zeros Tensor (3x4):  
tensor([[0., 0., 0., 0.],  
        [0., 0., 0., 0.],  
        [0., 0., 0., 0.]])   

Ones Tensor (2x2, 32-bit int):  
tensor([[1, 1],  
        [1, 1]], dtype=torch.int32)  

Range Tensor (0 to 4):  
tensor([0, 1, 2, 3, 4])  

Random Tensor (2x3):  
tensor([[0.9874, 0.5358, 0.6103],  
        [0.5710, 0.9538, 0.8294]])

Reference

This post is licensed under CC BY 4.0 by the author.