import torch
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader, TensorDataset
# 1. 데이터 준비
X = torch.randn(1000, 10) # 1000개의 샘플, 10개의 피처
y = torch.randint(0, 2, (1000,)) # 이진 분류 레이블
# 2. 데이터 분할
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.3, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)
# 3. Dataset 생성
train_dataset = TensorDataset(X_train, y_train)
val_dataset = TensorDataset(X_val, y_val)
test_dataset = TensorDataset(X_test, y_test)
# 4. DataLoader 생성
batch_size = 32
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# 5. 모델 학습 루프 (간략화된 구조)
for epoch in range(10): # 10 epochs
# Training
model.train()
for batch in train_loader:
X_batch, y_batch = batch
# Forward pass
predictions = model(X_batch)
loss = loss_function(predictions, y_batch)
# Backward pass
loss.backward()
optimizer.step()
optimizer.zero_grad()
# Validation
model.eval()
val_loss = 0
with torch.no_grad():
for batch in val_loader:
X_batch, y_batch = batch
predictions = model(X_batch)
val_loss += loss_function(predictions, y_batch).item()
print(f"Epoch {epoch + 1}, Validation Loss: {val_loss / len(val_loader)}")
# 6. 최종 테스트
model.eval()
test_loss = 0
with torch.no_grad():
for batch in test_loader:
X_batch, y_batch = batch
predictions = model(X_batch)
test_loss += loss_function(predictions, y_batch).item()
print(f"Test Loss: {test_loss / len(test_loader)}")
# 2. 데이터 분할
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.3, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)
X_train, y_train: 학습에 사용할 Train Set (전체 데이터의 70%).X_temp, y_temp: 검증 및 테스트 데이터로 나누기 위해 임시로 저장된 데이터 (전체 데이터의 30%).X_temp, y_temp에 할당.X_train, y_train)로 사용.X_temp, y_temp).X_val, y_val: 검증에 사용할 Validation Set (전체 데이터의 15%).X_test, y_test: 테스트에 사용할 Test Set (전체 데이터의 15%).X_temp와 y_temp의 절반(50%)을 각각 검증 데이터(X_val, y_val)와 테스트 데이터(X_test, y_test)로 분리.첫 번째 분할과 마찬가지로 데이터 섞기를 재현 가능하도록 고정.