简体   繁体   English

为什么每次运行循环时都没有得到相同的结果?

[英]Why am I not getting the same result every time I run through my loop?

I'm doing some signal processing, and I have a loop in Python in which I'm trying to optimize a result, ln(B), over a parameter alpha.我正在做一些信号处理,我在 Python 中有一个循环,我试图在参数 alpha 上优化结果 ln(B)。 When I ran it, I got an optimal alpha value of -0.8, but when I used it in my regular code it gave me a different result than the loop had given me.当我运行它时,我得到了一个最佳的 alpha 值 -0.8,但是当我在常规代码中使用它时,它给我的结果与循环给我的结果不同。 For clarity's sake, the regular code's result was ~4 and the loop's result for alpha = -0.8 was ~5.为清楚起见,常规代码的结果是 ~4,而循环的 alpha = -0.8 的结果是 ~5。

I thought that was weird, so after double checking that the process was identical in each case I ran the loop code over one instance of alpha =-0.8 and got the same result as the regular code, 4, as opposed to the result the loop had given me at alpha = -0.8 when iterating over a range.我认为这很奇怪,所以在仔细检查每种情况下的过程是否相同后,我在 alpha =-0.8 的一个实例上运行循环代码并得到与常规代码 4 相同的结果,而不是循环的结果在迭代一个范围时给了我 alpha = -0.8。 I then iterated the code over the list [-0.8,-0.8,-0.8, -0.8, -0.8, -0.8] , and found that for the first -0.8, I got 4, and then for each subsequent one I got 5.然后我在列表[-0.8,-0.8,-0.8, -0.8, -0.8, -0.8]上迭代代码,发现对于第一个 -0.8,我得到 4,然后对于每个后续的我得到 5 .

Is there some reason a loop would give me a different answer or process for the first item than the rest of them?是否有某种原因,循环会给我第一个项目的答案或过程与其中的 rest 不同? I've been staring at it for hours and I can't find my mistake.我已经盯着它看了好几个小时,我找不到我的错误。 I thought maybe I wasn't resetting a variable, but the difference only happens between the first iteration and the rest, not for each iteration.我想也许我没有重置变量,但差异只发生在第一次迭代和 rest 之间,而不是每次迭代。

This is my loop:这是我的循环:

alpharange = [-0.8,-0.8,-0.8, -0.8, -0.8, -0.8]

for alpha in alpharange:
  run += 1
  print("Run {0}, alpha = {1}".format(run, alpha))

  #find var_n
  denominator = 0 
  r = np.arange(1,16)
  for n in r:
    if n*fecho <= fmax: 
        denominator += (n*fecho)**(2-2*alpha)/(var_f[n*nf])**2
  var_n = numerator/denominator 
  print("var_n = ", var_n)

  #find lnB
  YB_ln = np.zeros(spec_H1.shape)
  B_t = np.arange(0,len(YB_ln[0,:]),1) #length of a row
  B_f = np.arange(0,len(YB_ln[:,0]),1) #length of a column 

  for nt in tzoomindx:
    for nf in fzoomindx:
      for n in r:
          if n*nf<realfreqs.size-1:
              f = realfreqs[n*nf]
              YB_ln[nf,nt] += (np.abs(2*np.real(spec_H1[n*nf,nt]*np.conj(spec_L1[n*nf,nt])) + np.abs(spec_H1[n*nf,nt])**2 + np.abs(spec_L1[n*nf,nt])**2 ))/(1/(var_n*(1/f**alpha)) + 1/var_f[n*nf]) - np.log(1 + (var_n*(1/f**alpha))/var_f[n*nf])    
  peak = np.max(YB_ln)
  peakcoord = np.where((YB_ln==peak))

  if peak > lnB_max:
    alpha_max = alpha
    lnB_max = peak
    time_max = t[peakcoord[1]]-tinterval
    freq_max = realfreqs[peakcoord[0]]
    var_n_max = var_n
    print("!!!!!NEW MAX:  alpha = {0} with peak {1} at time {2} and frequency {3}".format(alpha_max,lnB_max,time_max,freq_max))

  alphalist.append(alpha)
  lnBlist.append(peak)
  timelist.append(t[peakcoord[1]]-tinterval)
  freqlist.append(realfreqs[peakcoord[0]])
  print("Peak lnB = {0} at time {1} and frequency {2}. Time: {3} min {4} s".format(peak,t[peakcoord[1]]-tinterval,realfreqs[peakcoord[0]],(time.time()-start_time)//60,(time.time()-start_time)%60))

print("lnB is optimized at alpha = {0} with peak {1} at time {2} and frequency {3}, var_n = {4}".format(alpha_max,lnB_max,time_max,freq_max,var_n_max))
print("Run took {0} min, {1} s".format((time.time()-start_time)//60,(time.time()-start_time)%60)) 

and the output:和 output:

Run 1, alpha = -0.8
var_n =  (1.1668471858083481e-14+0j)

/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:72: ComplexWarning: Casting complex values to real discards the imaginary part

!!!!!NEW MAX:  alpha = -0.8 with peak 4.115523906554817 at time [1.0625] and frequency [72.]
Peak lnB = 4.115523906554817 at time [1.0625] and frequency [72.]. Time: 0.0 min 0.3648514747619629 s
Run 2, alpha = -0.8
var_n =  (3.664163403845884e-14+0j)
!!!!!NEW MAX:  alpha = -0.8 with peak 5.330720524005124 at time [1.0625] and frequency [72.]
Peak lnB = 5.330720524005124 at time [1.0625] and frequency [72.]. Time: 0.0 min 0.702958345413208 s
Run 3, alpha = -0.8
var_n =  (3.664163403845884e-14+0j)
Peak lnB = 5.330720524005124 at time [1.0625] and frequency [72.]. Time: 0.0 min 1.0434083938598633 s
Run 4, alpha = -0.8
var_n =  (3.664163403845884e-14+0j)
Peak lnB = 5.330720524005124 at time [1.0625] and frequency [72.]. Time: 0.0 min 1.375929832458496 s
Run 5, alpha = -0.8
var_n =  (3.664163403845884e-14+0j)
Peak lnB = 5.330720524005124 at time [1.0625] and frequency [72.]. Time: 0.0 min 1.7248213291168213 s
Run 6, alpha = -0.8
var_n =  (3.664163403845884e-14+0j)
Peak lnB = 5.330720524005124 at time [1.0625] and frequency [72.]. Time: 0.0 min 2.0683481693267822 s
lnB is optimized at alpha = -0.8 with peak 5.330720524005124 at time [1.0625] and frequency [72.], var_n = (3.664163403845884e-14+0j)
Run took 0.0 min, 2.069751739501953 s

(I ignore that error because the complex values only have a real part). (我忽略了这个错误,因为复数值只有实部)。

It's clear to me that it's the variable var_n that's changing and that's what's throwing off my result.我很清楚,变量 var_n 正在发生变化,这就是我的结果的原因。 I'm just not sure why it's different only for the first iteration.我只是不确定为什么它只在第一次迭代时有所不同。

My full code with all the variable definitions is as follows, I just didn't want to clutter the one above:我的所有变量定义的完整代码如下,我只是不想弄乱上面的代码:

start_time = time.time()

#find the energy over the leading seconds

dt = t[1] - t[0]

inspiral = np.where((t-tinterval >= -2) & (t-tinterval <= 0))
Einspiral_sum = np.sum(E[inspiral])*dt

print("Summed E_inspiral = ", Einspiral_sum)

#find the 'constant'

noise = np.where((t-tinterval <= -5) & (t-tinterval >= -50))
Enoise = np.sum(E[noise])/(E[noise].size)

print("E_noise = ", Enoise)

#finding the variance 

var_f = var_f_same

fecho = 72 
nf = np.where((realfreqs==fecho))
nf = int(nf[0])
fmax = 300

tzoomindx = np.where((t-tinterval>=0.5)&(t-tinterval<=1.5))
tzoomindx = np.array(tzoomindx[0])
fzoomindx = np.where((realfreqs>=63)&(realfreqs<=92))
fzoomindx=np.array(fzoomindx[0])

upperbound = 0
lowerbound = -2
numerator = (Einspiral_sum - (Enoise*upperbound-Enoise*lowerbound))

run = 0
lnB_max = -1e5
lnBlist = []
alphalist = []
timelist = []
freqlist = []

#alpharange = np.arange(-1.5,1,0.1)
#alpharange = np.array([-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.2,0.3,0.4])
alpharange = [-0.8,-0.8,-0.8, -0.8, -0.8, -0.8]

for alpha in alpharange:
  run += 1
  print("Run {0}, alpha = {1}".format(run, alpha))

  #find var_n
  denominator = 0 
  r = np.arange(1,16)
  for n in r:
    if n*fecho <= fmax: 
        denominator += (n*fecho)**(2-2*alpha)/(var_f[n*nf])**2
  var_n = numerator/denominator #for Einspiral = sum

  #find lnB
  YB_ln = np.zeros(spec_H1.shape)
  B_t = np.arange(0,len(YB_ln[0,:]),1) #length of a row
  B_f = np.arange(0,len(YB_ln[:,0]),1) #length of a column 

  for nt in tzoomindx:
    for nf in fzoomindx:
      for n in r:
          if n*nf<realfreqs.size-1:
              f = realfreqs[n*nf]
              YB_ln[nf,nt] += (np.abs(2*np.real(spec_H1[n*nf,nt]*np.conj(spec_L1[n*nf,nt])) + np.abs(spec_H1[n*nf,nt])**2 + np.abs(spec_L1[n*nf,nt])**2 ))/(1/(var_n*(1/f**alpha)) + 1/var_f[n*nf]) - np.log(1 + (var_n*(1/f**alpha))/var_f[n*nf])    
  peak = np.max(YB_ln)
  peakcoord = np.where((YB_ln==peak))

  if peak > lnB_max:
    alpha_max = alpha
    lnB_max = peak
    time_max = t[peakcoord[1]]-tinterval
    freq_max = realfreqs[peakcoord[0]]
    var_n_max = var_n
    print("!!!!!NEW MAX:  alpha = {0} with peak {1} at time {2} and frequency {3}".format(alpha_max,lnB_max,time_max,freq_max))

  alphalist.append(alpha)
  lnBlist.append(peak)
  timelist.append(t[peakcoord[1]]-tinterval)
  freqlist.append(realfreqs[peakcoord[0]])
  print("Peak lnB = {0} at time {1} and frequency {2}. Time: {3} min {4} s".format(peak,t[peakcoord[1]]-tinterval,realfreqs[peakcoord[0]],(time.time()-start_time)//60,(time.time()-start_time)%60))

print("lnB is optimized at alpha = {0} with peak {1} at time {2} and frequency {3}, var_n = {4}".format(alpha_max,lnB_max,time_max,freq_max,var_n_max))
print("Run took {0} min, {1} s".format((time.time()-start_time)//60,(time.time()-start_time)%60))                 

E is the energy of my signal, spec_H1/spec_L1 are the spectrograms of my signal, and all in all I am trying to find the Bayes factor of a signal in a certain time and frequency range. E 是我的信号的能量,spec_H1/spec_L1 是我的信号的频谱图,总而言之,我试图在某个时间和频率范围内找到一个信号的贝叶斯因子。

Possibly, as you iterate over nf in fzoomindx , you change nf , which is used in calculation of denominator in denominator += (n*fecho)**(2-2*alpha)/(var_f[n*nf])**2 ...可能,当您nf in fzoomindx ,您会更改nf ,它用于计算denominator denominator += (n*fecho)**(2-2*alpha)/(var_f[n*nf])**2中的分母denominator += (n*fecho)**(2-2*alpha)/(var_f[n*nf])**2 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么每次在此代码中运行“退出”时都会出现关键错误? - Why am I getting a key error every time I run 'exit' in this code? 为什么我在 for 循环的每次迭代中随机生成的名称都相同? - Why are the names that I am randomly generating the same in every iteration of my for loop? 为什么我的预测 model 每次运行时都会给出不同的预测结果? - Why does my prediction model keep giving a different prediction result every time I run it? 为什么每次运行我的函数时都会出错? - Why am I getting an error whenever I run my function? 为什么我收到一个NameError试图运行此For循环 - Why am I getting a NameError which trying to run this For loop 为什么我的 python 循环每次运行都会给出不同的数组,以及如何让它每次都产生相同的结果? - Why does my python loop give a different array every run, and how to make it produce the same result everytime? 当我在同一代码集中第二次运行 requests.get 和 json 时,为什么会得到一个空数组? - Why am I getting an empty array when I run a requests.get and a json a second time in the same code set? 为什么我的 while 循环会出现值错误? - Why am I getting a value error from my while loop? 为什么我在 python 中的循环出现索引错误? - Why am I getting a index error for my loop in python? 为什么我得到其他所有线路? - Why am I getting every other line?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM