Ejemplo n.º 1
0
def predict(image_path, model, topk=5, gpu='cuda'):
    ''' Predict the class (or classes) of an image using a trained deep learning model.
    '''
    
    model.to(gpu)
    
    image = processing_functions.process_image(image_path)
    
    # Convert image to PyTorch tensor first
    image = torch.from_numpy(image).type(torch.cuda.FloatTensor)
    
    # Returns a new tensor with a dimension of size one inserted at the specified position.
    image = image.unsqueeze(0)
    
    output = model.forward(image)
    
    probabilities = torch.exp(output)
    
    # Probabilities and the indices of those probabilities corresponding to the classes
    top_probabilities, top_indices = probabilities.topk(topk)
    
    # Convert to lists
    top_probabilities = top_probabilities.detach().type(torch.FloatTensor).numpy().tolist()[0] 
    top_indices = top_indices.detach().type(torch.FloatTensor).numpy().tolist()[0] 
    
    # Convert topk_indices to the actual class labels using class_to_idx
    # Invert the dictionary so you get a mapping from index to class.
    
    idx_to_class = {value: key for key, value in model.class_to_idx.items()}
    #print(idx_to_class)
    
    top_classes = [idx_to_class[index] for index in top_indices]
    
    return top_probabilities, top_classes                    
Ejemplo n.º 2
0
                    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)

print(probabilities)
print(classes)

# Display the image along with the top 5 classes
processing_functions.display_image(arguments.image_dir, class_to_name_dict,
                                   classes)