python - 使用 python scipy 最小化的线性规划问题
问题描述
我正在尝试使用 python 优化scipy.optimize.minimize
一个人使用可用食品并坚持预算的卡路里摄入量。
问题陈述是:有 n 种食物,每种都有不同的数量。他们的价格每天都在变化。每种都有不同的营养价值,每天都会减少。我需要在一个月内购买食物,以使总营养最接近我的目标,并且我使用我确切的每月预算来购买它们。
#df_available has 1 row each for each item's available quantity at the beginning of the month
#df_bought has initial guesses for purchase of each item for each day of the month. This is based on prorated allotment of my total budget to each item on each day.
#df_price has price of each item on each day of the month.
#df_nutrition['nutrition'] has initial nutrition value per unit. it decreases by 1 unit each year, so 1/365 each day.
#strt is start date of the month.
#tot_nutrition is monthly total nutrition target for the month
#tot_budget is my monthly budget
def obj_func():
return (df_bought.sum()*(df_nutrition['nutrition'] - strt/365).sum())
#constraint 1 makes sure that I buy exactly at my budget
def constraint1():
return ((df_bought * df_price).sum().sum()- tot_budget)
cons1 = {'type':'eq', 'fun':constraint1}
#constraint 2 makes sure that I dont buy more than available quantity of any item
def constraint2():
return df_available - df_bought
cons2 = {'type':'ineq', 'fun':constraint2}
cons = ([cons1, cons2])
#bounds ensure that I dont buy negative quantity of any item
bnds = (0, None)
res = minimize(obj_func, df_bought_nominal_m, bounds= bnds, constraints=cons)
print(res)
对于输出,我希望调整 df_bought 值以最小化 obj_function。
该代码给出以下错误:
TypeError: constraint1() takes no arguments (1 given)
如果我犯了任何新手错误,我深表歉意。我是 python 新手,在网上找不到针对此问题的适当帮助。
解决方案
推荐阅读
- react-native - 世博会问题启动应用程序(显示三个屏幕按钮) - React Native
- ubuntu - 无法链接到 libglew 或 libglfw
- vue.js - 在 vue 项目中设置全局 sass 变量
- jekyll - 使用包含标签访问 Jekyll 的 _data 文件夹中的 csv
- groovy - 如何解决 Groovy 错误“无法解析类 spock.lang.Specification”?
- model-view-controller - 通过 HTTPS 连接时 Ajax.BeginForm OnFailure 返回空结果
- javascript - 从头开始将 JS 数组传递给 PHP 以获取联系表单
- php - 无法从 symfony 3 中的 ajax 发布请求访问请求数据
- ocaml - Ocaml 将类型转换为字符串
- python - 即使我安装了它,也没有名为“Kivy”的模块