R语言绘制MNIST数据集图像报错:‘z’必须为矩阵
Hey there! Let's break down what's going wrong with your MNIST digit display code and fix it step by step.
1. Why is your matrix m all zeros?
Looking at your output, tmp has columns like V17015, V17021—this suggests the pixel columns in your train dataset aren't the first 784 columns! When you run tmp[1,1:784], you're selecting columns 1 to 784, but those might not be the pixel data (they could be unrelated columns or even non-pixel metadata).
First, confirm which columns in train correspond to the 28x28 pixel values. MNIST datasets typically have one label column followed by 784 pixel columns. Adjust your code to select the correct pixel range, and always convert to numeric—this fixes a common issue where imported columns get treated as factors instead of raw pixel values:
# Adjust this to match your actual pixel column range (e.g., 2:785 if label is column 1) pixel_cols <- 2:785 tmp <- train[train$label == 0, ] # Extract and convert pixel values to numeric first pixel_values <- as.numeric(tmp[1, pixel_cols]) # Reshape into a 28x28 matrix m <- matrix(pixel_values, ncol = 28, nrow = 28, byrow = TRUE)
2. Fixing the apply() and image() errors
Your apply(m, 2, rev) call was returning a list instead of a matrix because m was likely a non-numeric matrix (from factor columns). Even after converting to a matrix, non-numeric values trigger the 'z' must be numeric or logical error.
Here's the corrected, full workflow:
# 1. Define correct pixel columns and filter for label 0 pixel_cols <- 2:785 # Update based on your dataset's structure tmp <- train[train$label == 0, ] # 2. Extract and clean pixel data pixel_values <- as.numeric(tmp[1, pixel_cols]) m <- matrix(pixel_values, ncol = 28, nrow = 28, byrow = TRUE) # 3. Fix orientation (MNIST is often stored upside-down) m_flipped <- apply(m, 2, rev) # 4. Plot the digit image(1:28, 1:28, z = m_flipped, col = gray.colors(256), axes = FALSE) title(main = "MNIST Digit: 0")
- The
byrow = TRUEargument ensures pixel values are arranged in the correct row-major order (matches how MNIST data is stored). - Converting to numeric explicitly guarantees
mis a numeric matrix, soapply()returns a valid matrix forimage().
3. Quick sanity checks
Before plotting, run these to verify your data:
str(tmp[pixel_cols]): Confirm all pixel columns are numeric (not factors or characters).range(pixel_values): Should return0 255(standard MNIST pixel intensity range; a range of0 1means your data is scaled, which is also fine).
内容的提问来源于stack exchange,提问作者kKenny

