Handle full-store nearest-neighbour queries and single-class votes
#1
by emberian - opened
Files changed (2)
- test_exemplar_contract.pyAdded+39
- vision/exemplar.py+17-2
123456789101112131415161718192021222324252627282930313233343536373839"""Run with python -m unittest test_exemplar_contract; requires NumPy only."""import unittestimport numpy as npfrom vision.exemplar import ExemplarStore
class ExemplarContract(unittest.TestCase): def test_all_neighbours_in_similarity_order(self): store = ExemplarStore(np.eye(2), np.array([0, 1]), 2) idx, sim = store.neighbours(np.array([[1., 0.]]), 2) np.testing.assert_array_equal(idx, [[0, 1]]) np.testing.assert_allclose(sim, [[1., 0.]])
def test_one_class_vote_has_full_margin(self): store = ExemplarStore(np.array([[1., 0.]]), np.array([0]), 1) idx, sim = store.neighbours(np.array([[1., 0.]]), 1) label, margin, vote = store.vote(idx, sim, 1) np.testing.assert_array_equal(label, [0]) np.testing.assert_allclose(margin, [1.]) np.testing.assert_allclose(vote, [[1.]])
def test_reject_invalid_inputs(self): for vec, labels, classes in [(np.array([[np.nan]]), np.array([0]), 1), (np.ones((1, 1)), np.array([1]), 1), (np.ones((1, 1)), np.array([.5]), 1)]: with self.subTest(vec=vec, labels=labels), self.assertRaises(ValueError): ExemplarStore(vec, labels, classes) store = ExemplarStore(np.eye(2), np.array([0, 1]), 2) for k in [0, 3]: with self.subTest(k=k), self.assertRaises(ValueError): store.neighbours(np.eye(2), k) idx, sim = store.neighbours(np.eye(2), 1) for temp in [0, -1, float('nan')]: with self.subTest(temp=temp), self.assertRaises(ValueError): store.vote(idx, sim, 1, temp)
if __name__ == '__main__': unittest.main()13 unmodified lines141516171819202122232425262 unmodified lines29303132333435363713 unmodified linesself.V = vecs.astype(np.float32)self.y = labels.astype(np.int64)self.C = n_classesdef neighbours(self, Q, k, batch=512):idx = np.empty((len(Q), k), np.int64)sim = np.empty((len(Q), k), np.float32)for s in range(0, len(Q), batch):S = Q[s:s + batch] @ self.V.Tpart = np.argpartition(-S, k, axis=1)[:, :k]ps = np.take_along_axis(S, part, 1)order = np.argsort(-ps, axis=1)idx[s:s + batch] = np.take_along_axis(part, order, 1)2 unmodified linesdef vote(self, idx, sim, k, temp=0.05):"""similarity-weighted vote over the k nearest; returns label, margin (top1 - top2 share) and the votes"""w = np.exp((sim[:, :k] - sim[:, :1]) / temp)votes = np.zeros((len(idx), self.C), np.float32)np.add.at(votes, (np.repeat(np.arange(len(idx)), k), self.y[idx[:, :k]].ravel()), w.ravel())votes /= votes.sum(1, keepdims=True)top = np.sort(votes, 1)return votes.argmax(1), top[:, -1] - top[:, -2], votes13 unmodified lines1415161718192021222324252627282930313233343536372 unmodified lines4041424344454647484950515213 unmodified linesself.V = vecs.astype(np.float32)self.y = labels.astype(np.int64)self.C = n_classesif self.V.ndim != 2 or not len(self.V) or not self.V.shape[1] or not np.isfinite(self.V).all():raise ValueError("nonempty finite two-dimensional vectors required")if type(n_classes) is not int or n_classes < 1 or self.y.shape != (len(self.V),) or not np.array_equal(self.y, labels):raise ValueError("one integer class label per vector required")if np.any(self.y < 0) or np.any(self.y >= n_classes):raise ValueError("class label outside declared range")def neighbours(self, Q, k, batch=512):Q = np.asarray(Q, dtype=np.float32)if Q.ndim != 2 or Q.shape[1] != self.V.shape[1] or not np.isfinite(Q).all():raise ValueError("query vectors must match the finite store dimension")if type(k) is not int or not 1 <= k <= len(self.V) or type(batch) is not int or batch < 1:raise ValueError("k must select one through all exemplars and batch must be positive")idx = np.empty((len(Q), k), np.int64)sim = np.empty((len(Q), k), np.float32)for s in range(0, len(Q), batch):S = Q[s:s + batch] @ self.V.Tpart = np.argpartition(-S, k - 1, axis=1)[:, :k]ps = np.take_along_axis(S, part, 1)order = np.argsort(-ps, axis=1)idx[s:s + batch] = np.take_along_axis(part, order, 1)2 unmodified linesdef vote(self, idx, sim, k, temp=0.05):"""similarity-weighted vote over the k nearest; returns label, margin (top1 - top2 share) and the votes"""if not np.isfinite(temp) or temp <= 0 or type(k) is not int or not 1 <= k <= idx.shape[1] or idx.shape != sim.shape:raise ValueError("positive finite temperature and matching nonempty neighbour arrays required")if np.any(idx < 0) or np.any(idx >= len(self.V)) or not np.isfinite(sim).all():raise ValueError("invalid neighbour indices or similarities")w = np.exp((sim[:, :k] - sim[:, :1]) / temp)votes = np.zeros((len(idx), self.C), np.float32)np.add.at(votes, (np.repeat(np.arange(len(idx)), k), self.y[idx[:, :k]].ravel()), w.ravel())votes /= votes.sum(1, keepdims=True)top = np.sort(votes, 1)return votes.argmax(1), top[:, -1] - (top[:, -2] if self.C > 1 else 0), votes
test_exemplar_contract.pyAdded+39
vision/exemplar.py+17-2