运行此代码时,我想在matplotlib中显示图像,但我在some_digit_image = some_digit.reshape(28, 28)
中得到ValueError时是否遇到错误:无法将大小为1的数组重塑为形状(28,28(。有什么方法可以解决这个问题并在matplotlib中获取图像吗。谢谢你帮我解决这个问题。
from sklearn.datasets import fetch_openml
mnist = fetch_openml('mnist_784')
X, y = mnist["data"], mnist["target"]
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
some_digit = X.loc[[36000]]
print(some_digit)
some_digit_image = some_digit.reshape(28, 28)
plt.imshow(some_digit_image, cmap=matplotlib.cm.binary, interpolation='nearest')
plt.axis('off')
plt.show()
您正在尝试对数据帧对象执行整形。将数据帧对象转换为numpy数组(some_digt=X.loc[[36000]].to_num(((。这将解决此问题。
some_digit
是一个DataFrame,它没有.reshape()
方法。您需要获取其底层numpy
阵列:
In [3]: some_digit = X.loc[[36000]].to_numpy()
In [4]: type(some_digit)
Out[4]: numpy.ndarray
In [5]: some_digit.reshape(28, 28)
Out[5]:
array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0.], ...