'Issue reshaping an array into (28, 28) for an MNIST image
When running this code, I want to show the image in matplotlib but am I getting an error in some_digit_image = some_digit.reshape(28, 28) where I get the ValueError: cannot reshape array of size 1 into shape (28, 28). Is there any way to fix this issue and get the image in the matplotlib. Thanks for helping me solve the issue.
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()
Solution 1:[1]
some_digit is a DataFrame, which does not have a .reshape() method. You need to get its underlying numpy array:
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.], ...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ddejohn |
