通过对训练数据的一致映射来分解实时数据?

时间:2018-08-21 06:45:28

标签: python pandas machine-learning

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

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

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

但是,堆叠和遍历整个过程(进行整个要素工程,训练和预测)非常耗时。

  • 整个过程:15分钟 vs。模型。仅预测:3秒

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

或者我只能通过“手动”来做到,例如

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

这会导致很长的编码吗?

3 个答案:

答案 0 :(得分:0)

如果您的意思是解释传入的新颖分类值(例如,您获得df.color的新值“ blue-green”),则可以将所有意外值反弹到相同的-1存储桶(未知),然后在后期处理中或在您重新调整模型时进行处理。

从本质上讲,您可以捕获类别异常,然后在以后处理它们。

答案 1 :(得分:0)

工作几个小时后,我从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秒钟来加载数据,进行特征工程和预测。

答案 2 :(得分:0)

您使用哪种算法?我遇到了相同的问题,但是由于我使用的是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')