カイ二乗検定の理論度数を計算するプログラム

こんにちは。Yuinaです。

今日はカイ二乗検定の理論度数を計算するプログラムを、美容業界のマーケティングを想定した例で作成します。

「化粧品A」の購入と「化粧品B」の購入に関連性がないと仮定した場合、それぞれの商品がどれくらい一緒に購入されるか(理論度数)を計算します。

シナリオ

あるECサイトが、以下の集計データを持っているとします。

データから、「化粧品Aの購入」と「化粧品Bの購入」に関係がないと仮定した場合の理論度数を計算します。

作成したコード

def calculate_theoretical_frequencies_beauty(observed_data):

# 行の合計を計算
row_totals = [sum(row) for row in observed_data]

# 列の合計を計算
col_totals = [sum(col) for col in zip(*observed_data)]

# 全体の合計を計算
grand_total = sum(row_totals)

# 理論度数を格納する2x2のリストを初期化
theoretical_frequencies = [[0, 0], [0, 0]]

# 理論度数 = (行の合計) * (列の合計) / (全体の合計)
for i in range(2):
for j in range(2):
theoretical_frequencies[i][j] = (row_totals[i] * col_totals[j]) / grand_total

return theoretical_frequencies

# 美容商品の購入データ
observed_data = [[80, 120], [60, 140]]

# 理論度数を計算
theoretical_table = calculate_theoretical_frequencies_beauty(observed_data)

# 結果を出力
print(f"化粧品Bを購入 | 化粧品Bを購入しない")
print("-----------------------------------")
print(f"Aを購入 | {theoretical_table[0][0]:.0f}人 | {theoretical_table[0][1]:.0f}人")
print(f"Aを購入しない | {theoretical_table[1][0]:.0f}人 | {theoretical_table[1][1]:.0f}人")

結果

ありがとうございました✨

タイトルとURLをコピーしました