Sch*_*121 1 r linear-discriminant
我正在使用 R 中的 lda 函数来拟合模型。拟合模型后,我想使用拟合结果放入计算机程序中,根据输入进行分类。我只看到线性判别式和组均值的系数。我认为我需要截距和系数才能获得每组的实际分数。
简短的回答是:
iris.lda <- lda(x = iris[, 1:4], grouping = iris$Species)
iris.lda$scores <- predict(iris.lda)$x
Run Code Online (Sandbox Code Playgroud)
确切的过程有点隐藏,getAnywhere(predict.lda)因为该函数需要处理更多事情,例如在 R 环境中查找原始数据。如果您想了解如何在 R 中或在纸上手动完成此操作,从 LDA 系数获取实际 LDA 分数的过程可归结为以下 4 个步骤:
1)计算每个变量的组均值
# tapply solution
grmeans <- sapply(1:4, function(x) tapply(iris[,x], INDEX = iris$Species, FUN = mean))
# # dplyr solution
# library(dplyr)
# grmeans <- iris %>% group_by(Species) %>% summarize_all(list(mean))
grmeans
# [,1] [,2] [,3] [,4]
#setosa 5.006 3.428 1.462 0.246
#versicolor 5.936 2.770 4.260 1.326
#virginica 6.588 2.974 5.552 2.026
# check group means
iris.lda <- lda(iris[, 1:4], iris$Species)
all.equal(unname(iris.lda$means), unname(grmeans)) # it's the same!
#[1] TRUE
Run Code Online (Sandbox Code Playgroud)
2)计算每个变量的组均值的平均值
center <- colMeans(grmeans)
# center <- apply(grmeans, 2, mean) # apply solution
center
#[1] 5.843333 3.057333 3.758000 1.199333
Run Code Online (Sandbox Code Playgroud)
3)将数据集中在组均值处
iris.c <- scale(x = iris[, 1:4], center = center, scale = FALSE)
Run Code Online (Sandbox Code Playgroud)
x中的参数可以scale是原始数据,也可以是想要投影(预测)到拟合判别空间中的任何新数据。然而,人们总是必须使用原始数据定义的中心向量(center在我们的示例中用于 LDA 模型拟合)来相应地中心化新数据。
4) 将中心数据与存储的 LD 系数(= 载荷)相乘,$scaling得到实际分数
iris.lda <- lda(iris[, 1:4], iris$Species)
iris.lda$scores <- iris.c %*% iris.lda$scaling
# iris.lda$scores <- predict(iris.lda)$x # equivalent
Run Code Online (Sandbox Code Playgroud)
最后一步是矩阵乘法,它对应于计算变量项和相关载荷(系数)的所有线性组合,如多元线性回归中:
# example for the first centered observation (row)
(ex <- iris.c[1,])
#Sepal.Length Sepal.Width Petal.Length Petal.Width
# -0.7433333 0.4426667 -2.3580000 -0.9993333
(coef <- iris.lda$scaling[,"LD1"])
#Sepal.Length Sepal.Width Petal.Length Petal.Width
# 0.8293776 1.5344731 -2.2012117 -2.8104603
(score <- unname(coef[1] * ex[1] + coef[2] * ex[2] + coef[3] * ex[3] + coef[4] * ex[4]))
#[1] 8.0618
all.equal(score, unname(iris.lda$scores[1,"LD1"])) # it's the same!
#[1] TRUE
Run Code Online (Sandbox Code Playgroud)
其他 LD 函数的分数以相同的方式计算(将上面代码中的“LD1”替换为“LD2”等)。
所有这些步骤都是由predict.lda函数完成的:
all.equal(predict(iris.lda)$x, iris.lda$scores) # it's the same!
#[1] TRUE
Run Code Online (Sandbox Code Playgroud)
摘要:LDA 分数可以使用 计算predict(iris.lda)$x。$means它们仅由中心变量(以 为中心)和 LDA 系数(载荷,存储在 中)的线性组合组成$scaling。
人们可以将 LDA 分数视为多元线性回归的拟合值
# y = a + b1*x1 + b2*x2 + ...
Run Code Online (Sandbox Code Playgroud)
在哪里
# y LDA score (`predict(iris.lda)$x`)
# a = 0 (no intercept since the data is centered)
# b1, b2, ... LDA coefficients (`$scaling`)
# x1, x2, ... centered data (at mean of group `$means`)
Run Code Online (Sandbox Code Playgroud)