Scipy优化最小化函数始终返回初始值

2024-10-02 18:24:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难让我的scipy优化工作,我想这是因为我的限制。我的代码的目标是找到最佳的x和y坐标,以便为散点图点放置标签,而该标签不会接近旧标签。我的优化是散点图点和标签点之间的欧几里德距离(以便标签尽可能靠近该点)。“我的约束”检查所有使用的x和y值,并确保新标签x和y值(nx和ny)不接近任何旧的x和y值。如果x或y在1范围内,则约束返回1而不是0。我认为这应该是正确的方式,因为约束是一个“eq”

然而,我猜问题在于约束不是一个光滑的方程,因此优化不知道如何处理它

有没有别的办法可以解决这个问题

#SECTION 1: Scatterplot: Labeling Points
#optimize (minimize) Euclidean Distance
usedx = []
usedy = []

#bounds
b = (0,10)
bnds = (b,b)

#objective
def objective(x, y):
    nx = x[0]
    ny = x[1]
    ox = y[0]
    oy = y[1]
    p1 = (ox,oy)
    p2 = (nx, ny)
    return distance.euclidean(p1, p2)

#constraint
def constraint(p, x, y):
    test = 0
    nx = p[0]
    ny = p[1]
    for i in x:
        if abs(i - nx) < 1:
            test = 1
    for i in y:
        if abs(i - ny) < 1:
            test = 1
    return test
const = {'type': 'eq', 'fun': constraint, 'args': (usedx, usedy)}

for i, txt in enumerate(selectedFirmCurrent.sht_fund_name):
    originaly = selectedFirmCurrent.iloc[i]['category_score']
    originalx = selectedFirmCurrent.iloc[i]['fund_score']
    originalpoint = [originalx, originaly]
    #initial guess
    p0 = (originalx, originaly -.25)
    #optimization
    solution = minimize(objective, args = originalpoint, x0 = p0,bounds = bnds,constraints = const)
    #variable assign
    newx = solution.x[0]
    newy = solution.x[1]
    usedx.append(newx)
    usedy.append(newy)
    print(originalx, ": ", newx)
    print(originaly, ": ", newy+0.25)
    #implement
    ax.annotate(txt, (originalx,originaly), (newx,newy), arrowprops= dict(arrowstyle = '->'))

Tags: intestfor标签nxobjectiveconstraintny