| import numpy as np |
|
|
| |
| similarity_matrix = np.random.rand(10, 200) |
|
|
| |
| center = np.random.randint(0, 100, size=(10,)) |
| width = np.random.randint(10, 20, size=(10,)) |
|
|
| |
| start_indices = np.clip(center - width // 2, 0, similarity_matrix.shape[1]) |
| end_indices = np.clip(center + width // 2, 0, similarity_matrix.shape[1]) |
|
|
| |
| col_indices = np.arange(similarity_matrix.shape[1]) |
|
|
| |
| topk = 5 |
| topk_values = [] |
| topk_indices = [] |
|
|
| for start, end in zip(start_indices, end_indices): |
| |
| range_values = similarity_matrix[:, start:end] |
|
|
| |
| sorted_indices = np.argsort(range_values, axis=1)[:, -topk:] |
| sorted_indices += start |
|
|
| |
| row_indices = np.arange(len(sorted_indices))[:, np.newaxis] |
| indices_flat = np.ravel_multi_index((row_indices.flatten(), sorted_indices.flatten()), similarity_matrix.shape) |
| |
| |
| topk_values.append(np.take(similarity_matrix, indices_flat)) |
| topk_indices.append(np.column_stack((row_indices.repeat(topk, axis=1).flatten(), sorted_indices.flatten()))) |
|
|
| |
| topk_values = np.array(topk_values) |
| topk_indices = np.array(topk_indices) |
|
|
| print("Topk values within the specified range:", topk_values) |
| print("Topk indices within the specified range:", topk_indices) |
|
|
|
|