Pytorch Tensor 的 Matplot 直方图

发布于 2025-01-13 16:36:50 字数 511 浏览 3 评论 0原文

我有一个大小为 10 的张量,只有 2 值:01

我想简单地使用 matplotlib.pyplot.hist 绘制上面张量的直方图。这是我的代码:

import torch
import matplotlib.pyplot as plt
t = torch.tensor([0., 1., 1., 1., 0., 1., 1., 0., 0., 0.])
print(t)
plt.hist(t, bins=2)
plt.show()

输出:

在此处输入图像描述

为什么直方图中有这么多值?其余的值从哪里来?如何为我的张量绘制正确的直方图?

I have a tensor of size 10, with only 2 values: 0 and 1.

I want to plot an histogram of the tensor above, simply using matplotlib.pyplot.hist. This is my code:

import torch
import matplotlib.pyplot as plt
t = torch.tensor([0., 1., 1., 1., 0., 1., 1., 0., 0., 0.])
print(t)
plt.hist(t, bins=2)
plt.show()

And the output:

enter image description here

Why are there so many values in the histogram? Where did the rest of the values come from? How can I plot a correct histogram for my tensor?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只有一腔孤勇 2025-01-20 16:36:50

plt.hist(t, bins=2) 函数不适用于张量。为了使其正常工作,您可以尝试使用 t.numpy()t.tolist() 代替。据我自学,使用 pytorch 计算直方图的方法是通过 torch.histc() 函数并使用 plt.bar() 绘制直方图函数如下:

import torch
import matplotlib.pyplot as plt

t = torch.tensor([0., 0., 1., 1., 0., 1., 1., 0., 0., 0.])
hist = torch.histc(t, bins = 2, min = 0, max = 1)

bins = 2
x = range(bins)
plt.bar(x, hist, align='center')
plt.xlabel('Bins')

可以看到一些绘制直方图的来源 此处这里。我找不到根本原因,如果有人可以教育我,那就太好了,但据我所知,这是绘制张量的方法,

我将张量更改为 4 '1.0' 和 6 '0.0 ' 能够看到差异

The plt.hist(t, bins=2) function is not meant to work with tensors. For this to work properly, you can try using t.numpy() or t.tolist() instead. As far as I could educate myself, the way to compute a histogramwith pytorch is through the torch.histc() function and to plot the histogram you use plt.bar() function as follows:

import torch
import matplotlib.pyplot as plt

t = torch.tensor([0., 0., 1., 1., 0., 1., 1., 0., 0., 0.])
hist = torch.histc(t, bins = 2, min = 0, max = 1)

bins = 2
x = range(bins)
plt.bar(x, hist, align='center')
plt.xlabel('Bins')

Some sources for plotting a histogram can be seen here and here . I could not find the root cause for this and if some could educate me it will be great, but as far as I am aware, this is the way to plot a tensor

I changed the tensor to have 4 '1.0' and 6 '0.0' to be able to see the difference

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文