Last active
February 8, 2024 15:45
-
-
Save do-me/5d9bc9120960723c828e0c2de9ae51bb to your computer and use it in GitHub Desktop.
Wieghted average embedding in Python with numpy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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