def setUp(self): super().setUp() algorithm_globals.random_seed = 10598 self.optimizer = COBYLA(maxiter=25) # pylint: disable=no-member self.backend = qiskit.providers.aer.AerSimulator(method="statevector") data_block = ZZFeatureMap(2) trainable_block = ZZFeatureMap(2) training_parameters = trainable_block.parameters for i, _ in enumerate(training_parameters): training_parameters[i]._name = f"θ[{i}]" self.feature_map = data_block.compose(trainable_block).compose( data_block) self.training_parameters = training_parameters self.sample_train = np.asarray([ [3.07876080, 1.75929189], [6.03185789, 5.27787566], [6.22035345, 2.70176968], [0.18849556, 2.82743339], ]) self.label_train = np.asarray([0, 0, 1, 1]) self.sample_test = np.asarray([[2.199114860, 5.15221195], [0.50265482, 0.06283185]]) self.label_test = np.asarray([1, 0]) self.quantum_kernel = QuantumKernel( feature_map=self.feature_map, training_parameters=self.training_parameters, quantum_instance=self.backend, )
def setUp(self): super().setUp() # Create an arbitrary 3-qubit feature map circuit circ1 = ZZFeatureMap(3) circ2 = ZZFeatureMap(3) user_params = circ2.parameters for i, _ in enumerate(user_params): user_params[i]._name = f"θ[{i}]" self.feature_map = circ1.compose(circ2).compose(circ1) self.user_parameters = user_params
def setUp(self): super().setUp() # specify "run configuration" self.quantum_instance_sv = QuantumInstance(StatevectorSimulator()) self.quantum_instance_qasm = QuantumInstance(QasmSimulator(shots=100)) # define feature map and ansatz num_qubits = 2 feature_map = ZZFeatureMap(num_qubits, reps=1) var_form = RealAmplitudes(num_qubits, reps=1) # construct circuit self.qc = QuantumCircuit(num_qubits) self.qc.append(feature_map, range(2)) self.qc.append(var_form, range(2)) # store params self.input_params = list(feature_map.parameters) self.weight_params = list(var_form.parameters) # define interpret functions def interpret_1d(x): return sum([s == '1' for s in '{0:0b}'.format(x)]) % 2 self.interpret_1d = interpret_1d self.output_shape_1d = 2 # takes values in {0, 1} def interpret_2d(x): return np.array([self.interpret_1d(x), 2 * self.interpret_1d(x)]) self.interpret_2d = interpret_2d self.output_shape_2d = (2, 3) # 1st dim. takes values in {0, 1} 2nd dim in {0, 1, 2}
def __init__( self, feature_map: Optional[QuantumCircuit] = None, enforce_psd: bool = True, batch_size: int = 900, quantum_instance: Optional[Union[QuantumInstance, Backend]] = None, training_parameters: Optional[Union[ParameterVector, Sequence[Parameter]]] = None, ) -> None: """ Args: feature_map: Parameterized circuit to be used as the feature map. If None is given, the `ZZFeatureMap` is used with two qubits. enforce_psd: Project to closest positive semidefinite matrix if x = y. Only enforced when not using the state vector simulator. Default True. batch_size: Number of circuits to batch together for computation. Default 900. quantum_instance: Quantum Instance or Backend training_parameters: Iterable containing ``Parameter`` objects which correspond to quantum gates on the feature map circuit which may be tuned. If users intend to tune feature map parameters to find optimal values, this field should be set. """ # Class fields self._feature_map = None self._unbound_feature_map = None self._training_parameters = None self._training_parameter_binds = None self._enforce_psd = enforce_psd self._batch_size = batch_size self._quantum_instance = quantum_instance # Setters self.feature_map = feature_map if feature_map is not None else ZZFeatureMap( 2) if training_parameters is not None: self.training_parameters = training_parameters
def feature_map(): # BUILD FEATURE MAP HERE - START feature_dim = 3 # equal to the dimension of the data # from qiskit.circuit import QuantumCircuit, ParameterVector # num_qubits = 3 # reps = 1 # number of times you'd want to repeat the circuit # x = ParameterVector('x', length=num_qubits) # creating a list of Parameters # custom_circ = QuantumCircuit(num_qubits) # # defining our parametric form # for _ in range(reps): # for i in range(num_qubits): # custom_circ.rx(x[i], i) # for i in range(num_qubits): # for j in range(0, 1): # custom_circ.cx(i, j) # if i in {1,0} or j in {1,0}: # custom_circ.u1(x[i] * x[j], j) # custom_circ.cx(i, j) # import required qiskit libraries if additional libraries are required # build the feature map # feature_map = ZFeatureMap(feature_dimension=feature_dim, reps=5) # feature_map = PauliFeatureMap(feature_dimension=feature_dim,entanglement='full',reps=1, paulis = ['X','Y','XY']) feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=10, entanglement='linear', insert_barriers=True) # 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() self.random_seed = 10598 self.shots = 12000 aqua_globals.random_seed = self.random_seed self.training_data = {'A': np.asarray([[2.95309709, 2.51327412], [3.14159265, 4.08407045]]), 'B': np.asarray([[4.08407045, 2.26194671], [4.46106157, 2.38761042]])} self.testing_data = {'A': np.asarray([[3.83274304, 2.45044227]]), 'B': np.asarray([[3.89557489, 0.31415927]])} num_qubits = 2 warnings.filterwarnings('ignore', category=DeprecationWarning) # data encoding using a FeatureMap type feature_map = SecondOrderExpansion(feature_dimension=num_qubits, depth=2, entangler_map=[[0, 1]]) warnings.filterwarnings('always', category=DeprecationWarning) # data encoding using a circuit library object library_circuit = ZZFeatureMap(feature_dimension=num_qubits, reps=2) # data encoding using a plain QuantumCircuit circuit = QuantumCircuit(num_qubits).compose(library_circuit) circuit.ordered_parameters = library_circuit.ordered_parameters self.data_preparation = {'wrapped': feature_map, 'circuit': circuit, 'library': library_circuit}
def __init__(self, h, w, outputs): super(DQN, self).__init__() qi = QuantumInstance(Aer.get_backend('statevector_simulator')) num_inputs=4 feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, entanglement='linear', reps=1) qc = QuantumCircuit(num_inputs) qc.append(feature_map, range(num_inputs)) qc.append(ansatz, range(num_inputs)) parity = lambda x: '{:b}'.format(x).count('1') % num_inputs output_shape =num_inputs # parity = 0, 1 qnn = CircuitQNN(qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, quantum_instance=qi) #set up PyTorch Module initial_weights = 0.1*(2*np.random.rand(qnn.num_weights) - 1) # Our final network choice. It is wide enough to capture a lot of detail but not too # large to have problems with vanishing gradients on such a small sample size self.conv1 = nn.Conv2d(1, 256, kernel_size=2, stride=1, padding=1) self.bn1 = nn.BatchNorm2d(256) self.fcl1 = nn.Linear(20736,10000) self.fcl2 = nn.Linear(10000, num_inputs) self.qnn = TorchConnector(qnn, initial_weights)
def _create_circuit_qnn(self, quantum_instance: QuantumInstance) -> Tuple[CircuitQNN, int, int]: num_inputs = 2 feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) # construct circuit qc = QuantumCircuit(num_inputs) qc.append(feature_map, range(2)) qc.append(ansatz, range(2)) # construct qnn def parity(x): return f"{x:b}".count("1") % 2 output_shape = 2 qnn = CircuitQNN( qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, sparse=False, interpret=parity, output_shape=output_shape, quantum_instance=quantum_instance, ) return qnn, num_inputs, ansatz.num_parameters
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, ) self.feature_map = ZZFeatureMap(feature_dimension=2, reps=2) self.sample_train = np.asarray([ [3.07876080, 1.75929189], [6.03185789, 5.27787566], [6.22035345, 2.70176968], [0.18849556, 2.82743339], ]) self.label_train = np.asarray([0, 0, 1, 1]) self.sample_test = np.asarray([[2.199114860, 5.15221195], [0.50265482, 0.06283185]]) self.label_test = np.asarray([0, 1])
def setUp(self): super().setUp() self.x = [1, 1] self.y = [2, 2] self.z = [3] self.feature_map = ZZFeatureMap(feature_dimension=2, reps=1)
def test_warm_start(self, config): """Test VQC with warm_start=True.""" opt, q_i = config if q_i == "statevector": quantum_instance = self.sv_quantum_instance elif q_i == "qasm": quantum_instance = self.qasm_quantum_instance else: quantum_instance = None if opt == "bfgs": optimizer = L_BFGS_B(maxiter=5) elif opt == "cobyla": optimizer = COBYLA(maxiter=25) else: optimizer = None num_inputs = 2 feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) # Construct the data. num_samples = 10 # pylint: disable=invalid-name X = algorithm_globals.random.random((num_samples, num_inputs)) y = 1.0 * (np.sum(X, axis=1) <= 1) while len(np.unique(y)) == 1: X = algorithm_globals.random.random((num_samples, num_inputs)) y = 1.0 * (np.sum(X, axis=1) <= 1) y = np.array([y, 1 - y ]).transpose() # VQC requires one-hot encoded input. # Initialize the VQC. classifier = VQC( feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, warm_start=True, quantum_instance=quantum_instance, ) # Fit the VQC to the first half of the data. num_start = num_samples // 2 classifier.fit(X[:num_start, :], y[:num_start]) first_fit_final_point = classifier._fit_result.x # Fit the VQC to the second half of the data with a warm start. classifier.fit(X[num_start:, :], y[num_start:]) second_fit_initial_point = classifier._initial_point # Check the final optimization point from the first fit was used to start the second fit. np.testing.assert_allclose(first_fit_final_point, second_fit_initial_point) # Check score. score = classifier.score(X, y) self.assertGreater(score, 0.5)
def setUp(self): super().setUp() self.seed = 50 aqua_globals.random_seed = self.seed self.training_data = { 'A': np.asarray([[2.95309709, 2.51327412], [3.14159265, 4.08407045]]), 'B': np.asarray([[4.08407045, 2.26194671], [4.46106157, 2.38761042]]) } self.testing_data = { 'A': np.asarray([[3.83274304, 2.45044227]]), 'B': np.asarray([[3.89557489, 0.31415927]]) } self.ref_opt_params = np.array([ 0.47352206, -3.75934473, 1.72605939, -4.17669389, 1.28937435, -0.05841719, -0.29853266, -2.04139334, 1.00271775, -1.48133882, -1.18769138, 1.17885493, 7.58873883, -5.27078091, 2.5306601, -4.67393152 ]) self.ref_opt_params = np.array([ 4.40301812e-01, 2.10844304, -2.10118578, -5.25903194, 2.07617769, -9.25865371, -5.33834788, 8.59005180, 3.39886480, 6.33839643, 1.24425033, -1.39701513e+01, -7.16008545e-03, 3.36206032, 4.38001391, -3.47098082 ]) self.ref_train_loss = 0.5869304 self.ref_prediction_a_probs = [[0.8984375, 0.1015625]] self.ref_prediction_a_label = [0] self.ryrz_wavefunction = TwoLocal(2, ['ry', 'rz'], 'cz', reps=3, insert_barriers=True) self.data_preparation = ZZFeatureMap(2, reps=2) self.statevector_simulator = QuantumInstance( BasicAer.get_backend('statevector_simulator'), shots=1, seed_simulator=self.seed, seed_transpiler=self.seed) self.qasm_simulator = QuantumInstance( BasicAer.get_backend('qasm_simulator'), shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed) self.spsa = SPSA(maxiter=10, save_steps=1, c0=4.0, c1=0.1, c2=0.602, c3=0.101, c4=0.0, skip_calibration=True)
def test_matrix_psd(self): """ Test kernel matrix positive semi-definite enforcement. """ try: from cvxpy.error import DQCPError except ImportError: self.skipTest('cvxpy does not appeat to be installed') seed = 10598 feature_dim = 2 _, training_input, _, _ = ad_hoc_data( training_size=10, test_size=5, n=feature_dim, gap=0.3 ) training_input, _ = split_dataset_to_data_and_labels(training_input) training_data = training_input[0] training_labels = training_input[1] labels = training_labels * 2 - 1 # map label from 0 --> -1 and 1 --> 1 labels = labels.astype(float) feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement='linear') try: with self.assertRaises(DQCPError): # Sampling noise means that the kernel matrix will not quite be positive # semi-definite which will cause the optimize svm to fail backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed) kernel_matrix = QSVM.get_kernel_matrix(quantum_instance, feature_map=feature_map, x1_vec=training_data, enforce_psd=False) _ = optimize_svm(kernel_matrix, labels, lambda2=0) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) return # This time we enforce that the matrix be positive semi-definite which runs logic to # make it so. backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed) kernel_matrix = QSVM.get_kernel_matrix(quantum_instance, feature_map=feature_map, x1_vec=training_data, enforce_psd=True) alpha, b, support = optimize_svm(kernel_matrix, labels, lambda2=0) expected_alpha = [0.855861781, 2.59807482, 0, 0.962959215, 1.08141696, 0.217172547, 0, 0, 0.786462904, 0, 0.969727949, 1.98066946, 0, 0, 1.62049430, 0, 0.394212728, 0, 0.507740935, 1.02910286] expected_b = [-0.17543365] expected_support = [True, True, False, True, True, True, False, False, True, False, True, True, False, False, True, False, True, False, True, True] np.testing.assert_array_almost_equal(alpha, expected_alpha) np.testing.assert_array_almost_equal(b, expected_b) np.testing.assert_array_equal(support, expected_support)
def test_classifier_with_circuit_qnn_and_cross_entropy(self, config): """ Test Neural Network Classifier with Circuit QNN and Cross Entropy loss.""" opt, q_i = config if q_i == 'statevector': quantum_instance = self.sv_quantum_instance else: quantum_instance = self.qasm_quantum_instance if opt == 'bfgs': optimizer = L_BFGS_B(maxiter=5) else: optimizer = COBYLA(maxiter=25) loss = CrossEntropyLoss() num_inputs = 2 feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) # construct circuit qc = QuantumCircuit(num_inputs) qc.append(feature_map, range(2)) qc.append(ansatz, range(2)) # construct qnn def parity(x): return '{:b}'.format(x).count('1') % 2 output_shape = 2 qnn = CircuitQNN(qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, sparse=False, interpret=parity, output_shape=output_shape, quantum_instance=quantum_instance) # construct classifier - note: CrossEntropy requires eval_probabilities=True! classifier = NeuralNetworkClassifier(qnn, optimizer=optimizer, loss=loss, one_hot=True) # construct data num_samples = 5 X = np.random.rand(num_samples, num_inputs) # pylint: disable=invalid-name y = 1.0 * (np.sum(X, axis=1) <= 1) y = np.array([y, 1 - y]).transpose() # fit to data classifier.fit(X, y) # score score = classifier.score(X, y) self.assertGreater(score, 0.5)
def setUp(self): super().setUp() algorithm_globals.random_seed = 12345 # specify "run configuration" self.quantum_instance_sv = QuantumInstance( qiskit.Aer.get_backend("aer_simulator_statevector"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) # pylint: disable=no-member self.quantum_instance_qasm = QuantumInstance( qiskit.providers.aer.AerSimulator(), shots=100, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) self.quantum_instance_pm = QuantumInstance( qiskit.providers.aer.AerSimulator(), shots=100, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, pass_manager=level_1_pass_manager( PassManagerConfig.from_backend(FakeToronto())), bound_pass_manager=level_2_pass_manager( PassManagerConfig.from_backend(FakeToronto())), ) # define feature map and ansatz num_qubits = 2 feature_map = ZZFeatureMap(num_qubits, reps=1) var_form = RealAmplitudes(num_qubits, reps=1) # construct circuit self.qc = QuantumCircuit(num_qubits) self.qc.append(feature_map, range(2)) self.qc.append(var_form, range(2)) # store params self.input_params = list(feature_map.parameters) self.weight_params = list(var_form.parameters) # define interpret functions def interpret_1d(x): return sum([s == "1" for s in f"{x:0b}"]) % 2 self.interpret_1d = interpret_1d self.output_shape_1d = 2 # takes values in {0, 1} def interpret_2d(x): return np.array([self.interpret_1d(x), 2 * self.interpret_1d(x)]) self.interpret_2d = interpret_2d self.output_shape_2d = ( 2, 3, ) # 1st dim. takes values in {0, 1} 2nd dim in {0, 1, 2}
def test_vqc_on_wine(self, mode): """Test VQE on the wine test using circuits as feature map and variational form.""" feature_dim = 4 # dimension of each data point training_dataset_size = 6 testing_dataset_size = 3 _, training_input, test_input, _ = wine( training_size=training_dataset_size, test_size=testing_dataset_size, n=feature_dim, plot_data=False) aqua_globals.random_seed = self.seed if mode == 'wrapped': warnings.filterwarnings('ignore', category=DeprecationWarning) data_preparation = SecondOrderExpansion(feature_dim) wavefunction = RYRZ(feature_dim, depth=1) else: data_preparation = ZZFeatureMap(feature_dim) x = data_preparation.ordered_parameters wavefunction = TwoLocal(feature_dim, ['ry', 'rz'], 'cz', reps=1, insert_barriers=True) theta = ParameterVector('theta', wavefunction.num_parameters) resorted = [] for i in range(2 * feature_dim): layer = wavefunction.ordered_parameters[2 * feature_dim * i:2 * feature_dim * (i + 1)] resorted += layer[::2] resorted += layer[1::2] wavefunction.assign_parameters(dict(zip(resorted, theta)), inplace=True) if mode == 'circuit': data_preparation = QuantumCircuit(feature_dim).compose( data_preparation) wavefunction = QuantumCircuit(feature_dim).compose(wavefunction) vqc = VQC(COBYLA(maxiter=100), data_preparation, wavefunction, training_input, test_input) # sort parameters for reproducibility if mode in ['circuit', 'library']: vqc._feature_map_params = list(x) vqc._var_form_params = list(theta) else: warnings.filterwarnings('always', category=DeprecationWarning) result = vqc.run( QuantumInstance(BasicAer.get_backend('statevector_simulator'), shots=1024, seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) self.log.debug(result['testing_accuracy']) self.assertLess(result['testing_accuracy'], 0.6)
def test_batches_with_incomplete_labels(self, config): """Test VQC when some batches do not include all possible labels.""" opt, q_i = config if q_i == "statevector": quantum_instance = self.sv_quantum_instance elif q_i == "qasm": quantum_instance = self.qasm_quantum_instance else: quantum_instance = None if opt == "bfgs": optimizer = L_BFGS_B(maxiter=5) elif opt == "cobyla": optimizer = COBYLA(maxiter=25) else: optimizer = None num_inputs = 2 feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) # Construct the data. features = algorithm_globals.random.random((15, num_inputs)) target = np.asarray([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2]) num_classes = len(np.unique(target)) # One-hot encode the target. target_onehot = np.zeros((target.size, int(target.max() + 1))) target_onehot[np.arange(target.size), target.astype(int)] = 1 # Initialize the VQC. classifier = VQC( feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, warm_start=True, quantum_instance=quantum_instance, ) classifier._get_interpret = self.get_num_classes( classifier._get_interpret) # Fit the VQC to the first third of the data. classifier.fit(features[:5, :], target_onehot[:5]) # Fit the VQC to the second third of the data with a warm start. classifier.fit(features[5:10, :], target_onehot[5:10]) # Fit the VQC to the third third of the data with a warm start. classifier.fit(features[10:, :], target_onehot[10:]) # Check all batches assume the correct number of classes self.assertTrue( (np.asarray(self.num_classes_by_batch) == num_classes).all())
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 feature_dim = 3 # build the feature map feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=6) # BUILD FEATURE MAP HERE - END #return the feature map which is either a FeatureMap or QuantumCircuit object return feature_map
def test_vqc(self, config): """Test VQC.""" opt, q_i = config if q_i == "statevector": quantum_instance = self.sv_quantum_instance elif q_i == "qasm": quantum_instance = self.qasm_quantum_instance else: quantum_instance = None if opt == "bfgs": optimizer = L_BFGS_B(maxiter=5) elif opt == "cobyla": optimizer = COBYLA(maxiter=25) else: optimizer = None num_inputs = 2 feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) # fix the initial point initial_point = np.array([0.5] * ansatz.num_parameters) # construct classifier - note: CrossEntropy requires eval_probabilities=True! classifier = VQC( feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance, initial_point=initial_point, ) # construct data num_samples = 5 # pylint: disable=invalid-name X = algorithm_globals.random.random((num_samples, num_inputs)) y = 1.0 * (np.sum(X, axis=1) <= 1) while len(np.unique(y)) == 1: X = algorithm_globals.random.random((num_samples, num_inputs)) y = 1.0 * (np.sum(X, axis=1) <= 1) y = np.array([y, 1 - y]).transpose() # VQC requires one-hot encoded input # fit to data classifier.fit(X, y) # score score = classifier.score(X, y) self.assertGreater(score, 0.5)
def __init__(self, num_qubits: int, feature_map: QuantumCircuit = None, var_form: QuantumCircuit = None, observable: Union[QuantumCircuit, OperatorBase] = None, quantum_instance: Optional[Union[QuantumInstance, BaseBackend, Backend]] = None): r"""Initializes the Two Layer Quantum Neural Network. Args: num_qubits: The number of qubits to represent the network. feature_map: The (parametrized) circuit to be used as feature map. If None is given, the `ZZFeatureMap` is used. var_form: The (parametrized) circuit to be used as variational form. If None is given, the `RealAmplitudes` circuit is used. observable: observable to be measured to determine the output of the network. If None is given, the `Z^{\otimes num_qubits}` observable is used. """ self.num_qubits = num_qubits # TODO: circuits need to have well-defined parameter order! self.feature_map = feature_map if feature_map else ZZFeatureMap( num_qubits) idx = np.argsort([p.name for p in self.feature_map.parameters]) input_params = list(self.feature_map.parameters) input_params = [input_params[i] for i in idx] # TODO: circuits need to have well-defined parameter order! self.var_form = var_form if var_form else RealAmplitudes(num_qubits) idx = np.argsort([p.name for p in self.var_form.parameters]) weight_params = list(self.var_form.parameters) weight_params = [weight_params[i] for i in idx] # construct circuit self.qc = QuantumCircuit(num_qubits) self.qc.append(self.feature_map, range(num_qubits)) self.qc.append(self.var_form, range(num_qubits)) # construct observable self.observable = observable if observable else PauliSumOp.from_list( [('Z' * num_qubits, 1)]) # combine all to operator operator = ~StateFn(self.observable) @ StateFn(self.qc) super().__init__(operator, input_params, weight_params, quantum_instance=quantum_instance)
def setUp(self): super().setUp() # specify "run configuration" backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) # define QNN feature_map = ZZFeatureMap(2) var_form = RealAmplitudes(2, reps=1) self.qnn = TwoLayerQNN(2, feature_map=feature_map, var_form=var_form, quantum_instance=quantum_instance)
def __init__(self, input_size: int, hidden_size: int, n_qubits: int = 4, n_qlayers: int = 1, batch_first=True, backend='statevector_simulator'): super(QLSTM, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.concat_size = input_size + hidden_size self.n_qubits = n_qubits self.n_qlayers = n_qlayers self.batch_first = batch_first self.clayer_in = nn.Linear(self.concat_size, n_qubits) self.clayer_out = nn.Linear(self.n_qubits, self.hidden_size) self.qi = QuantumInstance(Aer.get_backend('statevector_simulator')) feature_map = ZZFeatureMap(self.n_qubits) ansatz = RealAmplitudes(self.n_qubits, reps=self.n_qlayers) self.qnn1 = TwoLayerQNN(self.n_qubits, feature_map, ansatz, exp_val=AerPauliExpectation(), quantum_instance=self.qi) self.qnn2 = TwoLayerQNN(self.n_qubits, feature_map, ansatz, exp_val=AerPauliExpectation(), quantum_instance=self.qi) self.qnn3 = TwoLayerQNN(self.n_qubits, feature_map, ansatz, exp_val=AerPauliExpectation(), quantum_instance=self.qi) self.qnn4 = TwoLayerQNN(self.n_qubits, feature_map, ansatz, exp_val=AerPauliExpectation(), quantum_instance=self.qi) self.qlayer = { 'forget': TorchConnector(self.qnn1), 'input': TorchConnector(self.qnn2), 'update': TorchConnector(self.qnn3), 'output': TorchConnector(self.qnn4) }
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 = ZZFeatureMap(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 setUp(self): super().setUp() self.random_seed = 10598 self.shots = 12000 algorithm_globals.random_seed = self.random_seed self.training_data = { 'A': np.asarray([[2.95309709, 2.51327412], [3.14159265, 4.08407045]]), 'B': np.asarray([[4.08407045, 2.26194671], [4.46106157, 2.38761042]]) } self.testing_data = { 'A': np.asarray([[3.83274304, 2.45044227]]), 'B': np.asarray([[3.89557489, 0.31415927]]) } self.ref_kernel_training = np.array( [[1., 0.85366667, 0.12341667, 0.36408333], [0.85366667, 1., 0.11141667, 0.45491667], [0.12341667, 0.11141667, 1., 0.667], [0.36408333, 0.45491667, 0.667, 1.]]) self.ref_kernel_testing = { 'qasm': np.array([[0.14316667, 0.18208333, 0.4785, 0.14441667], [0.33608333, 0.3765, 0.02316667, 0.15858333]]), 'statevector': np.array([[0.1443953, 0.18170069, 0.47479649, 0.14691763], [0.33041779, 0.37663733, 0.02115561, 0.16106199]]) } self.ref_support_vectors = np.array([[2.95309709, 2.51327412], [3.14159265, 4.08407045], [4.08407045, 2.26194671], [4.46106157, 2.38761042]]) self.ref_alpha = np.array( [0.34902907, 1.48325913, 0.03073616, 1.80155205]) self.ref_bias = np.array([-0.03059395]) self.qasm_simulator = QuantumInstance( BasicAer.get_backend('qasm_simulator'), shots=self.shots, seed_simulator=self.random_seed, seed_transpiler=self.random_seed) self.statevector_simulator = QuantumInstance( BasicAer.get_backend('statevector_simulator'), shots=1, seed_simulator=self.random_seed, seed_transpiler=self.random_seed) self.data_preparation = ZZFeatureMap(feature_dimension=2, reps=2)
def setUp(self): super().setUp() # specify "run configuration" quantum_instance = QuantumInstance(StatevectorSimulator()) # define QNN num_qubits = 2 feature_map = ZZFeatureMap(num_qubits) ansatz = RealAmplitudes(num_qubits, reps=1) self.qnn = TwoLayerQNN(num_qubits, feature_map=feature_map, ansatz=ansatz, quantum_instance=quantum_instance) self.qnn_no_qi = TwoLayerQNN(num_qubits, feature_map=feature_map, ansatz=ansatz)
def __init__(self, h, w, outputs): super(DQN, self).__init__() # We did a lot of experimentation with model sizes and types, so we decided to leave some # of our attempts here #1 # self.conv1 = nn.Conv2d(1, 16, kernel_size=5, stride=2) # self.bn1 = nn.BatchNorm2d(16) # self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2) # self.bn2 = nn.BatchNorm2d(32) # self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2) # self.bn3 = nn.BatchNorm2d(32) #2 # # Number of Linear input connections depends on output of conv2d layers # # and therefore the input image size, so compute it. # def conv2d_size_out(size, kernel_size = 5, stride = 2): # return (size - (kernel_size - 1) - 1) // stride + 1 # convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) # convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) # linear_input_size = convw * convh * 32 #3 # self.conv1 = nn.Conv2d(1, 128, kernel_size=2, stride=1, padding=1) # self.bn1 = nn.BatchNorm2d(128) # self.conv2 = nn.Conv2d(128, 256, kernel_size=5, stride=1, padding=1) # self.bn2 = nn.BatchNorm2d(256) # self.fcl1 = nn.Linear(12544,5000) # self.fcl2 = nn.Linear(5000, 64) qi = QuantumInstance(Aer.get_backend('statevector_simulator')) feature_map = ZZFeatureMap(4) ansatz = RealAmplitudes(4, reps=1) qnn = TwoLayerQNN(4, feature_map, ansatz, exp_val=AerPauliExpectation(), quantum_instance=qi) #4 # Our final network choice. It is wide enough to capture a lot of detail but not too # large to have problems with vanishing gradients on such a small sample size self.conv1 = nn.Conv2d(1, 256, kernel_size=2, stride=1, padding=1) self.bn1 = nn.BatchNorm2d(256) self.fcl1 = nn.Linear(20736, 10000) self.fcl2 = nn.Linear(10000, 4) self.qnn = TorchConnector(qnn)
def setUp(self): super().setUp() algorithm_globals.random_seed = 10598 self.shots = 12000 self.batch_size = 3 self.circuit_counts = [] self.statevector_simulator = QuantumInstance( BasicAer.get_backend("statevector_simulator"), shots=1, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) # monkey patch the statevector simulator self.statevector_simulator.execute = self.count_circuits( self.statevector_simulator.execute) self.qasm_simulator = QuantumInstance( BasicAer.get_backend("qasm_simulator"), shots=self.shots, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) # monkey patch the qasm simulator self.qasm_simulator.execute = self.count_circuits( self.qasm_simulator.execute) self.feature_map = ZZFeatureMap(feature_dimension=2, reps=2) # data generated using # sample_train, label_train, _, _ = ad_hoc_data(training_size=4, test_size=2, n=2, gap=0.3) self.sample_train = np.asarray([ [5.90619419, 1.25663706], [2.32477856, 0.9424778], [4.52389342, 5.0893801], [3.58141563, 0.9424778], [0.31415927, 3.45575192], [4.83805269, 3.70707933], [5.65486678, 6.09468975], [5.46637122, 4.52389342], ]) self.label_train = np.asarray([0, 0, 0, 0, 1, 1, 1, 1])
def __init__(self, feature_map: Optional[QuantumCircuit] = None, enforce_psd: bool = True, batch_size: int = 1000, quantum_instance: Optional[ Union[QuantumInstance, BaseBackend, Backend]] = None) -> None: """ Args: feature_map: Parameterized circuit to be used as the feature map. If None is given, the `ZZFeatureMap` is used with two qubits. enforce_psd: Project to closest positive semidefinite matrix if x = y. Only enforced when not using the state vector simulator. Default True. batch_size: Number of circuits to batch together for computation. Default 1000. quantum_instance: Quantum Instance or Backend """ self._feature_map = feature_map if feature_map else ZZFeatureMap(2) self._enforce_psd = enforce_psd self._batch_size = batch_size self._quantum_instance = quantum_instance
def test_wine(self): """Test VQE on the wine dataset.""" feature_dim = 4 # dimension of each data point training_dataset_size = 6 testing_dataset_size = 3 _, training_input, test_input, _ = wine(training_size=training_dataset_size, test_size=testing_dataset_size, n=feature_dim, plot_data=False) aqua_globals.random_seed = self.seed data_preparation = ZZFeatureMap(feature_dim) wavefunction = TwoLocal(feature_dim, ['ry', 'rz'], 'cz', reps=2) vqc = VQC(COBYLA(maxiter=100), data_preparation, wavefunction, training_input, test_input) result = vqc.run(self.statevector_simulator) self.log.debug(result['testing_accuracy']) self.assertGreater(result['testing_accuracy'], 0.3)