numpy concatenate" 有什么问题?

1 投票
2 回答
2078 浏览
提问于 2025-04-18 09:12

我正在尝试查看使用scipy.optimize中的minimize函数时的优化进展。

我想创建一个类,在这个类里使用一些在实际优化函数外部的变量——x_it就是其中一个。每次迭代后,新的x向量应该和之前的向量连接在一起。我这样做是因为我想用matplotlib来评估这些迭代(在下面的代码中没有包含),而且因为scipy对某些优化方法不支持回调函数:

class iter_progress:  
    x_it=[]
    def __init__(self):
        pass
    def build_iter():
        import numpy as np
        iter_progress.y_it=np.zeros((1,1), dtype=float)
        iter_progress.x_it=np.zeros((1,2), dtype=float)
    def obj(x):
        import numpy as np

        out=x[0]**2+x[1]**2

        out=np.array([[out]])
        x_copy=x.copy()[None]

        #iter_progress.x_it=np.concatenate(iter_progress.x_it.copy(), x_copy) 
        #the above line is commented because it does not work
        return out

    def mine():
        import numpy as np
        from scipy.optimize import minimize

        x0=np.array([[4,6]])

        res=minimize(iter_progress.obj,x0=x0, method='SLSQP')
        print(res.x)

在控制台中,我执行:

>>>from iter_progress import iter_progress

>>>iter_progress.build_iter()

>>>iter_progress.mine()

这段代码可以正常工作,但当我取消注释我做备注的那一行时,我得到了:

iter_progress.x_it=np.concatenate(iter_progress.x_it.copy(), x_copy)
TypeError: only length-1 arrays can be converted to Python scalars

2 个回答

3

在使用 concatenate 这个函数时,第二个参数应该是你想要拼接的轴。numpy 误以为你想在 x_copy 这个轴上进行拼接。

你可以查看 这里,了解如何正确使用 concatenate 函数。

2

为了让@BiRico的评论更清楚:你忘了在你想要连接的数组周围加上括号。应该这样写 np.concatenate((iter_progress.x_it.copy(), x_copy))

传给 np.concatenate 的第一个参数应该是一个可以迭代的数组集合,也就是说,它应该是一个包含多个数组的列表。加上额外的括号可以把这个参数变成一个元组,这样代码就能正常运行了。

撰写回答