mirror of
https://github.com/jung-geun/PSO.git
synced 2026-09-20 14:11:48 +09:00
Migrate the package and examples to the tensor-native PyTorch implementation, add benchmark evidence, and add the guarded post-training convergence protocol with TensorBoard progress monitoring and hash-verified recovery. Constraint: Preserve one-shot official-test sealing and auditable research artifacts Rejected: Commit local .omc runs and downloaded datasets | multi-gigabyte runtime state is machine-local Confidence: high Scope-risk: broad Not-tested: Production CUDA run on pieroot-server
10 KiB
10 KiB
In [ ]:
# Google Colab 및 시스템 환경 uv 패키지 설치
!pip install -q uv
!uv pip install 'pso2keras[examples]' --systemIn [ ]:
import sys
import torch
print("Python version:", sys.version)
print("PyTorch version:", torch.__version__)
# Metal MPS (Apple Silicon GPU) 가속 백엔드 진단
built = hasattr(torch.backends, "mps") and torch.backends.mps.is_built()
avail = hasattr(torch.backends, "mps") and torch.backends.mps.is_available()
print(f"MPS Backend - Built: {built}, Available: {avail}")
In [ ]:
import torch
import torch.nn as nn
from torchvision import datasets, transforms
from sklearn.decomposition import PCA
from pso import Optimizer
# 재현 가능한 시드 설정
torch.manual_seed(42)
# 1. MNIST 데이터셋 로드 (인터넷 다운로드 필요)
transform = transforms.Compose([transforms.ToTensor()])
mnist_train = datasets.MNIST(root="./data", train=True, download=True, transform=transform)
mnist_test = datasets.MNIST(root="./data", train=False, download=True, transform=transform)
# 2. 결정론적 샘플 서브셋 추출 (학습 5,000개, 검증 1,000개)
g = torch.Generator().manual_seed(42)
train_indices = torch.randperm(len(mnist_train), generator=g)[:5000]
test_indices = torch.randperm(len(mnist_test), generator=g)[:1000]
x_train_raw = mnist_train.data[train_indices].float() / 255.0
y_train = mnist_train.targets[train_indices].long()
x_test_raw = mnist_test.data[test_indices].float() / 255.0
y_test = mnist_test.targets[test_indices].long()
# 3. PCA 50차원 주성분 분석 전처리
x_train_flat = x_train_raw.view(x_train_raw.size(0), -1).numpy()
x_test_flat = x_test_raw.view(x_test_raw.size(0), -1).numpy()
pca = PCA(n_components=50, random_state=42)
x_train_pca = pca.fit_transform(x_train_flat)
x_test_pca = pca.transform(x_test_flat)
x_train = torch.tensor(x_train_pca, dtype=torch.float32)
x_test = torch.tensor(x_test_pca, dtype=torch.float32)
print(f"x_train : {x_train.shape} | y_train : {y_train.shape}")
print(f"x_test : {x_test.shape} | y_test : {y_test.shape}")
In [ ]:
class MNISTLogitNet(nn.Module):
def __init__(self, in_features=50, hidden_dim=32, num_classes=10):
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_features, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, num_classes)
)
def forward(self, x):
return self.net(x)
model = MNISTLogitNet()
loss_fn = nn.CrossEntropyLoss()
In [ ]:
pso_mnist = Optimizer(
model,
loss=loss_fn,
task="multiclass",
method="inertia",
initialization="model_noise",
evaluation="fixed_subset",
convergence="none",
refinement="adam",
fitness_size=2000,
n_particles=20,
c0=0.35,
c1=0.8,
w_min=0.6,
w_max=1.2,
particle_min=-3.0,
particle_max=3.0,
velocity_limit_ratio=0.1,
boundary_strategy="reflect",
initial_position_noise=0.05,
seed=42,
device=None,
refinement_epochs=100,
refinement_lr=0.01,
)
best_score = pso_mnist.fit(
x_train,
y_train,
epochs=15,
batch_size=500,
fitness_size=2000,
renewal="acc",
validation_data=(x_test, y_test),
output_dir="./result/mnist",
log_format="csv",
checkpoint_interval=5,
save_info=True,
refinement_epochs=100,
refinement_lr=0.01,
)
print(f"Optimization Completed! Best Training Score (loss, accuracy, mse): {best_score}")
val_score = pso_mnist.evaluate(x_test, y_test)
print(f"Validation Score (loss, accuracy, mse): {val_score}")In [ ]:
import os
ckpt_path = "./result/mnist/best_model.pt"
if os.path.exists(ckpt_path):
checkpoint = torch.load(ckpt_path, weights_only=True)
# 이식 가능한 state_dict 기반 모델 가중치 복원
eval_model = MNISTLogitNet()
eval_model.load_state_dict(checkpoint["model_state_dict"])
eval_model.eval()
print("Loaded Checkpoint Version:", checkpoint.get("version"))
print("Checkpoint Best Score: ", checkpoint.get("score"))
print("Execution Target Device: ", checkpoint.get("device"))