【问题标题】:Factorize real time data with consistent mappings to training data?通过与训练数据的一致映射来分解实时数据?
【发布时间】:2019-01-27 07:24:57
【问题描述】:

在生产层面,我想使用预先保存的模型来预测我的实时数据。

但是,在分解分类数据时,我不知道如何设置我的实时数据以与训练数据保持一致的映射。

From this article我知道我可以将训练数据和新数据叠加在一起并保持一致。

但是,堆叠和遍历整个过程(进行整个特征工程、训练和预测)太耗时了。

  • 整个过程:15 分钟 v.s. 仅 model.prediction:3 秒

由于生产级系统对时间敏感,我可以使用任何方法将新数据分解为与训练数据具有相同的映射?

或者我只能通过«手动»来完成,例如

 df.loc[df['col_name']=='YES', 'col_name'] =  '1'

这会导致很长的编码?

【问题讨论】:

  • 我找到了 pd.factorize 的替代工具 LabelEncoder。如果可能的话,让我试着报告一下效果。

标签: python pandas machine-learning


【解决方案1】:

如果您的意思是在新的分类值出现时考虑它们(例如,您为 df.color 获得了一个新的“蓝绿色”值),您可以将任何意外值反弹到同一个 -1 存储桶(假设是未知的),然后在后处理或重新调整模型时进行处理。

基本上,您可以捕获类别异常,然后再处理它们。

【讨论】:

    【解决方案2】:

    经过几个小时的工作,我从 pd.factorize 切换到 LabelEncoder()。 由于 LabelEncoder 仅支持 pd.series 数据,我尝试使用循环遍历所有列并将每个 LabelEncoder() 拟合模型存储到字典中。

    在训练数据部分

    # list you want to do Label encoding
    col_list =  ['colA', 'colB', 'colC']
    df[col_list]= df[col_list].fillna('NAN')
    
    # create  a dictionary to save LabelEncoder() model for each col
    model = {}
    
    # convert Categorical Data
    for x in col_list:
        encoder = LabelEncoder()
        df[x]=encoder.fit_transform(df.__getattr__(x))
        model[x]= encoder
    
    # save dictionary to pickle file
    with open('model.pkl', 'wb') as f:
        pickle.dump(model, f)
    

    实时数据部分:

    with open('model.pkl', 'rb') as f:
        model= pickle.load(f)
    
    for x in col_list:
        encoder = model[x]
        try:
            df[x]=encoder.transform(df[x].astype(str))
        except:
            df[x]=encoder.transform(df[x].astype(int))
    

    因此,我花了 1.5 秒来加载数据、进行特征工程和预测。

    【讨论】:

      【解决方案3】:

      您使用的是哪种算法?我遇到了同样的问题,但由于我使用的是 LGBM,事实证明不需要分解我的数据,该算法可以处理分类值。我不得不将数据类型从“对象”更改为“类别”。

      categorical_feats = [f for f in combined_data.columns if combined_data[f].dtype == 'object']
      
      categorical_feats
      for f_ in categorical_feats:
          # Set feature type as categorical
          combined_data[f_] = combined_data[f_].astype('category')
      

      【讨论】:

        猜你喜欢
        • 2020-03-28
        • 2014-04-21
        • 1970-01-01
        • 2017-08-27
        • 1970-01-01
        • 2020-10-28
        • 2019-10-17
        • 1970-01-01
        • 2022-01-11
        相关资源
        最近更新 更多