10 examples of 'pytorch load model' in Python

Every line of 'pytorch load model' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
91def load(self, model, checkpoint):
92 state_dict = torch.load(checkpoint, map_location='cpu')
93 filter = lambda x: x[7:] if x.startswith('module.') else x
94 state_dict = {filter(k):v for (k,v) in state_dict.items()}
95 model.load_state_dict(state_dict)
96 model.to(self.device)
97 model.eval()
98 return model
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

66def load_models(load_path):
67 model_args = json.load(open(os.path.join(load_path, 'options.json'), 'r'))
68 vars(args).update(model_args)
69 autoencoder = Seq2Seq(emsize=args.emsize,
70 nhidden=args.nhidden,
71 ntokens=args.ntokens,
72 nlayers=args.nlayers,
73 noise_r=args.noise_r,
74 hidden_init=args.hidden_init,
75 dropout=args.dropout,
76 gpu=args.cuda)
77 gan_gen = MLP_G(ninput=args.z_size, noutput=args.nhidden, layers=args.arch_g)
78 gan_disc = MLP_D(ninput=args.nhidden, noutput=1, layers=args.arch_d)
79
80 autoencoder = autoencoder.cuda()
81 gan_gen = gan_gen.cuda()
82 gan_disc = gan_disc.cuda()
83
84 word2idx = json.load(open(os.path.join(args.save, 'vocab.json'), 'r'))
85 idx2word = {v: k for k, v in word2idx.items()}
86
87 print('Loading models from {}'.format(args.save))
88 loaded = torch.load(os.path.join(args.save, "model.pt"))
89 autoencoder.load_state_dict(loaded.get('ae'))
90 gan_gen.load_state_dict(loaded.get('gan_g'))
91 gan_disc.load_state_dict(loaded.get('gan_d'))
92 return model_args, idx2word, autoencoder, gan_gen, gan_disc
92def load_model(self, encoder_path, decoder_path):
93 self.encoder.load_state_dict(torch.load(encoder_path, map_location=lambda storage, loc: storage))
94 self.decoder.load_state_dict(torch.load(decoder_path, map_location=lambda storage, loc: storage))
183def load_model(self):
184 # Check whether model exists
185 if not os.path.exists(self.args.model_dir):
186 raise Exception("Model doesn't exists! Train first!")
187
188 try:
189 self.bert_config = self.config_class.from_pretrained(self.args.model_dir)
190 logger.info("***** Config loaded *****")
191 self.model = self.model_class.from_pretrained(self.args.model_dir, config=self.bert_config, args=self.args)
192 self.model.to(self.device)
193 logger.info("***** Model Loaded *****")
194 except:
195 raise Exception("Some model files might be missing...")
18def load_model(weights_path=None):
19 """ Load model with IMAGENET weights if other pretrained weights
20 are not given
21 """
22 model, layers_to_remove = models.resnet34(pretrained=weights_path is None), 1
23 model = FTModel(model,
24 layers_to_remove=layers_to_remove,
25 num_features=128,
26 num_classes=100,
27 train_only_fc=False)
28
29 if weights_path is not None:
30 print('loading model weights')
31 if os.path.isfile(weights_path):
32 print(" => loading checkpoint '{}'".format(weights_path))
33 checkpoint = torch.load(weights_path, map_location=DEVICE)
34 model.load_state_dict(checkpoint['state_dict'])
35 print(" => loaded checkpoint '{}' (epoch {})"
36 .format(weights_path, checkpoint['epoch']))
37 else:
38 print("=> no checkpoint found at '{}'".format(weights_path))
39
40 model.to(DEVICE)
41 model.eval()
42
43 return model
112def load_model_from_checkpoint():
113 global E, G, D, E_trainer, G_trainer, D_trainer
114 checkpoint = T.load(save_path)
115 E.load_state_dict(checkpoint['E_model'])
116 G.load_state_dict(checkpoint['G_model'])
117 D.load_state_dict(checkpoint['D_model'])
118 E_trainer.load_state_dict(checkpoint['E_trainer'])
119 G_trainer.load_state_dict(checkpoint['G_trainer'])
120 D_trainer.load_state_dict(checkpoint['D_trainer'])
121 return checkpoint['epoch']
13def load_classifier(model_path, gpu_id):
14 if torch.cuda.is_available() and gpu_id != -1:
15 device = 'cuda:{}'.format(gpu_id)
16 else:
17 device = 'cpu'
18 model = DRNSub(1)
19 state_dict = torch.load(model_path, map_location='cpu')
20 model.load_state_dict(state_dict['model'])
21 model.to(device)
22 model.device = device
23 model.eval()
24 return model
17def load_model(net, input_file='model.state'):
18 """
19 Loads a pytorch model
20 :param net:
21 :param input_file:
22 :return:
23 """
24 state_dict = torch.load(input_file)
25 net.load_state_dict(state_dict)
107def load(self, modelpath):
108 state = torch.load(modelpath)
109 self.load_state_dict(state['model'])
110 return state['optimizer']
130def loadModel(optional=True):
131 model_exists = os.path.isfile(MODEL_PATH_BEST)
132 if model_exists:
133 checkpoint = torch.load(MODEL_PATH_BEST)
134 net.load_state_dict(checkpoint['state_dict'])
135 print("MODEL LOADED, CONTINUING TRAINING")
136 return "TRAINING AVG LOSS: {}\n" \
137 "TRAINING AVG DIFF: {}".format(
138 checkpoint["epoch_avg_loss"], checkpoint["epoch_avg_diff"])
139 else:
140 if optional:
141 pass # model loading was optional, so nothing to do
142 else:
143 # shit, no model
144 raise Exception("model couldn't be found:", MODEL_PATH_BEST)

Related snippets