jupyter笔记本固定在使用matplotlib(CPU 100%)绘制张量(Tensorflow 2)上
我正在关注视频教程,并使用matplotlib在jupyter笔记本中绘制张量张量。 牢房刚刚卡住,一个CPU获得了100%的速度。
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
import matplotlib.pyplot as plt
# %matplotlib inline
normal = tfd.Normal(loc=0, scale=1)
n = 10000
z = normal.sample(n)
scale = 4.5
shift = 7
scale_and_shift = tfb.Chain([tfb.Shift(shift), tfb.Scale(scale)])
x = scale_and_shift.forward(z)
plt.hist(z, bins=60, density=True)
plt.show()
在我关注的教程中,它运行顺利。但是在我的尝试中,它被卡住了。 为什么在我的情况下它不起作用?我应该安装任何软件包吗? z
是张量,可以直接绘制它吗?
我注意到如果我使用plt.hist.hist(z.numpy(),bins = 60,密度= true)
它起作用。但是仍然想知道为什么绘制z
直接在我的环境中不起作用。
I'm following a video tutorial and using matplotlib to plot a tensorflow tensor in a Jupyter Notebook.
The cell just stuck and one CPU went 100%.
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
import matplotlib.pyplot as plt
# %matplotlib inline
normal = tfd.Normal(loc=0, scale=1)
n = 10000
z = normal.sample(n)
scale = 4.5
shift = 7
scale_and_shift = tfb.Chain([tfb.Shift(shift), tfb.Scale(scale)])
x = scale_and_shift.forward(z)
plt.hist(z, bins=60, density=True)
plt.show()
In the tutorial I'm following, it runs smoothly. But in my attempt it got stuck. Why it doesn't work in my case? Is there any package I should install? z
is a tensor, is it OK to plot it directly?
I noticed if I use plt.hist(z.numpy(), bins=60, density=True)
it works. But still wondering why plotting z
directly does not work in my environment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,这不是丢失的软件包问题,通常直接绘制张量没有问题。例如,您可以完成
plt.plot(z)
而没有问题。如果您检查plt.hist.hist
a>您可以看到这个:在您的情况下,由于您正在绘制分布中的样本值(

z
是[10000]形状张量),因此您在第二类中([N0,N1,...])实际上,您正在创建10000个重叠直方图。为了清楚起见,请参见s = 4
:这就是为什么您的CPU被超载 - 尝试一次创建10000个直方图(也就是为什么每行都是不同的颜色 - >不同的直方图)。
当您使用
Tensor.numpy()
时,它将张量转换为使用Numpy数组,并能够正确创建直方图。PS不确定为什么它在教程中工作。也许Trey're使用不同的软件包的版本 - 但是
z.numpy()
应该给您相同的结果Firstly, that's not a missing package problem and generally there's no problem in plotting tensors directly. For example you could have done
plt.plot(z)
without as issue. If you checkplt.hist
documentation you can see this:In your case, since you're plotting sample values from the distribution (with

z
being a [10000] shaped tensor), you are on the second category ([n0, n1, ...]) and you're actually creating 10000 overlapping histograms. To make it clear, see this fors=4
:That's why your CPU is overloaded - trying to create 10000 histograms at once (also thats why each line is a different color --> different histograms).
When you use
tensor.numpy()
it converts the Tensor to a NumPy array using and is able to create the histogram correctly.PS not sure why it's working in the tutorial. Maybe trey're using different packages' version - but
z.numpy()
should give you the same results