尝试运行以下代码时,出现以下错误。
import torch
import matplotlib.pyplot as plt
data = torch.tensor([[0, 0, 1, 1, 0, 0],
[0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 1, 1, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0]]).view(-1, 1, 6, 6).float()
# Convert data to a 2D array
data_np = data[0, 0].cpu().detach().numpy()
plt.imshow(data_np, cmap='gray')
plt.axis('off')
plt.show()
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.12_3.12.1264.0_x64__qbz5n2kfra8p0\\Lib\\tkinter\__init_\_.py", line 1968, in __call__
return self.func(\*args)
^^^^^^^^^^^^^^^^
File "C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.12_3.12.1264.0_x64__qbz5n2kfra8p0\\Lib\\tkinter\__init_\_.py", line 862, in callit
func(\*args)
File "C:\\Users\\mori\\Desktop\\ML_learning\\venv\\Lib\\site-packages\\matplotlib\\backends_backend_tk.py", line 271, in idle_draw
self.draw()
File "C:\\Users\\mori\\Desktop\\ML_learning\\venv\\Lib\\site-packages\\matplotlib\\backends\\backend_tkagg.py", line 10, in draw
super().draw()
File "C:\\Users\\mori\\Desktop\\ML_learning\\venv\\Lib\\site-packages\\matplotlib\\backends\\backend_agg.py", line 387, in draw
self.figure.draw(self.renderer)
File "C:\\Users\\mori\\Desktop\\ML_learning\\venv\\Lib\\site-packages\\matplotlib\\artist.py", line 95, in draw_wrapper
result = draw(artist, renderer, \*args, \*\*kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\\Users\\mori\\Desktop\\ML_learning\\venv\\Lib\\site-packages\\matplotlib\\artist.py", line 72, in draw_wrapper
return draw(artist, renderer)
^^^^^^^^^^^^^^^^^^^^^^
File "C:\\Users\\mori\\Desktop\\ML_learning\\venv\\Lib\\site-packages\\matplotlib\\figure.py", line 3154, in draw
self.patch.draw(renderer)
File "C:\\Users\\mori\\Desktop\\ML_learning\\venv\\Lib\\site-packages\\matplotlib\\artist.py", line 72, in draw_wrapper
return draw(artist, renderer)
^^^^^^^^^^^^^^^^^^^^^^
File "C:\\Users\\mori\\Desktop\\ML_learning\\venv\\Lib\\site-packages\\matplotlib\\patches.py", line 632, in draw
self.\_draw_paths_with_artist_properties(
File "C:\\Users\\mori\\Desktop\\ML_learning\\venv\\Lib\\site-packages\\matplotlib\\patches.py", line 617, in \_draw_paths_with_artist_properties
renderer.draw_path(gc, \*draw_path_args)
File "C:\\Users\\mori\\Desktop\\ML_learning\\venv\\Lib\\site-packages\\matplotlib\\backends\\backend_agg.py", line 131, in draw_path
self.\_renderer.draw_path(gc, path, transform, rgbFace)
ValueError: object __array__ method not producing an array
我无法重现你的问题,尽管我已经匹配了你的库的版本(除了
torch
,它是2.3.1
,在我的系统上没有CUDA支持)。
尽管如此,下面的代码片段会导致同样的错误
import numpy as np
import matplotlib.pyplot as plt
data_np = np.ones((1, 1, 6, 6))
plt.imshow(data_np, cmap='gray')
plt.axis('off')
plt.show()
numpy.squeeze
去除长度为 1 的轴。然后,您提供给 plt.imshow
的数据将具有形状 (6,6),并且可以毫无问题地绘制它们。
import numpy as np
import matplotlib.pyplot as plt
data_np = np.ones((1, 1, 6, 6))
plt.imshow(np.squeeze(data_np), cmap='gray')
plt.axis('off')
plt.show()