728x90

(TensorFlow와 Keras 라이브러리 기반)

- 콜백 사용하기
콜백은 학습 중에 정기적으로 호출되는 함수로, 학습 과정을 모니터링하고 제어하는 데 사용된다. tf.keras.callbacks 모듈을 사용하여 로그를 출력하는 콜백을 만들면 다음과 같다.

# 콜백 정의
class CustomCallback(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs=None):
        print("Epoch {}: loss = {:.4f}, accuracy = {:.4f}".format(epoch, logs['loss'], logs['accuracy']))

# 모델 학습
history = model.fit(x_train, y_train,
                    epochs=10,
                    batch_size=32,
                    validation_split=0.2,
                    callbacks=[CustomCallback()])

 

 

- 루프를 사용하여 직접 출력하기
학습의 각 에포크 또는 배치에서 직접 로그를 출력하는 방법이다. 이 경우에는 반복문을 사용하여 각 단계에서의 손실과 정확도를 출력한다.

for epoch in range(10):
    loss = 0.0
    accuracy = 0.0
    for batch in range(len(x_train) // 32):  # 배치 크기 32로 가정
        batch_x = x_train[batch * 32 : (batch + 1) * 32]
        batch_y = y_train[batch * 32 : (batch + 1) * 32]
        batch_loss, batch_accuracy = model.train_on_batch(batch_x, batch_y)
        loss += batch_loss
        accuracy += batch_accuracy
    loss /= (len(x_train) // 32)
    accuracy /= (len(x_train) // 32)
    print("Epoch {}: loss = {:.4f}, accuracy = {:.4f}".format(epoch, loss, accuracy))

(tqdm 라이브러리를 사용하여 진행 상황 표시하기)

from tqdm import tqdm
import numpy as np
import time

# 가상의 학습 데이터 생성
x_train = np.random.random((1000, 20))
y_train = np.random.randint(2, size=(1000,))

# tqdm을 사용하여 반복 작업 진행 상황 표시
for epoch in tqdm(range(10), desc="Epochs"):
    loss_total = 0.0
    accuracy_total = 0.0
    for batch in tqdm(range(len(x_train) // 32), desc="Batches", leave=False):
        batch_x = x_train[batch * 32 : (batch + 1) * 32]
        batch_y = y_train[batch * 32 : (batch + 1) * 32]
        
        # 모델 학습 코드 (가상)
        batch_loss = np.random.random()
        batch_accuracy = np.random.random()
        
        loss_total += batch_loss
        accuracy_total += batch_accuracy
        
        time.sleep(0.01)  # 시간 지연을 위한 임시 코드
        
    avg_loss = loss_total / (len(x_train) // 32)
    avg_accuracy = accuracy_total / (len(x_train) // 32)
    print("Epoch {}: loss = {:.4f}, accuracy = {:.4f}".format(epoch, avg_loss, avg_accuracy))
    
    time.sleep(0.1)  # 시간 지연을 위한 임시 코드

(Pytorch로 사전 훈련된 ResNe-50 모델을 사용해서 만들기)

# 개와 고양이 분류 모델 만들기 예시
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import models, transforms
from torchvision.datasets import ImageFolder
from torch.utils.data import DataLoader

# ResNet-50 모델 불러오기
model = models.resnet50(pretrained=True)
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, 1)
model = model.to(device)

criterion = nn.BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader

# 데이터 로딩
transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
])

train_data = ImageFolder(root='path_to_train_data', transform=transform)
train_loader = DataLoader(train_data, batch_size=20, shuffle=True)

# 학습 진행 상황 출력
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
epochs = 10

for epoch in range(epochs):
    print(f"Epoch {epoch+1}/{epochs}")
    
    loss_total = 0.0
    accuracy_total = 0.0
    
    for batch_x, batch_y in tqdm(train_loader, desc="Batches", leave=False):
        batch_x = batch_x.to(device)
        batch_y = batch_y.to(device)
        
        optimizer.zero_grad()
        
        outputs = model(batch_x)
        loss = criterion(outputs, batch_y.float().view(-1, 1))
        loss.backward()
        optimizer.step()
        
        loss_total += loss.item()
        accuracy = ((outputs > 0) == batch_y.view(-1, 1)).sum().item() / len(batch_y)
        accuracy_total += accuracy
        
    avg_loss = loss_total / len(train_loader)
    avg_accuracy = accuracy_total / len(train_loader)
    print(f"Loss: {avg_loss:.4f}, Accuracy: {avg_accuracy:.4f}")

 

※ 예시 코드이므로 실제 구현시 수정이 필요하다.

728x90

+ Recent posts