使用TensorFlow Quantum进行多类分类

问题描述

我正在TensorFlow Quantum(TFQ)上运行一些示例和测试,并且正在努力执行多类分类。我将以mnist分类示例为基础(https://www.tensorflow.org/quantum/tutorials/mnist),因为这也是我的起点。

对于二进制分类,我使用了不同的类别示例和不同的Gates组合,分类结果是通过测量单个读出的qubit(qR)结果获得的,因此,如果qR = 0,我们将分类为0,如果qR = 1,然后是1类。

我将其扩展为多类问题,因此我们有4个类(0、1、2、3)。为此,我用tf.keras.utils.to_categorical(y_train)更改了类的标签,以使标签从单个值转换为向量(0->(1,0); 1->(0,1, 0,0);等。),使用tf.keras.losses.CategoricalHinge()作为模型损失,并创建4个读出qubit,每个类一个(M(qR0,qR1,qR2,qR3)=(0,1, 0)-> 2类),并且有效。

但是,这种方法大大增加了电路的尺寸。因此,我想做的是仅将2个读出的qubit传递给TFQ,并将组合的度量用于4个类的分类(| 00> = 0,| 10> = 1,| 01> = 2,| 11> = 3) 。理想情况下,这将允许2 ^ n个多类分类,其中n是量子位的数量。在Cirq中,我可以通过对两个读出的量子位执行cirq.measure(qR0,qR1,key='measure')来实现此输出。但是,我很难将这样的命令传递给TFQ,因为据我所知,它仅测量以单个量子位Pauli门结尾的量子位。

那么,TFQ的功能中我缺少什么东西可以在训练过程中进行此类测量吗?

解决方法

从以下代码段开始:

bit = cirq.GridQubit(0,0)
symbols = sympy.symbols('x,y,z')

# !This is important!
ops = [-1.0 * cirq.Z(bit),cirq.X(bit) + 2.0 * cirq.Z(bit)]
# !This is important!

circuit_list = [
    _gen_single_bit_rotation_problem(bit,symbols),cirq.Circuit(
        cirq.Z(bit) ** symbols[0],cirq.X(bit) ** symbols[1],cirq.Z(bit) ** symbols[2]
    ),cirq.Circuit(
        cirq.X(bit) ** symbols[0],cirq.Z(bit) ** symbols[1],cirq.X(bit) ** symbols[2]
    )
]
expectation_layer = tfq.layers.Expectation()
output = expectation_layer(
    circuit_list,symbol_names=symbols,operators = ops)
# Here output[i][j] corresponds to the expectation of all the ops
# in ops w.r.t circuits[i] where keras managed variables are
# placed in the symbols 'x','y','z'.
tf.shape(output)

我从这里带走的:https://www.tensorflow.org/quantum/api_docs/python/tfq/layers/Expectation

output张量的形状为[3,2],这里我有3个不同的电路,每个电路取两个期望值。 [1,0]output处的值为:

U value 0

enter image description here

那么[2,1]output的值将是:

U value

enter image description here

output的值的形状和内容部分由ops的形状和内容决定。如果我想使输出形状为[3,3],则可以向cirq.PauliSum列表中添加另一个有效的ops对象。在您的情况下,如果您希望在两个特定的cirq.GridQubit q0q1上获得00、01、10、11的概率,则可以执行以下操作:

def zero_proj(qubit):
  return (1 + cirq.Z(qubit)) / 2

def one_proj(qubit):
  return (1 - cirq.Z(qubit)) / 2

# ! This is important
ops = [
  zero_proj(q0) * zero_proj(q1),zero_proj(q0) * one_proj(q1),one_proj(q0) * zero_proj(q1),one_proj(q0)* one_proj(q1)
]
# ! This is important

使摄取了ops[whatever_your_batch_size_is,4]的任何图层的输出形状。这有助于清除一切吗?

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...