I use quantum CNN code in order to classify X-Ray image dataset, however I have several errors

First when use

import pennylane as qml

qml.enable_tape()

I got following error

AttributeError: module 'pennylane' has no attribute 'enable_tape'

So I try to disable it using

#qml.enable_tape()

Then I load data and defined data input

x_trn, y_trn_mul, y_trn_bin, x_tst, y_tst_mul, y_tst_bin = load_data(sufolder_trnX, sufolder_tstX, sufolder_lbls, 'train.txt', 'test.txt', size = im_size)

y_uniq = catch_unique(y_trn_bin)
y_trn  = get_numLabels(y_trn_bin, y_uniq)

y_uniq = catch_unique(y_tst_bin)
y_tst  = get_numLabels(y_tst_bin, y_uniq)

print('__________________   Checking dataset lastly  ____________________')
print('Length of x_trn is ' + str(len(x_trn)))
print('Length of y_trn is ' + str(len(y_trn)))

print('Length of x_tst is ' + str(len(x_tst)))
print('Length of y_tst is ' + str(len(y_tst)))

if len(x_trn) == len(y_trn):
    print('__________________   Dataset is ready !!!   ______________________')
else:
    print('Please check dataset again...')

And it loaded successfully as in following screenshot

Loading data e description here

The problem is in train section that code as in follows:

# Define output labels as quantum state vectors
def density_matrix(state):
    """Calculates the density matrix representation of a state.

    Args:
        state (array[complex]): array representing a quantum state vector

    Returns:
        dm: (array[complex]): array representing the density matrix
    """
    return state * np.conj(state).T

label_0 = [[1], [0]]
label_1 = [[0], [1]]
state_labels = [label_0, label_1]

n_qubits = 2  # number of class
dev_fc = qml.device("default.qubit", wires=n_qubits)

@qml.qnode(dev_fc)
def q_fc(params, inputs):
    """A variational quantum circuit representing the DRC.

    Args:
        params (array[float]): array of parameters
        inputs = [x, y]
        x (array[float]): 1-d input vector
        y (array[float]): single output state density matrix

    Returns:
        float: fidelity between output state and input
    """
    
    # layer iteration
    for l in range(len(params[0])):
        # qubit iteration
        for q in range(n_qubits):
            # gate iteration
            for g in range(int(len(inputs)/3)):
                qml.Rot(*(params[0][l][3*g:3*(g+1)] * inputs[3*g:3*(g+1)] + params[1][l][3*g:3*(g+1)]), wires=q)
    
    return [qml.expval(qml.Hermitian(density_matrix(state_labels[i]), wires=[i])) for i in range(n_qubits)]

dev_conv = qml.device("default.qubit", wires=9)
@qml.qnode(dev_conv)
def q_conv(conv_params, inputs):
    """A variational quantum circuit representing the Universal classifier + Conv.

    Args:
        params (array[float]): array of parameters
        x (array[float]): 2-d input vector
        y (array[float]): single output state density matrix

    Returns:
        float: fidelity between output state and input
    """
    # layer iteration
    for l in range(len(conv_params[0])):
        # RY layer
        # height iteration
        for i in range(3):
            # width iteration
            for j in range(3):
                qml.RY((conv_params[0][l][3*i+j] * inputs[i, j] + conv_params[1][l][3*i+j]), wires=(3*i+j))


    return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliZ(2) @ qml.PauliZ(3) @ qml.PauliZ(4) @ qml.PauliZ(5) @ qml.PauliZ(6) @ qml.PauliZ(7) @ qml.PauliZ(8))

a = np.zeros((2, 1, 9))
q_conv(a, x_trn[0, 0:3, 0:3])

a = np.zeros((2, 1, 9))
q_fc(a, x_trn[0, 0, 0:9])

# Alpha Custom Layer
class class_weights(tf.keras.layers.Layer):
    def __init__(self):
        super(class_weights, self).__init__()
        w_init = tf.random_normal_initializer()
        self.w = tf.Variable(
            initial_value=w_init(shape=(1, 2), dtype="float32"),
            trainable=True,
        )

    def call(self, inputs):
        return (inputs * self.w)

# Input image, size = 28 x 28
X = tf.keras.Input(shape = im_size, name = 'Input_Layer')

# Specs for Conv
c_filter  = 3
c_strides = 2

# First Quantum Conv Layer, trainable params = 18*L, output size = 13 x 13
num_conv_layer_1 = 2
q_conv_layer_1 = qml.qnn.KerasLayer(q_conv, {"conv_params": (2, num_conv_layer_1, 9)}, output_dim=(1), name='Quantum_Conv_Layer_1')
size_1 = int(1+(X.shape[1]-c_filter)/c_strides)
q_conv_layer_1_list = []
# height iteration
for i in range(size_1):
    # width iteration
    for j in range(size_1):
        temp = q_conv_layer_1(X[:, 2*i:2*(i+1)+1, 2*j:2*(j+1)+1])
        temp = tf.keras.layers.Reshape((1,))(temp)
        q_conv_layer_1_list += [temp]
concat_layer_1 = tf.keras.layers.Concatenate(axis=1)(q_conv_layer_1_list)
reshape_layer_1 = tf.keras.layers.Reshape((size_1, size_1))(concat_layer_1)


# Second Quantum Conv Layer, trainable params = 18*L, output size = 6 x 6
num_conv_layer_2 = 1
q_conv_layer_2 = qml.qnn.KerasLayer(q_conv, {"conv_params": (2, num_conv_layer_2, 9)}, output_dim=(1), name='Quantum_Conv_Layer_2')
size_2 = int(1+(reshape_layer_1.shape[1]-c_filter)/c_strides)
q_conv_layer_2_list = []
# height iteration
for i in range(size_2):
    # width iteration
    for j in range(size_2):
        temp = q_conv_layer_2(reshape_layer_1[:, 2*i:2*(i+1)+1, 2*j:2*(j+1)+1])
        temp = tf.keras.layers.Reshape((1,))(temp)
        q_conv_layer_2_list += [temp]
concat_layer_2 = tf.keras.layers.Concatenate(axis=1)(q_conv_layer_2_list)
reshape_layer_2 = tf.keras.layers.Reshape((size_2, size_2, 1))(concat_layer_2)


# Max Pooling Layer, output size = 9
max_pool_layer = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=None, name='Max_Pool_Layer')(reshape_layer_2)
reshape_layer_3 = tf.keras.layers.Reshape((9,))(max_pool_layer)


# Quantum FC Layer, trainable params = 18*L*n_class + 2, output size = 2
num_fc_layer = 1
q_fc_layer_0 = qml.qnn.KerasLayer(q_fc, {"params": (2, num_fc_layer, 9)}, output_dim=2)(reshape_layer_3)

# Alpha Layer
alpha_layer_0 = class_weights()(q_fc_layer_0)

model = tf.keras.Model(inputs = X, outputs = alpha_layer_0)
opt   = tf.keras.optimizers.Adam(learning_rate=0.1)
model.compile(opt, loss='mse', metrics=["accuracy"])

print('____   Training now ...________')
H = model.fit(x_trn, to_categorical(y_trn), epochs = EPOCHS, batch_size = BATCH_SIZE)
print('____   Training done !!!________')

I got error

Error

I try several fix but the error still appear

0

There are 0 answers