示例#1
0
def main(image_path, checkpoint, device, topk=1, category_name=None):
    model = h.load_checkpoint(checkpoint)
    probs, classes = predict(image_path, model, topk, device)

    # get probs and classes out of tensors
    probs = probs.cpu().detach().numpy()[0]
    classes = classes.cpu().numpy()[0]

    # map class number to name if JSON provided
    if category_name:
        mapping = h.load_mappings(category_name)
        classes = list(map(lambda x: mapping.get(str(x)), classes))

    return probs[0], classes
示例#2
0
def main():

    # 1. Getting Input Arguments
    args = get_input_arg()
    # 2. Loading Checkpoint (Trained Model)
    model, model_spec = load_checkpoint(args.checkpoint)
    # 3. Image Preprocessing
    np_img = process_image(args.input)
    # 4. further processing to fit numpy image to the trained model
    img = process_image_to_tensor(np_img)
    # 5. Decide using CPU or GPU for Prediction
    device = torch.device("cuda:0" if (
        torch.cuda.is_available() and args.gpu) else "cpu")
    print(f"Device used for prediction: {device}")
    # 6. Class Prediciton
    df_topk_predict, predicted_class = class_predict(img, model, device,
                                                     args.top_k)
    # 7. Parse Class inx back to label
    df = parse_idx_to_label(df_topk_predict, args.category_names, model_spec)
    print(f"Top {args. top_k} Prediciton: \n {df}")
示例#3
0
results = parser.parse_args()

img_path = results.img_path
checkpoint_path = results.checkpoint_path
top_k = results.top_k
category_names = results.category_names
gpu = results.switch

if gpu == True:
    using_gpu = torch.cuda.is_available()
    device = 'gpu'
    print('gpu On')
else:
    print('gpu Off')
    device = 'cpu'

model = utility_functions.load_checkpoint(checkpoint_path)
processed_image = utility_functions.process_image(img_path)
probs, classes = utility_functions.predict(processed_image, model, top_k,
                                           device)
# Label mapping
cat_to_name = utility_functions.labeling(category_names)

labels = []
for class_index in classes:
    labels.append(cat_to_name[str(class_index)])

# Converting from tensor to numpy-array
print('Name of class: ', labels)
print('Probability: ', probs)
示例#4
0
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
power = pa.gpu
input_img = pa.input_img
path = pa.checkpoint

training_loader, testing_loader, validation_loader = utility_functions.load_data(
)

utility_functions.nn_setup(structure, dropout, hidden_layer1, lr, power)
model_conv, criterion, optimizer_conv = nn_setup(structure, dropout,
                                                 hidden_layer1, lr, power)
utility_functions.load_checkpoint(path)

with open('cat_to_name.json', 'r') as json_file:
    cat_to_name = json.load(json_file)

probabilities = utility_functions.predict(path_image, model_conv,
                                          number_of_outputs, power)

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]))
示例#5
0
    print()
    print("Image network will predict flower image on {}, on the {} likely "
          "classes, using category name mapping {}, and gpu {}".format(
              image_path, top_k, category_names, gpu))
    print()

    # load our feature detector model
    model = models.vgg13(pretrained=True)
    model.classifier = Classifier(25088, 102, [500], drop_p=.2)

    # used trained model checkpoint from part 1
    checkout_point_dir = "/home/workspace/SavedModels"

    # load model checkpoint
    try:
        model, model_class_to_idx = load_checkpoint(
            checkout_point_dir + "/checkpoint.pth", model)
    except:
        print("Can not find provided model checkpoint.  Please try again.")
        exit()

    # predicts the flower image's class
    try:
        if gpu == "gpu":
            device = torch.device(
                "cuda:0" if torch.cuda.is_available() else "cpu")
        else:
            device = "cpu"
        probs, classes = predict(image_path, device, model, top_k)
    except:
        print("Can not find provided image or provided top K is invalid.  "
              "Please try again.")
示例#6
0
parser.add_argument("--gpu",
                    help="Optionally use GPU for inference",
                    action="store_true")

args = vars(parser.parse_args())
args_dict = dict(
    filter(lambda elem: (elem[1] != None) and (elem[1] != False),
           args.items()))

kwargs_mapping = {
    k: v
    for (k, v) in args_dict.items() if k in ['category_names']
}
cat_to_name = utility.load_class_mapping(**kwargs_mapping)

model, optimizer = utility.load_checkpoint(args_dict['checkpoint'])

kwargs_predict = {
    k: v
    for (k, v) in args_dict.items() if k in ['top_k', 'gpu']
}
probs, classes = model_functions.predict(args_dict['image_path'], model,
                                         **kwargs_predict)

classes_names = [cat_to_name[cl] for cl in classes]
predictions = zip(classes_names, probs)
print("Prediction:")
[
    print("{} with a probability of {:.3}".format(cl, p))
    for cl, p in predictions
]