当前位置: 首页>>代码示例>>Python>>正文


Python model.Net方法代码示例

本文整理汇总了Python中model.Net方法的典型用法代码示例。如果您正苦于以下问题:Python model.Net方法的具体用法?Python model.Net怎么用?Python model.Net使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在model的用法示例。


在下文中一共展示了model.Net方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: generate_rollout

# 需要导入模块: import model [as 别名]
# 或者: from model import Net [as 别名]
def generate_rollout(self, iter_train, iter_dev, verbose=False):
        self.log_probs = []
        self.actions = []
        self.entropies = []
        self.reward = None

        state = torch.zeros(self.hidden_size)
        terminated = False
        self.reward = 0

        while not terminated:
            log_prob, state, terminated = self.step(state)
            self.log_probs.append(log_prob)

        if verbose:
            print('\nGenerated network:')
            print(self.actions)

        net = Net(self.actions)
        accuracy = net.fit(iter_train, iter_dev)
        self.reward += accuracy

        return self.reward 
开发者ID:nicklashansen,项目名称:minimal-nas,代码行数:25,代码来源:controller.py

示例2: main

# 需要导入模块: import model [as 别名]
# 或者: from model import Net [as 别名]
def main():
    from  train import Trainer
    net=Net(VinConfig)
    net=net.cuda()
    net=net.double()
    trainer=Trainer(VinConfig,net)
    trainer.train() 
开发者ID:MrGemy95,项目名称:visual-interaction-networks-pytorch,代码行数:9,代码来源:vin.py

示例3: hello_world

# 需要导入模块: import model [as 别名]
# 或者: from model import Net [as 别名]
def hello_world(args): 
    from functools import reduce
    from operator import mul
    model = Net(args).to(args.device)
    state = model.state_dict()
    total_size = 0
    for key, value in state.items():
        print(f'{key}: {value.size()}')
        total_size += reduce(mul, value.size())
    print(f'Parameters: {total_size} Size: {total_size * 4 / 1024 / 1024} MB') 
开发者ID:RanhaoKang,项目名称:PWC-Net_pytorch,代码行数:12,代码来源:main.py

示例4: summary

# 需要导入模块: import model [as 别名]
# 或者: from model import Net [as 别名]
def summary(args):
    model = Net(args).to(args.device)
    summary_(model, args.input_shape) 
开发者ID:RanhaoKang,项目名称:PWC-Net_pytorch,代码行数:5,代码来源:main.py

示例5: test

# 需要导入模块: import model [as 别名]
# 或者: from model import Net [as 别名]
def test(args):
    print('load model...')
    model = Net(args).to(args.device)
    model.load_state_dict(torch.load(args.load))

    print('build eval dataset...')
    test_dataset = eval(args.dataset)(args.dataset_dir, 'test')
    test_loader = DataLoader(test_dataset,
                            batch_size = 1,
                            shuffle = True,
                            num_workers = args.num_workers,
                            pin_memory = True)


    total_batches = len(test_loader)

    # logs
    # ============================================================
    time_logs = []; total_epe = 0



    for batch_idx, (data, target) in enumerate(test_loader):
        # Forward Pass
        # ============================================================
        t_start = time.time()
        data, target = [d.to(args.device) for d in data], [t.to(args.device) for t in target]
        with torch.no_grad():
            flows, summaries = model(data[0])
        time_logs.append(time.time() - t_start)



        # Compute EPE
        # ============================================================
        # epe = EPE(flows, target[0])
        # total_epe += epe.item()
        print(f'[{batch_idx}/{total_batches}]  Time: {time_logs[batch_idx]:.2f}s')#  EPE:{total_epe / batch_idx}') 
开发者ID:RanhaoKang,项目名称:PWC-Net_pytorch,代码行数:40,代码来源:main.py

示例6: main

# 需要导入模块: import model [as 别名]
# 或者: from model import Net [as 别名]
def main(objects, **kwargs):
    nets = [
        model.Net(objects).cuda(),
        model.Baseline(objects).cuda(),
    ]
    loader = get_loader(objects, **kwargs)
    plins = run(nets, loader, 1000, train=True)
    accs = run(nets, loader, 200, train=False)
    return {'plins': plins, 'accs': accs} 
开发者ID:Cyanogenoid,项目名称:vqa-counting,代码行数:11,代码来源:train.py

示例7: main

# 需要导入模块: import model [as 别名]
# 或者: from model import Net [as 别名]
def main():
    # Training settings
    parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
    parser.add_argument('--batch-size', type=int, default=512, metavar='N',
                        help='input batch size for training (default: 64)')
    parser.add_argument('--test-batch-size', type=int, default=512, metavar='N',
                        help='input batch size for testing (default: 1000)')
    parser.add_argument('--epochs', type=int, default=10, metavar='N',
                        help='number of epochs to train (default: 10)')
    parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
                        help='learning rate (default: 0.01)')
    parser.add_argument('--no-cuda', action='store_true', default=False,
                        help='disables CUDA training')
    parser.add_argument('--seed', type=int, default=1, metavar='S',
                        help='random seed (default: 1)')
    parser.add_argument('--log-interval', type=int, default=10, metavar='N',
                        help='how many batches to wait before logging training status')
    args = parser.parse_args()
    use_cuda = not args.no_cuda and torch.cuda.is_available()

    torch.manual_seed(args.seed)

    device = torch.device("cuda" if use_cuda else "cpu")

    kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
    train_loader = torch.utils.data.DataLoader(
        datasets.MNIST('../data', train=True, download=True,
                       transform=transforms.Compose([
                           transforms.ToTensor(),
                           transforms.Normalize((0.1307,), (0.3081,))
                       ])),
        batch_size=args.batch_size, shuffle=True, **kwargs)
    test_loader = torch.utils.data.DataLoader(
        datasets.MNIST('../data', train=False, transform=transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize((0.1307,), (0.3081,))
        ])),
        batch_size=args.test_batch_size, shuffle=True, **kwargs)

    model = Net(device=device).to(device)
    optimizer = optim.Adam(model.parameters(), lr=args.lr)

    for epoch in range(1, args.epochs + 1):
        train(args, model, device, train_loader, optimizer, epoch)
        test(args, model, device, test_loader) 
开发者ID:dmlc,项目名称:dgl,代码行数:47,代码来源:main.py

示例8: pred

# 需要导入模块: import model [as 别名]
# 或者: from model import Net [as 别名]
def pred(args):
    # Get environment
    # Build Model
    # ============================================================
    model = Net(args).to(args.device)
    model.load_state_dict(torch.load(args.load))
    
    # Load Data
    # ============================================================
    x1_raw, x2_raw = map(imageio.imread, args.input)

    class StaticCenterCrop(object):
        def __init__(self, image_size, crop_size):
            self.th, self.tw = crop_size
            self.h, self.w = image_size
            print(self.th, self.tw, self.h, self.w)
        def __call__(self, img):
            return img[(self.h-self.th)//2:(self.h+self.th)//2, (self.w-self.tw)//2:(self.w+self.tw)//2,:]

    x1_raw = np.array(x1_raw)
    x2_raw = np.array(x2_raw)

    # if args.crop_shape is not None:
    #     cropper = StaticCenterCrop(x1_raw.shape[:2], args.crop_shape)
    #     x1_raw = cropper(x1_raw)
    #     x2_raw = cropper(x2_raw)
    # if args.resize_shape is not None:
    #     resizer = partial(cv2.resize, dsize = (0,0), dst = args.resize_shape)
    #     x1_raw, x2_raw = map(resizer, [x1_raw, x2_raw])
    # elif args.resize_scale is not None:
    #     resizer = partial(cv2.resize, dsize = (0,0), fx = args.resize_scale, fy = args.resize_scale)
    #     x1_raw, x2_raw = map(resizer, [x1_raw, x2_raw])

    # pad to multiples of 64
    H, W = x1_raw.shape[:2]
    print(x1_raw.shape)
    x1_raw = np.pad(x1_raw, ((0, (64 - H % 64) if H % 64 else 0), (0, (64 - W % 64) if H % 64 else 0), (0, 0)), mode = 'constant')
    x2_raw = np.pad(x2_raw, ((0, (64 - H % 64) if H % 64 else 0), (0, (64 - W % 64) if H % 64 else 0), (0, 0)), mode = 'constant')

    x1_raw = x1_raw[np.newaxis,:,:,:].transpose(0,3,1,2)
    x2_raw = x2_raw[np.newaxis,:,:,:].transpose(0,3,1,2)

    x = np.stack([x1_raw, x2_raw], axis = 2)
    x = torch.Tensor(x).to(args.device)
    

    # Forward Pass
    # ============================================================
    with torch.no_grad():
        flows, summaries = model(x)
    flow = flows[-1]
    flow = np.array(flow.data).transpose(0,2,3,1).squeeze(0)
    save_flow(args.output, flow)
    flow_vis = vis_flow(flow)
    imageio.imwrite(args.output.replace('.flo', '.png'), flow_vis)
    import matplotlib.pyplot as plt
    plt.imshow(flow_vis)
    plt.show() 
开发者ID:RanhaoKang,项目名称:PWC-Net_pytorch,代码行数:60,代码来源:main.py


注:本文中的model.Net方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。