我正在使用 MNIST 数据集并对其执行不同的分类方法,但我的运行时间很荒谬,所以我正在寻找一种方法来可能使用该集的训练部分的一部分,但将测试部分保持在 10K 。我尝试了多种不同的选择,但没有任何效果。
我需要从整个集合中抽取样本,或者将训练 x 和 y 从 60000 降低到 20000。
我当前的代码:
library(keras)
mnist <- dataset_mnist()
train_images <- mnist$train$x
train_labels <- mnist$train$y
test_images <- mnist$test$x
test_labels <- mnist$test$y
我尝试过使用
sample()
函数和其他类型的分割,但没有成功。
在下面的示例中,我自己下载 MNIST 并通过
reticulate
/ numpy
加载它。应该没有太大区别。当您想使用“sample()”获取样本时,通常会获取用于提交的索引样本。为了获得平衡的样本,您可能需要从每个标签组中抽取特定的数字或比例:
library(reticulate)
library(dplyr)
# Download MNIST dataset as numpy npz,
# load through reticulate, build something along the lines of keras::dataset_mnist() output
np <- import("numpy")
mnist_npz <- curl::curl_download("https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz", "mnist.npz")
mnist_np <- np$load(mnist_npz)
mnist_lst <- list(
train = list(
x = mnist_np[["x_train"]],
y = mnist_np[["y_train"]]
),
test = list(
x = mnist_np[["x_test"]],
y = mnist_np[["y_test"]]
)
)
train_images <- mnist_lst$train$x
train_labels <- mnist_lst$train$y
test_images <- mnist_lst$test$x
test_labels <- mnist_lst$test$y
# sample row indices,
# 100 per class to keep the dataset balanced
sample_idx <-
train_labels |>
tibble(y = _) |>
tibble::rowid_to_column("idx") |>
slice_sample(n = 100, by = y ) |>
arrange(idx) |>
pull(idx)
# use sample_idx for subsetting
train_images_sample <- train_images[sample_idx,,]
train_labels_sample <- train_labels[sample_idx]
str(train_images_sample)
#> int [1:1000, 1:28, 1:28] 0 0 0 0 0 0 0 0 0 0 ...
str(train_labels_sample)
#> int [1:1000(1d)] 9 7 5 6 8 7 7 5 2 9 ...
# original label distribution
table(train_labels)
#> train_labels
#> 0 1 2 3 4 5 6 7 8 9
#> 5923 6742 5958 6131 5842 5421 5918 6265 5851 5949
# sample distribution
table(train_labels_sample)
#> train_labels_sample
#> 0 1 2 3 4 5 6 7 8 9
#> 100 100 100 100 100 100 100 100 100 100
创建于 2024-03-29,使用 reprex v2.1.0