Python ValueError:目标函数必须返回标量

时间:2018-01-13 20:09:41

标签: python pandas numpy matplotlib scipy

嘿我试图在这个函数上运行一个优化器。它应该返回X = 1.5。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as spo

def f(x):
    # Given a scalar X, return some value (a real number)
    Y = (X - 1.5)**2 + 0.5
    print "X = {}, Y = {}".format(X, Y)
    return Y

def test_run():
    Xguess = 2.0
    min_result = spo.minimize(f, Xguess, method = 'SLSQP', options = {'disp': True})
    print "Minima found at:"
    print "X = {}, Y = {}".format(min_result.x, min_result.fun)

if __name__ == "__main__":
    test_run()

1 个答案:

答案 0 :(得分:1)

您对# test input in reproducible form dates <- format(as.Date("2015-01-01") + 1:1100, "%d/%m/%Y") d <- data.frame(dates, value = seq_along(dates)) write.csv(d, "testfile.csv", row.names = FALSE, quote = FALSE) 的论证是小写的f()。但是你在函数中引用大写的x。将您的函数定义更改为X,您的代码可以正常运行。

使用f(X)

f(X)