Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
polarsのudfとかpluginとか触ってみた
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
T88
August 21, 2024
3.4k
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
polarsのudfとかpluginとか触ってみた
T88
August 21, 2024
More Decks by T88
See All by T88
HMSコンペ 11th Solution (team : kansai-kaggler)
t88
2
1.5k
忙しくて手を動かせない時もいい感じに進捗出してくれるAgent作りたい
t88
10
5.9k
レコメンドコンペ入門
t88
1
1.5k
Featured
See All Featured
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
0
520
Automating Front-end Workflow
addyosmani
1370
210k
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
10
1.2k
Introduction to Domain-Driven Design and Collaborative software design
baasie
1
820
For a Future-Friendly Web
brad_frost
183
10k
HU Berlin: Industrial-Strength Natural Language Processing with spaCy and Prodigy
inesmontani
PRO
0
400
Sam Torres - BigQuery for SEOs
techseoconnect
PRO
0
280
Why Our Code Smells
bkeepers
PRO
340
58k
SERP Conf. Vienna - Web Accessibility: Optimizing for Inclusivity and SEO
sarafernandez
2
1.5k
The Pragmatic Product Professional
lauravandoore
37
7.3k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
25
1.9k
The Organizational Zoo: Understanding Human Behavior Agility Through Metaphoric Constructive Conversations (based on the works of Arthur Shelley, Ph.D)
kimpetersen
PRO
0
360
Transcript
2024/8/22 polars Data Crunch #3 / T88 pol arsのudfとかpl ugi
nとか触ってみた
自己紹介 01 竹原孝祐 (T88) メーカでデータをあれこれしている kaggle Competitions Master (金:2 銀:6
銅:5) polarsはデータ量が多いテーブルコンペで利用 (実務ではpandas, pysparkを使うことが多い)
02 久しぶり、polars 記憶を遡るとpolarsを使ったのが、 2023年6月のコンペ以来 (polarsのversion : 0.18.2) 現在
本日のお題 03 polarsのexpressionsにないユーザ独自の処理を実現したい 出来らあっ!
polarsでのユーザ独自関数処理 04 user-defined function pythonで独自関数を記述 Expression plugins rustで実装した関数をコンパイルして利用
values int64 5 3 8 7 10 4 user-defined function
05 map_elements() 各要素ごとに独立して処理が実行される map_batches() Series単位でまとめて処理が実行される
処理 処理時間 pl.col( “value” ).map_elements(lambda x: math.log(x)) 11.38s pl.col( “value”
).map_elements(lambda x: np.log(x)) 56.72s pl.col( “value” ).map_batches(lambda x: math.log(x)) ComputeError: TypeError: must be real number, not Series pl.col( “value” ).map_batches(lambda x: np.log(x)) 0.63s pl.col( “value” ).log() 0.62s 簡易的な実験 06 特定列の各要素のlogを取る処理のパフォーマンスを計測 (レコード数 : 1億件) ・map_elements()は個別にpython処理が走るため、非常に処理が重い ・map_batches()なら一度のpython処理となるため、パフォーマンスへの影響が少ない ※今回の例では、nativeのexpressionでも実装可能。またnp.log(pl.col(“value”))という形のExprとしても記述できる
ちなみに 07 map_elements()を実行すると、 パフォーマンスに関するwarningが出て nativeのexpressionsへの 書き換えが提案される 中の処理ではBytecodeParserによる 関数やlambda式の構文解析と 書き換えが行われている
Expression plugins 08 rustで実装した関数をコンパイルして使える pythonが介在せず動作し、nativeのexpressionと同等の最適化・並列化・ パフォーマンスが期待できる Polars plugins tutorial https://marcogorelli.github.io/polars-plugins-tutorial/
rust 書けません...
Community plugins 09 polars-xdt 日時データに関する拡張機能 polars-distance 2点間の距離、編集距離などが算出できる polars-ds データ分析に関する多数の機能 polars-hash
ハッシュ化 polars-reverse-geocode 入力座標に対する最近傍地点を抽出する polarsコミュニティで作成されたプラグインが公開されている
導入 : polars-ds 10 サンプル: https://github.com/abstractqqq/polars_ds_extension/blob/main/examples/basics.ipynb 線形回帰 メトリクスの計算
Diagnosis and DIA (Data Inspection Assistant) polars-ds 11 https://github.com/abstractqqq/polars_ds_extension/blob/main/examples/diagnosis.ipynb EDAにとても役立ちそう
polars-ds機能 12 (注) 公式doc(https://polars-ds-extension.readthedocs.io/en/latest/index.html)をもとに chatgpt-4oによりpolars-dsの機能を一覧化 filter: DataFrameにフィルタリングを適用 impute: 欠損値の補完 nan_to_null:
NaN値をnullに変換 linear_impute: 線形回帰を使用して欠損値を補完 scale: 列のスケーリング robust_scale: 列のロバストスケーリング center: 列のセンタリング(平均値を引く) select: 列の選択 shrink_dtype: データ型の縮小 winsorize: 列のウィンザー化(異常値の除去) target_encode: 目的変数のエンコーディング woe_encode: Weight of Evidenceによるエンコーディング iv_encode: 情報値によるエンコーディング one_hot_encode: ワンホットエンコーディング rename: 列の名前変更 lowercase: 列名を小文字に変換 pipeline
polars-ds機能 13 (注) 公式doc(https://polars-ds-extension.readthedocs.io/en/latest/index.html)をもとに chatgpt-4oによりpolars-dsの機能を一覧化 downsample: 条件が真である部分集合をダウンサンプリング random_cols: データフレームからランダムに列を選択 sample:
データフレームをサンプリング volume_neutral: 各セグメントからボリュームニュートラルなポピュレーションを選択 sample Linear Models fit: 線形回帰モデルをNumPyデータに適合 fit_df: データフレームに基づいて線形回帰モデルを適合 predict: 線形モデルによる予測を行う predict_df: データフレームに予測結果を追加 set_input_features: 入力特徴の名前を設定 linear_regression_report: 線形回帰モデルのレポートを生成
polars-ds機能 14 (注) 公式doc(https://polars-ds-extension.readthedocs.io/en/latest/index.html)をもとに chatgpt-4oによりpolars-dsの機能を一覧化 Time Series Features query_abs_energy: 絶対エネルギーを計算
query_approx_entropy: 近似エントロピーを計算 query_avg_streak: 条件が真である平均の連続長を計算 query_c3_stats: C3統計量で非線形性を測定 query_cond_entropy: 条件付きエントロピーを計算 query_knn_entropy: KNNエントロピーを計算 query_sample_entropy: サンプルエントロピーを計算 query_streak: 条件が真である連続長を全列で計算 query_transfer_entropy: 転送エントロピーを推定 symmetry_ratio: シンメトリ比を計算
polars-ds機能 15 (注) 公式doc(https://polars-ds-extension.readthedocs.io/en/latest/index.html)をもとに chatgpt-4oによりpolars-dsの機能を一覧化 KNN Queries is_knn_from: 特定の点からk最近傍の点をブール列で返す query_knn_avg:
特徴量を使用してk最近傍の平均を計算 query_knn_freq_cnt: 他の点からのk最近傍である回数をカウント query_knn_ptwise: 各行に対してk最近傍を求める query_nb_cnt: 指定した半径内の近傍点の数を返す within_dist_from: 特定の点から指定した半径内にある点をブール列で返す
polars-ds機能 16 (注) 公式doc(https://polars-ds-extension.readthedocs.io/en/latest/index.html)をもとに chatgpt-4oによりpolars-dsの機能を一覧化 Numerical Extension convolve: カーネルを使用して畳み込みを行う detrend:
線形または平均法を使用してトレンドを除去 exp2: 2のx乗を返す gamma: ガンマ関数を適用 haversine: ハバースイン距離を計算 query_gcd: 2つの整数列の最大公約数を計算 query_lcm: 2つの整数列の最小公倍数を計算 query_pca: 主成分分析を行う query_psi: 人口安定指数を計算 softmax: ソフトマックス関数を適用
polars-ds機能 17 (注) 公式doc(https://polars-ds-extension.readthedocs.io/en/latest/index.html)をもとに chatgpt-4oによりpolars-dsの機能を一覧化 Stats Extension add_noise: カラムにノイズを追加 bicor:
Biweight Midcorrelationを計算 corr: さまざまな相関係数を計算 cosine_sim: コサイン類似度を計算 gmean: 幾何平均を計算 hmean: 調和平均を計算 kendall_tau: ケンドールのタウ相関を計算 jitter: ガウスノイズを追加 normal_test: 正規性検定を実行 perturb: データに小さな摂動を加える
polars-ds機能 18 (注) 公式doc(https://polars-ds-extension.readthedocs.io/en/latest/index.html)をもとに chatgpt-4oによりpolars-dsの機能を一覧化 String Extension extract_numbers: 文字列から数値を抽出 filter_by_hamming:
ハミング距離を基にフィルタリング is_stopword: ストップワードかどうかをチェック map_words: 指定されたマッピングに基づいて単語を置換 normalize_string: Unicode文字列の正規化 remove_diacritics: ダイアクリティックを削除 replace_non_ascii: 非ASCII文字を置換 str_jaccard: ジャカード類似度を計算 str_leven: レーベンシュタイン距離を計算 to_snake_case: スネークケースに変換
polars-ds機能 19 (注) 公式doc(https://polars-ds-extension.readthedocs.io/en/latest/index.html)をもとに chatgpt-4oによりpolars-dsの機能を一覧化 ML Metrics/Loss Extension query_adj_r2: 調整済み決定係数を計算
query_binary_metrics: バイナリ分類のメトリクス(精度、再現率、Fスコアなど)を計算 query_cat_cross_entropy: カテゴリカルクロスエントロピーを計算 query_confusion_matrix: 混同行列を計算 query_huber_loss: Huber損失を計算 query_l1: L1損失(平均絶対誤差)を計算 query_l2: L2損失(平均二乗誤差)を計算 query_mape: 平均絶対パーセンテージ誤差を計算 query_r2: 決定係数を計算 query_roc_auc: ROC AUCを計算
polars-ds機能 20 (注) 公式doc(https://polars-ds-extension.readthedocs.io/en/latest/index.html)をもとに chatgpt-4oによりpolars-dsの機能を一覧化 special_values_report: Null値、NaN、非有限値のチェック numeric_profile: 数値プロファイルとヒストグラムの作成 plot_null_distribution:
Null値の分布を可視化 str_stats: 文字列列の基本統計情報を生成 corr: 数値列間の相関関係を計算 plot_corr: 相関ヒートマップをプロット infer_prob: 確率の可能性がある列を識別 infer_high_null: Null値の割合が高い列を検出 infer_const: 定数の列を推測 infer_binary: 二値の列を識別 infer_k_distinct: k個の異なる値を持つ列を検出 plot_lstsq: 二変数間の最小二乗法をプロット plot_distribution: 特徴量の分布をプロット plot_pca: PCAプロット(2Dまたは3D)の作成 plot_dependency: 条件付きエントロピーに基づく列間の依存関係を可視化 DIA(データインスペクションアシスタント)
polarsでのユーザ独自関数は、pythonで実装するuser-defined-function(udf)と rustを用いるexpression pluginsがある udfでmap_elements()を使うと個別要素で処理されるので非常に遅い map_batches()で処理ができればマシ(普通にExprs使えるならそれで... 公開されているpluginsはpip installするだけで利用できて便利 とくにpolars-dsは機能が非常に充実している (個人的にはEDA関連が充実しているのに驚いたし、活用可能性が高そう) まとめ
21 しばらく触れてなかったが、非常に良いツールだと思うので もっとpolarsと仲良くしていきたい