Skip to content

Instantly share code, notes, and snippets.

@nilsabdi
Created August 9, 2023 22:53
Show Gist options
  • Select an option

  • Save nilsabdi/1c8f924be6dff7f4540250bcb53de717 to your computer and use it in GitHub Desktop.

Select an option

Save nilsabdi/1c8f924be6dff7f4540250bcb53de717 to your computer and use it in GitHub Desktop.
def weight_proc(matrix, name, k, diag=0, checks=False):
if checks:
if not all(matrix[i][j] == matrix[j][i] for i, neighbors in matrix.neighbors.items() for j in neighbors):
print("Matrix is not symmetric!")
full_matrix, ids = matrix.full()
np.fill_diagonal(full_matrix, diag)
# Convert to a sparse matrix
sparse_matrix = csr_matrix(full_matrix)
# Convert to WSP (sparse weights) and then to W
wsp = WSP(sparse_matrix)
w = wsp.to_W()
if checks:
# Sanity checks
# Negative weights?
if any(w_ij < 0 for neighbors in w.weights.values() for w_ij in neighbors):
print("There are negative weights!")
# Isolated rows?
isolated_rows = [
i for i, neighbors in w.neighbors.items() if not neighbors]
if isolated_rows:
print(f"There are {len(isolated_rows)} isolated rows.")
# Diagonal elements one?
full_w_matrix, _ = w.full()
if not all(np.diagonal(full_w_matrix) == 1):
print("Not all diagonal elements are ones!")
# Save as NEW kernel matrix
with open(name + "_" + k + "_Proc_Diag_"+diag+".pkl", 'wb') as f:
pickle.dump(w, f)
return w.full()
with open('gaussian_2.pkl', 'rb') as f:
kernel = pickle.load(f)
weight_proc(kernel, "gaussian", "2", diag=0, checks=False)
weight_proc(kernel, "gaussian", "2", diag=1, checks=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment