現在のコードは各列の組み合わせごとにDataFrameに新しい列を追加しているため、非常に遅くなっています。以下、高速化した2つのアプローチを提案します。
アプローチ1: 相関係数のみを計算(メモリ効率的)
python Copy code
import pandas as pd
import numpy as np
from itertools import combinations_with_replacement
from tqdm import tqdm
def calculate_operation_correlations(df, target_col, operations=['add', 'sub', 'mul', 'div']):
"""
数値列同士の四則演算結果とターゲットとの相関係数を計算
Parameters:
-----------
df : DataFrame
入力データフレーム
target_col : str
ターゲット列名
operations : list
実行する演算のリスト
Returns:
--------
DataFrame : 相関係数の結果
"""
# 数値列のみを抽出
numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
if target_col in numeric_cols:
numeric_cols.remove(target_col)
target = df[target_col]
results = []
# 各列の組み合わせで演算
for col1, col2 in tqdm(combinations_with_replacement(numeric_cols, 2),
total=len(numeric_cols)*(len(numeric_cols)+1)//2):
# 各演算を実行
for op in operations:
if op == 'add':
result = df[col1] + df[col2]
op_name = f"{col1}_{col2}_add"
elif op == 'sub':
result = df[col1] - df[col2]
op_name = f"{col1}_{col2}_sub"
elif op == 'mul':
result = df[col1] * df[col2]
op_name = f"{col1}_{col2}_mul"
elif op == 'div':
# ゼロ除算を避ける
with np.errstate(divide='ignore', invalid='ignore'):
result = df[col1] / df[col2].replace(0, np.nan)
op_name = f"{col1}_{col2}_div"
# 相関係数を計算
corr = result.corr(target)
results.append({
'feature': op_name,
'col1': col1,
'col2': col2,
'operation': op,
'correlation': corr
})
# 結果をDataFrameに変換してソート
results_df = pd.DataFrame(results)
results_df = results_df.sort_values('correlation', key=abs, ascending=False)
return results_df
# 使用例
# correlations = calculate_operation_correlations(train, 'target', operations=['add'])
アプローチ2: ベクトル化による高速な特徴量生成
python Copy code
def create_arithmetic_features_fast(df, target_col=None, operations=['add'], top_k=None):
"""
高速に四則演算特徴量を生成し、相関係数でフィルタリング
Parameters:
-----------
df : DataFrame
入力データフレーム
target_col : str
ターゲット列名(相関係数でフィルタリングする場合)
operations : list
実行する演算のリスト
top_k : int
相関係数の上位k個の特徴量のみを保持
Returns:
--------
DataFrame : 新しい特徴量を含むDataFrame
"""
# 数値列のみを抽出
numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
if target_col and target_col in numeric_cols:
numeric_cols.remove(target_col)
# 元のデータをコピー
result_df = df.copy()
# 相関係数を保存するリスト
feature_correlations = []
# バッチ処理用の新しい列を保存
new_features = {}
for i, col1 in enumerate(tqdm(numeric_cols)):
for j in range(i, len(numeric_cols)):
col2 = numeric_cols[j]
for op in operations:
if op == 'add':
new_col = df[col1].values + df[col2].values
feature_name = f"{col1}_{col2}_add"
elif op == 'sub':
new_col = df[col1].values - df[col2].values
feature_name = f"{col1}_{col2}_sub"
elif op == 'mul':
new_col = df[col1].values * df[col2].values
feature_name = f"{col1}_{col2}_mul"
elif op == 'div':
with np.errstate(divide='ignore', invalid='ignore'):
new_col = np.where(df[col2].values != 0,
df[col1].values / df[col2].values,
np.nan)
feature_name = f"{col1}_{col2}_div"
# ターゲットとの相関を計算
if target_col:
corr = np.corrcoef(new_col[~np.isnan(new_col)],
df[target_col].values[~np.isnan(new_col)])[0, 1]
feature_correlations.append((feature_name, abs(corr)))
new_features[feature_name] = new_col
# top_kが指定されている場合、相関の高い特徴量のみを選択
if target_col and top_k:
feature_correlations.sort(key=lambda x: x[1], reverse=True)
selected_features = [f[0] for f in feature_correlations[:top_k]]
new_features = {k: v for k, v in new_features.items() if k in selected_features}
# 新しい特徴量を一度に追加
new_features_df = pd.DataFrame(new_features)
result_df = pd.concat([result_df, new_features_df], axis=1)
return result_df
# 使用例
# train_with_features = create_arithmetic_features_fast(train, 'target', ['add'], top_k=100)
さらなる高速化のためのTips
python Copy code
# 並列処理を使用した版
from joblib import Parallel, delayed
def compute_correlation_parallel(df, col1, col2, target, operation):
"""単一の演算と相関計算"""
if operation == 'add':
result = df[col1] + df[col2]
elif operation == 'sub':
result = df[col1] - df[col2]
elif operation == 'mul':
result = df[col1] * df[col2]
elif operation == 'div':
with np.errstate(divide='ignore', invalid='ignore'):
result = df[col1] / df[col2].replace(0, np.nan)
corr = result.corr(target)
return f"{col1}_{col2}_{operation}", corr
def calculate_correlations_parallel(df, target_col, operations=['add'], n_jobs=-1):
"""並列処理で相関係数を計算"""
numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
if target_col in numeric_cols:
numeric_cols.remove(target_col)
target = df[target_col]
# 全ての組み合わせを生成
tasks = []
for col1, col2 in combinations_with_replacement(numeric_cols, 2):
for op in operations:
tasks.append((df, col1, col2, target, op))
# 並列実行
results = Parallel(n_jobs=n_jobs)(
delayed(compute_correlation_parallel)(*task) for task in tqdm(tasks)
)
# 結果を整形
results_df = pd.DataFrame(results, columns=['feature', 'correlation'])
results_df = results_df.sort_values('correlation', key=abs, ascending=False)
return results_df
主な改善点:
ベクトル化 : NumPy配列での演算により高速化
バッチ処理 : 新しい列を一度に追加
メモリ効率 : 必要な特徴量のみを保持
並列処理 : 複数コアを活用した計算
使用する際は、データサイズとメモリに応じて適切なアプローチを選択してください。