| 1 |
# utils.py |
| 2 |
# Author: Jacob Schreiber <[email protected]> |
| 3 |
|
| 4 |
""" |
| 5 |
This code contains utility functions to support the main functionality of |
| 6 |
the code. |
| 7 |
""" |
| 8 |
|
| 9 |
import numbers |
| 10 |
import numpy |
| 11 |
import itertools |
| 12 |
|
| 13 |
from heapq import heappush |
| 14 |
from heapq import heappop |
| 15 |
from heapq import heapify |
| 16 |
from heapq import heapreplace |
| 17 |
|
| 18 |
from scipy.sparse import csr_matrix |
| 19 |
|
| 20 |
from sklearn.metrics import pairwise_distances |
| 21 |
from sklearn.neighbors import KNeighborsTransformer |
| 22 |
|
| 23 |
class PriorityQueue(object): |
| 24 |
"""A priority queue implementation. |
| 25 |
|
| 26 |
This is an implemented of a priority queue using a heap implemtnation. It |
| 27 |
has O(log n) time for adding and popping elements but constant time |
| 28 |
deletion. It is based off of the implementation that is provided at |
| 29 |
|
| 30 |
https://docs.python.org/2/library/heapq.html |
| 31 |
|
| 32 |
This implementation assumes that the items with the highest priority |
| 33 |
are the ones with the lowest "weight" that gets passed in. If higher |
| 34 |
weights are supposed to correspond to higher priority, consider reversing |
| 35 |
the sign of the weight. |
| 36 |
|
| 37 |
Parameters |
| 38 |
---------- |
| 39 |
None |
| 40 |
|
| 41 |
Attributes |
| 42 |
---------- |
| 43 |
pq : list |
| 44 |
A list containing the heapified priority queue. |
| 45 |
|
| 46 |
lookup : dict |
| 47 |
A dictionary containing links to each of the elements, allowing |
| 48 |
constant time lookups and deletions. |
| 49 |
""" |
| 50 |
|
| 51 |
def __init__(self, items=None, weights=None): |
| 52 |
self.counter = itertools.count() |
| 53 |
self.pq = [] |
| 54 |
|
| 55 |
if items is not None and weights is not None: |
| 56 |
for item, weight in zip(items, weights): |
| 57 |
entry = [weight, next(self.counter), item] |
| 58 |
self.pq.append(entry) |
| 59 |
|
| 60 |
heapify(self.pq) |
| 61 |
|
| 62 |
def add(self, item, weight): |
| 63 |
"""Add an element to the priority queue. Runtime is O(log n). |
| 64 |
|
| 65 |
This adds in an element to the priority queue. If that element is |
| 66 |
already there it will automatically delete the previous instance |
| 67 |
and replace it with the new instance. |
| 68 |
|
| 69 |
Parameters |
| 70 |
---------- |
| 71 |
item : object |
| 72 |
The object to be encoded. |
| 73 |
|
| 74 |
weight : double |
| 75 |
The priority of the item. The lower the weight the higher the |
| 76 |
priority when items get dequeued. If a higher weight is supposed |
| 77 |
to correspond to a higher priority, consider reversing the sign of |
| 78 |
the weight. |
| 79 |
|
| 80 |
Returns |
| 81 |
------- |
| 82 |
None |
| 83 |
""" |
| 84 |
|
| 85 |
#if item in self.lookup: |
| 86 |
# self.remove(item) |
| 87 |
|
| 88 |
entry = [weight, next(self.counter), item] |
| 89 |
heappush(self.pq, entry) |
| 90 |
|
| 91 |
def pop(self): |
| 92 |
"""Pop the highest priority element from the queue. Runtime is O(log n). |
| 93 |
|
| 94 |
This will remove the highest priority element from the queue. If there |
| 95 |
are no elements left in the queue it will raise an error. |
| 96 |
|
| 97 |
Parameters |
| 98 |
---------- |
| 99 |
None |
| 100 |
|
| 101 |
Returns |
| 102 |
------- |
| 103 |
weight : double |
| 104 |
The weight of the element as passed in in the `add` method |
| 105 |
|
| 106 |
item : object |
| 107 |
The item that was passed in in the `add` method |
| 108 |
""" |
| 109 |
|
| 110 |
weight, _, item = heappop(self.pq) |
| 111 |
return weight, item |
| 112 |
|
| 113 |
def peek(self): |
| 114 |
"""Peek at the first element in the priority queue. |
| 115 |
|
| 116 |
Parameters |
| 117 |
---------- |
| 118 |
None |
| 119 |
|
| 120 |
Returns |
| 121 |
------- |
| 122 |
weight : double |
| 123 |
The weight of the element as passed in in the `add` method |
| 124 |
|
| 125 |
item : object |
| 126 |
The item that was passed in in the `add` method |
| 127 |
""" |
| 128 |
|
| 129 |
return self.pq[0][0], self.pq[0][2] |
| 130 |
|
| 131 |
def swap(self, item, weight): |
| 132 |
"""An efficient way to pop the first element and add a new element. |
| 133 |
|
| 134 |
This is useful in our context because it allows us to pop the smallest |
| 135 |
element and to add a new element, i.e., remove an element and re-add it |
| 136 |
with the updated gain. |
| 137 |
|
| 138 |
Parameters |
| 139 |
---------- |
| 140 |
item : object |
| 141 |
The object to be encoded. |
| 142 |
|
| 143 |
weight : double |
| 144 |
The priority of the item. The lower the weight the higher the |
| 145 |
priority when items get dequeued. If a higher weight is supposed |
| 146 |
to correspond to a higher priority, consider reversing the sign of |
| 147 |
the weight. |
| 148 |
|
| 149 |
Returns |
| 150 |
------- |
| 151 |
None |
| 152 |
""" |
| 153 |
|
| 154 |
entry = [weight, next(self.counter), item] |
| 155 |
heapreplace(self.pq, entry) |
| 156 |
|
| 157 |
def check_random_state(seed): |
| 158 |
"""Turn seed into a np.random.RandomState instance. |
| 159 |
|
| 160 |
This function will check to see whether the input seed is a valid seed |
| 161 |
for generating random numbers. This is a slightly modified version of |
| 162 |
the code from sklearn.utils.validation. |
| 163 |
|
| 164 |
Parameters |
| 165 |
---------- |
| 166 |
seed : None | int | instance of RandomState |
| 167 |
If seed is None, return the RandomState singleton used by np.random. |
| 168 |
If seed is an int, return a new RandomState instance seeded with seed. |
| 169 |
If seed is already a RandomState instance, return it. |
| 170 |
Otherwise raise ValueError. |
| 171 |
""" |
| 172 |
|
| 173 |
if seed is None or seed is numpy.random: |
| 174 |
return numpy.random.mtrand._rand |
| 175 |
if isinstance(seed, (numbers.Integral, numpy.integer)): |
| 176 |
return numpy.random.RandomState(seed) |
| 177 |
if isinstance(seed, numpy.random.RandomState): |
| 178 |
return seed |
| 179 |
raise ValueError('%r cannot be used to seed a numpy.random.RandomState' |
| 180 |
' instance' % seed) |
| 181 |
|
| 182 |
def _calculate_pairwise_distances(X, Y=None, metric='precomputed', n_neighbors=None): |
| 183 |
if metric in ('precomputed', 'ignore'): |
| 184 |
return X |
| 185 |
|
| 186 |
if n_neighbors is None: |
| 187 |
if metric == 'euclidean': |
| 188 |
X_pairwise = pairwise_distances(X, Y=Y, metric=metric, squared=True) |
| 189 |
elif metric == 'correlation' or metric == 'cosine': |
| 190 |
# An in-place version of: |
| 191 |
# X_pairwise = 1 - (1 - pairwise_distances(X, metric=metric)) ** 2 |
| 192 |
|
| 193 |
X_pairwise = pairwise_distances(X, Y=Y, metric=metric) |
| 194 |
X_pairwise = numpy.subtract(1, X_pairwise, out=X_pairwise) |
| 195 |
X_pairwise = numpy.square(X_pairwise, out=X_pairwise) |
| 196 |
X_pairwise = numpy.subtract(1, X_pairwise, out=X_pairwise) |
| 197 |
else: |
| 198 |
X_pairwise = pairwise_distances(X, Y=Y, metric=metric) |
| 199 |
else: |
| 200 |
if metric == 'correlation' or metric == 'cosine': |
| 201 |
# An in-place version of: |
| 202 |
# X = 1 - (1 - pairwise_distances(X, metric=metric)) ** 2 |
| 203 |
|
| 204 |
X = pairwise_distances(X, Y=Y, metric=metric) |
| 205 |
X = numpy.subtract(1, X, out=X) |
| 206 |
X = numpy.square(X, out=X) |
| 207 |
X = numpy.subtract(1, X, out=X) |
| 208 |
metric = 'precomputed' |
| 209 |
|
| 210 |
if isinstance(n_neighbors, int): |
| 211 |
X_pairwise = KNeighborsTransformer( |
| 212 |
n_neighbors=n_neighbors, metric=metric |
| 213 |
).fit_transform(X) |
| 214 |
|
| 215 |
elif isinstance(n_neighbors, KNeighborsTransformer): |
| 216 |
X_pairwise = n_neighbors.fit_transform(X) |
| 217 |
|
| 218 |
if metric == 'correlation' or metric == 'cosine': |
| 219 |
if isinstance(X_pairwise, csr_matrix): |
| 220 |
X_pairwise.data = numpy.subtract(1, X_pairwise.data, |
| 221 |
out=X_pairwise.data) |
| 222 |
else: |
| 223 |
X_pairwise = numpy.subtract(1, X_pairwise, |
| 224 |
out=X_pairwise) |
| 225 |
else: |
| 226 |
if isinstance(X_pairwise, csr_matrix): |
| 227 |
X_pairwise.data = numpy.subtract(X_pairwise.max(), |
| 228 |
X_pairwise.data, out=X_pairwise.data) |
| 229 |
else: |
| 230 |
X_pairwise = numpy.subtract(X_pairwise.max(), X_pairwise, |
| 231 |
out=X_pairwise) |
| 232 |
|
| 233 |
return X_pairwise |