Дело в том, что при вызове SciPy он работает немного быстрее (~0,55 мс против ~0,69 мс), и я не понимаю почему, поскольку моя реализация похожа на ту, что была в SciPy, с удалением некоторых проверки, которые, как я ожидал, сделают это быстрее.
Почему функция SciPy работает быстрее?
Код: Выделить всё
import time
import math
import numpy as np
from scipy.spatial import distance
EXECUTIONS = 10000
path = "" # From https://github.com/joseprupi/cosine-similarity-comparison/blob/master/tools/vectors.csv
file_data = np.genfromtxt(path, delimiter=',')
A,B = np.moveaxis(file_data, 1, 0).astype('f')
accum = 0
for _ in range(EXECUTIONS):
start_time = time.time()
cos_sim = distance.cosine(A,B)
accum += (time.time() - start_time) * 1000
print(" %s ms" % (accum/EXECUTIONS))
cos_sim_scipy = cos_sim
def cosine(u, v, w=None):
uv = np.dot(u, v)
uu = np.dot(u, u)
vv = np.dot(v, v)
dist = 1.0 - uv / math.sqrt(uu * vv)
# Clip the result to avoid rounding error
return np.clip(dist, 0.0, 2.0)
accum = 0
for _ in range(EXECUTIONS):
start_time = time.time()
cos_sim = cosine(A,B)
accum += (time.time() - start_time) * 1000
print(" %s ms" % (accum/EXECUTIONS))
cos_sim_manual = cos_sim
print(np.isclose(cos_sim_scipy, cos_sim_manual))
Код для создания A и B приведен ниже, а точные файлы, которые я использую, можно найти по адресу:https://github.com/joseprupi/cosine-sim ... ectors.csv
Код: Выделить всё
def generate_random_vector(size):
"""
Generate 2 random vectors with the provided size
and save them in a text file
"""
A = np.random.normal(loc=1.5, size=(size,))
B = np.random.normal(loc=-1.5, scale=2.0, size=(size,))
vectors = np.stack([A, B], axis=1)
np.savetxt('vectors.csv', vectors, fmt='%f,%f')
generate_random_vector(640000)
- 12-ядерный процессор AMD Ryzen 9 3900X
- 64 ГБ ОЗУ
- Debian 12
- Python 3.11.2
- scipy 1.13.0
- numpy 1.26.4
Подробнее здесь: https://stackoverflow.com/questions/784 ... ectly-exec