我正在尝试编写一个将列表的索引作为输入n1
的python函数,然后在大小为w
的间隔中,选择[n1-w,n1+w]
并选择另一个索引n2根据{{1}}和n1
之间的距离而衰减并返回索引n2
和与n2
对应的列表元素的概率。
在我当前的实现中(“尝试1”),首先我使用计算所有概率,然后选择具有权重的索引。
给定一个列表n2
,这很好(我认为)
如果我的[0,1,2,3,4,5,6,7,8,9]
位于n1
和5
的中间位置,则从区间w=2
中选择一个概率权重为
[3 4 5 6 7]
的元素。
我要处理的问题是,如果我从末端选择一个元素,例如选择[0.16666667 0.33333333 0. 0.33333333 0.16666667]
会给出
n2choice(8)
相反,我想间隔
[6 7 8 9]#indices interval
[0.2 0.4 0. 0.4]#weights
或者类似地,在另一端,[6 7 8 9 0]# indices interval
[0.16666667 0.33333333 0. 0.33333333 0.16666667]#weights
给出n2choice(1)
相反,我想得到
[0 1 2 3]#interval
[0.2 0.4 0. 0.4]#weights
基本上,我想将我已经实现的当前“吸收”边界条件转换为“周期性边界”,其中1D列表实际上被视为1D环。
为此,我曾经尝试使用[9 0 1 2 3]# indices interval
[0.16666667 0.33333333 0. 0.33333333 0.16666667]#weights
运算符(请参阅尝试2)。但是,这将引发“ IndexError:列表索引超出范围”。我可以使用一些帮助来对此代码进行故障排除,也可以通过快速,Python的方式提出建议。我希望能够对任意长度和任意w的数组执行此操作,而不是此处介绍的这个简单测试用例。
%
#Attempt 1
import numpy as np
import random
a = [0,1,2,3,4,5,6,7,8,9]
w =2
mylist = np.array(a)
indices_list = np.arange(mylist.size)
def n2choice(n1):
prob_wts = [0 if i+(n1-w) == n1 else 1/(abs(i+(n1-w)-n1))**(1.) for i in np.arange(mylist[max(n1-w,0):n1+w+1].size)]
prob_wts = np.array(prob_wts)/sum(prob_wts)
#for i in np.arange(mylist[max(n1-w,0):n1+w+1].size):
#print(i, i+(n1-w))
print(prob_wts)
print(sum(prob_wts))
print(indices_list[max(n1-w,0):n1+w+1])
n2 = random.choices(indices_list[max(n1-w,0):n1+w+1], weights=prob_wts,k=1)
print(prob_wts[max(n1-w,0):n1+w+1])
n2_c = (n2[0], mylist[n2[0]])
return np.array(n2_c)
n2choice(5)