def main(): user_input = get_input_args() model = modfunc.load_checkpoint(checkpoint_file=user_input.checkpoint) cat_to_name = load_cat_name(user_input.catname) probs, top_class = predict(image_path=user_input.im_dir, model=model, topk=user_input.topk, with_gpu=user_input.gpu) for cl, prob in zip(top_class, probs): print("{} : {}".format(cat_to_name[cl], prob))
def main(): # Parse the arguments passed by the user parsed_arguments = arg_parser() # Check if both checkpoint and image file exist if os.path.isfile(parsed_arguments.path_to_image) and os.path.isfile( parsed_arguments.checkpoint): # Make sure that the model is available on the used device device = torch.device("cuda:0" if ( torch.cuda.is_available() and parsed_arguments.gpu) else "cpu") print(device) # Load a model from a checkpoint loaded_model = model_functions.load_checkpoint( parsed_arguments.checkpoint) loaded_model.to(device) #print(loaded_model) processed_image = data_functions.process_image( parsed_arguments.path_to_image) # Don't allow the top_K to be lower than 1 topk = parsed_arguments.top_K if topk < 1: topk = 1 probs, classes = model_functions.predict(processed_image, loaded_model, parsed_arguments.gpu, topk) if os.path.isfile(parsed_arguments.category_names): # Create a mapping from category label to category name cat_to_name = data_functions.label_mapping( parsed_arguments.category_names) for item, prob in zip(classes, probs): print("The probability that image {} is a '{}' is {}%".format( parsed_arguments.path_to_image, cat_to_name[str(item)], prob)) else: print( 'Failed to get category to name mapping! File does not exist: %s', parsed_argument.category_names) print('Probabilities {}'.format(probs)) print('Classes {}'.format(classes)) else: print( "Either image or the checkpoint file doesn't exist. Please check the parameters." ) return
help='Number of top results to show') parser.add_argument('--gpu', type=bool, default=False, help='use gpu?') return parser.parse_args() arguments = get_input_args() #getting the arguments ready to use if arguments.gpu: device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") else: device = "cpu" #load checkpoint loaded_checkpoint = load_checkpoint(arguments.checkpoint, device) criterion = loaded_checkpoint['criterion'] optimizer = loaded_checkpoint['optimizer'] epochs = loaded_checkpoint['epochs'] model = loaded_checkpoint['model'] #load class names mapping mapping_of_categories = load_classes_json(arguments.category_names) # #predict probs top_outputs = predict(arguments.path, model, mapping_of_categories,arguments.top_k, device) # print("Command Line Arguments:\n path =", arguments.path, # "\n checkpoint =", arguments.checkpoint, # "\n category_names =", arguments.category_names, # "\n gpu =", arguments.gpu,
def classify(): image = None #----------------- Uploading User Tree image from URL or File ------------------- st.title( 'Please provide an image - will be identified as pepper tree, willow tree, or neither.' ) #----------------- Side Bar Options for User Image ------------------------------ st.title("Upload Options") input_method = st.radio("Options", ('File Upload', 'URL')) flag = 0 if input_method == 'File Upload': user_upload_image = st.file_uploader("Upload a picture of Tree", type=['png', 'jpeg', 'jpg']) if user_upload_image is not None: file_details = { "FileName": user_upload_image.name, "FileType": user_upload_image.type, "FileSize": user_upload_image.size } # st.write(file_details) flag = 1 if flag == 1: image_source = user_upload_image.name image = Image.open(user_upload_image) st.image( image, caption=user_upload_image.name + ' ' + user_upload_image.type + ' ' + str(user_upload_image.size) + ' bytes', width=300, use_column_width=True, ) # Image from URL if input_method == 'URL': image_url = st.text_area("Enter the complete Url", key="user_url_choice") image_url_status = st.button('Upload') if image_url_status: image_source = image_url image = Image.open(urllib.request.urlopen(image_url)) st.image( image, caption=str(image), width=300, use_column_width=True, ) else: st.warning('click on upload') #---------------------- Choosing Classification Method --------------------------- st.title('Choose the model for Analysis') model_selected = st.radio("Options", ['Pre Trained Model']) # model_selected = st.sidebar.radio( # "Options", # ('Pre Trained Model', 'CNN Model', 'FFN Model', 'Random Forest', 'Logistic Regression', 'Ensemble'),0) if model_selected == 'Pre Trained Model': model_selected2 = st.selectbox("Choose the Pretrained Model", ['VGG16']) # model_selected2 = st.sidebar.selectbox("Choose the Pretrained Model", # ['VGG16','PTM2','PTM2','PTM2','PTM2','PTM2','PTM2','PTM2']) if model_selected2 == 'VGG16' and image != None: # note that the predict function returns top_probabilities, top_classes model = load_checkpoint( '/home/kate/data_and_models/ai_models/vgg16-tree-3class-model.pth') probs, classes = predict(image, model) st.title('Tree Classification Results') with open('tree_to_name.json', 'r') as f: tree_to_name = json.load(f) tree_names = [tree_to_name[i] for i in classes] chart_data = pd.DataFrame(data=[probs], columns=tree_names) # st.write("chart_data type ", type(chart_data)) if (chart_data["willow tree"][0]) > 0.5: tree_detected = "Willow Tree" elif (chart_data["pepper tree"][0]) > 0.5: tree_detected = "Pepper Tree" else: tree_detected = "Not a Pepper Tree or a Willow Tree" st.write('The image is: ', tree_detected) st.write('Percentage confidence in the image identification ', chart_data) st.bar_chart(chart_data)
from workspace_utils import active_session from model_functions import load_checkpoint from utils_functions import process_image from collections import OrderedDict from PIL import Image # set input args to variables image_path = args['image_path'] checkpoint = args['checkpoint'] topk = args['topk'] category_map = args['category_names'] device = torch.device("cuda:0" if args['gpu'] is True else "cpu") model = load_checkpoint(checkpoint) # move model to cuda and use in eval mode model.to(device) model.eval() #load and process image and convert to torch tensor processed_image = process_image(image_path) image = torch.from_numpy(processed_image) # add additional dimension to torch tensor to match input size - should be (1,3,224,224) image = image.unsqueeze(0) image = image.to(device) # predict classification using the trained model (output will be from softmax function) with torch.no_grad():
type=int, default=5, help='Top k classes and probabilities') parser.add_argument('--json', type=str, default='Landmarks_to_name.json', help='class_to_name json file') parser.add_argument('--gpu', type=str, default='cuda', help='GPU or CPU') arguments = parser.parse_args() # Load in a mapping from category label to category name class_to_name_dict = processing_functions.load_json(arguments.json) # Load pretrained network model = model_functions.load_checkpoint(arguments.checkpoint) print(model) checkpoint = torch.load(arguments.checkpoint) # Scales, crops, and normalizes a PIL image for the PyTorch model; returns a Numpy array image = processing_functions.process_image(arguments.image_dir, checkpoint['hidden_layer_units']) # Display image processing_functions.imshow(image) # Highest k probabilities and the indices of those probabilities corresponding to the classes (converted to the actual class labels) probabilities, classes = model_functions.predict(arguments.image_dir, model, arguments.topk, arguments.gpu)
default=5, dest="top_k", action="store", type=int) parser.add_argument('--category_names', dest="category_names", action="store", default='cat_to_name.json') parse = parser.parse_args() outputs = parse.top_k processor = parse.gpu input_img = parse.img chkt_path = parse.checkpoint model_load = model_functions.load_checkpoint(chkt_path) model_functions.load_checkpoint(filepath) # cpu device = torch.device("cpu") # gpu if parse.gpu: device = torch.device("cuda:0") with open(category_names) as json_file: cat_to_name = json.load(json_file) top_probabilities, top_classes = model_functions.predict( img_path, model, outputs)
##### ARGPARSER parser = argparse.ArgumentParser('Enter path to image file.') parser.add_argument('image', action='store') parser.add_argument('checkpoint', action='store') parser.add_argument('--cat_names', action='store', default='cat_to_name.json') parser.add_argument('--gpu', action='store', type=bool, default=True) parser.add_argument('--top_k', action='store', type=int, default=5) args = parser.parse_args() ##### PREDICTION ### Load model checkpoint and dictionary #train_dataset, trainloader = load_train('flowers/train') model, epochs, learn, optim_state, optimizer, criterion, classes_d = load_checkpoint( args.checkpoint) label_dict = get_labels(args.cat_names) #model.class_to_idx = train_dataset.class_to_idx ### Configure device to use - gpu or cpu device = choose_device(args.gpu) ### Load and process image, run forward propagation to obtain probabilities and classes for top_k predictions image = process_image(args.image) probabilities, classes = predict(image, model, device, classes_d, k=args.top_k) ### Print result print('The top {} predictions of the model are the following:'.format( args.top_k))
if args["topk"] <= 0: print("Please set the valid top numbers") exit() # make the dictionary from category(file) name to flower name with open(args["category_names"]) as f: cat_to_name = json.load(f) # create the torch.device object if args["gpu"] == True: device = torch.device("cuda" if torch.cuda.is_available() else "cpu") else: device = torch.device("cpu") # load the file and recreate the model model, cat_to_idx = model_functions.load_checkpoint(args["checkpoint_path"], device) # make the dictionary from idx (of output) to the category(file name) idx_to_cat = {val: key for key, val in cat_to_idx.items()} # transfer the model to gpu if availavle model = model.to(device) # predict the top k probability and categories top_p, top_class = utility_functions.predict(args["image_path"], model, device, args["topk"]) # print out the prediction in the console for i in range(args["topk"]): label = cat_to_name[idx_to_cat[top_class[0][i].item()]] clas = top_class[0][i].item()
def main(): # def predict( class_dict, topk=5): ''' Predict the class (or classes) of an image using a trained deep learning model. Arguments: - image_path (str - path to image to process) - model (trained neural network model) - class_dict (class_to_idx dictionary from checkpoint) - topk (int - number of top classes/probabilities to calculate) Output: - probs (list - top 5 predicted probabilities) - classes (list - top 5 predicted classes) ''' topk = 5 # Topk probabilities/classes # Get command line arguments in_arg = get_input_args() # Get image path for testing image_path = in_arg.img_path checkpoint = in_arg.chk_pt # Switch to "cpu" mode device = torch.device("cpu") # Load the checkpoint model = model_functions.load_checkpoint(checkpoint) model.to(device) model.eval() # Run image through the model with torch.no_grad(): # Process image image = utility_functions.process_image(image_path) image = image.unsqueeze(0) image.to(device) # Run through model log_pbs = model.forward(image) ps = torch.exp(log_pbs) top_p, top_c = ps.topk(topk, dim=1, largest=True, sorted=True) probs = top_p.tolist()[0] classes = top_c.tolist()[0] # Print out the top 5 classes and corresponding flower names # Invert the class dictionary class_dict_invert = dict([[v, k] for k, v in model.class_to_idx.items()]) # Load the category to name json file cat_to_name = utility_functions.import_cat_to_names(in_arg.cat_names) flower_names = [] class_num = [] for c in classes: class_num.append(class_dict_invert[c]) flower_names.append(cat_to_name[class_dict_invert[c]]) # Print functions ------------ print("/n") print("Image: {}".format(image_path)) print("Top Flower Name: {}".format(flower_names[0].title())) print("Top Probability: {:.3f}".format(probs[0])) print("---------------------") print("Top 5 Class:Probabilities") print("{}: {:.3f}".format(flower_names[0].title(), probs[0])) print("{}: {:.3f}".format(flower_names[1].title(), probs[1])) print("{}: {:.3f}".format(flower_names[2].title(), probs[2])) print("{}: {:.3f}".format(flower_names[3].title(), probs[3])) print("{}: {:.3f}".format(flower_names[4].title(), probs[4])) print("/n")
from model_functions import build_model, load_checkpoint, predict import argparse parser = argparse.ArgumentParser( description='use trained model to predict class of a image ') parser.add_argument('path_to_image', help='the path of image') parser.add_argument('model_directory', help='the directory of model that has been trained') parser.add_argument('--top_K', type=int, default=3, help='return the top K most possible classes') parser.add_argument('--category_names', default='', help='output the actual class name') parser.add_argument('--gpu', action='store_true', default=False, help='the training mode') args = parser.parse_args() model, other_info = load_checkpoint(args.model_directory) image = process_image(args.path_to_image) classes, probs = predict(image, model, topk=args.top_K, category_name=args.category_names, gpu_truth=args.gpu, other_info=other_info) print(classes) print(probs)