admin 管理员组

文章数量: 1086933

pytorch k 折

### Load datasettrainset = datasets.ImageFolder(train_dir, transform=transform)
testset = datasets.ImageFolder(test_dir, transform=transform)import torch
from sklearn.model_selection import KFolddata_induce = np.arange(0, len(trainset))  # 将“训练集”分为训练集和验证集
kf = KFold(n_splits=5)  # 分成 5 份for k, (train_index, val_index) in enumerate(kf.split(data_induce)):print('{} - FOLD'.format(k))train_subset = torch.utils.data.dataset.Subset(trainset, train_index)val_subset = torch.utils.data.dataset.Subset(trainset, val_index)trainloader = DataLoader(dataset=train_subset, batch_size=bs, pin_memory=True)valloader = DataLoader(dataset=val_subset, batch_size=bs, pin_memory=True)### Build modelcriterion = nn.CrossEntropyLoss()model = torchvision.models.resnet18(pretrained=False)num_ftrs = model.fc.in_featuresmodel.fc = nn.Linear(num_ftrs, 2)  ## 2 classesmodel.to(DEVICE)### Design optimizeroptimizer = optim.Adam(model.parameters(), lr=modellr)for epoch in range(1, EPOCHS + 1):adjust_learning_rate(optimizer, epoch)train(model, DEVICE, trainloader, optimizer, epoch, k)val(model, DEVICE, valloader, k)torch.save(model, 'model_{}_fold.pth'.format(k))

在原创基础上加工,原创有点找不到了,仅作记录

本文标签: pytorch k 折