簡體   English   中英

使用 TensorFlow Quantum 進行多類分類

[英]Multiclass classification using TensorFlow Quantum

我正在 TensorFlow Quantum (TFQ) 上運行一些示例和測試,並且正在努力執行多類分類。 我將使用 MNIST 分類示例作為基礎( https://www.tensorflow.org/quantum/tutorials/mnist ),因為這也是我的起點。

對於二元分類,我玩了不同類別的例子和不同的門組合,分類結果是通過測量單個讀出量子位(qR)結果獲得的,因此如果 qR=0 我們分類為 0 類,如果 qR=1 那么我們有1級。

我將其擴展為多類問題,因此我們有 4 個類(0、1、2、3)。 為此,我使用tf.keras.utils.to_categorical(y_train)更改類的標簽,以便將標簽從單個值轉換為向量 (0 -> (1,0,0,0); 1-> (0,1,0,0); 等..),使用tf.keras.losses.CategoricalHinge()作為模型的損失並創建 4 個讀出量子位,每個類一個 (M(qR0, qR1, qR2, qR3 ) = (0,0,1,0) -> class 2),這是有效的。

然而,這種方法極大地增加了電路的尺寸。 所以我想要做的是僅將 2 個讀出量子位傳遞給 TFQ,並使用 4 類分類的組合測量 (|00> = 0, |10> = 1, |01> = 2, |11> = 3) . 理想情況下,這將允許 2^n 多類分類,其中 n 是量子位的數量。 在 Cirq 中,我可以通過對兩個讀出量子位執行cirq.measure(qR0, qR1, key='measure')來實現此輸出。 然而,我正在努力將這樣的命令傳遞給 TFQ,因為據我所知,它只測量以單個量子比特泡利門結尾的量子比特。

那么,我在 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 個不同的電路,我對每個電路取了兩個期望值。 output [1, 0]處的值將是:

U 值 0

在此處輸入圖片說明

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

U值

在此處輸入圖片說明

output值的形狀和內容部分由ops的形狀和內容決定。 如果我想制作輸出形狀[3, 3]我可以將另一個有效的cirq.PauliSum對象添加到ops列表中。 在您的情況下,如果您希望在兩個特定的cirq.GridQubit s 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] 這有助於解決問題嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM