2
$\begingroup$
import sympy
import cirq
from cirq.contrib.svg import SVGCircuit
import tensorflow_quantum as tfq
import tensorflow as tf
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from tensorflow.keras.utils import to_categorical
from tensorflow.keras import layers
import os

class CircuitLayerBuilder():
     def __init__(self,data_qubits,readout):
         self.data_qubits=data_qubits
         self.readout=readout
         
     def add_layer(self,circuit,gate,prefix):
         for i,qubit in enumerate(self.data_qubits):
             symbol=sympy.Symbol(prefix+ '-' +str(i))
             circuit.append(gate(qubit,self.readout)**symbol)
                              


demo_builder=CircuitLayerBuilder(data_qubits=cirq.GridQubit.rect(32,32),readout=cirq.GridQubit(-1,1))
circuit=cirq.Circuit()
demo_builder.add_layer(circuit,gate=cirq.XX,prefix='xx')
SVGCircuit(circuit)


def create_quantum_model():
    data_qubits=cirq.GridQubit.rect(32,32)
    readout=cirq.GridQubit(-1,1)
    circuit=cirq.Circuit()
    
    circuit.append(cirq.X(readout))
    circuit.append(cirq.H(readout))
    
    builder=CircuitLayerBuilder(data_qubits=data_qubits,readout=readout)
    
    builder.add_layer(circuit,cirq.XX, "xx1")
    builder.add_layer(circuit,cirq.ZZ ,"zz1")
    
    circuit.append(cirq.H(readout))
    
    return circuit,cirq.Z(readout)



def convert_to_circuit(filename):
    values=np.ndarray.flatten(filename)
    qubits=cirq.GridQubit.rect(32,32)
    circuit=cirq.Circuit()
    for i,value in enumerate(values):
        if value:
            circuit.append(cirq.X(qubits[i]))
            
    return circuit
        

file =np.load('CWRU_48k_load_1_CNN_data.npz')
data = file['data']
labels = file['labels']
category_labels = np.unique(labels)
labels = pd.Categorical(labels, categories = category_labels).codes
train_data, test_data, train_labels, test_labels = train_test_split(data, labels, test_size = 1000, random_state = 829, 
  stratify = labels)

# reshape data
train_data = train_data.reshape(len(train_data),32,32,1)
test_data = test_data.reshape(len(test_data),32,32,1)

#train_labels = to_categorical(train_labels)
#test_labels = to_categorical(test_labels)

x_train_circ=[convert_to_circuit(x) for x in train_data]
x_test_circ=[convert_to_circuit(x) for x in test_data]
x_train_tfcirc=tfq.convert_to_tensor(x_train_circ)
x_test_tfcirc=tfq.convert_to_tensor(x_test_circ)

model_circuit,model_readout=create_quantum_model()


model=tf.keras.Sequential([tf.keras.layers.Input(shape=(),dtype=tf.string),
                           tfq.layers.PQC(model_circuit,model_readout),
                           ])

index = np.random.permutation(len(train_labels))
trian_data, trian_labels = train_data[index], train_labels[index]



SVGCircuit(x_train_circ[0])

y_train_hinge=2.0*test_data-1.0
y_test_hinge=2.0*test_labels-1.0

def hinge_accuracy(y_true, y_pred):
    y_true = tf.squeeze(y_true) > 0.0
    y_pred = tf.squeeze(y_pred) > 0.0
    result = tf.cast(y_true == y_pred, tf.float32)

    return tf.reduce_mean(result)

model.compile(loss=tf.keras.losses.Hinge(),
              optimizer=tf.keras.optimizers.Adam(),
              metrics=[hinge_accuracy])

epochs=25
batch_size=16
num_examples=len(x_train_tfcirc)
x_train_tfcirc_sub=x_train_tfcirc[:num_examples]
y_train_hinge_sub=y_train_hinge[:num_examples]
history = model.fit(x=x_train_tfcirc_sub,
                         y=y_train_hinge_sub,
                         batch_size=16,
                         epochs=25,
                         verbose=1,validation_data=(x_test_tfcirc,y_test_hinge))
print(model.summary())                   
qnn_results=model.evaluate(x_test_tfcirc,test_labels)
print(qnn_results)
$\endgroup$
5
  • $\begingroup$ What do you exacatly want to do? To convert binary strings to qubits, or to prepare some initial quantum state? Please add more information to your question. $\endgroup$ Jan 20 at 14:09
  • $\begingroup$ i want to ''fit'' the classical data on to the circuit, so i can create the model, in order to find the accuracy this code is somehow copyied from original tensorflow quantum tutorial and modified by me, but when i run it i got error on validation_data ( x,y got not the same size ) and when i change the y_ to the same size as x it runs but never got a result..my pc crushes $\endgroup$ Jan 20 at 14:15
  • $\begingroup$ circuit.rect(32,32) its too big, but when i create a 4x4 grid, its to small.. got a list out of index $\endgroup$ Jan 20 at 14:17
  • $\begingroup$ I dont know exactly what else to do =( $\endgroup$ Jan 20 at 14:17
  • $\begingroup$ i want both Martin I got a big dataset, and i cant get the whole result. My pc crushes $\endgroup$ Jan 26 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.