【问题标题】:Python: How to make machine learning predictions run faster in production?Python:如何让机器学习预测在生产中运行得更快?
【发布时间】:2017-06-13 00:24:56
【问题描述】:

我在 scikit-learn 中创建了一个机器学习模型,我需要在生产环境中使用实时数据进行部署。例如,功能如下所示:

  date          event_id  user_id     feature1    feature2    featureX...
  2017-01-27    100       5555        1.23        2           2.99
  2017-01-27    100       4444        2.55        5           3.16
  2017-01-27    100       3333        0.45        3           1.69
  2017-01-27    105       1212        3.96        4           0.0
  2017-01-27    105       2424        1.55        2           5.56
  2017-01-27    105       3636        0.87        4           10.28

所以,每天都有不同的活动。在活动开始之前,我基本上通过从数据库中提取它们并将其存储在数据框中并使用腌制的 scikit 模型计算预测:

df_X = df.drop(['date', 'event_id', 'user_id'], axis=1)
loaded_model = joblib.load("model.joblib.dat")
prediction = loaded_model.predict_proba(df_X)

然后我将预测匹配回 df 并根据需要作为输出发送到 API 或文件。

当事件开始时,featureX 会不断更新,这是我从 API 获得的。为了进行更新,我使用循环遍历每个 event_id 和 user_id 并使用新的 df 值更新 featureX,重新计算并再次发送到输出。

为此,我正在做这样的事情:

# get list of unique event ids
events = set(df['event_id'].tolist())

try:
    while True:
        start = time.time()
        for event in events:
            featureX = request.get(API_URL + event)
            featureX_json = featureX.json()

            for user in featureX_json['users']:
                df.loc[df.user_id == user['user_id'],
                       'featureX'] = user['featureX']

        df_X = df.drop(['date', 'event_id', 'user_id'], axis=1)
        df['prediction'] = loaded_model.predict_proba(df_X)

        # send to API or write to file

        end = time.time()
        print('recalculation time {} secs'.format(end - start))

except KeyboardInterrupt:
    print('exiting !')

这对我来说很好,但整个预测更新在服务器中大约需要 4 秒,我需要它在 1 秒以下。我想弄清楚我可以在while loop 中更改什么来获得我需要的加速?

已根据event_id = 100 URL http://myapi/api/event_users/<event_id> 的请求添加了 json 示例:

{
    "count": 3,
    "users": [
        {
            "user_id": 4444,
            "featureY": 34,
            "featureX": 4.49,
            "created": "2017-01-17T13:00:09.065498Z"
        },
        {
            "user_id": 3333,
            "featureY": 22,
            "featureX": 1.09,
            "created": "2017-01-17T13:00:09.065498Z"
        },
         {
            "user_id": 5555,
            "featureY": 58,
            "featureX": 9.54,
            "created": "2017-01-17T13:00:09.065498Z"
        }
    ]
}

【问题讨论】:

  • 能否提供featureX_json的样本数据集?
  • @MaxU 我已将示例数据集添加到问题中。

标签: python pandas optimization machine-learning scikit-learn


【解决方案1】:

您可以尝试使用算法的加速实现 - 例如 scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex。这是一款免费软件 AI 加速器,可为各种应用带来超过 10-100 倍的加速。

此库将为训练和预测提供极大的性能改进。

Example of speedup that you can achieve

第一个安装包

pip install scikit-learn-intelex

然后添加你的python脚本

from sklearnex import patch_sklearn
patch_sklearn()

【讨论】:

    【解决方案2】:

    订阅某种消息队列会更好,比如 Kafka。然后,您可以在 FeatureX 更新时使用它,而不是在循环中无休止地进行批处理 API 调用,然后遍历整个数据源等。

    关于预测,利用更具可扩展性的方法可能是有意义的。您可以将数据帧拆分为多个块,并向可扩展的高吞吐量预测 API 发出异步请求。使用这种方法,您只受网络延迟和可以同时发出多少请求的限制。如果预测 API 可以每秒处理数千/10k/100k 的请求,您的预测时间可以减少到不到一秒(可能只有几百毫秒)。

    我的服务mlrequest 是一个低延迟、高吞吐量、高可用性的机器学习 API,非常适合此类问题。我们每秒可以处理和扩展成千上万的预测。下一版本(即将推出)将支持 Scikit Learn 模型和 Pandas Dataframes。下面是一个简单的训练和预测示例。您可以获得free api key,每月可以获得 50,000 次模型交易。

    安装 mlrequest Python 客户端

    $pip install mlrequest
    

    训练模型并将其部署到全球 5 个数据中心非常简单:

    from mlrequest import Classifier
    classifier = Classifier('my-api-key')
    features = {'feature1': 'val1','feature2': 100}
    training_data = [{'features': features, 'label': 1}, ...]
    r = classifier.learn(training_data=training_data, model_name='my-model', class_count=2) 
    

    预测

    features = [{'feature1': 'val1', 'feature2': 77}, ...]
    r = classifier.predict(features=features, model_name='my-model', class_count=2)
    r.predict_result
    

    【讨论】:

      【解决方案3】:
      # get list of unique event ids
      events = df['event_id'].unique().tolist()
      
      try:
          while True:     # i don't understand why do you need this loop...
              start = time.time()
              for event in events:
                  featureX = request.get(API_URL + event)
                  tmp = pd.DataFrame(featureX.json()['users'])
      
                  df.loc[(df.event_id == event), 'featureX'] = \
                      df.loc[df.event_id == event, 'user_id'] \
                        .map(tmp.set_index('user_id').featureX)
      
              df_X = df.drop(['date', 'event_id', 'user_id'], axis=1)
              df['prediction'] = loaded_model.predict_proba(df_X)
      
              # send to API or write to file
      
              end = time.time()
              print('recalculation time {} secs'.format(end - start))
      
      except KeyboardInterrupt:
          print('exiting !')
      

      演示: for event_id == 100

      首先让我们从您的 JSON 对象创建一个 DF:

      tmp = pd.DataFrame(featureX_json['users'])
      
      In [33]: tmp
      Out[33]:
                             created  featureX  featureY  user_id
      0  2017-01-17T13:00:09.065498Z      4.49        34     4444
      1  2017-01-17T13:00:09.065498Z      1.09        22     3333
      2  2017-01-17T13:00:09.065498Z      9.54        58     5555
      

      现在我们可以摆脱for user in featureX_json['users']:循环:

      In [29]: df.loc[df.event_id == 100, 'featureX'] = \
                   df.loc[df.event_id == 100, 'user_id'].map(tmp.set_index('user_id').featureX)
      
      In [30]: df
      Out[30]:
               date  event_id  user_id  feature1  feature2  featureX
      0  2017-01-27       100     5555      1.23         2      9.54   # 2.99 -> 9.54
      1  2017-01-27       100     4444      2.55         5      4.49   # 3.16 -> 4.49
      2  2017-01-27       100     3333      0.45         3      1.09   # 1.69 -> 1.09
      3  2017-01-27       105     1212      3.96         4      0.00
      4  2017-01-27       105     2424      1.55         2      5.56
      5  2017-01-27       105     3636      0.87         4     10.28
      

      【讨论】:

        猜你喜欢
        • 2017-12-02
        • 2020-10-29
        • 1970-01-01
        • 1970-01-01
        • 2020-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-06
        相关资源
        最近更新 更多