从训练集数据中排除项目

Exclude items from training set data

我的数据有两个 colorsexcluded_colors

colors包含所有颜色 excluded_colors 包含一些我希望从我的训练集中排除的颜色。

我正在尝试将数据拆分为训练和测试集,并确保 excluded_colors 中的颜色不在我的训练集中但存在于测试集中。

为了实现上面的效果,我是这样做的

var colors = spark.sql("""
   select colors.* 
   from colors 
   LEFT JOIN excluded_colors 
   ON excluded_colors.color_id = colors.color_id
   where excluded_colors.color_id IS NULL
"""
)
val trainer: (Int => Int) = (arg:Int) => 0
val sqlTrainer = udf(trainer)
val tester: (Int => Int) = (arg:Int) => 1
val sqlTester = udf(tester)

val rsplit = colors.randomSplit(Array(0.7, 0.3))  
val train_colors = splits(0).select("color_id").withColumn("test",sqlTrainer(col("color_id")))
val test_colors = splits(1).select("color_id").withColumn("test",sqlTester(col("color_id")))

但是,我意识到通过执行上述操作,excluded_colors 中的颜色将被完全忽略。他们甚至不在我的测试集中。

问题 如何在 70/30 中拆分数据,同时确保 excluded_colors 中的颜色不在训练中但存在于测试中。

我们想要做的是从训练集中删除 "excluded colors",但将它们放在测试中,并有一个 training/test 70/30 的分割。

我们需要一点数学知识。

给定总数据集 (TD) 和排除的颜色数据集 (E),我们可以说对于训练数据集 (Tr) 和测试数据集 (Ts):

|Tr| = x * (|TD|-|E|)
|Ts| = |E| + (1-x) * |TD|

我们也知道|Tr| = 0.7 |TD|

因此x = 0.7 |TD| / (|TD| - |E|)

现在我们知道采样因子 x,我们可以说:

Tr = (TD-E).sample(withReplacement = false, fraction = x)
// where (TD - E) is the result of the SQL expr above

Ts = TD.sample(withReplacement = false, fraction = 0.3)
// we sample the test set from the original dataset