我是R的新用户,试图摆脱SAS。我在这里问这个问题,因为我对R的所有软件包和源代码感到有点沮丧,我似乎无法使这个工作主要是由于数据大小。
我有以下内容:
本地MySQL数据库中名为SOURCE的表,具有200个预测器功能和一个类变量。该表有300万条记录,大小为3GB。每个类的实例数不相等。
我想:
答案 0 :(得分:2)
我要继续的方式是:
1)将表的id列表提取到R,可以使用RMySQL库通过简单的SQL查询执行此操作。
2)以R中的任何方式拆分id,然后使用RMySQL再次执行后续SQL查询(我发现这两步法比直接在MySQL中采样快得多)。
3)根据您使用基本R kmeans实现可以逃脱的样本大小,但是对于更大的样本,这可能会失败,在这种情况下,您应该考虑使用库biganalytics中的bigkmeans。
答案 1 :(得分:0)
我可以帮你解决两个问题。 1-分层抽样 2分割训练和测试(即校准验证)
n = c(2.23, 3.5, 12,2, 93, 57, 0.2,
33, 5,2, 305, 5.3,2, 3.9, 4)
s = c("aa", "bb", "aa","aa", "bb", "cc","aa", "bb",
"bb","aa", "aa","aa","aa","bb", "cc")
id = c(1, 2, 3,4, 5, 6,7, 8, 9,
10, 11, 12,13, 14, 15)
df = data.frame(id, n, s ) # df is a data frame
source("http://news.mrdwab.com/stratified")
sample<- stratified(df=df,
id=1, #ID of your dataframe,
#if there isn't you have to create it
group=3, #the position of your predictor features
size=2, #cardinality of selection
seed="NULL")
#then add a new column to your selection
sample["cal_val"]<- 1
#now, you have a random selection of group 3,
#but you need to split it for cal and val, so:
sample2<- stratified(df=sample, #use your previous selection
id=1,
group=3, #sample on the same group used previously
size=1,#half of the previous selection
seed="NULL")
sample2["val"]<- 1
#merge the two selection
merge<- merge(sample, sample2, all.x=T, by="id")
merge[is.na(merge)] <- 0 #delete NA from merge
#create a column where 1 is for calibration and 2 for validation
merge["calVal"]<- merge$cal_val.x + merge$cal_val.y
#now "clean" you dataframe, because you have too many useless columns
id<- merge$id
n<- merge$n.x
s<- merge$s.x
calval<- merge$calVal
final_sample<- data.frame(id, n, s, calval)
答案 2 :(得分:0)
我认为使用插入符号包可以解决许多问题。关于具有相同类成员资格的随机抽样,我将其推回到SQL中,只需运行两个具有指定每个类所需大小的查询。其他人提到RMySql,RODBC或RJDBC也可以。要将数据分成训练集和测试集,请使用以下插入符函数:
# separate data into test and train sets, 70/30 split in this case
splitIndex <- createDataPartition(mydata$mytargetcolumn, p = 0.7, list = FALSE)
train <- mydata[splitIndex, ]
test <- mydata[-splitIndex, ]
testInd <- test[ ,!colnames(test) %in% "mytargetcolumn"]
testDep <- as.factor(test[, names(test) == "mytargetcolumn"])
您也可以使用插入符号来执行KNN,如下所示:
modelKNN <- knn3(mytargetcolumn ~ ind1 + ind2, data = train, k = neighborCount, prob = TRUE)
然后预测很简单:
# prediction using KNN to get class probabilities, change 'type' if you just want class prediction
predKNN <- predict(modelKNN, testInd, type = "prob")
您也可以使用插入符号进行评估:
# Generate confusion matrix from class predictions and actual values
confKNN <- confusionMatrix(testDep, predKNN)
虽然我个人使用AUC(通过pROC包)进行分类模型评估,因为它是分类器强度比精度更细粒度的度量。