[英]scipy.optimize() Value Error:Shape mismatch for sum
嗨,我是scipy和numpy的新手,
我正在尝试使用解决QP问题进行类分配
minimize x^t * H * x + f^t * x
where x > 0
其中H是2 X 2块矩阵,每个元素是ak X k维矩阵,x和f是2 X 1向量,每个元素是ak维向量。
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
我是否缺少明显的东西?
问题是x_init
被opt.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
也将被展平,需要相同的重塑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.