Catboost中每个分类值的最小样本数

时间:2018-12-05 10:41:44

标签: categorical-data catboost

如何告诉CatBoost用很少的样本将分类值组合在一起。 例如,假设我有一个名为“国家/地区”的列,其中“柬埔寨”只有1个样本,“蒙古”只有2个样本,而999,998个其他国家/地区中的每个国家至少有100个样本。 我想告诉CatBoost,不要在那些稀有国家/地区使用CTR魔术,而只是将它们视为“其他”。

1 个答案:

答案 0 :(得分:0)

假设您有一个熊猫数据框,并且有一个想要转换的训练/测试集。小代码段会将您的小数量代码转换为“其他”代码。我将阈值设为100,但是您可以将其更改为所需的值!

基本上,代码获取计数较低的值列表,并将其替换为所需的值。

注意:在转换类别列之前,您可以在列上运行 .value_counts()来查看其中的内容。

def transform_lowcount_cat(train=train, test=test, colstoreplace=colstoreplace, replaceval = 'other',  threshold=100): 
  for col in colstoreplace:
      unique_vals_cat = pd.DataFrame(train[col].value_counts())
      low_val_cat = unique_vals_cat[unique_vals_cat[col] < threshold].index.values
      train[col].replace(low_val_cat, replaceval, inplace=True)
      print(col + ' - TRAIN set transformed')
      if test == None:
        print('TEST set NOT transformed')
      else:
        test[col].replace(low_val_cat, replaceval, inplace=True)
        print(col + ' - TEST set transformed')

然后创建要进行转换的列/列的列表,并使用所需的替换值和阈值限制运行代码。请注意,这会进行就地转换。

colstoreplace = ['Col1','Col2']
transform_lowcount_cat(train=train, test=test, colstoreplace=colstoreplace, replaceval='whatever you want!', threshold = 100)
相关问题