Pytorch Tensor 的 Matplot 直方图

Matplot histogram of Pytorch Tensor

我有一个大小为 10 的张量,只有 1 个值: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()

并且输出:

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

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')

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

我将张量更改为具有 4 个“1.0”和 6 个“0.0”以便能够看到差异