def feature_map(): # BUILD FEATURE MAP HERE - START # import required qiskit libraries if additional libraries are required # build the feature map def self_product(x: np.ndarray) -> float: """ Define a function map from R^n to R. Args: x: data Returns: float: the mapped value """ coeff = x[0] if len(x) == 1 else \ functools.reduce(lambda m, n:np.square( m * n), np.pi - x) return coeff feature_dim = 5 # equal to the dimension of the data feature_map = ZFeatureMap(feature_dimension=feature_dim, data_map_func=self_product, reps=2) feature_map.draw() # BUILD FEATURE MAP HERE - END #return the feature map which is either a FeatureMap or QuantumCircuit object return feature_map # the write_and_run function writes the content in this cell into the file "variational_circuit.py"
def test_parameter_prefix(self): """Test the Parameter prefix""" encoding_pauli = PauliFeatureMap(feature_dimension=2, reps=2, paulis=["ZY"], parameter_prefix="p") encoding_z = ZFeatureMap(feature_dimension=2, reps=2, parameter_prefix="q") encoding_zz = ZZFeatureMap(feature_dimension=2, reps=2, parameter_prefix="r") x = ParameterVector("x", 2) y = Parameter("y") self.assertEqual( str(encoding_pauli.parameters), "ParameterView([ParameterVectorElement(p[0]), ParameterVectorElement(p[1])])", ) self.assertEqual( str(encoding_z.parameters), "ParameterView([ParameterVectorElement(q[0]), ParameterVectorElement(q[1])])", ) self.assertEqual( str(encoding_zz.parameters), "ParameterView([ParameterVectorElement(r[0]), ParameterVectorElement(r[1])])", ) encoding_pauli_param_x = encoding_pauli.assign_parameters(x) encoding_z_param_x = encoding_z.assign_parameters(x) encoding_zz_param_x = encoding_zz.assign_parameters(x) self.assertEqual( str(encoding_pauli_param_x.parameters), "ParameterView([ParameterVectorElement(x[0]), ParameterVectorElement(x[1])])", ) self.assertEqual( str(encoding_z_param_x.parameters), "ParameterView([ParameterVectorElement(x[0]), ParameterVectorElement(x[1])])", ) self.assertEqual( str(encoding_zz_param_x.parameters), "ParameterView([ParameterVectorElement(x[0]), ParameterVectorElement(x[1])])", ) encoding_pauli_param_y = encoding_pauli.assign_parameters({1, y}) encoding_z_param_y = encoding_z.assign_parameters({1, y}) encoding_zz_param_y = encoding_zz.assign_parameters({1, y}) self.assertEqual(str(encoding_pauli_param_y.parameters), "ParameterView([Parameter(y)])") self.assertEqual(str(encoding_z_param_y.parameters), "ParameterView([Parameter(y)])") self.assertEqual(str(encoding_zz_param_y.parameters), "ParameterView([Parameter(y)])")
def feature_map(): # BUILD FEATURE MAP HERE - START # import required qiskit libraries if additional libraries are required # build the feature map feature_dim = 3 # equal to the dimension of the data feature_map = ZFeatureMap(feature_dimension=feature_dim, reps=4) feature_map.draw() # BUILD FEATURE MAP HERE - END #return the feature map which is either a FeatureMap or QuantumCircuit object return feature_map
def setUp(self): super().setUp() algorithm_globals.random_seed = 10598 self.statevector_simulator = QuantumInstance( BasicAer.get_backend("statevector_simulator"), shots=1, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) # number of qubits is equal to the number of features self.q = 2 # number of steps performed during the training procedure self.tau = 100 self.feature_map = ZFeatureMap(feature_dimension=self.q, reps=1) sample, label = make_blobs(n_samples=20, n_features=2, centers=2, random_state=3, shuffle=True) sample = MinMaxScaler(feature_range=(0, np.pi)).fit_transform(sample) # split into train and test set self.sample_train = sample[:15] self.label_train = label[:15] self.sample_test = sample[15:] self.label_test = label[15:] # The same for a 4-dimensional example # number of qubits is equal to the number of features self.q_4d = 4 self.feature_map_4d = ZFeatureMap(feature_dimension=self.q_4d, reps=1) sample_4d, label_4d = make_blobs(n_samples=20, n_features=self.q_4d, centers=2, random_state=3, shuffle=True) sample_4d = MinMaxScaler( feature_range=(0, np.pi)).fit_transform(sample_4d) # split into train and test set self.sample_train_4d = sample_4d[:15] self.label_train_4d = label_4d[:15] self.sample_test_4d = sample_4d[15:] self.label_test_4d = label_4d[15:]
def feature_map(): # BUILD FEATURE MAP HERE - START # import required qiskit libraries if additional libraries are required # build the feature map feature_dim = 3 # equal to the dimension of the data feature_map = ZFeatureMap(feature_dimension=feature_dim, reps=2) feature_map.draw() # BUILD FEATURE MAP HERE - END #return the feature map which is either a FeatureMap or QuantumCircuit object return feature_map # the write_and_run function writes the content in this cell into the file "variational_circuit.py"
def test_partial_large_circuit(self, method): np.random.seed(21) featuremap = ZFeatureMap(2, reps=1) featuremap.assign_parameters(np.random.random( featuremap.num_parameters), inplace=True) ansatz = RealAmplitudes(2, reps=1) params = ansatz.ordered_parameters[:] values = np.random.random(ansatz.num_parameters) init = Statevector.from_int(1, dims=(2, 2)) circuit = featuremap.compose(ansatz) grad = StateGradient(X ^ X, circuit, init, params) grads = getattr(grad, method)(dict(zip(params, values))) ref = [-0.7700884147948044, 0.011116605029003569, -0.6889501710944109, -0.07972088641561373] np.testing.assert_array_almost_equal(grads, ref)
def test_first_order_circuit(self): """Test a first order expansion circuit.""" times = [0.2, 1, np.pi, -1.2] encoding = ZFeatureMap(4, reps=3).assign_parameters(times) ref = QuantumCircuit(4) for _ in range(3): ref.h([0, 1, 2, 3]) for i in range(4): ref.p(2 * times[i], i) self.assertTrue(Operator(encoding).equiv(ref))
def _build(self): # wipe current state self._data = [] self._parameter_table = ParameterTable() # get UCCSD circuit featmap = ZFeatureMap(self.num_qubits, reps=self.reps) ansatz = RealAmplitudes(self.num_qubits, reps=self.reps, entanglement='circular') # store the parameters in a list for assigning them self._params = ansatz.ordered_parameters # set the data circuit with some input data featmap.assign_parameters(np.random.random(featmap.num_parameters), inplace=True) # combine the circuit self.compose(featmap, inplace=True) self.compose(ansatz, inplace=True)
def test_first_order_circuit(self): """Test a first order expansion circuit.""" times = [0.2, 1, np.pi, -1.2] encoding = ZFeatureMap(4, reps=3).assign_parameters(times) # ┌───┐ ┌────────┐┌───┐ ┌────────┐┌───┐ ┌────────┐ # q_0: ┤ H ├─┤ P(0.4) ├┤ H ├─┤ P(0.4) ├┤ H ├─┤ P(0.4) ├ # ├───┤ └┬──────┬┘├───┤ └┬──────┬┘├───┤ └┬──────┬┘ # q_1: ┤ H ├──┤ P(2) ├─┤ H ├──┤ P(2) ├─┤ H ├──┤ P(2) ├─ # ├───┤ ┌┴──────┤ ├───┤ ┌┴──────┤ ├───┤ ┌┴──────┤ # q_2: ┤ H ├─┤ P(2π) ├─┤ H ├─┤ P(2π) ├─┤ H ├─┤ P(2π) ├─ # ├───┤┌┴───────┴┐├───┤┌┴───────┴┐├───┤┌┴───────┴┐ # q_3: ┤ H ├┤ P(-2.4) ├┤ H ├┤ P(-2.4) ├┤ H ├┤ P(-2.4) ├ # └───┘└─────────┘└───┘└─────────┘└───┘└─────────┘ ref = QuantumCircuit(4) for _ in range(3): ref.h([0, 1, 2, 3]) for i in range(4): ref.p(2 * times[i], i) self.assertTrue(Operator(encoding).equiv(ref))
# Generate synthetic training and test sets from the SecondOrderExpansion quantum feature map feature_dim = 2 sample_Total, training_dataset, test_dataset, class_labels = ad_hoc_data( training_size=20, test_size=10, n=feature_dim, gap=0.3, plot_data=False) # Using the statevector simulator backend = BasicAer.get_backend('statevector_simulator') random_seed = 10598 quantum_instance = QuantumInstance(backend, seed_simulator=random_seed, seed_transpiler=random_seed) # Generate the feature map feature_map = ZFeatureMap(feature_dimension=feature_dim, reps=2) # Run the Quantum Kernel Estimator and classify the test data qsvm = QSVM(feature_map=feature_map, training_dataset=training_dataset, test_dataset=test_dataset) result = qsvm.run(quantum_instance) print("testing success ratio: ", result['testing_accuracy']) feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2) qsvm = QSVM(feature_map=feature_map, training_dataset=training_dataset, test_dataset=test_dataset)
import numpy as np # this code generates the data for the easy quantum models' fisher information eigenvalue distribution plot \ # in the Supplementary Information figure # Global variables n = [ 1000, 2000, 8000, 10000, 40000, 60000, 100000, 150000, 200000, 500000, 1000000, 10000000, 10000000000, 10000000000000 ] blocks = 9 num_inputs = 100 num_thetas = 100 ################################################################################### num_qubits = 6 fm = ZFeatureMap(feature_dimension=num_qubits, reps=1) circ = RealAmplitudes(num_qubits, reps=blocks) qnet = QuantumNeuralNetwork(var_form=circ, feature_map=fm) ed = EffectiveDimension(qnet, num_thetas=num_thetas, num_inputs=num_inputs) f, trace = ed.get_fhat() effdim = ed.eff_dim(f, n) np.save("6qubits_9layer_f_hats_easy.npy", f) #################################################################################### num_qubits = 8 fm = ZFeatureMap(feature_dimension=num_qubits, reps=1) circ = RealAmplitudes(num_qubits, reps=blocks) qnet = QuantumNeuralNetwork(var_form=circ, feature_map=fm) ed = EffectiveDimension(qnet, num_thetas=num_thetas, num_inputs=num_inputs) f, trace = ed.get_fhat() effdim = ed.eff_dim(f, n)
import numpy as np TOKEN = 'insert token here' IBMQ.save_account(TOKEN, overwrite=True) provider = IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-internal', group='deployed', project='default') backend_name = 'ibmq_montreal' backend_ibmq = provider.get_backend(backend_name) properties = backend_ibmq.properties() coupling_map = backend_ibmq.configuration().coupling_map noise_model = NoiseModel.from_backend(properties) # layout = [0, 1, 2, 3] layout = [3, 5, 8, 11, 14, 13, 12, 10] # might need to change qi_ibmq_noise_model = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), noise_model=noise_model, optimization_level=0, shots=8000, seed_transpiler=2, initial_layout=layout) qi = qi_ibmq_noise_model compile_config = {'initial_layout': layout, 'seed_transpiler': 2, 'optimization_level': 3 } n = [1000, 2000, 8000, 10000, 40000, 60000, 100000, 150000, 200000, 500000, 1000000, 10000000, 10000000000, 10000000000000] qubits = 8 fm = ZFeatureMap(qubits, reps=1) varform = RealAmplitudes(qubits, reps=9, entanglement='full') qnet = QuantumNeuralNetwork(fm, varform) ed = EffectiveDimension(qnet, 100, 100) fhat, _ = ed.get_fhat() effdim = ed.eff_dim(fhat, n) np.save('8qubits_fhats_noise_linearZ_full.npy', fhat) np.save('8qubits_effective_dimension_noise_linearZ_full.npy', effdim)
from sklearn import preprocessing import numpy as np from qiskit.quantum_info import Statevector from functions_fr import * # This code trains a fixed easy quantum model 100 times and computes the average Fisher-Rao norm which is equal to \ # W^T*F*W where # trained parameters = W and F = Fisher information iris = datasets.load_iris() x = preprocessing.normalize(iris.data) iris_x = x[:100] n = 4 blocks = 1 sv = Statevector.from_label('0' * n) feature_map = ZFeatureMap(n, reps=1) var_form = RealAmplitudes(n, reps=blocks) circuit = feature_map.combine(var_form) d = circuit.num_parameters effdims = [] frnorms = [] nrange = [100000000] # randomly initialize the parameters for i in range(100): file = 'opt_params_easy_%d.npy' % i opt_params_one = np.load(file) opt_params = np.tile(opt_params_one, (100, 1)) x_train = iris_x cnet = QuantumNeuralNetwork(feature_map=feature_map, var_form=var_form) ed = EffectiveDimension(cnet, x_train) f = ed.get_fhat()
def setUp(self): super().setUp() algorithm_globals.random_seed = 1234 qi_sv = QuantumInstance( Aer.get_backend("aer_simulator_statevector"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) # set up quantum neural networks num_qubits = 3 feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1) ansatz = RealAmplitudes(num_qubits, reps=1) # CircuitQNNs qc = QuantumCircuit(num_qubits) qc.append(feature_map, range(num_qubits)) qc.append(ansatz, range(num_qubits)) def parity(x): return f"{x:b}".count("1") % 2 circuit_qnn_1 = CircuitQNN( qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=2, sparse=False, quantum_instance=qi_sv, ) # qnn2 for checking result without parity circuit_qnn_2 = CircuitQNN( qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, sparse=False, quantum_instance=qi_sv, ) # OpflowQNN observable = PauliSumOp.from_list([("Z" * num_qubits, 1)]) opflow_qnn = TwoLayerQNN( num_qubits, feature_map=feature_map, ansatz=ansatz, observable=observable, quantum_instance=qi_sv, ) self.qnns = { "circuit1": circuit_qnn_1, "circuit2": circuit_qnn_2, "opflow": opflow_qnn } # define sample numbers self.n_list = [ 5000, 8000, 10000, 40000, 60000, 100000, 150000, 200000, 500000, 1000000 ] self.n = 5000