You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中创建适配Keras的矩阵数组(仿dataset_mnist格式)

问题:合并多个矩阵为Keras适配的3维数组

我需要创建适配Keras的(N×N)矩阵数组,格式与dataset_mnist()加载的数据一致。执行以下代码:

mnist <- dataset_mnist()
x_train <- mnist$train$x
str(x_train)

得到的结构为:

int [1:60000, 1:28, 1:28] 0 0 0 0 0 0 0 0 0 0 ...

现在我有2000个不同的100×100整数矩阵mat1到mat2000,希望将它们合并为结构如下的对象,用于Keras模型输入:

int [1:2000, 1:100, 1:100] ...

我尝试过以下代码,但未得到正确结构:

as.vector(c(mat1, mat2))
as.array(c(mat1, mat2))
rbind(mat1, mat2)

解决方案

MNIST的x_train是3维数组,维度顺序为「样本数 × 图像高度 × 图像宽度」。要将多个100×100矩阵合并成对应结构,可通过以下两种方法实现:

方法1:使用abind包(直观易读)

abind包支持沿指定维度合并多维数组,适合批量处理:

# 安装并加载包(首次使用需安装)
install.packages("abind")
library(abind)

# 将所有矩阵批量存入列表(利用命名规律简化操作)
mat_list <- mget(paste0("mat", 1:2000))

# 沿第1维(样本维度)合并所有矩阵
combined_array <- abind(mat_list, along = 1)

# 验证结构
str(combined_array)

方法2:手动重构数组(无需额外包)

通过将列表展开为向量,再重新定义维度实现:

# 将所有矩阵批量存入列表
mat_list <- mget(paste0("mat", 1:2000))

# 展开列表为向量,再重构为3维数组
combined_array <- array(unlist(mat_list), dim = c(2000, 100, 100))

# 验证结构
str(combined_array)

为什么之前的方法无效?

  • c(mat1, mat2)会将矩阵按列展平为一维向量,即使转成数组也无法恢复3维结构;
  • rbind(mat1, mat2)会将矩阵按行拼接,最终得到200000×100的二维矩阵,不符合Keras需要的3维输入格式。

内容的提问来源于stack exchange,提问作者aparish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:10:47