在 R 编程中将缩放矩阵转换为其原始形式 - 使用矩阵计算
在 R 编程中,可以使用scale()
函数对矩阵进行缩放和居中。但是,没有内置函数可以将缩放矩阵转换回原始矩阵。在本文中,我们将学习使用一些简单的计算将缩放矩阵转换回原始矩阵。
使用矩阵属性
缩放矩阵的属性可用于将矩阵缩放回其原始矩阵。
R
# Create matrix
mt <- matrix(c(1:20), ncol = 5)
# Print original matrix
cat("Original matrix:\n")
print(mt)
# Scale the matrix
scaled.mt <- scale(mt)
# Print Scaled matrix
cat("Scaled matrix:\n")
print(scaled.mt)
# Unscale the matrix
unscaled.mt <- t(apply(scaled.mt, 1,
function(r) r * attr(scaled.mt, 'scaled:scale') +
attr(scaled.mt, 'scaled:center')))
# Print Unscaled matrix
cat("Unscaled matrix:\n")
print(unscaled.mt)
R
# Create matrix
a <- rnorm(5, 5, 2)
b <- rnorm(5, 7, 5)
mt <- cbind(a, b)
# get center and scaling values
m <- apply(df, 2, mean)
s <- apply(df, 2, sd)
# Print original matrix
cat("Original matrix:\n")
print(mt)
# Scale the matrix
scaled.mt <- scale(mt, center = m, scale = s)
# Print Scaled matrix
cat("Scaled matrix:\n")
print(scaled.mt)
# Unscale the matrix
unscaled.mt <- t((t(scaled.mt) * s) + m)
# Print Unscaled matrix
cat("Unscaled matrix:\n")
print(unscaled.mt)
输出:
Original matrix:
[, 1] [, 2] [, 3] [, 4] [, 5]
[1, ] 1 5 9 13 17
[2, ] 2 6 10 14 18
[3, ] 3 7 11 15 19
[4, ] 4 8 12 16 20
Scaled matrix:
[, 1] [, 2] [, 3] [, 4] [, 5]
[1, ] -1.1618950 -1.1618950 -1.1618950 -1.1618950 -1.1618950
[2, ] -0.3872983 -0.3872983 -0.3872983 -0.3872983 -0.3872983
[3, ] 0.3872983 0.3872983 0.3872983 0.3872983 0.3872983
[4, ] 1.1618950 1.1618950 1.1618950 1.1618950 1.1618950
attr(, "scaled:center")
[1] 2.5 6.5 10.5 14.5 18.5
attr(, "scaled:scale")
[1] 1.290994 1.290994 1.290994 1.290994 1.290994
Unscaled matrix:
[, 1] [, 2] [, 3] [, 4] [, 5]
[1, ] 1 5 9 13 17
[2, ] 2 6 10 14 18
[3, ] 3 7 11 15 19
[4, ] 4 8 12 16 20
使用均值和标准差
在此示例中,我们将使用原始矩阵的均值和标准差对缩放矩阵进行缩放。
R
# Create matrix
a <- rnorm(5, 5, 2)
b <- rnorm(5, 7, 5)
mt <- cbind(a, b)
# get center and scaling values
m <- apply(df, 2, mean)
s <- apply(df, 2, sd)
# Print original matrix
cat("Original matrix:\n")
print(mt)
# Scale the matrix
scaled.mt <- scale(mt, center = m, scale = s)
# Print Scaled matrix
cat("Scaled matrix:\n")
print(scaled.mt)
# Unscale the matrix
unscaled.mt <- t((t(scaled.mt) * s) + m)
# Print Unscaled matrix
cat("Unscaled matrix:\n")
print(unscaled.mt)
输出:
Original matrix:
a b
[1, ] 5.552301 1.9865159
[2, ] 3.936486 17.5327829
[3, ] 5.379720 15.0981877
[4, ] 3.546333 0.5230305
[5, ] 5.043194 2.0930855
Scaled matrix:
a b
[1, ] 0.01543556 -2.062174
[2, ] -0.69057233 5.252016
[3, ] -0.05997146 4.106591
[4, ] -0.86104456 -2.750713
[5, ] -0.20701146 -2.012036
attr(, "scaled:center")
a b
5.516974 6.369655
attr(, "scaled:scale")
a b
2.288663 2.125494
Unscaled matrix:
a b
[1, ] 5.552301 1.9865159
[2, ] 3.936486 17.5327829
[3, ] 5.379720 15.0981877
[4, ] 3.546333 0.5230305
[5, ] 5.043194 2.0930855
attr(, "scaled:center")
a b
5.516974 6.369655
attr(, "scaled:scale")
a b
2.288663 2.125494