Skip to main content
IBM Quantum Platform

결과 시각화

  • 이 페이지의 코드는 다음 요구 사항을 사용하여 개발되었습니다. 다음 버전 이상을 사용하는 것이 좋습니다.

    qiskit[all]~=2.5.2
    

플롯 히스토그램

plot_histogram 함수는 QPU에서 양자 회로를 샘플링한 결과를 시각화합니다.

함수 출력 사용

이 함수는 matplotlib.Figure 객체를 반환합니다. 코드 셀의 마지막 줄에서 이러한 객체를 출력하면 Jupyter 노트북은 해당 객체를 셀 아래에 표시합니다. 다른 환경이나 스크립트에서 이러한 함수를 호출하는 경우 출력을 명시적으로 표시하거나 저장해야 합니다.

두 가지 옵션이 있습니다:

  • 반환된 객체에서 .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: 표시할 용어의 수를 정수로 받습니다. 나머지는 "휴식"이라는 단일 막대에 함께 그룹화됩니다
  • 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

플롯 추정기 결과

키스킷에는 추정기 결과를 플로팅하는 기능이 내장되어 있지 않지만, 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에서 버그, 오타를 보고하거나 컨텐츠를 요청하십시오.