【问题标题】:Scipy Objective functionScipy 目标函数
【发布时间】:2020-02-23 22:47:23
【问题描述】:

我正在尝试将我的 gurobi 代码转换为 scipy,但我无法定义目标函数。在测试我是否正确定义了函数时,我得到了错误:

TypeError: 'float' object is not iterable

代码在这里:

import pandas as pd
import numpy as np
import scipy as sp
from scipy.optimize import minimize
import matplotlib.pyplot as plt
%matplotlib inline
step=80
f1load=[44,48,53,28,32,36,41,48,38,32,38,34,44,36,41,48,38,32,44,48,53,28,32,36,41,48,38,32,38,34,44,36,41,48,38,32,44,48,53,28,32,36,41,48,38,32,38,34,44,36,41,48,38,32,44,48,53,28,32,36,41,48,38,32,38,34,44,36,41,48,38,32,44,48,53,28,32,36,41,48,38,32,38,34,44,36,41,48]
fload=f1load[0:step+1]
i1load=[40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40]
iload=i1load[0:step+1]
#Following command converts fload&iload to arrays and subtracts them from each other 
load1=np.array(iload)-np.array(fload)
load1
#This command converts array to list so we can use it as a list in the rest of the code
load2=load1.tolist()
load=load2
x = np.zeros(80)
x = x.tolist()
def objective(x,load):
# this line is from my gurobi code    obj1=sum(((load[i+1]-(6*x[i]))*(load[i+1]-(6*x[i])) for i in range (n)))
    for i in range(step):
        obj1 = sum((load[i+1]-(6*x[i]))*(load[i+1]-(6*x[i])))
        obj2 = obj2 + obj1
    return obj2

objective(x,load)

错误的完整堆栈跟踪:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-cef8470baf0d> in <module>
----> 1 objective(x,load)

<ipython-input-25-a9de3ab9ff2b> in objective(x, load)
      2 #     obj1=sum(((load[i+1]-(6*x[i]))*(load[i+1]-(6*x[i])) for i in range (n)))
      3     for i in range(step):
----> 4         obj1 = sum((load[i+1]-(6*x[i]))*(load[i+1]-(6*x[i])))
      5         obj2 = obj2 + obj1
      6     return obj2

TypeError: 'float' object is not iterable

【问题讨论】:

    标签: python pandas numpy scipy scipy-optimize-minimize


    【解决方案1】:

    在这一行:

    obj1 = sum((load[i+1]-(6*x[i]))*(load[i+1]-(6*x[i])))
    

    括号内的表达式(load[i+1]-(6*x[i]))*(load[i+1]-(6*x[i])) 的计算结果为float,在该表达式上调用sum 会出现错误,因为sum 函数需要一个可迭代的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 2019-05-17
      相关资源
      最近更新 更多