Quantencomputer auf der Titanic

Autorinnen: Katharina Simbeck, Shirin Riazy

Im Beitrag „Quantencomputer auf der Titanic“ in der Reihe „Beiträge und Positionen der HTW Berlin 2019“ stellen wir erste Schritte in der Programmierung von Quantencomputern vor sowie die Anwendung von Quanten Machine Learning Algorithmen.

Die Codebeispiele zum Artikel (Python) orientieren sich am edX Onlinekurs „Quantum Machine Learning“ von Peter Wittek an der University of Toronto.

Listing 1: Ein einziges Qubit.

from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import BasicAer

backend = BasicAer.get_backend('qasm_simulator')

q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
circuit.measure(q, c)
job = execute(circuit, backend, shots=100)
result = job.result()
print(result.get_counts(circuit))

Listing 2: Bloch-Kugel

from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import BasicAer
from qiskit.tools.visualization import plot_bloch_multivector


backend_statevector = BasicAer.get_backend('statevector_simulator')
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
circuit.measure(q, c)
job = execute(circuit, backend_statevector)
plot_bloch_multivector(job.result().get_statevector(circuit)).savefig("bloch1.png")

circuit.h(q[0])
job = execute(circuit, backend_statevector)
plot_bloch_multivector(job.result().get_statevector(circuit)).savefig("bloch2.png")

Listing 3: Quantengatter

from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import BasicAer
from qiskit.tools.visualization import circuit_drawer, plot_histogram

q = QuantumRegister(2)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.cx(q[0], q[1])
circuit_drawer(circuit).savefig("circuit.png")
circuit.measure(q, c)
circuit_drawer(circuit).savefig("circuit_measured.png")
backend = BasicAer.get_backend('qasm_simulator')
job = execute(circuit, backend, shots=100)
plot_histogram(job.result().get_counts(circuit)).savefig("hist.png")

Listing 4: Titanic-Daten vorbereiten

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import numpy as np
import sklearn
from sklearn.svm import SVC
from qiskit import Aer
from qiskit.aqua.utils import split_dataset_to_data_and_labels

# Read Data
Titanic_DF = pd.read_csv('titanic.csv')
from sklearn import preprocessing
lb_make = preprocessing.LabelEncoder()
Titanic_DF['Sex'] = lb_make.fit_transform(Titanic_DF['Sex'])
le_name_mapping = dict(zip(lb_make.classes_, lb_make.transform(lb_make.classes_)))
print(le_name_mapping)
FeatureNames = [x for x in list(Titanic_DF.columns) if x not in ['Name','Survived']]
Data = Titanic_DF[FeatureNames].values
Labels = Titanic_DF['Survived'].values


def PrepareData(training_size, test_size, n):
    class_labels = [r'0', r'1']
    sample_train, sample_test, label_train, label_test = train_test_split(Data, Labels, test_size=0.3, random_state=12)

    # Now we standarize for gaussian around 0 with unit variance
    std_scale = StandardScaler().fit(sample_train)
    sample_train = std_scale.transform(sample_train)
    sample_test = std_scale.transform(sample_test)

    # Now reduce number of features to number of qubits
    pca = PCA(n_components=n).fit(sample_train)
    sample_train = pca.transform(sample_train)
    sample_test = pca.transform(sample_test)

    # Scale to the range (-1,+1)
    samples = np.append(sample_train, sample_test, axis=0)
    minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
    sample_train = minmax_scale.transform(sample_train)
    sample_test = minmax_scale.transform(sample_test)
    return sample_train, sample_test, label_train, label_test, class_labels
    
def QuantumFormat(sample_train, sample_test, label_train, label_test, training_size, test_size, class_labels):
    training_input = {key: (sample_train[label_train == k, :])[:training_size] for k, key in enumerate(class_labels)}
    test_input = {key: (sample_test[label_test == k, :])[:test_size] for k, key in enumerate(class_labels)}
    return training_input, test_input

Listing 5: Quanten-SVM und klassische SVM

# Set up
feature_dim=2
sample_train, sample_test, label_train, label_test, class_labels = PrepareData(training_size=10, test_size=10, n=feature_dim)
training_input, test_input = QuantumFormat(sample_train, sample_test, label_train, label_test, 10, 10, class_labels)
datapoints, class_to_label = split_dataset_to_data_and_labels(test_input)

# QSVM
feature_map = SecondOrderExpansion(feature_dim, depth=2, entanglement='linear')
qsvm = QSVM(feature_map, training_input, test_input, None)
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = qsvm.run(quantum_instance)
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.savefig('kernelQSVM.pdf')
plt.show()

# Classical SVM
svc = SVC(probability=True, gamma='auto')
svc.fit(sample_train, label_train)
kernel_matrix2=sklearn.metrics.pairwise.rbf_kernel(sample_train, sample_train)
img = plt.imshow(np.asmatrix(kernel_matrix2[0:10,0:10]),interpolation='nearest',origin='upper',cmap='bone_r')
plt.savefig('kernelSVM.pdf')
plt.show()

# Error Rate
label_predict=svc.predict(sample_test)
print('Error rate: ' + str(sum(label_predict==label_test)/len(label_predict)))