def predict():

    device = args.device

    # label mapping..
    with open(args.category_names, 'r') as f:
        cat_to_name = json.load(f)

    image_input = process_image(args.opts[0])
    image_input = image_input.type(torch.cuda.FloatTensor)
    image_input.unsqueeze_(0)
    image_input = image_input.to(device)

    model = load_model(args.opts[1])
    model.to(device)

    index_to_class = {value: key for key, value in model.class_to_idx.items()}

    with torch.no_grad():
        # set to evaluation mode..
        model.eval()

        output = model.forward(image_input)
        ps = torch.exp(output)
        top_k, top_classes = ps.topk(args.top_k, dim=1)

        top_k = top_k.cpu().numpy()[0]
        top_classes = top_classes.cpu().numpy()[0]

        labels = [cat_to_name[str(index_to_class[x])] for x in top_classes]

        percentage = ['{:.5f}'.format(x) for x in top_k]

        preds = dict(zip(labels, percentage))
        return preds
Beispiel #2
0
def predict(image_path, model, topk):
    ''' Predict the class (or classes) of an image using a trained deep learning model.
    '''
    model.eval()
    model.cpu()
    img = predict_utils.process_image(image_path)
    img = img.unsqueeze_(0)
    img = img.float()

    with torch.no_grad():
        output = model.forward(img)
        probs, classes = torch.topk(input=output, k=topk)
        top_prob = probs.exp()

    idx_to_class = {val: key for key, val in model.class_to_idx.items()}
    top_classes = [idx_to_class[each] for each in classes.cpu().numpy()[0]]

    return top_prob[0].numpy(), top_classes
Beispiel #3
0
def main():
    # Parse input arguments
    args = parse_inputs()
    

    # We get the image as a FloatTensor
    img = process_image(args.image)
  

    # We now have to load the checkpoint and build the model
    model = loadcheckpoint(args)
    

    # We will performe the calculation in the select device
    device = "cuda:0" if torch.cuda.is_available() and args.gpu else "cpu"
    print(f'These computations are performed in {device}')
    model.to(device)

    # We set the model to evaluation mode (so that we are not using dropout)
    model.eval()
    with torch.no_grad():
        probs,classes = predict(img, model, args.top_k, device)

    # Now, if we indicated a category_name:
    if args.category_names:
        try:
            with open(args.category_names, 'r') as f:
                cat_to_name = json.load(f)
        except FileNotFoundError:
            print("The category names file has not been found.")
            print("Please introduce a valid file.")
            sys.exit("Program terminating.")
        classes = [cat_to_name[item] for item in classes]
 

    # Printing out the results
    print(f'The {args.top_k} most likely classes of flowers are:')
    
    for key, value in zip(classes, probs):
        print(f'Flower: {key};    '
              f'Probability: {value}')
def predict(image_path, model, top_k=5, gpu=False, verbose=False):
    """ Predict the class (or classes) of an image using a trained deep learning model.
        Parameters:
          image path - filepath to image to be analyzed
          model - trained model to use for inference/prediction
          top KKK - specify the number of top K most likely class results to produce
          GPU flag - flag to enable use of GPU if available
          verbose flag - flag to enable verbose output

        Returns:
          probabilities - list of probabilities
          numeric classes - list of classes in the form of numeric codes
          name classes - list of classes in the form of name strings
    """

    device = torch.device(
        "cuda" if torch.cuda.is_available() and gpu else "cpu")
    if verbose: print(f"Running in {device} mode.")

    model.to(device)
    model.eval()

    image = process_image(image_path)
    image = torch.FloatTensor(image).to(device)

    #image.requires_grad_(False)
    with torch.no_grad():
        image.unsqueeze_(0)
        logps = model.forward(image)
        ps = torch.exp(logps)
        ps = ps.cpu(
        )  # just force this to cpu always since remaining computations are trivial?
        top_probs, top_labels = ps.topk(top_k, dim=1)

        probs = top_probs.numpy()[0].tolist()
        labels = top_labels.numpy()[0].tolist()

        num_classes = [model.idx_to_class[x] for x in labels]
        name_classes = [model.cat_to_name[str(x)] for x in num_classes]

    return probs, num_classes, name_classes
Beispiel #5
0
def main():
    # get command line arguments
    in_arg = predict_utils.get_input_args()

    # process image
    print('Processing image...')
    image = predict_utils.process_image(in_arg.image_path)
    print('Image processed\n')

    # load model
    print('Loading saved model...')
    model = predict_utils.load_model(in_arg.checkpoint_path)
    print('Model loaded\n')

    print('Predicting...')
    with torch.no_grad():
        if in_arg.gpu == True:
            model.to('cuda')
            output = model.forward(image.cuda())
            model.to('cpu')
        else:
            output = model.forward(image)
    print('Prediction finished\n')

    if in_arg.gpu == True:
        probes, classes = torch.exp(output.cpu()).topk(in_arg.top_k)
    else:
        probes, classes = torch.exp(output).topk(in_arg.top_k)

    probes = probes.detach().numpy().tolist()[0]
    indices = classes.detach().numpy().tolist()[0]
    idx_to_class = {val: key for key, val in model.class_to_idx.items()}
    classes = [idx_to_class[idx] for idx in indices]

    cat_to_name = predict_utils.load_category_names(in_arg.category_names)
    flowers = [cat_to_name[c] for c in classes]

    for i in range(len(probes)):
        print('{}: {:.2f}%'.format(flowers[i], probes[i] * 100))
Beispiel #6
0
                        dest='k',
                        type=int,
                        help='Number of prediction classes to return')
    parser.add_argument('--category_names',
                        action='store',
                        dest='classnames_path',
                        help='Path to a JSON file containing classnames')
    arguments = parser.parse_args()

    # Load the tensorflow model
    # Reference: https://github.com/tensorflow/tensorflow/issues/26835
    model = tf.keras.models.load_model(
        arguments.model_path, custom_objects={'KerasLayer': hub.KerasLayer})

    # Load the image
    image = predict_utils.process_image(arguments.img_path)

    # Make predictions
    results = model.predict(image)
    results = results[0]

    # See if a classname JSON has been passed
    if arguments.classnames_path:
        classnames = predict_utils.read_json(arguments.classnames_path)
    else:
        classnames = None

    # Check for arguments
    # If K has been passed, print the top K classes
    if arguments.k and classnames:
        top_probs, top_classes = predict_utils.k_results(results, arguments.k)
Beispiel #7
0
parser.add_argument('checkpoint_path', help="Path to model checkpoint to use")
parser.add_argument('--topk',
                    help="Number of classes and probabilities to display",
                    default=1,
                    type=int)
parser.add_argument('--category_names',
                    help="File with name mappings for classes")
parser.add_argument(
    '--gpu',
    help="Flag to use GPU for training data, recommended if GPU available.",
    action='store_true')

A = parser.parse_args()

#process the image
im = put.process_image(A.image_path)

#load the checkpoint into the model
model = put.load_model(A.checkpoint_path)

#predict the flower class
probabilities, classes = put.predict(model, im, A.topk, A.gpu)

#output something
print(f"Probabilities: {probabilities}")
if A.category_names is not None:
    with open(A.category_names, 'r') as f:
        cat_to_name = json.load(f)
    names = [cat_to_name[key] for key in classes]
    print(f"Names: {names}")
else:
                    help='A mapping of numerical categories to their names')
args = parser.parse_args()

image_path = args.image_path
model_path = args.model_path
top_k = args.top_k
category_names = args.category_names
class_names = None
if (category_names):
    with open(category_names, 'r') as f:
        class_names = json.load(f)
model = tf.keras.models.load_model(
    model_path, custom_objects={'KerasLayer': hub.KerasLayer})
model.summary()

im = np.expand_dims(pu.process_image(image_path), axis=0)
ps = model.predict(im)[0]
if top_k:
    probs = np.flip(ps[np.argsort(ps)[-top_k:]]).tolist()
else:
    probs = np.flip(ps[np.argsort(ps)]).tolist()
classes = []
for prob in probs:
    prob_index = np.where(ps == prob)
    class_label = np.asscalar(np.array(prob_index)) + 1
    if (not class_names):
        classes.append(class_label)
    else:
        classes.append(class_names[str(class_label)])
print(probs)
print(classes)