【问题标题】:Increase precision when standardizing test dataset标准化测试数据集时提高精度
【发布时间】:2021-12-09 16:36:27
【问题描述】:

我正在处理 R 中的数据集,分为训练和测试。我预先处理数据中心化并除以标准差,因此,我想存储训练集的平均值和 sd 值,以使用相同的值缩放测试集。但是,使用scale 函数获得的精度比使用colmeansapply(x, 2, sd) 函数时要好得多。

set.seed(5)
a = matrix(rnorm(30000,  mean=10, sd=5), 10000, 3)  # Generate data

a_scale = scale(a) # scale using the scale function
a_scale_custom = (a - colMeans(a)) / apply(a, 2, sd) # Using custom function

现在如果我比较两个矩阵的平均值:

colMeans(a_scale)
[1] -9.270260e-17 -1.492891e-16  1.331857e-16

colMeans(a_scale_custom)
[1]  0.007461065 -0.004395052 -0.003046839

使用scale得到的矩阵的列均值为0,而使用colMeans减去均值得到的矩阵有10^-2的顺序误差。比较标准差时也会发生同样的情况。

在不使用scalefunction 的情况下缩放数据时,有什么方法可以获得更好的精度?

【问题讨论】:

  • whats 2 and sd in apply?
  • sd是计算标准差的R函数,2指apply函数中的轴。 apply(x, 2, sd) 将计算 x 的每一列的标准差。

标签: r precision standardized


【解决方案1】:

自定义函数在矩阵布局中存在错误。您需要先转置矩阵,然后再用t() 减去向量,然后再转置回来。请尝试以下操作:

set.seed(5)
a <- matrix(rnorm(30000,  mean=10, sd=5), 10000, 3)  # Generate data

a_scale <- scale(a) # scale using the scale function
a_scale_custom <- t((t(a) - colMeans(a)) / apply(a, 2, sd))

colMeans(a_scale)
colMeans(a_scale_custom)

另请参阅:How to divide each row of a matrix by elements of a vector in R

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 2020-08-26
    • 2020-12-17
    • 2020-01-10
    • 1970-01-01
    • 2016-01-16
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多