🙄

Python+Supabase+UMAPで「アーティスト文脈マップ」を一気に作成&可視化してみる

に公開

音楽データから「アーティストごとの特徴」をベクトル化し、UMAPで可視化。その一連処理をPython+Supabaseでサクッと自動化してみました。

ゴール:アーティストの文脈マップをDB化&可視化する
下図のような、「アーティスト×文脈特徴」の分布図をDBで管理できる状態が最終目標です。

実装フローとコード

  1. 必要なライブラリ&環境設定
import os
import numpy as np
import pandas as pd
import umap
import json
from dotenv import load_dotenv
from supabase import create_client, Client

load_dotenv()

SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_KEY")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)

→ 事前に pip install supabase pandas numpy umap-learn python-dotenv が必要です。

2. 楽曲データの取得&前処理

response = supabase.table('hiphop_tracks').select('artist, themes, ctx_vec').execute()
if not response.data:
    print("データなし")
    exit()
df = pd.DataFrame(response.data)
df['ctx_vec'] = df['ctx_vec'].apply(lambda v: np.array(json.loads(v)))
artist_groups = df.groupby('artist')

・Supabaseテーブルから「アーティスト・テーマ・文脈ベクトル」を取得
・ベクトルはJSON形式→NumPy配列へ整形

3. アーティストごとに集約処理

def aggregate_themes(series):
    all_themes = []
    for theme_list in series:
        if isinstance(theme_list, list):
            all_themes.extend(theme_list)
    return list(set(all_themes))

artist_vectors = artist_groups.agg(
    ctx_vec=('ctx_vec', lambda vecs: np.mean(np.vstack(vecs), axis=0)),
    themes=('themes', aggregate_themes),
    track_count=('artist', 'size')
)

・複数楽曲分のベクトル=アーティストごとに平均
・テーマ(ジャンル等)は重複除去してユニーク化

4. UMAPで次元削減&座標化

vector_matrix = np.vstack(artist_vectors['ctx_vec'].values)
n_neighbors = min(len(artist_vectors) - 1, 15)
reducer = umap.UMAP(n_components=2, n_neighbors=n_neighbors, metric='cosine', random_state=42, init='random')
embedding = reducer.fit_transform(vector_matrix)
artist_vectors['x'] = embedding[:, 0]
artist_vectors['y'] = embedding[:, 1]

・UMAPで高次元ベクトル→2次元(X/Y)座標に圧縮
・コサイン類似度で「意味が近いアーティスト同士」が近くなる

5. 可視化コード例(matplotlib)

import matplotlib.pyplot as plt

plt.figure(figsize=(8, 6))
for idx, row in artist_vectors.iterrows():
    plt.scatter(row['x'], row['y'], label=idx)
plt.legend()
plt.title('アーティスト文脈マップ (UMAP可視化)')
plt.xlabel('UMAP-X')
plt.ylabel('UMAP-Y')
plt.show()

6. DBへのアップサート

records_to_upsert = []
for artist_name, row in artist_vectors.iterrows():
    records_to_upsert.append({
        'artist_name': artist_name,
        'x': float(row['x']),
        'y': float(row['y']),
        'track_count': row['track_count'],
        'themes': row['themes']
    })
supabase.table('artist_map').upsert(records_to_upsert, on_conflict='artist_name').execute()

・結果を「artist_map」テーブルに保存
・upsert: 既存エントリは更新、新規は挿入

補足・応用例
・複数作品を持つクリエイターの「特徴分布」可視化
・類似アーティスト探索やレコメンドアルゴリズムの前処理
・AIエージェントの「個性」データ分析にも利用可

まとめ
Python+Supabase+UMAPを組み合わせることで、アーティストごとの文脈特徴を一括集計&可視化し、DBで管理するワークフローが簡単に実装できます。
参考になると嬉しいです!

Discussion