将 MNIST 图像的数组重塑为 (28, 28)
Issue reshaping an array into (28, 28) for an MNIST image
当 运行 这段代码时,我想在 matplotlib 中显示图像,但我在 some_digit_image = some_digit.reshape(28, 28)
中收到错误消息,其中出现 ValueError: cannot reshape array of size 1 into shape (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_digit = X.loc[[36000]].to_numpy())。它会解决问题。
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.], ...
当 运行 这段代码时,我想在 matplotlib 中显示图像,但我在 some_digit_image = some_digit.reshape(28, 28)
中收到错误消息,其中出现 ValueError: cannot reshape array of size 1 into shape (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_digit = X.loc[[36000]].to_numpy())。它会解决问题。
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.], ...