def main(): model, class_to_idx = utilities.load_checkpoint(file_path) map_location = 'cpu' strict = False img_datasets, data_loaders = utilities.transform_load_data(data_directory) with open(category_names, 'r') as f: cat_to_name = json.load(f) probs, classes = utilities.predict(path_image, model, number_of_outputs, device) print("THERE ARE THE PROBABILITIES: ", probs) print("THESE ARE THE CLASSES: ", classes) class_names = img_datasets['train'].classes flower_names = [cat_to_name[class_names[e]] for e in classes] print("THESE ARE THE TOP 5 CATEGORY FLOWER NAMES: ", flower_names)
def main(): parser.add_argument( 'image_dir', action="store", default= "/home/workspace/ImageClassifier/flowers/test/10/image_07090.jpg") parser.add_argument( 'checkpoint', action="store", default="/home/workspace/ImageClassifier/checkpoint.pth") parser.add_argument('--top_k', action="store", dest="top_k", type=int, default=5) parser.add_argument( '--category_names', action="store", dest="classes_names", default="/home/workspace/ImageClassifier/cat_to_name.json") parser.add_argument('--gpu', action="store", dest="device", default="gpu") p_args = parser.parse_args() #gpu or cpu device = torch.device("cpu") if torch.cuda.is_available() and p_args.device == 'gpu': device = torch.device("cuda:0") #load the categories names cat_names = ut.load_categories(p_args.classes_names) #load the checkpoint chkpoint = ut.load_checkpoint(p_args.checkpoint) #configure the model model = chkpoint['model'] model.load_state_dict(chkpoint['model_state']) #process the image image = ut.process_image(p_args.image_dir) #predict probs, classes = brain.predict(image, model, p_args.top_k, device) #configure the probabilities and class names probs = probs.cpu().numpy().flatten().tolist() classes = classes.cpu().numpy().flatten().tolist() index_to_class = {value: key for key, value in model.class_to_idx.items()} print("\n\n\n\n{:30s}{:20s}".format("Class Name", " Probability")) for i in range(len(classes)): name = [cat_names[index_to_class[classes[i]]]][0] probability = probs[i] * 100 print("{:30s}{:0.3f}".format(name, probability))
def main(): #Load checkpoint from saved path if available model=utilities.load_checkpoint(path) #get categories from json file with open('cat_to_name.json', 'r') as json_file: cat_to_name = json.load(json_file) #Predict picture category using trained model probabilities = utilities.predict(path_image, model, number_of_outputs) #Get labels and probabilities of prediciton for printing labels = [cat_to_name[str(index + 1)] for index in np.array(probabilities[1][0])] probability = np.array(probabilities[0][0]) i=0 while i < number_of_outputs: print("{} with a probability of {}".format(labels[i], probability[i])) i += 1
def main(): args = parse_args() gpu = args.gpu model = load_checkpoint(args.checkpoint) cat_to_name = load_cat_names(args.category_names) if args.filepath == None: img_num = random.randint(1, 102) image = random.choice(os.listdir('./flowers/test/' + str(img_num) + '/')) img_path = './flowers/test/' + str(img_num) + '/' + image prob, classes = predict(img_path, model, int(args.top_k), gpu) print('Image selected: ' + str(cat_to_name[str(img_num)])) else: img_path = args.filepath prob, classes = predict(img_path, model, int(args.top_k), gpu) print('File selected: ' + img_path) print(prob) print(classes) print([cat_to_name[x] for x in classes])
def main(): in_args = get_input_args() model = load_checkpoint(in_args) gpu = in_args.gpu image_path = in_args.image topk = in_args.top_k labels_path = in_args.labels cat_to_name = category_names(labels_path) probs, classes = predict(image_path, model, gpu, topk) labels = [cat_to_name[str(index)] for index in classes] output = [] for i in range(0, len(labels)): output.append([labels[i], classes[i], probs[i]]) l1, l2 = len(output), len(output[0]) print(pd.DataFrame(output, index=[''] * l1, columns=[''] * l2).T)
def main(): # Get the arguments passed to the python script in_arg = get_input_args_predict() # Load check point from pass model = load_checkpoint(in_arg.checkpoint) # Send model to gpu model_gpu, device = hw_control(model, in_arg.gpu) # Perform the prediction probs, classes = predict(in_arg.path, model, in_arg.top_k, in_arg.gpu) with open('cat_to_name.json', 'r') as f: cat_to_name = json.load(f) Class_names = [cat_to_name[str(class_name)] for class_name in classes] print("Most probable cat.:\t", Class_names) print("Probalbilities \t", probs) return probs, classes
print('Calculations are done on: ', device) # read in the dictionary enoding the real labels relating to the directories if FLAGS.category_names != None: # Check whether the category names file really exists otherwise raise an error if os.path.isfile(FLAGS.category_names): category_names_file = os.path.normpath(FLAGS.category_names) with open(category_names_file, 'r') as f: cat_to_name = json.load(f) else: raise ValueError("Couldn't not identify the category names file.") # load the CNN from the checkpoint file if os.path.isfile(FLAGS.checkpoint_file): checkpoint_file = os.path.normpath(FLAGS.checkpoint_file) dnn_model, _ = utilities.load_checkpoint(checkpoint_file, device) else: raise ValueError("Couldn't not identify the checkpoint file.") # load image and do the inference if os.path.isfile(FLAGS.image_file): image_file = os.path.normpath(FLAGS.image_file) inference = utilities.predict(image_file, dnn_model, device, topk=FLAGS.top_k) else: raise ValueError("Couldn't not identify the image file.") # get real names of the infered classes if FLAGS.category_names != None:
ap.add_argument('base_input', nargs='*', action="store") ap.add_argument('--top_k', dest="top_k", action="store", default=1, type=int) ap.add_argument('--category_names', dest="category_names", action="store", default='./cat_to_name.json') ap.add_argument('--gpu', dest="gpu", action="store_true") arguments = ap.parse_args() input_image = arguments.base_input[0] checkpoint = arguments.base_input[1] top_k = arguments.top_k category_names = arguments.category_names use_gpu = arguments.gpu and torch.cuda.is_available() model, optimizer, criterion = utilities.load_checkpoint(checkpoint) results = utilities.predict(input_image, model, use_gpu=use_gpu, top_k=top_k) if use_gpu: probabilities = results[0].cpu().numpy()[0] else: probabilities = results[0].numpy()[0] if use_gpu: names = results[1].cpu().numpy()[0] else: names = results[1].numpy()[0] print("----- Results: -------") for i in range(top_k): print("{} with a probability of {:.2%}".format(
parser = argparse.ArgumentParser() parser.add_argument('--image_path', action="store", dest="image_path") parser.add_argument('--checkpoint', action="store", dest="checkpoint") parser.add_argument('--top_k', action="store", default=5, type=int, dest="topk") parser.add_argument('--category_name', action="store", default=None, dest="cat") parser.add_argument('--gpu', action="store_true", default=False, dest="gpu") results = parser.parse_args() model, classes = utilities.load_checkpoint(results.checkpoint, results.gpu) if results.cat: classes_index = utilities.load_classes(results.cat) labels, probs, label_index = utilities.predict(results.image_path, model, classes, results.topk, classes_index, results.gpu) print('the label index of the image-the file name-', label_index) print('the name of the flower :', labels) print('the probabilities of each name: ', probs) ''' python predict.py --image_path 'flowers/test/79/image_06708.jpg' --checkpoint checkpointvgg.pth --category_name cat_to_name.json --top_k 5 --gpu '''
from network import Network device = torch.device("cuda" if torch.cuda.is_available() else "cpu") parser_sec = argparse.ArgumentParser() parser_sec.add_argument('b_img_path', action='store') # image path parser_sec.add_argument('checkpoint', action='store') # checkpoint file parser_sec.add_argument('--top_k', nargs='?', type=int) parser_sec.add_argument('--category_names', nargs='?') parser_sec.add_argument('--gpu', action='store_true') args = parser_sec.parse_args() args = vars(args) arg_sec_inputs = [] for key, value in args.items(): arg_sec_inputs.append(value) if arg_sec_inputs[3] is None: arg_sec_inputs[3] = 'cat_to_name.json' with open(arg_sec_inputs[3], 'r') as f: cat_to_name = json.load(f) Network.model = utilities.load_checkpoint('saves/mycheckpoint.pth') image = utilities.process_image(arg_sec_inputs[0]) utilities.predict_image(image, Network.model, True, cat_to_name, arg_sec_inputs[2])
help="use a mapping of categories to real names") parser.add_argument('--gpu', action='store_true', default=False, dest="gpu", help="use gpu") # Capture command line arguments results = parser.parse_args() image_path = results.image checkpoint = results.checkpoint top_k = results.top_k category_names = results.category_names gpu = results.gpu # Load the provided checkpoint model = utilities.load_checkpoint(checkpoint) # Get the inverse of class_to_idx idx_to_class = {v: k for k, v in model.class_to_idx.items()} # Calculate top k probabilities and classes, using gpu if requested probs, classes = utilities.predict(image_path, checkpoint, idx_to_class, top_k, gpu) # Get label map if provided cat_to_name = utilities.label_mapping(category_names) # Print image class and top k class probabilities utilities.print_image_prob(image_path, cat_to_name, top_k, probs, classes)
type=str) ap.add_argument('--top_k', default=5, dest="top_k", action="store", type=int) ap.add_argument('--category_names', dest="category_names", action="store", default='cat_to_name.json') ap.add_argument('--gpu', default="gpu", action="store", dest="gpu") pa = ap.parse_args() path_image = pa.input_img number_of_outputs = pa.top_k device = pa.gpu input_img = pa.input_img path = pa.checkpoint utilities.load_checkpoint(path) with open('cat_to_name.json', 'r') as json_file: cat_to_name = json.load(json_file) probabilities = utilities.predict(path_image, model, number_of_outputs, device) labels = [ cat_to_name[str(index + 1)] for index in np.array(probabilities[1][0]) ] probability = np.array(probabilities[0][0]) i = 0 while i < number_of_outputs: print("{} with a probability of {}".format(labels[i], probability[i])) i += 1
args = get_args_pred() # Build dictionary of the mapping from class indices to class names if args.category_names != None: cat_to_name = build_cat_to_name(args.category_names) else: cat_to_name = build_cat_to_name() # Set the number of most likely classes to return if args.top_k != None: top_k = args.top_k else: top_k = 5 # Load model model = load_checkpoint(args.checkpoint) # Predict using the model probs, classes = predict(args.path_to_image, model, use_gpu=args.gpu, topk=top_k) # Format the predictions objects = [] for class_idx in np.array(classes).flatten(): for key, value in model.class_to_idx.items(): if class_idx == value: objects.append(cat_to_name[key]) y_pos = np.arange(len(objects))
if category_names_path: idx_to_class = load_class_mapping(category_names_path) print( f'category name: {str([idx_to_class[idx] for idx in class_idx]).strip("[]")}\n' f'class probability: {str(class_probs).strip("[]")}') else: print(f'class index: {str(class_idx).strip("[]")}\n' f'class probability: {str(class_probs).strip("[]")}') if __name__ == "__main__": parser = ArgumentParser( __file__, description='make prediction using a trained network') parser.add_argument("image_path", type=str, help="path specifying location of input image") parser.add_argument("checkpoint", type=str, help="path specifying location of model checkpoint") parser.add_argument("--gpu", "-g", action="store_true", default=False) parser.add_argument("--arch", "-a", type=str, default=None) parser.add_argument("--top_k", "-c", type=int, default=1) parser.add_argument("--category_names", "-m", type=str, default=None) args = parser.parse_args() model, model_checkpoint = load_checkpoint(args.checkpoint, args.gpu, args.arch) class_probs, class_idx = predict(args.image_path, model, args.top_k) show_class_name(class_idx, class_probs, args.category_names)