Beispiel #1
0
def main():

    # Getting input arguments by user when running the program from terminal
    in_arg = get_input_args()
    print('Arguments in')

    # Preprocessing image format before prediction
    img = process_image(in_arg.image_path)
    print('Image processed')

    # Load checkpoint file and rebuilding model
    model = load_checkpoint_file(in_arg.checkpoint_file, in_arg.arch)
    print('Rebuilt model and reloaded model state')

    # Predicting top K probabilities and their corresponding classes
    ps_topk, cat_topk = predict(img, model, in_arg.topk)
    print('Prediction done')

    # Creating a mapping dictionary between image category and its name
    with open(in_arg.category_names, 'r') as f:
        cat_to_name_dict = json.load(f)

    # Transforming image categories to labels for plotting
    labels = [cat_to_name_dict[clas] for clas in cat_topk]
    ps_topk_formatted = ["%.1f" % (ps * 100) for ps in ps_topk]

    # Printing prediction
    print('Top {} predicted categories and probabilities'.format(in_arg.topk))
    print('    Categories: {}'.format(labels))
    print('    Probabilities, %: ', ps_topk_formatted)

    print('END')
def main():
    args = get_args()
    model = load_checkpoint(args.checkpoint)
    prob, label = predict(args.image_path, model, args.top_k, args.gpu)
    print("predeicted categories are: ", label, " with probabilities ", prob,
          ", respectivly")
    if args.category_names:
        cat_names = sanity_check(prob, label, args.cat_path)
        print("category names: ", cat_names)
Beispiel #3
0
def prediction():
    ''' Function takes in image as command line argument and will print out it's predicted
    class (or classes) using a trained deep learning model.
    '''

    in_arg = get_input_args()
    device = torch.device("cuda" if torch.cuda.is_available() and in_arg.gpu == "gpu" else "cpu")
    print("Loading model...\n")
    model, optimizer, criterion = create_model(device)
    load_checkpoint(model, optimizer)
    trainloader, testloader, validationloader, train_data, test_transforms = data_loading()
    probabilities, classes = predict(model, train_data, device)
    print("\nTop {} prediction/s for input image are as follows:\n".format(in_arg.top_k))
    print_outcome(probabilities, classes, model, train_data, device)
Beispiel #4
0
    default='gpu',
    type=str)
parser.add_argument('--topk',
                    help="The number of topk probabilities to be displayed",
                    default=1,
                    type=int)
parser.add_argument(
    '--class_to_cat',
    help='JSON file that maps the class values to other category names',
    default='cat_to_name.json',
    type=str)

args = parser.parse_args()

image = args.image
checkpoint_path = args.checkpoint
device = args.gpu
topk = args.topk
class_to_cat = args.class_to_cat

#Loads and build the model from the path
cat_to_name = pf.to_open_json(class_to_cat)

model, checkpoint = pf.load_checkpoint(checkpoint_path)

# Scales, crops, and normalizes a PIL image for a PyTorch model, returns an Numpy array
pf.process_image(image)

probabilities, classes = pf.predict(model, image, topk, checkpoint)

pf.display_flower_name(probabilities, classes, cat_to_name)
Beispiel #5
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('input',
                        type=str,
                        default='flowers/test/54/image_05413.jpg',
                        help='filename of the Image to be classified')
    parser.add_argument('checkpoint',
                        type=str,
                        help='Checkpoint file to be used')
    parser.add_argument(
        '--top_k',
        type=int,
        default=5,
        help='Number of the top most likely classes to be shown')
    parser.add_argument('--category_names',
                        type=str,
                        default='cat_to_name.json',
                        help='Dictionary Json file number vs names')
    parser.add_argument('--gpu',
                        action='store_true',
                        default=False,
                        help='Please Use GPU for Prediction')

    args = parser.parse_args()
    print(
        "\n\n##########################################################################################"
    )
    print(
        "The Neural Network for the Prediction has been created with the following Parametres:"
    )
    print("The Image for the Prediction is: {}".format(args.input))
    print("The checkpoint with all the details is: {}".format(args.checkpoint))
    print("The Number of the most lively classes to be show is : {}".format(
        args.top_k))
    print("The Dictionary Json file number vs names is: {}".format(
        args.category_names))

    if args.gpu:
        print("The model will run use the GPU ".format(args.gpu))
    else:
        print("....Please add the GPU......")
        exit()
    print(
        "##########################################################################################\n\n"
    )
    checkpoint = args.checkpoint
    image_path = args.input
    map_file = args.category_names
    topk = args.top_k

    print("....Running The Prediction... ")
    model = predict_functions.load_checkpoint(filepath=checkpoint)
    print("phase1")
    probs, classes = predict_functions.predict(image_path, model, topk=topk)
    print("phase2")

    with open(map_file, 'r') as f:
        cat_to_name = json.load(f)
    print("Flower Class Name: Associated Probability: ")
    for i in range(0, len(classes)):
        print("Class: {} (Probability: {:.3f})".format(cat_to_name[classes[i]],
                                                       probs[i]))

    return probs, classes
Beispiel #6
0
    # Removing RunTimeError for missing batch size - add batch size of 1
    pytorch_tensor = pytorch_tensor.unsqueeze(0)

    # Run model in evaluation mode to make predictions
    model.to(device)
    model.eval()
    LogSoftmax_predictions = model.forward(pytorch_tensor)
    predictions = torch.exp(LogSoftmax_predictions)

    # Identify top predictions and top labels
    top_p, top_class = predictions.topk(topk)

    top_p = top_p.detach().numpy().tolist()

    top_class = top_class.tolist()

    labels = pd.DataFrame({
        'class': pd.Series(model.class_to_idx),
        'flower_name': pd.Series(cat_to_name)
    })
    labels = labels.set_index('class')
    labels = labels.iloc[top_class[0]]
    labels['predictions'] = top_p[0]

    return labels


labels = predict(image_path, model, topk)
print(labels)
Beispiel #7
0
def main():
    # Calling the get_input_args_predict function to get the input arguments.
    in_arg = get_input_args_predict()

    # checking what device the user want to train by.
    if in_arg.gpu:
        device = 'cuda'
    else:
        device = 'cpu'

    # Using try statement to check if the passed image_path by the user is available or not.
    image_path = in_arg.input
    try:
        Image.open(image_path)
    except:
        print("The Image path is not Defined!")
        print("Please try again with the correct path of the Image!")
        sys.exit(0)

    cat_to_name = in_arg.category_names
    # The dfault of cat_to_name is None, so if it isn't None and the user passed a value, check the file.
    if cat_to_name != None:
        # Using try statement to check if the passed category_names by the user is available or not.
        try:
            with open(cat_to_name, 'r'):
                pass
        except FileNotFoundError:
            print("The path of Category Names file is not Defined!")
            print("Please try again with the correct path!")
            sys.exit(0)

    filepath = in_arg.checkpoint
    # Loading the model by passing the path of it, if it's available
    # and the device which the user want to predict with.
    model = load_checkpoint(filepath, device)

    topk = in_arg.top_k
    # Calling predict_classes_names to obtain the most likely 5 predicted classes with their prbabilities.
    probs, classes = predict(image_path, model, device, topk)

    # If there's a categories to names file is passed, call predict_classes_names function to
    # create the category names from the classes labels.
    # Then adjust the word variable for the result printing process.
    if cat_to_name != None:
        classes = predict_classes_names(cat_to_name, classes_output=classes)
        word = "Flower Name"

    else:
        word = "Class Number"

    if len(probs) == 1:
        # if topk = 1, the probs list will contain a single value, so print once.
        print(
            "Predicted {}: {}\t\t ... \t Predicted Class Probability: {:.3f}".
            format(word, classes[0], probs[0]))

    else:
        # if topk > 1, the probs list will contain multiple value, so loop through them and to print.
        print("Top {} most likely Classes".format(topk))
        for i in range(len(probs)):
            print(
                "Predicted {} ({}): {:>20}\t ... \tPredicted Class Probability: {:.3f}"
                .format(word, i + 1, classes[i], probs[i]))
Beispiel #8
0

print(parser.parse_args())
pred_Image_params = parser.parse_args()

retval, desc = pf.validate_cmdlineargs(pred_Image_params)

if(retval == False):
    print(desc)
    



if(retval == True):
    
    data_dir = pred_Image_params.datadir
    train_dir = data_dir + '/train'
    valid_dir = data_dir + '/valid'
    test_dir = data_dir + '/test'
    
    chkpoint_path = pred_Image_params.chkpointdir + 'checkpoint.pth'
    modelv2, optimv2 = pf.load_checkpoint(chkpoint_path)
    pf.predict(pred_Image_params.testimgpath, modelv2, pred_Image_params.topK, pred_Image_params.noGPU)

'''
# command line arguments
python predict.py -datadir 'flowers' -topK 5 -testimgpath "flowers/test/10/image_07090.jpg"
python predict.py -datadir 'flowers' -topK 5 -testimgpath "flowers/test/12/image_04014.jpg"
python predict.py -datadir 'flowers' -topK 5 -testimgpath "flowers/test/11/image_03151.jpg"
'''