Python 如何随机选择2个实例(2行)进行测试&;在数据集中进行剩余训练

Python 如何随机选择2个实例(2行)进行测试&;在数据集中进行剩余训练,python,r,Python,R,我如何随机选择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 Try(在R中) indx在随机样本和其他样本之间分割数据集的一种简单方法

我如何随机选择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
Try(在R中)


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

这里有一个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

如果您不介意传入列表被函数洗牌,您可以跳过浅层副本。

我不确定我是否理解您的要求。您显示的数据是3行5列,因此很难知道在这种数据集中10列来自何处。你想要一个随机的数据样本,还是别的什么?到目前为止,您编写了什么代码来处理您的数据?为什么标记为
r
?@Blckknght我刚刚编辑了这个问题。@nrussell我正在尝试编写一个r函数来将此数据集拆分为训练集和测试集,但是您有4个数字列和1个字符,您想以相同的方式处理它们吗??
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
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