76 lines
2.3 KiB
Python
Executable File
76 lines
2.3 KiB
Python
Executable File
import numpy as np
|
|
from sklearn.metrics.pairwise import cosine_similarity
|
|
import orjson
|
|
from pathlib import Path
|
|
|
|
def cos_sim(vectors_ids):
|
|
"""
|
|
Pair all vectors uniquely by cosine similarity
|
|
Output: [[id1, id2], [id3, id4], ...]
|
|
"""
|
|
|
|
ids = [item['id'] for item in vectors_ids]
|
|
X = np.array([item['embedding'] for item in vectors_ids], dtype=np.float32)
|
|
|
|
# Normalize for cosine similarity
|
|
X /= np.linalg.norm(X, axis=1, keepdims=True)
|
|
|
|
# Compute cosine similarities
|
|
sims = cosine_similarity(X)
|
|
|
|
n = len(ids)
|
|
used = set()
|
|
pairs = []
|
|
|
|
print(f'--- {n} Item ---')
|
|
|
|
# در هر مرحله نزدیکترین جفت با بیشترین شباهت انتخاب میشود
|
|
while len(used) < n:
|
|
# ماسک برای استفاده نشدهها
|
|
mask = [i for i in range(n) if i not in used]
|
|
if len(mask) < 2:
|
|
break
|
|
|
|
# پیدا کردن بیشترین شباهت بین استفادهنشدهها
|
|
sub_sims = sims[np.ix_(mask, mask)]
|
|
i_rel, j_rel = np.unravel_index(np.argmax(sub_sims - np.eye(len(mask))), sub_sims.shape)
|
|
i, j = mask[i_rel], mask[j_rel]
|
|
|
|
pairs.append([ids[i], ids[j]])
|
|
used.add(i)
|
|
used.add(j)
|
|
|
|
# اگر یکی ماند (تعداد فرد)
|
|
if len(used) < n:
|
|
remaining = [i for i in range(n) if i not in used]
|
|
pairs.append([ids[remaining[0]], None])
|
|
|
|
return pairs
|
|
|
|
def save_orjson(path, data):
|
|
with open(path, "wb") as f:
|
|
f.write(
|
|
orjson.dumps(data, option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS)
|
|
)
|
|
|
|
def load_orjson(path: str | Path):
|
|
path = Path(path)
|
|
with path.open("rb") as f: # باید باینری باز بشه برای orjson
|
|
return orjson.loads(f.read())
|
|
|
|
data = load_orjson('./embdings.json')
|
|
vectors_ids = [{'id': i['id'], "embedding":i['embed']} for i in data]
|
|
|
|
# vectors_ids = [
|
|
# {"id": "a", "embedding": np.random.rand(1024)},
|
|
# {"id": "b", "embedding": np.random.rand(1024)},
|
|
# {"id": "c", "embedding": np.random.rand(1024)},
|
|
# {"id": "d", "embedding": np.random.rand(1024)},
|
|
# {"id": "e", "embedding": np.random.rand(1024)},
|
|
# ]
|
|
|
|
result = cos_sim(vectors_ids)
|
|
save_orjson(
|
|
data=result,
|
|
path='./mapping_embed.json'
|
|
) |