我对这段代码有疑问,我真的不明白为什么它不能达到以下最内部的第二个周期:
def remove_random_links(A,E):
rs = random.sample(A.edges, E)
A.remove_edges_from(rs)
N = 30
L = [0,60,30,40,30,30,20,40]
rep = 15
d = []
g = []
for j in range(rep):
R = nx.grid_graph(dim=[N,N])
_deg = []
_gap = []
for i in L:
remove_random_links(R,i)
A = nx.adj_matrix(R)
L = nx.laplacian_matrix(R)
eigwd, eigv = LA.eigh(L.todense())
eigw = np.sort(eigwd)
eigw0 = eigw[0]
eigw1 = eigw[1]
eigw2 = eigw[2]
eigw3 = eigw[3]
gap = eigw2 - eigw1
deg = eigw3 - eigw2
_deg.append(deg)
_gap.append(gap)
print("meow")
d.append(_deg)
g.append(_gap)
print("M")
mean_deg = [np.mean(d[i]) for i in range(rep)]
mean_gap = [np.mean(g[i]) for i in range(rep)]
std_deg = [np.std(d[i]) for i in range(rep)]
std_gap = [np.std(g[i]) for i in range(rep)]
它先执行第一个循环(j中的那个),然后进入第一个i循环,完成它,然后由于功能remove_random_links()的错误而无法执行第二个,这给了我以下错误:
文件“ /Users/Sofia/Desktop/delta.py”,第23行,在 remove_random_links(R,i)
文件“ /Users/Sofia/Desktop/delta.py”,第9行,在remove_random_links中 rs = random.sample(A.edges,E)
示例中的文件“ /anaconda3/lib/python3.6/random.py”,第317行 如果不是0 <= k <= n:
文件 “ /anaconda3/lib/python3.6/site-packages/scipy/sparse/compressed.py”, 第322行,位于 ge “将稀疏矩阵与标量进行比较”
文件 “ /anaconda3/lib/python3.6/site-packages/scipy/sparse/compressed.py”, _inequality中的第272行 引发NotImplementedError(“> =和<=不适用于0。”)
NotImplementedError:> =和<=不适用于0。
答案 0 :(得分:0)
这是因为您两次在同一个变量L
中使用过一次,
L = [0,60,30,40,30,30,20,40]
然后在此处进行迭代时重新分配它
for i in L:
remove_random_links(R,i)
A = nx.adj_matrix(R)
L = nx.laplacian_matrix(R) #<--------change variable name
使用不同的变量名,这应该可以解决问题,例如,尝试一下
import random
from numpy import linalg as LA
def remove_random_links(A,E):
print A.edges, E
rs = random.sample(A.edges, E)
A.remove_edges_from(rs)
N = 30
L_edges = [0,60,30,40,30,30,20,40] #<--- changed it to L_edges
rep = 15
d = []
g = []
for j in range(rep):
R = nx.grid_graph(dim=[N,N])
_deg = []
_gap = []
for i in L_edges: #<--- changed it to L_edges
remove_random_links(R,i)
A = nx.adj_matrix(R)
L = nx.laplacian_matrix(R)
eigwd, eigv = LA.eigh(L.todense())
eigw = np.sort(eigwd)
eigw0 = eigw[0]
eigw1 = eigw[1]
eigw2 = eigw[2]
eigw3 = eigw[3]
gap = eigw2 - eigw1
deg = eigw3 - eigw2
_deg.append(deg)
_gap.append(gap)
print("meow")
d.append(_deg)
g.append(_gap)
print("M")
mean_deg = [np.mean(d[i]) for i in range(rep)]
mean_gap = [np.mean(g[i]) for i in range(rep)]
std_deg = [np.std(d[i]) for i in range(rep)]
std_gap = [np.std(g[i]) for i in range(rep)]