Skip to content

Instantly share code, notes, and snippets.

@do-me
Last active February 8, 2024 15:45
Show Gist options
  • Select an option

  • Save do-me/5d9bc9120960723c828e0c2de9ae51bb to your computer and use it in GitHub Desktop.

Select an option

Save do-me/5d9bc9120960723c828e0c2de9ae51bb to your computer and use it in GitHub Desktop.
Wieghted average embedding in Python with numpy
import numpy as np
# takes an arbitrary number of vectors/weights as input
def weighted_mean_embedding(vectors, weights):
if len(vectors) != len(weights):
raise ValueError("Number of vectors must be equal to the number of weights")
# Convert lists to NumPy arrays and cast to float
vectors = [np.array(vector, dtype=float) for vector in vectors]
weighted_sum = np.zeros_like(vectors[0], dtype=float)
total_weight = sum(weights)
for vector, weight in zip(vectors, weights):
weighted_sum += vector * weight
weighted_mean = weighted_sum / total_weight
return weighted_mean.tolist()
# Example usage:
list1 = [1, 1, 1, 1]
list2 = [4, 5, 6, 7]
list3 = [0,0,0,0]
weights = [1, 0.5, 1]
weighted_mean_embedding([list1, list2, list3], weights)
# [1.2, 1.4, 1.6, 1.8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment