Skip to main content
IBM Quantum Platform

結果の可視化

  • このページのコードは、以下の要件に基づいて開発された。 これらのバージョンまたは新しいバージョンの使用をお勧めします。

    qiskit[all]~=2.5.1
    

プロットヒストグラム

plot_histogram 、QPU上で量子回路をサンプリングした結果を可視化する機能。

関数からの出力の使用

この関数は matplotlib.Figure オブジェクトを返す。 コード・セルの最終行がこれらのオブジェクトを出力すると、Jupyterノートブックはセルの下にそれらを表示する。 他の環境やスクリプトでこれらの関数を呼び出す場合は、明示的に出力を表示または保存する必要があります。

選択肢は2つある:

  • 返されたオブジェクトに対して .show() を呼び出し、画像を新しいウィンドウで開きます(設定されている matplotlib バックエンドが対話型であると仮定します)。
  • .savefig("out.png") を呼び出し、現在の作業ディレクトリの out.png に図を保存する。 savefig() メソッドはパスを取るので、出力を保存する場所とファイル名を調整できる。 例えば、plot_state_city(psi).savefig("out.png")です。

例えば、2量子ビットのベル状態を作る:

from qiskit.primitives import StatevectorSampler as Sampler
from qiskit.transpiler import generate_preset_pass_manager

from qiskit.circuit import QuantumCircuit
from qiskit.visualization import plot_histogram
# Quantum circuit to make a Bell state
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()

pm = generate_preset_pass_manager(optimization_level=1)
isa_circuit = pm.run(bell)

# execute the quantum circuit
sampler = Sampler()
job = sampler.run([isa_circuit])
result = job.result()

print(result)

Output:

PrimitiveResult([SamplerPubResult(data=DataBin(meas=BitArray(<shape=(), num_shots=1024, num_bits=2>)), metadata={'shots': 1024, 'circuit_metadata': {}})], metadata={'version': 2})
plot_histogram(result[0].data.meas.get_counts())

Output:

Output of the previous code cell

ヒストグラム作成時のオプション

plot_histogram 、以下のオプションを使用して出力グラフを調整する。

  • legend:実行のラベルを提供する。 各実行結果のラベルに使われる文字列のリストを取る。 これは、複数の実行結果を同じヒストグラムにプロットするときに便利です
  • sort:ヒストグラムのバーの順序を調整します。 で昇順、 asc で降順に設定できます。 desc
  • number_to_keep:表示する項の数を整数で指定する。 残りは "rest "と呼ばれる1本の小節にまとめられている
  • color:バーの色を調整します。各実行でバーに使用する色を文字列または文字列のリストで指定します
  • bar_labels:ラベルをバーの上に印刷するかどうかを調整します
  • figsize:出力数字を作るためにインチ単位のサイズのタプルを取る
# Execute two-qubit Bell state again

job = sampler.run([isa_circuit], shots=1000)
second_result = job.result()

# Plot results with custom options
plot_histogram(
    [
        result[0].data.meas.get_counts(),
        second_result[0].data.meas.get_counts(),
    ],
    legend=["first", "second"],
    sort="desc",
    figsize=(15, 12),
    color=["orange", "black"],
    bar_labels=False,
)

Output:

Output of the previous code cell

プロット推定結果

QiskitにはEstimatorの結果をプロットする機能は内蔵されていませんが、 Matplotlib 'の bar プロットを使って素早く視覚化することができます。

次のセルは、量子状態上の7つの異なる観測量の期待値を推定します。

import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.primitives import StatevectorEstimator as Estimator
from qiskit.transpiler import generate_preset_pass_manager
from matplotlib import pyplot as plt

# Simple estimation experiment to create results
qc = QuantumCircuit(2)
qc.h(0)
qc.crx(1.5, 0, 1)

observables_labels = ["ZZ", "XX", "YZ", "ZY", "XY", "XZ", "ZX"]
observables = [SparsePauliOp(label) for label in observables_labels]

pm = generate_preset_pass_manager(optimization_level=1)
isa_circuit = pm.run(qc)
isa_observables = [
    operator.apply_layout(isa_circuit.layout) for operator in observables
]

# Reshape observable array for broadcasting
reshaped_ops = np.fromiter(isa_observables, dtype=object)
reshaped_ops = reshaped_ops.reshape((7, 1))

estimator = Estimator()
job = estimator.run([(isa_circuit, reshaped_ops)])
result = job.result()[0]
exp_val = job.result()[0].data.evs
print(result)

# Since the result array is structured as a 2D array where each element is a
# list containing a single value, you need to flatten the array.

# Plot using Matplotlib
plt.bar(observables_labels, exp_val.flatten())

Output:

PubResult(data=DataBin(evs=np.ndarray(<shape=(7, 1), dtype=float64>), stds=np.ndarray(<shape=(7, 1), dtype=float64>), shape=(7, 1)), metadata={'target_precision': 0.0, 'circuit_metadata': {}})
<BarContainer object of 7 artists>
Output of the previous code cell

以下のセルでは、各結果の推定標準誤差を使用し、エラーバーとして加えている。 プロットの完全な説明については、 bar プロットのドキュメントを参照してください。

standard_error = job.result()[0].data.stds

_, ax = plt.subplots()
ax.bar(
    observables_labels,
    exp_val.flatten(),
    yerr=standard_error.flatten(),
    capsize=2,
)
ax.set_title("Expectation values (with standard errors)")

Output:

Text(0.5, 1.0, 'Expectation values (with standard errors)')
Output of the previous code cell
このページは役に立ちましたか?
バグや誤字の報告、またはコンテンツの要求はGitHubで行ってください。