3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rolling rankを行うpythonライブラリを作りました

Last updated at Posted at 2020-04-03

rollingrank

rollingrankという、rolling window内での順位を計算するpythonライブラリを作ったので紹介です。kaggleで使ってください。バグ報告はgithubのissueでお願いします。

リポジトリ
https://github.com/contribu/rollingrank

背景

  1. kaggleなどで時系列予測の問題を解きたい。
  2. rolling window内での順位を特徴量としたい。
  3. それを行うpythonライブラリが見つからなかった。
  4. pandasでの実装は見つかったが遅かった( https://github.com/pandas-dev/pandas/issues/9481 )

私が解いていた問題では、
rolling window内での順位を特徴量とすることが汎化性能を出す鍵になりました。
時期によって分布が偏らないことがポイントと見ています。

有用そうな一方で(自分の事例しか知らないので一般に有用かどうかは知らない)、
kaggle界隈ではあまり見かけません。

その理由はかんたんに使えないことが原因かもしれません。
このライブラリを使うとかんたんにrolling rankを使えるので、とりあえず今解いている問題で使ってみては?

インストール

pip install rollingrank

使い方

import numpy as np
import rollingrank

# numpy arrayを入力すると同じ長さのnumpy arrayが返ります。
x = np.array([0.1, 0.2, 0.3, 0.25, 0.1, 0.2, 0.3])
y = rollingrank.rollingrank(x, window=3)
print(y)
# [nan nan  2.  1.  0.  1.  2.]

# pctを使うと、[0, 1]で返ります
y = rollingrank.rollingrank(x, window=3, pct=True)
print(y)
# [nan nan 1.  0.5 0.  0.5 1. ]

順位のカスタマイズ

に定義してあるmethodのうち、average, min, max, firstをmethodオプションで渡して使えます。

注意

計算量が、O(n * log(w))のものを作りたかったのですが、
実装してからよく見ると O(n * w)になっていました。
平衡木を工夫すれば O(n * log(w))にできるはずです。
だれかお願いします。

以下のようなものを改造すれば良さそう。
https://github.com/mpaland/avl_array

個人メモ

pipライブラリの作り方: https://blog.amedama.jp/entry/packaging-python

rolling rank: https://github.com/pandas-dev/pandas/issues/9481

C++との連携はpybind11が便利でした。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?