【问题标题】:scipy.optimize() Value Error:Shape mismatch for sumscipy.optimize() 值错误:sum 的形状不匹配
【发布时间】:2013-11-03 10:12:06
【问题描述】:

嗨,我是 scipy 和 numpy 的新手,

我正在尝试将 QP 问题用于课堂作业

minimize x^t * H * x  + f^t * x 
where x > 0

其中 H 是一个 2 X 2 块矩阵,每个元素是一个 k X k 维矩阵,并且 x 和 f 是 2 X 1 个向量,每个元素是一个 k 维向量。

np.shape(H) = (2, 2, k, k)
np.shape(x) = (2, k)

即使我认为函数正确,我也会收到形状不匹配错误

这是我的实现:

def func(x):    #This function runs perfectly ,returns a value 

    return 0.5 * np.tensordot(x, np.tensordot(H, x, axes=([1,3],[0,1]))) + np.tensordot(x,f)

x_init = np.ones((2, k))

bnds = (0, None)

theta = opt.minimize(func , x_init, bounds = bnds)
# I get an error here. 
# ValueError: shape-mismatch for sum

我是否遗漏了一些明显的东西?

【问题讨论】:

    标签: python optimization numpy scipy


    【解决方案1】:

    问题是x_initopt.minimize 压扁了。您可以通过在函数内部重塑 x 来解决此问题:

    def func(x):
        x = x.reshape(2, -1)
        return 0.5 * np.tensordot(x, np.tensordot(H, x, axes=([1,3],[0,1]))) + np.tensordot(x,f)
    

    结果由theta 捕获,并从属性theta.x 优化x,您将看到它也被展平,需要相同的重塑。

    【讨论】:

    • 非常感谢!也许我会更好地减少我的矩阵和向量的维度。
    猜你喜欢
    • 2015-11-06
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2019-03-05
    • 2016-05-13
    相关资源
    最近更新 更多