본문 바로가기

AI Tutorials (AI 학습 자료)

Python으로 AI 프로젝트 시작하기: Visual Studio + PyTorch + Poetry 활용 가이드


1. AI 프로젝트의 개요

어느사이엔가 인공지능(AI)은 다양한 산업 분야에서 혁신을 이끌고 있죠. 이 인공지능 앱이나 솔루션을 만드는 프로그래밍 언어로서 특히 Python이 AI 프로젝트 개발의 핵심 언어로 자리 잡았습니다. 본 글에서는 Visual Studio와 Poetry를 활용하여 PyTorch 기반 AI 프로젝트를 Windows 환경에서 구축하는 방법을 단계별로 설명드리겠습니다. Windows 기준입니다!

2. Windows 환경 설정 및 도구 설치

1) Visual Studio 설치 및 설정
1. Visual Studio 다운로드 및 설치
• 공식 사이트에서 Visual Studio Community 2022 버전을 다운로드합니다.
• 설치 시 Python 개발 워크로드를 선택하세요.
2. 확장 프로그램 추가
• 메뉴에서 확장 > 관리 > Python 검색 후 Python Extension을 설치합니다.
• 추가로 Jupyter Notebook 확장을 설치해 코드 실행 및 시각화 작업을 쉽게 할 수 있습니다.

2) Python 및 Poetry 설치
1. Python 설치
• Python 공식 사이트에서 최신 버전을 다운로드합니다.
• 설치 시 Add Python to PATH 옵션을 체크합니다.
2. Poetry 설치

(Windows PowerShell 실행)

Invoke-WebRequest -Uri https://install.python-poetry.org | python -



3. 환경 변수 설정 확인

poetry --version


3. 프로젝트 구조 설정 및 환경 구성

1) 새 프로젝트 생성

mkdir ai_project
cd ai_project
poetry init


2) 의존성 설치

poetry add torch torchvision torchaudio
poetry add matplotlib pandas scikit-learn


3) 가상환경 활성화

poetry shell


4. AI 프로젝트 실습 예제: 이미지 분류 모델 구축 (PyTorch)

1) 데이터 로드 및 전처리

import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt

# 데이터 변환 및 로드
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True)

# 데이터 시각화
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

dataiter = iter(trainloader)
images, labels = next(dataiter)

# 이미지 출력
def imshow(img):
    img = img / 2 + 0.5  # 비정규화
    plt.imshow(torchvision.utils.make_grid(img).permute(1, 2, 0))
    plt.show()

imshow(images)
print(' '.join(f'{classes[labels[j]]}' for j in range(4)))


2) 모델 정의 및 학습

import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

# 모델 정의
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 32, 3, 1)
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        self.fc1 = nn.Linear(64 * 6 * 6, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, 2, 2)
        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, 2, 2)
        x = torch.flatten(x, 1)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

net = Net()


3) 손실 함수 및 최적화 설정

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

# 모델 학습
for epoch in range(10):  # 10회 반복
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        inputs, labels = data
        optimizer.zero_grad()

        # forward, backward, optimize
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if i % 2000 == 1999:
            print(f'[{epoch + 1}, {i + 1}] loss: {running_loss / 2000:.3f}')
            running_loss = 0.0

print('학습 완료')


4) 성능 평가 및 결과 시각화

correct = 0
total = 0
with torch.no_grad():
    for data in trainloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print(f'정확도: {100 * correct / total:.2f}%')

plt.plot([i+1 for i in range(10)], [loss], label='Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()


5. 배포 및 운영 전략

1) Streamlit을 활용한 모델 배포

poetry add streamlit
streamlit run app.py

import streamlit as st
import torch

st.title('AI Image Classification')
uploaded_file = st.file_uploader("이미지를 업로드하세요.", type=["jpg", "png"])

if uploaded_file:
    # 이미지 처리 및 예측
    st.image(uploaded_file, caption='Uploaded Image', use_column_width=True)
    st.write("AI 예측 결과: 개")


6. 프로젝트 최적화 팁
1. GPU 활성화 확인

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'사용 장치: {device}')


2. 데이터 증강 및 전처리 강화
• 이미지 크기 조절, 회전, 노이즈 추가.
3. 전이 학습 활용
• ResNet, VGG 등 사전 학습된 모델을 활용해 빠른 성능 최적화.
4. 모델 경량화
• ONNX 변환 및 퀀타이제이션 적용으로 최적화.

7. 마무리 및 다음 단계

이번 글에서는 Poetry와 PyTorch를 활용한 AI 프로젝트 환경 설정부터 데이터 로드, 모델 개발, 평가, 배포까지 실습을 진행했습니다.


Q&A 섹션

Q1: PyTorch가 TensorFlow와 비교해 어떤 장점이 있나요?
A1: PyTorch는 코드 작성이 직관적이고 동적 계산 그래프(Define-by-Run)를 지원하여 실시간 디버깅이 쉽습니다.

Q2: Poetry로 가상환경을 관리하는 이유는 무엇인가요?
A2: 의존성 관리가 간편하며, 프로젝트별 가상환경 격리를 제공하여 안정적인 개발 환경을 유지할 수 있습니다.

Q3: Streamlit을 활용한 배포가 실제 서비스에도 적합한가요?
A3: Streamlit은 프로토타입 개발과 내부 데모용으로 적합하지만, 상용 배포는 Flask 또는 FastAPI가 더 적합합니다.

이 글을 참고하여 AI 프로젝트를 직접 시작해 보세요!