Skip to content

Instantly share code, notes, and snippets.

@mazieres
Last active August 29, 2015 14:17
Show Gist options
  • Save mazieres/a210615ea69f6dd32f24 to your computer and use it in GitHub Desktop.
Save mazieres/a210615ea69f6dd32f24 to your computer and use it in GitHub Desktop.
import unittest
class TestExtract(unittest.TestCase):
def test_adjacency_matrix(self):
X = np.array([
[1, 8, 3],
[5, 0, 0],
[0, 4, 2]])
tested = adjacency_matrix(X)
expected = np.array([
[(0,), (1,), (2,)],
[(1,), (0,), (0,)],
[(2,), (0,), (0,)]], dtype=[('weight', '<i8')])
test = np.array_equal(expected, tested)
msg = '\nExpected:\n{}\nGot:\n{}'.format(expected, tested)
self.assertTrue(test, msg=msg)
def adjacency_matrix(mat):
'''
Returns adjacency matrix from a bipartite graph weights matrix
'''
n_samples = mat.shape[0]
res = np.ndarray((n_samples, n_samples), dtype=np.dtype([("weight", int)]))
i = 0
while i < n_samples:
j = 0
while j < n_samples:
if i == j:
res[i][j] = (0,)
else:
res[i][j] = (np.logical_and(mat[i], mat[j]).sum(),)
j += 1
i += 1
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment