|
| 1 | +import pennylane as qml |
| 2 | +from pennylane import numpy as np |
| 3 | +import matplotlib.pyplot as plt |
| 4 | +from matplotlib.animation import FuncAnimation |
| 5 | +from collections import Counter |
| 6 | + |
| 7 | +# Config |
| 8 | +num_visible = 2 |
| 9 | +num_hidden = 2 |
| 10 | +num_qubits = num_visible + num_hidden |
| 11 | +epochs = 50 |
| 12 | +shots = 1000 |
| 13 | + |
| 14 | +dev = qml.device("default.qubit", wires=num_qubits, shots=shots) |
| 15 | + |
| 16 | +# Target data (biased toward '11' and '00') |
| 17 | +target_bitstrings = ['11', '11', '11', '00', '00', '01'] |
| 18 | +target_counts = Counter(target_bitstrings) |
| 19 | +target_probs = { |
| 20 | + format(i, f'0{num_visible}b'): target_counts.get(format(i, f'0{num_visible}b'), 0) / len(target_bitstrings) |
| 21 | + for i in range(2**num_visible) |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +# Ansatz |
| 26 | +def vqbm_ansatz(params): |
| 27 | + for i in range(num_qubits): |
| 28 | + qml.RY(params[i], wires=i) |
| 29 | + for i in range(num_qubits - 1): |
| 30 | + qml.CNOT(wires=[i, i + 1]) |
| 31 | + for i in range(num_qubits): |
| 32 | + qml.RZ(params[i + num_qubits], wires=i) |
| 33 | + |
| 34 | +# Hamiltonian |
| 35 | +def generate_hamiltonian(): |
| 36 | + coeffs = [] |
| 37 | + observables = [] |
| 38 | + for i in range(num_qubits): |
| 39 | + coeffs.append(np.random.uniform(-1, 1)) |
| 40 | + observables.append(qml.PauliZ(wires=i)) |
| 41 | + for i in range(num_qubits): |
| 42 | + for j in range(i + 1, num_qubits): |
| 43 | + coeffs.append(np.random.uniform(-1, 1)) |
| 44 | + observables.append(qml.PauliZ(wires=i) @ qml.PauliZ(wires=j)) |
| 45 | + return qml.Hamiltonian(coeffs, observables) |
| 46 | + |
| 47 | +H = generate_hamiltonian() |
| 48 | + |
| 49 | + |
| 50 | +@qml.qnode(dev) |
| 51 | +def energy_expectation(params): |
| 52 | + vqbm_ansatz(params) |
| 53 | + return qml.expval(H) |
| 54 | + |
| 55 | +@qml.qnode(dev) |
| 56 | +def sample_circuit(params): |
| 57 | + vqbm_ansatz(params) |
| 58 | + return qml.sample(wires=range(num_visible)) |
| 59 | + |
| 60 | +# Helper: Convert samples to bitstring histogram |
| 61 | +def get_distribution(samples): |
| 62 | + bitstrings = ["".join(str(bit) for bit in s) for s in samples] |
| 63 | + counts = Counter(bitstrings) |
| 64 | + total = sum(counts.values()) |
| 65 | + return { |
| 66 | + format(i, f'0{num_visible}b'): counts.get(format(i, f'0{num_visible}b'), 0) / total |
| 67 | + for i in range(2**num_visible) |
| 68 | + } |
| 69 | + |
| 70 | +# Training and storing distributions |
| 71 | +params = 0.01 * np.random.randn(2 * num_qubits, requires_grad=True) |
| 72 | +opt = qml.AdamOptimizer(stepsize=0.1) |
| 73 | +history = [] |
| 74 | + |
| 75 | +for epoch in range(epochs): |
| 76 | + params = opt.step(energy_expectation, params) |
| 77 | + learned_dist = get_distribution(sample_circuit(params)) |
| 78 | + history.append(learned_dist) |
| 79 | + if epoch % 10 == 0: |
| 80 | + print(f"Epoch {epoch} energy: {energy_expectation(params):.4f}") |
| 81 | + |
| 82 | +# Animation setup |
| 83 | +states = [format(i, f'0{num_visible}b') for i in range(2**num_visible)] |
| 84 | + |
| 85 | +fig, ax = plt.subplots() |
| 86 | +bar1 = ax.bar(states, [0]*len(states), color='skyblue', label="VQBM") |
| 87 | +bar2 = ax.bar(states, [target_probs[s] for s in states], color='orange', alpha=0.6, label="Target") |
| 88 | +ax.set_ylim(0, 1) |
| 89 | +ax.set_ylabel("Probability") |
| 90 | +ax.set_title("VQBM Learning Over Epochs") |
| 91 | +ax.legend() |
| 92 | + |
| 93 | +def update(frame): |
| 94 | + dist = history[frame] |
| 95 | + for i, state in enumerate(states): |
| 96 | + bar1[i].set_height(dist[state]) |
| 97 | + ax.set_title(f"Epoch {frame}") |
| 98 | + |
| 99 | +ani = FuncAnimation(fig, update, frames=len(history), repeat=False) |
| 100 | +plt.show() |
| 101 | + |
| 102 | + |
| 103 | +""" |
| 104 | +Define a target distribution (e.g., classical binary data). |
| 105 | +At each epoch: |
| 106 | +Train the model. |
| 107 | +Sample the VQBM output. |
| 108 | +Compute histogram probabilities. |
| 109 | +
|
| 110 | +Store results for animation. |
| 111 | +Use matplotlib.animation to animate VQBM’s learned distribution converging to the target. |
| 112 | +Trains a VQBM using an energy-based loss. |
| 113 | +Samples from the circuit at each epoch. |
| 114 | +Animates how the model’s output distribution converges toward the target. |
| 115 | +""" |
0 commit comments