def load_model(model_path: Path, data: train.Dataset): """Build the graph and load weights from disk.""" pre_wemb = np.load(str(WVECTORS), mmap_mode='r') model = train.build_network(pre_wemb, len(data.concept_ids), len(train.NER_TAGS), data.n_features) model.load_weights(str(model_path)) return model
def load_model(path): checkpoint = torch.load(path, map_location={'cuda:0': str(device)}) arch = checkpoint['arch'] out_features = len(checkpoint['class_to_idx']) hidden_layers = checkpoint['hidden_layers'] # For loading, use the same build_network function used to make saved model's network model = build_network(arch, out_features, hidden_layers) model.load_state_dict(checkpoint['state_dict']) model.class_to_idx = checkpoint['class_to_idx'] return model
state = data_transform(state).unsqueeze(0) # apply transformations state = state.to(device) # add additional dimension with torch.set_grad_enabled(False): # forward outputs = model(state) normalized = torch.nn.functional.softmax(outputs, dim=1) # translate from net output to env action max_action = np.argmax(normalized.cpu().numpy()[0]) action = available_actions[max_action] action[2] = 0.3 if action[2] != 0 else 0 # adjust brake power state, _, terminal, _ = env.step(action) # one step if terminal: state = env.reset() if human_wants_exit: env.close() return if __name__ == '__main__': dev = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") m = build_network() m.load_state_dict(torch.load(os.path.join(DATA_DIR, MODEL_FILE))) m.eval() m = m.to(dev) nn_agent_drive(m, dev)
def __init__(self, dumps, emb, **kwargs): pre_wemb = np.load(str(emb), mmap_mode='r') self.graph = train.build_network(pre_wemb, **kwargs) self.weights = list(self._read_weights(dumps))
def main(): # Parse arguments # python predict.py "flowers/test/1/image_06764.jpg" "checkpoints/checkpoint.pth" --top_k=6 --category_names="cat_to_name.json" --gpu=True parser = argparse.ArgumentParser() parser.add_argument('image_path', action="store", type=str) parser.add_argument('checkpoint', action="store", type=str) parser.add_argument('--top_k', dest="top_k", type=int) parser.add_argument('--category_names', dest="category_names", type=str) parser.add_argument('--gpu', dest="gpu", default=False, type=bool) parser.add_argument('--data_directory', dest="data_directory", default="flowers", type=str) args = parser.parse_args() #print(args) # Setup devivce and load checkpoint if args.gpu and torch.cuda.is_available(): device = torch.device("cuda:0") checkpoint = torch.load(args.checkpoint) else: device = torch.device("cpu") # https://gist.github.com/jzbontar/b50f8c9dd22e49ff68c7c91dad63166a checkpoint = torch.load(args.checkpoint, map_location=lambda storage, loc: storage) # Load te model model = train.build_network(checkpoint['hidden_layers'], checkpoint['drop_p'], checkpoint['model_network']) model.load_state_dict(checkpoint['state_dict']) model.class_to_idx = checkpoint['class_to_idx'] # Predict categories if args.top_k is not None: topk = args.top_k else: topk = 5 probs, labels = predict(args.image_path, model, args.gpu, topk) # Print most likely image class and it's associated probability print("Most likely image class: {}".format(labels[0])) print("Probability of this image class: {}%".format( round(100 * probs[0], 2))) # Print top K classes along with associated probabilities if args.top_k is not None: index = 0 print("-" * 20) print("Top {} categories and their probabilities:".format(args.top_k)) for i in np.nditer(probs): print("{} : {}%".format(labels[index], round(100 * i, 2))) index += 1 # load a JSON file that maps the class values to other category names if args.category_names is not None: with open(args.category_names, 'r') as f: cat_to_name = json.load(f) print("-" * 20) print("Top {} flowers categories and their probabilities:".format( args.top_k)) index = 0 for i in np.nditer(probs): print("{} : {}%".format(cat_to_name[labels[index]].title(), round(100 * i, 2))) index += 1
import torch from nn_agent import nn_agent_play from train import \ DATA_DIR, \ MODEL_FILE, \ build_network, \ train if __name__ == '__main__': # create cuda device dev = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # create the network model = build_network() # if true, try to restore the network from the data file restore = False if restore: model_path = os.path.join(DATA_DIR, MODEL_FILE) model.load_state_dict(torch.load(model_path)) # set the model to evaluation (and not training) mode model.eval() # transfer to the gpu model = model.to(dev) # train train(model, dev)