def load_model(pretrained_model): state_dict = torch.load(pretrained_model) new_state_dict = OrderedDict() for k, value in state_dict['state_dict'].iteritems(): key = "module.{}".format(k) new_state_dict[key] = value torch.load_state_dict(new_state_dict) optimizer = state_dict['optimizer'] return optimizer
def load_checkpoint(self, file_name): """ Latest Checkpoint loader :param file_name: name of checkpoint file :return: """ file_name = os.path.join(self.config["checkpoint_dir"], file_name) checkpoint = torch.load(file_name) self.model = torch.load_state_dict(checkpoint['model']) self.optimizer = torch.load_state_dict(checkpoint['optimizer']) is_best = checkpoint["is_best"] if is_best: self.max_accuracy = checkpoint['valid_accuracy'] self.misclassified = checkpoint['misclassified_data']
def load_model(fn): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # with open(os.path.join(model_dir, f'{fn}.pth'), 'rb') as f: # model.load_state_dict(torch.load(f)) f = os.path.join(args.model_directory, f'{fn}.pt') model = torch.load_state_dict(torch.load(f)) return model.to(device)
def load_checkpoint(self): print("..loading checkpoint") T.load_state_dict(T.load(self.checkpoint_file))
def load_checkpoint(self): T.load_state_dict(T.load(self.checkpoint_file))
import torch #保存整个模型的结构信息和参数信息 torch.save(model, './model.pth') #只保存模型的状态 torch.save(model.state_dict(), './model_state.pth') #加载整个模型 model = torch.load('./model.pth') #加载模型的参数信息 model = torch.load_state_dict(torch.load('./model_state.pth'))
def _load_model(self, checkpoint): torch.load_state_dict(self.model, checkpoint.pop("model"))
def load_checkpoint(checkpoint): """Function for loading checkpoints.""" print('/Loading checkpoint..') torch.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer'])
return args if __name__ == '__main__': """ python grad_cam.py <path_to_image> 1. Loads an image with opencv. 2. Preprocesses it for VGG19 and converts to a pytorch variable. 3. Makes a forward pass to find the category index with the highest score, and computes intermediate activations. Makes the visualization. """ args = get_args() # Can work with any model, but it assumes that the model has a # feature method, and a classifier method, # as in the VGG models in torchvision. grad_cam = GradCam(model = torch.load_state_dict('mnist_cnn.pt'), \ target_layer_names = ["35"], use_cuda=args.use_cuda) img = cv2.imread(args.image_path, 1) img = np.float32(cv2.resize(img, (224, 224))) / 255 input = preprocess_image(img) # If None, returns the map for the highest scoring category. # Otherwise, targets the requested xxxxxxx`index. target_index = None mask = grad_cam(input, target_index) show_cam_on_image(img, mask) gb_model = GuidedBackpropReLUModel(model = models.vgg19(pretrained=True), use_cuda=args.use_cuda)
def load_actor(self, file_path): torch.load_state_dict(torch.load(file_path))
torch.save(state, args.cv_dir + '/ckpt_E_%d_A_%.3f' % (epoch, accuracy)) #--------------------------------------------------------------------------------------------------------# trainset, testset = utils.get_dataset(args.train_csv, args.val_csv) trainloader = torchdata.DataLoader(trainset, batch_size=args.batch_size, shuffle=True, num_workers=16) testloader = torchdata.DataLoader(testset, batch_size=args.batch_size, shuffle=False, num_workers=4) net = utils.get_model() if args.parallel: net = nn.DataParallel(net) net.cuda() if args.load: checkpoint = torch.load(args.load) torch.load_state_dict(checkpoint) start_epoch = 0 optimizer = optim.Adam(net.parameters(), lr=args.lr) configure(args.cv_dir + '/log', flush_secs=5) for epoch in range(start_epoch, start_epoch + args.max_epochs + 1): train(epoch) if epoch % 1 == 0: test(epoch) lr_scheduler.step()
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=0, drop_last=True) torch.set_default_dtype(torch.float64) device = torch.device('cuda') reg = AcosRegressor(batch_size=batch_size).cuda() smpl = SMPLModel(device=device) loss_op = nn.L1Loss() optimizer = optim.Adam(reg.parameters(), lr=0.0005, betas=(0.5, 0.999), weight_decay=1e-4) scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', factor=0.25, patience=1, verbose=True) batch_num = 0 ckpt_path = 'checkpoints_0225_direct_training'.format(theta_var) if not os.path.isdir(ckpt_path): os.mkdir(ckpt_path) if batch_num > 0 and os.path.isfile('%s/regressor_%03d.pth' % (ckpt_path, batch_num)): state_dict = torch.load_state_dict('%s/regressor_%03d.pth' % (ckpt_path, batch_num)) reg.load(state_dict) # copy current file into checkpoint folder to record parameters, ugly. if platform == 'linux': cmd = 'cp train_acos_regressor.py ./{}/snapshot.py'.format(ckpt_path) else: cmd = r'copy train_acos_regressor.py {}\snapshot.py'.format(ckpt_path) print(cmd) os.system(cmd) file = open('{}/validation.txt'.format(ckpt_path), 'w') trans = torch.zeros((batch_size, 3), dtype=torch.float64, device=device) while batch_num < max_batch_num:
# CREATING NETWORKS if opt.load_pretrained == 0: net_g = define_G(opt.input_nc, opt.output_nc, opt.ngf, 'batch', False, 'normal', 0.02, gpu_id=device) else: print('Loading pretrained model') net_g = torch.load(join(opt.dest_train, 'checkpoint', 'netG_model_epoch_100.pth'), map_location=torch.device(device)).to(device) net_g = torch.load_state_dict(checkpoint_g['net_g']) criterionL1 = nn.L1Loss().to(device) criterionMSE = nn.MSELoss().to(device) # setup optimizer if opt.load_pretrained == 0: optimizer_g = optim.Adam(net_g.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999)) else: print('Loading pretrained optimizer') optimizer_g = torch.load_state_dict(checkpoint_g['optim_g']) net_g_scheduler = get_scheduler(optimizer_g, opt)
def load_checkpoint(self): print('.... loading checkpoint .....') torch.load_state_dict(torch.load(self.checkpoint_file))
def load_checkpoint(self): print('loading checkpoint') torch.load_state_dict(torch.load(self.chk_file))
def load_checkpoint(self): torch.load_state_dict(torch.load(self.checkpoint_file))