import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets, models, transforms from torch.utils.data import DataLoader import os # 1. Cấu hình thiết bị (Ưu tiên dùng Card đồ họa) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(f"[INFO] Đang sử dụng thiết bị tính toán: {device}") # 2. Chuẩn bị và làm phong phú dữ liệu (Data Augmentation) # Giúp AI học tốt hơn bằng cách tự động lật ảnh, thay đổi kích thước cho chuẩn data_transforms = transforms.Compose([ transforms.Resize((224, 224)), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) # Load dữ liệu từ thư mục data_dir = 'dataset/train' image_dataset = datasets.ImageFolder(data_dir, data_transforms) dataloader = DataLoader(image_dataset, batch_size=16, shuffle=True) # In ra các nhãn để kiểm tra (thường sẽ là {'fake': 0, 'real': 1}) print(f"[INFO] Các nhãn đã nhận diện: {image_dataset.class_to_idx}") # 3. Khởi tạo Mô hình AI (MobileNetV2) print("[INFO] Đang tải cấu trúc mạng MobileNetV2...") model = models.mobilenet_v2(weights=models.MobileNet_V2_Weights.DEFAULT) # Thay đổi lớp cuối cùng để chỉ phân loại 2 lớp: Fake và Real num_ftrs = model.classifier[1].in_features model.classifier[1] = nn.Linear(num_ftrs, 2) model = model.to(device) # Đẩy model lên GPU # 4. Định nghĩa hàm tính sai số (Loss) và bộ tối ưu hóa (Optimizer) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.001) # 5. Vòng lặp Huấn luyện (Training Loop) num_epochs = 10 # Cho AI học đi học lại 10 lần qua toàn bộ dữ liệu print("[INFO] Bắt đầu quá trình huấn luyện...") for epoch in range(num_epochs): model.train() # Đặt mô hình ở chế độ huấn luyện running_loss = 0.0 corrects = 0 for inputs, labels in dataloader: inputs = inputs.to(device) labels = labels.to(device) optimizer.zero_grad() # Xóa bộ nhớ đệm # Lan truyền tiến (Đưa ảnh qua mạng AI) outputs = model(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) # Lan truyền ngược (Cập nhật trọng số để AI thông minh hơn) loss.backward() optimizer.step() running_loss += loss.item() * inputs.size(0) corrects += torch.sum(preds == labels.data) epoch_loss = running_loss / len(image_dataset) epoch_acc = corrects.double() / len(image_dataset) print(f"Vòng lặp (Epoch) {epoch+1}/{num_epochs} | Sai số (Loss): {epoch_loss:.4f} | Độ chính xác (Acc): {epoch_acc:.4f}") # 6. Lưu lại "bộ não" đã được huấn luyện os.makedirs('models', exist_ok=True) save_path = 'models/anti_spoofing_model.pth' torch.save(model.state_dict(), save_path) print(f"[INFO] Huấn luyện hoàn tất! Mô hình đã được lưu tại: {save_path}")