| 127 | |
| 128 | |
| 129 | class NearestNeighborDistanceMetric(object): |
| 130 | def __init__(self, metric, matching_threshold, budget=None): |
| 131 | |
| 132 | if metric == "cosine": |
| 133 | self._metric = _nn_cosine_distance |
| 134 | else: |
| 135 | raise ValueError( |
| 136 | "Invalid metric; must be either 'euclidean' or 'cosine'") |
| 137 | self.matching_threshold = matching_threshold |
| 138 | self.budget = budget |
| 139 | self.samples = {} |
| 140 | |
| 141 | def partial_fit(self, features, targets, active_targets): |
| 142 | for feature, target in zip(features, targets): |
| 143 | self.samples.setdefault(target, []).append(feature) |
| 144 | if self.budget is not None: |
| 145 | self.samples[target] = self.samples[target][-self.budget:] |
| 146 | self.samples = {k: self.samples[k] for k in active_targets} |
| 147 | |
| 148 | def distance(self, features, targets): |
| 149 | cost_matrix = np.zeros((len(targets), len(features))) |
| 150 | for i, target in enumerate(targets): |
| 151 | cost_matrix[i, :] = self._metric(self.samples[target], features) |
| 152 | return cost_matrix |
| 153 | |
| 154 | |
| 155 | class DeepSort(object): |