Esempio n. 1
0
# import numpy as np
import torch.optim as optim
# import os
import time

import loadData
startTime = time.time()
#%%
# 读取数据

numOfBatch = 9
pixel = 64
flag = 0
root = f'./{numOfBatch}/data'
batchSize = 2
train_data = loadData.MyDataset(txt=f'files_train.txt')
test_data = loadData.MyDataset(txt=f'files_test.txt')
train_loader = DataLoader(dataset=train_data,
                          batch_size=batchSize,
                          shuffle=True,
                          num_workers=2)
test_loader = DataLoader(dataset=test_data,
                         batch_size=batchSize,
                         shuffle=False,
                         num_workers=2)
print('num_of_trainData:', len(train_data))
print('num_of_testData:', len(test_data))

#%%
kernelSize = 3
Esempio n. 2
0
def trainValSegmentation(args):
    if not os.path.isfile(args.cached_data_file):
        dataLoader = ld.LoadData(args.data_dir, args.classes, args.attrClasses,
                                 args.cached_data_file)
        if dataLoader is None:
            print("Error while cacheing the data.")
            exit(-1)
        data = dataLoader.processData()
    else:
        print("load cacheing data.")
        data = pickle.load(open(args.cached_data_file, 'rb'))
    # only unet for segmentation now.
    # model= unet.UNet(args.classes)
    # model = r18unet.ResNetUNet(args.classes)
    model = mobileunet.MobileUNet(args.classes)
    print("UNet done...")
    # if args.onGPU == True:
    model = model.cuda()
    # devices_ids=[2,3], device_ids=range(2)
    # device = torch.device('cuda:' + str(devices_ids[0]))
    # model = model.to(device)
    if args.visNet == True:
        x = Variable(torch.randn(1, 3, args.inwidth, args.inheight))
        if args.onGPU == True:
            x = x.cuda()
        print("before forward...")
        y = model.forward(x)
        print("after forward...")
        g = viz.make_dot(y)
        # g1 = viz.make_dot(y1)
        g.render(args.save_dir + '/model', view=False)
    model = torch.nn.DataParallel(model)
    n_param = sum([np.prod(param.size()) for param in model.parameters()])
    print('network parameters: ' + str(n_param))

    #define optimization criteria
    weight = torch.from_numpy(data['classWeights'])
    print(weight)
    if args.onGPU == True:
        weight = weight.cuda()
    criteria = CrossEntropyLoss2d(weight)
    # if args.onGPU == True:
    # 	criteria = criteria.cuda()

    trainDatasetNoZoom = myTransforms.Compose([
        myTransforms.RandomCropResize(args.inwidth, args.inheight),
        # myTransforms.RandomHorizontalFlip(),
        myTransforms.ToTensor(args.scaleIn)
    ])
    trainDatasetWithZoom = myTransforms.Compose([
        # myTransforms.Zoom(512,512),
        myTransforms.RandomCropResize(args.inwidth, args.inheight),
        myTransforms.RandomHorizontalFlip(),
        myTransforms.ToTensor(args.scaleIn)
    ])
    valDataset = myTransforms.Compose([
        myTransforms.RandomCropResize(args.inwidth, args.inheight),
        myTransforms.ToTensor(args.scaleIn)
    ])
    trainLoaderNoZoom = torch.utils.data.DataLoader(
        ld.MyDataset(data['trainIm'],
                     data['trainAnnot'],
                     transform=trainDatasetNoZoom),
        batch_size=args.batch_size,
        shuffle=True,
        num_workers=args.num_workers,
        pin_memory=True)
    trainLoaderWithZoom = torch.utils.data.DataLoader(
        ld.MyDataset(data['trainIm'],
                     data['trainAnnot'],
                     transform=trainDatasetWithZoom),
        batch_size=args.batch_size,
        shuffle=True,
        num_workers=args.num_workers,
        pin_memory=True)
    valLoader = torch.utils.data.DataLoader(ld.MyDataset(data['valIm'],
                                                         data['valAnnot'],
                                                         transform=valDataset),
                                            batch_size=args.batch_size_val,
                                            shuffle=True,
                                            num_workers=args.num_workers,
                                            pin_memory=True)

    #define the optimizer
    optimizer = torch.optim.Adam(model.parameters(),
                                 args.lr, (0.9, 0.999),
                                 eps=1e-08,
                                 weight_decay=2e-4)
    # optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=0.99, weight_decay=5e-4)
    # optimizer = torch.optim.SGD([
    #        {'params': [param for name, param in model.named_parameters() if name[-4:] == 'bias'],
    #         'lr': 2 * args.lr},
    #        {'params': [param for name, param in model.named_parameters() if name[-4:] != 'bias'],
    #         'lr': args.lr, 'weight_decay': 5e-4}
    #    ], momentum=0.99)

    if args.onGPU == True:
        cudnn.benchmark = True
    start_epoch = 0
    if args.resume:
        if os.path.isfile(args.resumeLoc):
            print("=> loading checkpoint '{}'".format(args.resumeLoc))
            checkpoint = torch.load(args.resumeLoc)
            start_epoch = checkpoint['epoch']
            model.load_state_dict(checkpoint['state_dict'])
            print("=> loaded checkpoint '{}' (epoch{})".format(
                args.resume, checkpoint['epoch']))
        else:
            print("=> no checkpoint found at '{}'".format(args.resumeLoc))

    logfileLoc = args.save_dir + os.sep + args.logFile
    print(logfileLoc)
    if os.path.isfile(logfileLoc):
        logger = open(logfileLoc, 'a')
        logger.write("parameters: %s" % (str(n_param)))
        logger.write("\n%s\t%s\t%s\t%s\t%s\t%s\t%s\t" %
                     ('Epoch', 'Loss(Tr)', 'Loss(val)', 'Overall acc(Tr)',
                      'Overall acc(val)', 'mIOU (tr)', 'mIOU (val'))
        logger.flush()
    else:
        logger = open(logfileLoc, 'w')
        logger.write("Parameters: %s" % (str(n_param)))
        logger.write("\n%s\t%s\t%s\t%s\t%s\t%s\t%s\t" %
                     ('Epoch', 'Loss(Tr)', 'Loss(val)', 'Overall acc(Tr)',
                      'Overall acc(val)', 'mIOU (tr)', 'mIOU (val'))
        logger.flush()

    #lr scheduler
    scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer,
                                                     milestones=[30, 60, 90],
                                                     gamma=0.1)
    best_model_acc = 0
    for epoch in range(start_epoch, args.max_epochs):
        scheduler.step(epoch)
        lr = 0
        for param_group in optimizer.param_groups:
            lr = param_group['lr']
        # train(args,trainLoaderWithZoom,model,criteria,optimizer,epoch)
        lossTr, overall_acc_tr, per_class_acc_tr, per_class_iu_tr, mIOU_tr = train(
            args, trainLoaderNoZoom, model, criteria, optimizer, epoch)
        # print(per_class_acc_tr,per_class_iu_tr)
        lossVal, overall_acc_val, per_class_acc_val, per_class_iu_val, mIOU_val = val(
            args, valLoader, model, criteria)

        #save_checkpoint
        torch.save(
            {
                'epoch': epoch + 1,
                'arch': str(model),
                'state_dict': model.state_dict(),
                'optimizer': optimizer.state_dict(),
                'lossTr': lossTr,
                'lossVal': lossVal,
                'iouTr': mIOU_tr,
                'iouVal': mIOU_val,
            }, args.save_dir + '/checkpoint.pth.tar')

        #save model also
        # if overall_acc_val > best_model_acc:
        # 	best_model_acc = overall_acc_val
        model_file_name = args.save_dir + '/model_' + str(epoch + 1) + '.pth'
        torch.save(model.state_dict(), model_file_name)
        with open('../acc/acc_' + str(epoch) + '.txt', 'w') as log:
            log.write(
                "\nEpoch: %d\t Overall Acc (Tr): %.4f\t Overall Acc (Val): %.4f\t mIOU (Tr): %.4f\t mIOU (Val): %.4f"
                % (epoch, overall_acc_tr, overall_acc_val, mIOU_tr, mIOU_val))
            log.write('\n')
            log.write('Per Class Training Acc: ' + str(per_class_acc_tr))
            log.write('\n')
            log.write('Per Class Validation Acc: ' + str(per_class_acc_val))
            log.write('\n')
            log.write('Per Class Training mIOU: ' + str(per_class_iu_tr))
            log.write('\n')
            log.write('Per Class Validation mIOU: ' + str(per_class_iu_val))

        logger.write(
            "\n%d\t\t%.4f\t\t%.4f\t\t%.4f\t\t%.4f\t\t%.4f\t\t%.4f\t\t%.6f" %
            (epoch, lossTr, lossVal, overall_acc_tr, overall_acc_val, mIOU_tr,
             mIOU_val, lr))
        logger.flush()
        print("Epoch : " + str(epoch) + ' Details')
        print(
            "\nEpoch No.: %d\tTrain Loss = %.4f\tVal Loss = %.4f\t Train acc = %.4f\t Val acc = %.4f\t mIOU(tr) = %.4f\t mIOU(val) = %.4f"
            % (epoch, lossTr, lossVal, overall_acc_tr, overall_acc_val,
               mIOU_tr, mIOU_val))

    logger.close()
Esempio n. 3
0
# 读取数据
transforms = tv.transforms.Compose([
    # transforms.CenterCrop(64),
    # transforms.CenterCrop(128),
    transforms.ToTensor(),
    # transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])

numOfBatch = 9
pixel = 64
flag = 0
root = f'./{numOfBatch}/data'
batchSize = 2
# train_data = loadData.MyDataset(txt=f'{root}_{pixel}_{flag}_train.txt', transform=transforms)
# test_data = loadData.MyDataset(txt=f'{root}_{pixel}_{flag}_test.txt', transform=transforms)
train_data = loadData.MyDataset(txt=f'files_train.txt', transform=transforms)
test_data = loadData.MyDataset(txt=f'files_test.txt', transform=transforms)
train_loader = DataLoader(dataset=train_data,
                          batch_size=batchSize,
                          shuffle=True,
                          num_workers=2)
test_loader = DataLoader(dataset=test_data,
                         batch_size=batchSize,
                         shuffle=False,
                         num_workers=2)
print('num_of_trainData:', len(train_data))
print('num_of_testData:', len(test_data))

#%%

net = LeNetModel.LeNet()
Esempio n. 4
0
    # transforms.CenterCrop(128),
    transforms.ToTensor(),
    # transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])

numOfBatch = 5
dirPath = f'./{numOfBatch}/test_result'
targetFiles = sorted(os.listdir(dirPath))

erroCounter = 0
realLabels = []
predictedLabels = []
for targetFile in targetFiles:

    batchSize = 2
    test_data = loadData.MyDataset(txt=f'{dirPath}/{targetFile}',
                                   transform=transforms)
    test_loader = DataLoader(dataset=test_data,
                             batch_size=batchSize,
                             shuffle=False,
                             num_workers=2)

    correct = 0
    total = 0
    realLabel = []
    predictedLabel = []

    for data in test_loader:
        inputs, labels = data
        inputs, labels = inputs.cuda(), labels.cuda()
        realLabel.append([int(label) for label in labels])
        outputs = net(inputs)