Plotting Bloch Vectors in Qiskit: " 'Arrow3D' object has no attribute '_path2d' " - python

I am working through the Qiskit tutorial textbook, and in Section 1.4 ('Single Qubit Gates'), I can't seem to plot vectors on the Bloch Sphere.
I am using Google Colab and am importing as:
!pip install qiskit
!pip install qiskit[visualization]
from qiskit import QuantumCircuit, assemble, Aer
from math import pi, sqrt
from qiskit.visualization import plot_bloch_multivector, plot_histogram
sim = Aer.get_backend('aer_simulator')
and then the following code is taken directly from the textbook:
qc = QuantumCircuit(1)
qc.x(0)
qc.save_statevector()
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector()
plot_bloch_multivector(state)
Yet doing this gives the error: " 'Arrow3D' object has no attribute '_path2d' ". Any help would be greatly appreciated.
Edit: Adding a line plt.show() no longer brings up an error message, but still no image shows.

i had this same issue and upgrading matplotlib (to 3.5.1) fixed it for me

I'm having the same problem. One workaround that I found is to use the Kaleidoscope package link. It's a visualization package developed by someone working at IBM. I actually like this as it uses Plotly for the figures.
import kaleidoscope.qiskit
from kaleidoscope import bloch_sphere
Then you can just type
bloch_sphere(state)

Related

MatplotlibDeprecationWarning: Support for FigureCanvases without a required_interactive_framework attribute

I'm trying to use matplotlib and numpy to plot a graph but keep running into this error:
MatplotlibDeprecationWarning: Support for FigureCanvases without a required_interactive_framework attribute was deprecated in Matplotlib 3.6 and will be removed two minor releases later.
plt.plot(cache_sizes, hit_rates[i])
Any idea how to solve it?
Here's the code:
#!/usr/bin/env python3
import os
import subprocess
import matplotlib.pyplot as plt
import numpy as np
# cache_sizes = np.arange(0, 120, 20)
cache_sizes = np.arange(1, 5)
policies = ["FIFO", "LRU", "OPT", "UNOPT", "RAND", "CLOCK"]
# these were acheived after running `run.sh`
hit_rates = [
# FIFO
[45.03, 83.08, 93.53, 97.42],
# LRU
[45.03, 88.04, 95.20, 98.30],
# OPT
[45.03, 88.46, 96.35, 98.73],
# UNOPT
# NOTE: was unable to finish running this one, as it took too long.
[45.03, None, None, None],
# RAND
[45.03, 82.06, 93.16, 97.36],
# CLOCK
[45.03, 83.59, 94.09, 97.73],
]
for i in range(len(policies)):
plt.plot(cache_sizes, hit_rates[i])
plt.legend(policies)
plt.margins(0)
plt.xticks(cache_sizes, cache_sizes)
plt.xlabel("Cache Size (Blocks)")
plt.ylabel("Hit Rate")
plt.savefig("workload.png", dpi=227)
Best I can tell, this is related to the backend you're using and how it generates the FigureCanvas object. Matplotlib has introduced a deprecation and some other softwares are still in the process of being updated accordingly. Sadly, for now, it's generating a warning that is not very user friendly and the matplotlib documentation provides no help.
I was seeing this error in PyCharm, which by default uses its own internal backend for matplotlib: 'module://backend_interagg'. Google provides a bunch of examples of people getting errors to do with FigureCanvas and backend_interagg. Fortunately, updating to the newest version of PyCharm solved it for me.
If your problem is not PyCharm related, then perhaps try checking which backend you're using, and perhaps use a different one.
import matplotlib
matplotlib.get_backend()
will show you which backend you're using
matplotlib.use('')
will give you a list of available backends to try and then use will also allow you to select one. e.g. matplotlib.use('GTK3Agg')

how could I solve "a result has failed to un-serialize. please ensure that the objects returned by the function are always picklable." when I run LDA?

When I use the pyLDAvis.gensim functoion to construct visualization at google colab, it shows this error:
a result has failed to un-serialize. please ensure that the objects
returned by the function are always picklable.
My codes are:
!pip install pyldavis
import pyLDAvis
import pyLDAvis.gensim_models as pg
pyLDAvis.enable_notebook()
vis = pg.prepare(lda, corpus, dictionary, sort_topics=False) # construct visualization
Upgrading pandas to '1.2.0' version worked for me.

Matplotlib backend shifts when using object detection API, QtAgg to Agg

The figure doesn't show up when using matplotlib with object detection API, But it works fine before I import some test method.
I'm using Anaconda virtual envionment, python 3.6 and the google object detection API.
import matplotlib.pyplot as plt
import tensorflow as tf
from matplotlib import patches
from object_detection.anchor_generators.multiple_grid_anchor_generator import create_ssd_anchors
from object_detection.models.ssd_mobilenet_v2_feature_extractor_test import SsdMobilenetV2FeatureExtractorTest
from object_detection.models.ssd_mobilenet_v2_feature_extractor_test import SsdMobilenetV2FeatureExtractorTest
The change happens when it comes to the last line
from object_detection.models.ssd_mobilenet_v2_feature_extractor_test import SsdMobilenetV2FeatureExtractorTest"
Before, I can show the figure, like plt.subplot(2,2), I get the figure pop up and the following:
(<Figure size 640x480 with 4 Axes>,
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7f4615eb8ba8>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f4614d320f0>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x7f4614ce36a0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f4614c92c50>]],
dtype=object))
WARNING: The TensorFlow contrib module will not be included in TensorFlow 2.0.
For more information, please see:
* https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md
* https://github.com/tensorflow/addons
If you depend on functionality not listed there, please file an issue.
and "plt.get_backend()" shows "Qt5Agg".
but after the last line, the figure doesn't pop up, although I do get results from "plt.subplots(2,2)":
(<Figure size 640x480 with 4 Axes>,
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7f460b8a5f60>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f460b86b5c0>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x7f460a7b2fd0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f460a7cb630>]],
dtype=object))
Now when I type "plt.get_backend()", it shows "Agg", not the previous "Qt5Agg". and "plt.show()" throws an error:
UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
#!/usr/bin/env python2
the interpreter I was using is
~/anaconda3/envs/py36/bin/python
Is there a shift of environment here?
The script for the last line can be found here
Thanks a lot for your time!
Solved. Have found this line in ~/models/research/object_detecion/utils/visualization_utils.py :
import matplotlib; matplotlib.use('Agg') # pylint: disable=multiple-statements
just comment it and works fine.
Solved. I am running locally on a virtual enironment and tried several suggested solution but with no success.
I tried what Yunfei Fang was suggesting above but then realized that by, commenting out the line of code import matplotlib; matplotlib.use('Agg') in the ~/models/research/object_detecion/utils/visualization_utils.py folder wasn't enough.
I found out by putting this code in the body of my script: print('matplotlib backend= ',matplotlib.get_backend()) as this was still returning "agg" so I had to add this matplotlib.use('MacOSX') at the end of the import section of the script.
I am running on a MacBook Pro with macOS Big Sur

name 'ImageDataBunch' is not defined

I'm getting this error "name 'ImageDataBunch' is not defined" and am not able to find a solution on the Internet.
The full code can be found here: https://dzlab.github.io/jekyll/update/2018/11/13/audio-classification/.
np.random.seed(42)
data = ImageDataBunch.from_lists(path, fnames, labels, ds_tfms=None, size=224, bs=bs)
data.normalize(imagenet_stats)
data.show_batch(rows=5, figsize=(8,8))
I'm running this code on Google Colab and Python 3.6.
You just need to import the ImageDataBunch class from the fast.ai library. Here's the docs for it. Just add the following to the top of your code to import the entirety of the vision library classes:
from fastai.vision import *

Cannot find reference to Python package (plt.cm.py)

I have a small issue with running code from a tutorial that isn't working as it should. It's not a syntax problem for sure. I'm working with scikit-learn and matplotlib, and I'm getting a warning message in my IDE "Cannot find reference 'gray_r' in 'cm.py'..." All my packages are installed properly (via pip) and have worked for sample programs except this.
Any advice?
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
digits = datasets.load_digits()
print(digits.data)
print(digits.target)
print(digits.images[0])
clf = svm.SVC(gamma=0.001, C=100)
print(len(digits.data))
x, y = digits.data[:-1], digits.target[:-1]
clf.fit(x,y)
print('Prediction:', clf.predict(digits.data[-1])
plt.imshow(digits.images[-1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
Well for starters your missing a closing parenthesis on your last print statement: print('Prediction:', clf.predict(digits.data[-1])) Other than that, this code runs on my computer with only a deprecation warning. What does the traceback say?

Categories

Resources