ValueError: cannot reshape array of size N into shape (...)
Reshape can only rearrange elements, never add or remove them, and your target shape needs a different total count. Check where the element count came from — often an image with an unexpected channel count.
Updated
The error
ValueError: cannot reshape array of size 12288 into shape (100,100,3)
PyTorch phrases it as:
RuntimeError: shape '[100, 100, 3]' is invalid for input of size 12288
What it means
reshape rearranges existing elements into a new layout. It never invents elements and never throws any away. The rule is strict: the product of the target dimensions must equal the current element count. Here 100 × 100 × 3 = 30000, but the array holds 12288 elements. No arrangement can bridge that gap.
Why it happens
Usually the source array is not what you assumed. 12288 = 64 × 64 × 3 — this array is a 64×64 colour image, and the code assumed 100×100. Common versions of the surprise:
- An image loaded at a different resolution than expected.
- A grayscale image (one channel) where code expects three, or a PNG with an alpha channel giving four.
- Flattened model features whose count changed after you edited a layer.
- A file holding fewer records than the loader assumed.
The other cause is treating reshape as a resize. Reshape cannot scale an image from 64×64 to 100×100 — that is resampling, a different operation.
How to fix it
1. Factor the number in the message. It usually names the true shape.
print(arr.shape, arr.size)12288 = 64 * 64 * 3. The data is telling you what it is.
2. To resize an image, use a resize function, not reshape.
import cv2
img = cv2.resize(img, (100, 100)) # actual resamplingOr with PIL: img = img.resize((100, 100)).
3. Let one dimension be computed with -1. NumPy fills in whatever fits.
batch = arr.reshape(-1, 64, 64, 3) # infer the batch dimension-1 works for exactly one dimension, and still fails if the rest do not divide evenly — which is a useful early alarm.
4. When flattening features for a linear layer, derive the size from the data.
x = x.view(x.size(0), -1) # keep batch, flatten the restThis survives architecture changes that would break a hard-coded number.
5. Check channel count explicitly when loading images.
img = cv2.imread(path, cv2.IMREAD_COLOR) # force 3 channels, drops alphaHow to prevent it
Never hard-code sizes you can compute. Assert what you assume: assert img.shape == (64, 64, 3), img.shape fails with the real shape in the message. When a dataset mixes grayscale and colour images, normalise channels at load time, once.