未知的numpy.optimize.fmin错误

时间:2013-07-29 16:22:37

标签: python optimization scipy

我正在尝试编写一个程序,根据日志实用程序和同时发生的相关事件来计算最佳投注金额。

为了做到这一点,我试图使用numpy.optimize.fmin函数。我传递给它的函数anon工作并产生(希望)正确的输出,但当numpy尝试优化函数时,我得到以下错误

s[i].append(f[i][0]*w[i][0] + f[i][1]*w[i][1])
IndexError: invalid index to scalar variable.

由于我不知道fmin,我不知道导致此错误的原因。

我的代码在下面,希望不是tl;博士,但我不会责怪你。

附录

def main():
     p = [[0.1,0.1,0.2,   0.2,0.1,0,   0.1,0.1,0.1]]
     w = [[5,4]]
     MaxLU(p,w,True)

def MaxLU(p, w, Push = False, maxIter = 10):
    #Maximises LU, using Scipy in built function
    if Push == True:
        anon = lambda f: -PushLogUtility(p, w, f)
    else:
        anon = lambda f: -LogUtility(p, w, f)
    #We use multiple random starts
    f = []
    LU = []
    for i in range(0,maxIter):
        start = np.random.rand(len(p))
        start = start / 5 * np.sum(start)
        f.append(optimize.fmin(anon, start)) #Error occurs in here!
        if Push == True:
            LU.append(PushLogUtility(p, w, f[-1]))
        else:
            LU.append(LogUtility(p, w, f[-1]))

    #Now find the index of the max LU and return that same index of f
    return f[LU.index(np.max(LU))]

def PushLogUtility(p,w,f):
    #Outputs log utility incoroporating pushes and dependent totals, money data
    #p : 9xk length vector of joint probabilities for each of the k games, p = [[p_(W_T W_M), p_(W_T P_M), p_(W_T L_M), p_(P_T W_M) ... ]]
    #w : 2xk matrix of odds where w = [[total odds, money odds] ... ]
    #f : 2xk matrix of bankroll percentages to bet, f = [[f_T, f_M] ... ]
    utility = 0
    k = len(p)
    s = k*[[]]
    for i in range(0,k):
        s[i].append(f[i][0]*w[i][0] + f[i][1]*w[i][1])
        s[i].append(f[i][0]*w[i][0])
        s[i].append(f[i][0]*w[i][0] - f[i][1])
        s[i].append(f[i][1]*w[i][1])
        s[i].append(0)
        s[i].append(-f[i][1])
        s[i].append(-f[i][0] - f[i][1])
        s[i].append(-f[i][0] - f[i][1])
        s[i].append(-f[i][0] - f[i][1])

    for i in range(0,9 ** k):
        l = de2ni(i) #Converts number to base 9
        if i == 0:
            l += int(math.ceil(k - 1 - math.log(i + 1,9))) * [0]
        else:
            l += int(math.ceil(k - 1 - math.log(i,9))) * [0]
        productTerm = np.prod([p[i][l[i]] for i in range(0,k)])
        sumTerm = np.sum([s[i][l[i]] for i in range(0,k)])
        utility = utility + productTerm * np.log(1 + sumTerm)
    return utility

1 个答案:

答案 0 :(得分:1)

您可以在这里:

   s[i].append(f[i][0]*w[i][0] + f[i][1]*w[i][1])

如果你看一下类型,你会发现s[i][]f[i]0.104528w[i][5,4] 。然后,您尝试第二次索引f[i] - 这是不可能的,并导致错误。