File size: 1,623 Bytes
7b58366
7e7d672
7b58366
 
 
 
 
0da089d
7e7d672
0da089d
7e7d672
 
7b58366
 
0da089d
7b58366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0da089d
7b58366
 
 
 
 
0da089d
 
 
7b58366
 
 
0da089d
 
7b58366
 
7e7d672
 
7b58366
0da089d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import torch
import numpy as np
import pennylane as qml
from model import build_hybrid_model
from data_loaders import load_single_image, load_dataset, get_class_names
from helpers import imshow


def softmax(x):
    # Compute softmax values for each set of scores in x.
    e_x = np.exp(x - np.max(x))  # Subtracting max for numerical stability
    return e_x / e_x.sum(axis=0)


def generate_prediction(img_path="./image.jpeg"):
    N_QUBITS = 4
    PARAMETER_FILEPATH = "state.pt"

    # Initialize Pennylane backend
    dev = qml.device("default.qubit", wires=N_QUBITS)

    # Initialize PyTorch config
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    # Load Model
    model = build_hybrid_model(
        pennylane_dev=dev,
        device=device,
        n_qubits=N_QUBITS,
        q_depth=6,
        q_delta=0.01
    )

    # Load Model Parameters from Disk
    model.load_state_dict(torch.load(PARAMETER_FILEPATH))

    # Load [image] from Disk
    X = load_single_image(img_path)
    imshow(X)
    input = torch.stack([X, X, X, X])

    # Generate Model Prediction
    model.eval()

    with torch.no_grad():
        input = input.to(device)
        output = model(input)
        _, preds = torch.max(output, 1)

    # Load Dataset for class_names
    class_names = get_class_names(load_dataset())
    print("OUTPUT VEC:", output[0])
    print("HOT INDEX:", preds[0])

    # Return Model Prediction
    probabilities = softmax(output[0].cpu().numpy())
    prediction = {class_name.replace("_", " "): prob for class_name, prob in zip(class_names, probabilities)}

    return prediction