English material follows Korean material.
개발자든 비개발자든 AI 열풍이 부는 한, 뚝딱뚝딱 만들어보고 배우는 과정은 꼭 필요하다고 생각이 든다.
처음 알파고가 나와서 바둑을 둘 때가 벌써 10년이 다됐나?
그 때만 해도 온갖 환경설정부터 애먹이던 인공지능 공부는 이제와선 거의 언제 어디서든 시도해볼 수 있게 되었다.
오늘은 구글 코랩을 활용한 튜토리얼을 작성해보려고 한다. ChatGPT 만만세.

PyTorch는 연구와 프로덕션에서 널리 사용되는 강력하고 유연한 딥 러닝 프레임워크입니다. 이 튜토리얼에서는 Google Colab을 사용하여 PyTorch의 기본 사항을 안내합니다. Google Colab은 무료이며 설정이 필요하지 않은 사용하기 쉬운 플랫폼입니다.
Google Colab을 사용하는 이유
Google Colab은 다음과 같은 이유로 초보자에게 이상적입니다:
- 딥 러닝 작업에 필수적인 GPU와 TPU에 무료로 접근할 수 있습니다.
- PyTorch가 사전 구성된 Python 환경을 제공합니다.
- 간단한 링크를 통해 코드를 쉽게 공유할 수 있습니다.
1단계: Google Colab 설정
1.1 Google Colab 접속
- 브라우저를 열고 Google Colab으로 이동합니다.
- Google 계정으로 로그인합니다.
- File > New Notebook을 클릭하여 새 노트북을 만듭니다.
1.2 런타임 구성 (선택사항)
- Runtime > Change runtime type을 클릭합니다.
- Hardware accelerator에서 GPU(또는 필요한 경우 TPU)를 선택합니다.
- Save를 클릭합니다.
2단계: PyTorch 설치
Google Colab에는 일반적으로 PyTorch가 사전 설치되어 있지만, 설치를 확인하거나 업데이트하는 것이 좋습니다.
2.1 PyTorch 설치 확인
PyTorch가 설치되어 있는지 확인하려면 Colab 셀에 다음 코드를 실행합니다:
import torch
print(torch.__version__)
2.2 PyTorch 설치
최신 버전의 PyTorch를 설치하려면 다음 명령을 사용하세요:
!pip install torch torchvision torchinfo
3단계: PyTorch 기본 이해하기
3.1 텐서
텐서는 PyTorch의 기본 데이터 구조로, NumPy 배열과 유사하지만 GPU 가속 기능이 있습니다.
텐서 생성
import torch
# Create a tensor
x = torch.tensor([[1, 2], [3, 4]])
print(x)
텐서 연산
# Basic operations
x = torch.tensor([1.0, 2.0, 3.0])
y = torch.tensor([4.0, 5.0, 6.0])
# Addition
z = x + y
print("Addition:", z)
# Multiplication
z = x * y
print("Multiplication:", z)
GPU 사용 (선택사항)
# Move tensor to GPU (optional)
if torch.cuda.is_available():
x = x.to('cuda')
print("Tensor on GPU:", x)
3.2 Autograd: 자동 미분
PyTorch의 autograd 모듈은 신경망 최적화에 필수적인 그래디언트 계산을 자동화합니다.
예시:
# Define a tensor with gradients enabled
x = torch.tensor(2.0, requires_grad=True)
y = x ** 2
# Compute gradients
y.backward()
print("Gradient:", x.grad)
4단계: 신경망 구축하기
PyTorch의 torch.nn 모듈을 사용하여 데이터를 분류하는 간단한 신경망을 만들어 보겠습니다.
4.1 모델 정의
import torch.nn as nn
from torchinfo import summary
class SimpleNN(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(2, 4)
self.fc2 = nn.Linear(4, 1)
self.relu = nn.ReLU()
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
x = self.sigmoid(x)
return x
model = SimpleNN()
summary(model)
4.2 손실 함수 및 옵티마이저 정의
# Loss function
criterion = nn.BCELoss()
# Optimizer
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
4.3 학습 루프
# Dummy data
inputs = torch.tensor([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0], [1.0, 0.0]])
labels = torch.tensor([[0.0], [1.0], [1.0], [0.0]])
# Training loop
epochs = 100
for epoch in range(epochs):
# Forward pass
outputs = model(inputs)
loss = criterion(outputs, labels)
# Backward pass
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch + 1) % 10 == 0:
print(f'Epoch [{epoch+1:4d}/{epochs:4d}], Loss: {loss.item():.4f}')
5단계: 모델 저장 및 로드
모델 저장하기
torch.save(model.state_dict(), 'model.pth')
print("Model saved.")
모델 로드하기
model = SimpleNN()
model.load_state_dict(torch.load('model.pth'))
print("Model loaded.")
6단계: TensorBoard를 사용한 시각화
TensorBoard는 메트릭, 모델 그래프 등을 시각화하는 도구입니다.
6.1 TensorBoard 설치
!pip install tensorboard
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter()
6.2 데이터 로그 기록
# Example: Logging loss
epoch = 1
loss = 0.5
writer.add_scalar('Loss/train', loss, epoch)
writer.close()
6.3 TensorBoard 실행
Colab 셀에서 다음 명령을 실행하세요:
%load_ext tensorboard
%tensorboard --logdir=runs
결론
이 튜토리얼에서는 PyTorch의 기본 사항을 다루고 Google Colab을 사용하는 방법을 보여주었습니다. 경험이 쌓이면 사용자 지정 데이터셋, 복잡한 신경망 아키텍처, 분산 학습과 같은 고급 주제를 탐구할 수 있습니다. PyTorch의 공식 문서와 커뮤니티는 추가 학습을 위한 훌륭한 리소스입니다.
즐거운 코딩 되세요!
For English:
PyTorch is a powerful and flexible deep learning framework widely used for research and production. This tutorial will guide you through the basics of PyTorch using Google Colab, a free and easy-to-use platform that requires no setup.
Why Use Google Colab for PyTorch?
Google Colab is ideal for beginners because:
- It offers free access to GPUs and TPUs, essential for deep learning tasks.
- It provides a pre-configured Python environment with PyTorch installed.
- You can easily share your code via a simple link.
Step 1: Setting Up Google Colab
1.1 Access Google Colab
- Open your browser and navigate to Google Colab.
- Sign in with your Google account if you haven't already.
- Create a new notebook by clicking on File > New Notebook.
1.2 Configure the Runtime
- Click on Runtime > Change runtime type.
- Under Hardware accelerator, select GPU (or TPU if needed).
- Click Save.
Step 2: Installing PyTorch
Although Google Colab usually comes with PyTorch pre-installed, it’s a good idea to confirm or update the installation.
2.1 Verify PyTorch Installation
Run the following code in a Colab cell to check if PyTorch is installed:
import torch
print(torch.__version__)
If PyTorch is installed, this will print the version number. If not, follow the next step.
2.2 Install PyTorch
Use the following command to install the latest version of PyTorch:
!pip install torch torchvision
Step 3: Understanding PyTorch Basics
3.1 Tensors
Tensors are the fundamental data structure in PyTorch, similar to NumPy arrays but with GPU acceleration capabilities.
Creating a Tensor
import torch
# Create a tensor
x = torch.tensor([[1, 2], [3, 4]])
print(x)
Tensor Operations
# Basic operations
x = torch.tensor([1.0, 2.0, 3.0])
y = torch.tensor([4.0, 5.0, 6.0])
# Addition
z = x + y
print("Addition:", z)
# Multiplication
z = x * y
print("Multiplication:", z)
Using GPU
# Move tensor to GPU
if torch.cuda.is_available():
x = x.to('cuda')
print("Tensor on GPU:", x)
3.2 Autograd: Automatic Differentiation
PyTorch’s autograd module automates the computation of gradients, essential for optimizing neural networks.
Example:
# Define a tensor with gradients enabled
x = torch.tensor(2.0, requires_grad=True)
y = x ** 2
# Compute gradients
y.backward()
print("Gradient:", x.grad)
Step 4: Building a Neural Network
Let’s create a simple neural network to classify data using PyTorch’s torch.nn module.
4.1 Define the Model
import torch.nn as nn
import torch.nn.functional as F
class SimpleNN(nn.Module):
def __init__(self):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(2, 4)
self.fc2 = nn.Linear(4, 1)
def forward(self, x):
x = F.relu(self.fc1(x))
x = torch.sigmoid(self.fc2(x))
return x
model = SimpleNN()
print(model)
4.2 Define the Loss Function and Optimizer
# Loss function
criterion = nn.BCELoss()
# Optimizer
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
4.3 Training Loop
# Dummy data
inputs = torch.tensor([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0], [1.0, 0.0]])
labels = torch.tensor([[0.0], [1.0], [1.0], [0.0]])
# Training loop
for epoch in range(100):
# Forward pass
outputs = model(inputs)
loss = criterion(outputs, labels)
# Backward pass
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch + 1) % 10 == 0:
print(f'Epoch [{epoch+1}/100], Loss: {loss.item():.4f}')
Step 5: Saving and Loading Models
Saving a Model
torch.save(model.state_dict(), 'model.pth')
print("Model saved.")
Loading a Model
model = SimpleNN()
model.load_state_dict(torch.load('model.pth'))
print("Model loaded.")
Step 6: Visualizing with TensorBoard
TensorBoard is a tool for visualizing metrics, model graphs, and more.
6.1 Install TensorBoard
!pip install tensorboard
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter()
6.2 Log Data
# Example: Logging loss
epoch = 1
loss = 0.5
writer.add_scalar('Loss/train', loss, epoch)
writer.close()
6.3 Launch TensorBoard
Run the following command in a Colab cell:
%load_ext tensorboard
%tensorboard --logdir=runs
Conclusion
This tutorial covers the basics of PyTorch and shows how to get started with Google Colab. As you gain more experience, you can explore advanced topics like custom datasets, complex neural network architectures, and distributed training. PyTorch’s official documentation and community are also excellent resources for further learning.
Happy coding!
'Computer > 인공지능' 카테고리의 다른 글
| PyTorch 튜토리얼 (3): 합성곱신경망 CNN 을 활용한 CIFAR-10 이미지 분류기 (8) | 2025.01.18 |
|---|---|
| PyTorch 튜토리얼 (2): 심층신경망 DNN 을 활용한 집값 예측 (7) | 2025.01.14 |