运行prcomp时出现’closure’类型对象不可子集化的错误

我在尝试按照网上找到的代码在R中运行主成分分析(PCA),但与代码作者不同,我遇到了以下错误:

object of type ‘closure’ is not subsettable

我使用的是叶子数据集,你可以在这里找到它:

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 = dfdfCounts <- 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_trainstandardization <- 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_testpca <- prcomp[data = pca_train, center=FALSE, scale=FALSE]

但在运行最后一行代码后,我得到了上述错误,我实在不明白为什么。任何帮助都将不胜感激。


回答:

pca <- prcomp[data = pca_train, center=FALSE, scale=FALSE]

正如错误信息所指示的,你在这里使用了子集操作([…]操作符)。你应该使用(…)

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

另外两个建议:

你的standardization函数是不必要的。只要将center = TRUEscale = TRUE传递给prcomp即可。

并且不要使用require — 使用library代替

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注