Как разделить набор данных на все возможные комбинации теста и обучения в R? - PullRequest
0 голосов
/ 29 ноября 2018
    I have a dataset with 90 rows and 5 columns ,of which 4 independent variables and one is dependent variable .I need to split the dataset into test and train Leaving one out cross validation .For example 90th train ,rest all test ....89th train ..rest all train and so on


  Below is the code which I tried ,its not working

K = 90 крат <- rep_len (1: nrFolds, nrow (data)) </p>

# actual cross validation
for(k in 1:nrFolds) {
  # actual split of the data
  print(k)
  fold <- which(folds == k)
  data.train <- data[-fold,]
  dim(data.train)
  data.test <- data[fold,]
  dim(data.test)

}

Любая помощь будет принята с благодарностью. После этого мне нужно отправить этот тест и обучить набор данныхклассификатору для обучения и тестирования.Спасибо

Ответы [ 2 ]

0 голосов
/ 02 декабря 2018

Следующий код разбивает 70% данных, выбранных случайным образом, в обучающий набор, а оставшиеся 30% выборки - в набор тестовых данных.

data<-read.csv("c:/datafile.csv")

dt = sort(sample(nrow(data), nrow(data)*.7))
train<-data[dt,]
test<-data[-dt,]

Вот еще один хороший, очень хороший и очень общий пример.

library(ISLR)
attach(Smarket)
smp_siz = floor(0.75*nrow(Smarket))  # creates a value for dividing the data into train and test. In this case the value is defined as 75% of the number of rows in the dataset
smp_siz  # shows the value of the sample size

set.seed(123)   # set seed to ensure you always have same random numbers generated
train_ind = sample(seq_len(nrow(Smarket)),size = smp_siz)  # Randomly identifies therows equal to sample size ( defined in previous instruction) from  all the rows of Smarket dataset and stores the row number in train_ind
train =Smarket[train_ind,] #creates the training dataset with row numbers stored in train_ind
test=Smarket[-train_ind,]  # creates the test dataset excluding the row numbers mentioned in train_ind

require(caTools)  # loading caTools library

## Loading required package: caTools

set.seed(123)   #  set seed to ensure you always have same random numbers generated
sample = sample.split(Smarket,SplitRatio = 0.75) # splits the data in the ratio mentioned in SplitRatio. After splitting marks these rows as logical TRUE and the the remaining are marked as logical FALSE
train1 =subset(Smarket,sample ==TRUE) # creates a training dataset named train1 with rows which are marked as TRUE
test1=subset(Smarket, sample==FALSE)

https://rpubs.com/ID_Tech/S1

Также смотрите это.

https://edumine.wordpress.com/2015/04/06/splitting-a-data-frame-into-training-and-testing-sets-in-r/

0 голосов
/ 29 ноября 2018

Если я вас правильно понимаю: (Я использовал набор данных mtcars, так как вы не предоставили данные с вашим вопросом)

res <- lapply(1: (nrow(mtcars)-1), function(n){
  train_idx <- sample(1:nrow(mtcars), n)
  list(train = mtcars[train_idx,], test = mtcars[-train_idx,])
})

В результате будет создан следующий список:

str(res, max.level = 2)
List of 31
 $ :List of 2
  ..$ train:'data.frame':   1 obs. of  11 variables:
  ..$ test :'data.frame':   31 obs. of  11 variables:
 $ :List of 2
  ..$ train:'data.frame':   2 obs. of  11 variables:
  ..$ test :'data.frame':   30 obs. of  11 variables:
...
 $ :List of 2
  ..$ train:'data.frame':   30 obs. of  11 variables:
  ..$ test :'data.frame':   2 obs. of  11 variables:
 $ :List of 2
  ..$ train:'data.frame':   31 obs. of  11 variables:
  ..$ test :'data.frame':   1 obs. of  11 variables:

Для которого каждый элемент содержит запрошенный поезд и тест DF.Как отмечают другие, это будет генерировать различную комбинацию наблюдений при каждом запуске.(может быть set.seed(1) заранее?).Я также не видел этот тип раскола раньше.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...