admin管理员组文章数量:1353618
I would like to define a loss function for the CVXPy optimization that minimizes differences from the reference grouped target:
import cvxpy as cp
import pandas as pd
# toy example for demonstration purpose
target = pd.DataFrame(data={'a': ['X', 'X', 'Y', 'Z', 'Z'], 'b': [1]*5})
w = cp.Variable(target.shape[0])
beta = cp.Variable(target.shape[0])
def loss_func(w, beta):
x = pd.DataFrame(data={'a': target['a'], 'b': w @ beta}).groupby('a')['b'].sum()
y = target.groupby('a')['b'].sum()
return cp.norm2(x - y)**2 # <<<<<<<<<<<<<< ValueError: setting an array element with a sequence.
but this gives me the following error
ValueError: setting an array element with a sequence.
What would be the way to cover this use-case using CVXPy?
I would like to define a loss function for the CVXPy optimization that minimizes differences from the reference grouped target:
import cvxpy as cp
import pandas as pd
# toy example for demonstration purpose
target = pd.DataFrame(data={'a': ['X', 'X', 'Y', 'Z', 'Z'], 'b': [1]*5})
w = cp.Variable(target.shape[0])
beta = cp.Variable(target.shape[0])
def loss_func(w, beta):
x = pd.DataFrame(data={'a': target['a'], 'b': w @ beta}).groupby('a')['b'].sum()
y = target.groupby('a')['b'].sum()
return cp.norm2(x - y)**2 # <<<<<<<<<<<<<< ValueError: setting an array element with a sequence.
but this gives me the following error
ValueError: setting an array element with a sequence.
What would be the way to cover this use-case using CVXPy?
Share Improve this question edited Apr 1 at 9:48 Naveed Ahmed 5352 silver badges13 bronze badges asked Apr 1 at 9:39 SkyWalkerSkyWalker 14.3k20 gold badges102 silver badges210 bronze badges1 Answer
Reset to default 1Based on my understanding, your code calculates the sum of weighted values (w @ beta
) grouped by the unique values in column "a"
. However, since Pandas cannot handle CVXPY variables, this approach results in errors.
The hstack method, on the other hand, uses native CVXPY functions like cp.sum() and cp.hstack(), making it fully compatible and error-free while giving the same result. Therefore, it’s better to use the hstack approach.
for example:
import cvxpy as cp
import pandas as pd
# toy example for demonstration purpose
target = pd.DataFrame(data={"a": ["X", "X", "Y", "Z", "Z"], "b": [1] * 5})
w = cp.Variable(target.shape[0])
beta = cp.Variable(target.shape[0])
def loss_func2(w, beta):
x = cp.hstack([
cp.sum(w[target["a"] == group] * beta[target["a"] == group])
for group in target["a"].unique()
])
y = target.groupby("a")["b"].sum().values
return cp.norm2(x - y) ** 2
本文标签: pythonHow to do a groupby on a cxvpy Variable is there a way using pandasStack Overflow
版权声明:本文标题:python - How to do a groupby on a cxvpy Variable? is there a way using pandas? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743896339a2557853.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论