예제 #1
0
def Efficientnet(model_name, num_classes, test = False):
    '''
    model_name :'efficientnet-b0', 'efficientnet-b1-7'
    '''
    model = EfficientNet.from_name(model_name)
    if not test:
        if LOCAL_PRETRAINED[model_name] == None:
            state_dict = load_state_dict_from_url(model_urls[model_name], progress=True)
        else:
            state_dict = torch.load(LOCAL_PRETRAINED[model_name])
        model.load_state_dict(state_dict)
    fc_features = model._fc.in_features
    model._fc = nn.Linear(fc_features, num_classes)
    return model
예제 #2
0
    print('loss: %2.3f, top1: %2.3f, top5: %2.3f' %
          (tloss / len(loader), top1 / len(loader), top5 / len(loader)))


img_tfs = tfs.Compose([
    tfs.Resize((512, 512)),
    tfs.ToTensor(),
    tfs.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
])

if __name__ == '__main__':
    # net = Classifier()
    '''
    net = resnet50(True)
    '''
    net = EfficientNet.from_name('efficientnet-b0')
    if os.path.exists(args.model):
        net.load_state_dict(torch.load(args.model))
    imgnet = ImageFolder(args.data, transform=img_tfs)
    loader = DataLoader(imgnet,
                        args.batch_size,
                        shuffle=True,
                        num_workers=6,
                        pin_memory=True)
    criterion = torch.nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(net.parameters(), args.learning_rate)
    #optimizer=torch.optim.SGD(net.parameters(),args.learning_rate,args.momentum,weight_decay=args.weight_decay)
    '''
    train(loader,net,criterion,optimizer,args.epochs)
    '''
    validate(loader, net, criterion)
예제 #3
0
from sklearn.metrics import accuracy_score, roc_auc_score
from tqdm import tqdm
import time
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

opt = TestOptions().parse(print_options=False)
print("{} from {} model testing on {}".format(opt.arch, opt.source_dataset,
                                              opt.target_dataset))

gpu_id = opt.gpu_id
os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_id)
use_cuda = torch.cuda.is_available()
print("GPU device %d:" % (gpu_id), use_cuda)

model = EfficientNet.from_name(opt.arch, num_classes=opt.classes)

if opt.resume:
    pretrained = opt.resume
    print("=> using pre-trained model '{}'".format(pretrained))
    model.load_state_dict(torch.load(pretrained)['state_dict'])

model.to('cuda')
cudnn.benchmark = True
print('Total params: %.2fM' % (sum(p.numel()
                                   for p in model.parameters()) / 1000000.0))

criterion = nn.CrossEntropyLoss().cuda()
optimizer = optim.SGD(model.parameters(), lr=opt.lr, momentum=opt.momentum)

예제 #4
0
from utils.aug import data_augment, rand_bbox
from utils.train_utils import save_checkpoint, adjust_learning_rate

from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
from options.base import BaseOptions

opt = BaseOptions().parse(print_options=False)
#print("{} from {} model testing on {}".format(opt.arch, opt.source_dataset, opt.target_dataset))

gpu_id = opt.gpu_id
os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_id)
use_cuda = torch.cuda.is_available()
print("GPU device %d:" %(gpu_id), use_cuda)

model = EfficientNet.from_name(opt.arch, num_classes=opt.classes,
                              override_params={'dropout_rate': opt.dropout, 'drop_connect_rate': opt.dropconnect})
    
model.to('cuda')
cudnn.benchmark = True
best_acc = 0

data_dir = opt.source_dataset
train_dir = os.path.join(data_dir, 'train')
train_aug = transforms.Compose([
    transforms.Lambda(lambda img: data_augment(img, opt)),
    transforms.Resize(opt.size),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
#     transforms.RandomErasing(p=0.3, scale=(0.02, 0.10), ratio=(0.3, 3.3), value=0, inplace=True),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])