如何随机选择2个实例(2行)进行测试并保留在数据集中进行训练

问题描述 投票:0回答:2

如何随机选择2个实例(2行)进行测试,并在此样本数据集中进行训练。

dog.data

22.0,4566.0,56.4,89.3,Dog-fifota
81.0,3434.0,34.4,67.3,Dog-listem
30.0,8944.0,23.4,45.3,Dog-biker
55.0,3455.0,78.5,11.3,Dog-listem
41.4,3345.0,45.3,34.1,Dog-fifota
python r
2个回答
1
投票

尝试(在R中)

indx <- sample(nrow(dog.data), 2) 
test <- dog.data[indx, ] 
train <- dog.data[-indx, ]

编辑

如果你想把它作为一个函数,这样的东西会起作用:

spltfunc <- function(x){
  indx <- sample(nrow(x), 2)
  test <- x[indx, ] 
  train <- x[-indx, ]
  list2env(list(test = test, train = train), .GlobalEnv)
}

测试

set.seed(123) # setting the random seed so you can reproduce results
spltfunc(dog.data)
# <environment: R_GlobalEnv>
test
#   V1   V2   V3   V4         V5
# 2 81 3434 34.4 67.3 Dog-listem
# 4 55 3455 78.5 11.3 Dog-listem
train
#     V1   V2   V3   V4         V5
# 1 22.0 4566 56.4 89.3 Dog-fifota
# 3 30.0 8944 23.4 45.3  Dog-biker
# 5 41.4 3345 45.3 34.1 Dog-fifota

0
投票

在随机样本和其他样本之间分割数据集的一种简单方法是对整个数据集进行随机分组,然后进行切片。您将获得两个随机排序的项目列表。

这是一个Python函数,它可以做到这一点:

import random

def split_test_training(data, num_test_rows):
    data_copy = list(data)           # shallow copy
    random.shuffle(data)             # reorder the copied list in-place

    testing = data[:num_test_rows]   # slice the first num_test_rows for testing
    training = data[num_test_rows:]  # slice the rest for training

    return testing, training

如果你不介意传入的列表被函数改组,你可以跳过浅拷贝。

© www.soinside.com 2019 - 2024. All rights reserved.