【问题标题】:object of type 'closure' is not subsettable error when running prcomp运行 prcomp 时,“闭包”类型的对象不是子集错误
【发布时间】:2021-09-09 09:24:05
【问题描述】:

我正在尝试按照我在网上找到的一些代码在 r 上运行 PCA,但与编写代码的人不同,我得到了错误:

“闭包”类型的对象不可子集

我正在使用叶子数据集,您可以在这里找到:

http://archive.ics.uci.edu/ml/datasets/Leaf

特征包括:物种、试样数量、偏心率、纵横比、伸长率、实度、随机凸度、等周因子、最大压痕深度、裂度、平均强度、平均对比度、平滑度、第三矩、均匀度、熵

每一列都是数字,因为我想预测“物种”,所以我不需要样本编号:

leaf_data <- leaf_data[, c(1,3:ncol(leaf_data))]

现在,为了准备训练数据,我使用以下函数:

stratified_labels <- function(df, variable, size){
set.seed(1000)
require(sampling)
temp = df

dfCounts <- table(df[variable])
if (size > min(dfCounts)){
  size <- min(dfCounts)
  }

if (size < 1 ){
  size = ceiling(table(temp[variable])*size)
  } else if (size >=1){
      size = rep(size, times=length(table(temp[variable])))
      }

strat = strata(temp, stratanames=names(temp[variable]),
             size = size, method = 'srswor')
return(strat$ID_unit)
}

确保每个班级都有统一数量的代表。然后我们可以准备训练集和测试集:

training_set <- stratified_labels(leaf_data, 'Species', .8)
leaf_data$Species <- as.factor(leaf_data$Species)
leaf_train <- leaf_data[training_set,]
leaf_test <- leaf_data[-training_set,]

由于变量没有标准化,所以我把它们做成这样:

leaf_train_standard <- leaf_train

standardization <- function(x){
x <- (x-mean(x))/sd(x)
return(x)
}
leaf_train_standard[2:15]<-apply(leaf_train[2:15],2, standardization)

所以现在理论上我已经准备好运行 prcomp:

set.seed(1000)

pca_train <- leaf_train_standard[2:15]
pca_test <- leaf_test
pca <- prcomp[data = pca_train, center=FALSE, scale=FALSE]

但是在最后一行代码之后,我得到了上述错误,我真的不明白为什么。任何帮助表示赞赏。

【问题讨论】:

  • 什么是叶子数据集?可以提供源码吗?
  • 我刚刚添加了链接

标签: r machine-learning r-markdown pca


【解决方案1】:
pca <- prcomp[data = pca_train, center=FALSE, scale=FALSE]

正如错误消息所示,您在此处使用 subsetting[…] 运算符)。你想用(…):

pca <- prcomp(data = pca_train, center = FALSE, scale = FALSE)

另外两句:

您的standardization 函数是不必要的。只需将center = TRUEscale = TRUE 传递给prcomp

还有don’t use require — use library instead

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 2019-08-09
    • 2016-03-30
    相关资源
    最近更新 更多