简体   繁体   English

缺少 1 个必需的位置 arguments:

[英]missing 1 required positional arguments:

I am facing some issues with my python code for a few days now.几天来,我的 python 代码遇到了一些问题。 I am trying to optimize two unknown parameters by solving a set of simultaneous nonlinear coupled ODEs.我试图通过求解一组同时的非线性耦合 ODE 来优化两个未知参数。 I have coupled the solver_ivp with the minimization routine.我已将solver_ivp 与最小化例程相结合。 I would be extremely grateful if someone could help me with this.如果有人可以帮助我,我将不胜感激。 The code is as follows.代码如下。 Thank you.谢谢你。

import numpy as np
import scipy as sp
from scipy.integrate import solve_ivp
import scipy.optimize as opt
from scipy.optimize import curve_fit
from scipy.optimize import least_squares 
from scipy.optimize import minimize
import matplotlib.pylab as plt
import pandas as pd

df = pd.read_csv('dep_data_CMB3.csv')
#print(df.columns)

xdat1 = np.asarray(df['t3_1'], dtype = 'float')
ydat1 = np.asarray(df['CMB3_1'], dtype = 'float')
#ydat2 = np.asarray(df['y2'], dtype = 'float')
#ydat3 = np.asarray(df['y3'], dtype = 'float')

xdat1 = np.asarray(df['t3_1'], dtype = 'float')
ydat1 = np.asarray(df['CMB3_1'], dtype = 'float')
#ydat2 = np.asarray(df['y2'], dtype = 'float')
#ydat3 = np.asarray(df['y3'], dtype = 'float')

plt.plot(xdat1, ydat1, 'ob', markersize = 2)
#plt.plot(xdat2, ydat2, 'og')
#plt.plot(xdat3, ydat3, 'or')
plt.xscale('log')
plt.show()

def func(tspan, ko, ki, phi, H):
dphidt = ko * (1 - phi) * H
dHdt = -ki * phi * H
    return [dphidt, dHdt]

H0 = [0.04818]
#H5 = [0.08083]
#H7 = [0.11242]
phi0 = 0.0
#phi5 = [0.0]
#phi7 = [0.0]
k0 = 0.0125
k1 = 0.00051
k = [k0, k1]
tspan = [0, max(xdat1)]

def newfunc(ko, ki, x, y, H):
tspan = [0, max(xdat1)]
y0 = [0, 0.04818]
result = solve_ivp(func, tspan, y0, method = 'RK45', args = (k0, k1, H0), dense_output = True)
resultnew = result.sol(tspan).T
ephi = y - resultnew[:,0]
sumephi = np.sum((ephi**2))
#eH = H0 - resultnew[:,1]
#sumeH = np.sum((eH**2))
    return sumephi

wguess = (k0, k1)
arguments = (xdat1, ydat1, H0)
res = minimize(newfunc, wguess, args = arguments, method = 'bfgs')

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call 
last)
<ipython-input-11-95e9b490310a> in <module>
      1 wguess = (k0, k1)
      2 arguments = (xdat1, ydat1, H0)
----> 3 res = minimize(newfunc, wguess, args = arguments, method = 
'bfgs')

~\Anaconda3\lib\site-packages\scipy\optimize\_minimize.py in 
minimize(fun, x0, args, method, jac, hess, hessp, bounds, 
constraints, tol, callback, options)
612         return _minimize_cg(fun, x0, args, jac, callback, 
**options)
613     elif meth == 'bfgs':
--> 614         return _minimize_bfgs(fun, x0, args, jac, callback, 
**options)
615     elif meth == 'newton-cg':
616         return _minimize_newtoncg(fun, x0, args, jac, hess, 
hessp, callback,

~\Anaconda3\lib\site-packages\scipy\optimize\optimize.py in 
_minimize_bfgs(fun, x0, args, jac, callback, gtol, norm, eps, 
maxiter, disp, return_all, finite_diff_rel_step, **unknown_options)
1133         maxiter = len(x0) * 200
1134 
-> 1135     sf = _prepare_scalar_function(fun, x0, jac, args=args, 
epsilon=eps,
1136                                   
finite_diff_rel_step=finite_diff_rel_step)
1137 

~\Anaconda3\lib\site-packages\scipy\optimize\optimize.py in 
_prepare_scalar_function(fun, x0, jac, args, bounds, epsilon, 
finite_diff_rel_step, hess)
259     # ScalarFunction caches. Reuse of fun(x) during grad
260     # calculation reduces overall function evaluations.
--> 261     sf = ScalarFunction(fun, x0, args, grad, hess,
262                         finite_diff_rel_step, bounds, 
epsilon=epsilon)
263 

~\Anaconda3\lib\site- 
packages\scipy\optimize\_differentiable_functions.py in 
__init__(self, fun, x0, args, grad, hess, finite_diff_rel_step, 
finite_diff_bounds, epsilon)
134 
135         self._update_fun_impl = update_fun
--> 136         self._update_fun()
137 
138         # Gradient evaluation

~\Anaconda3\lib\site- 
packages\scipy\optimize\_differentiable_functions.py in 
_update_fun(self)
224     def _update_fun(self):
225         if not self.f_updated:
--> 226             self._update_fun_impl()
227             self.f_updated = True
228 

~\Anaconda3\lib\site- 
packages\scipy\optimize\_differentiable_functions.py in update_fun()
131 
132         def update_fun():
--> 133             self.f = fun_wrapped(self.x)
134 
135         self._update_fun_impl = update_fun

~\Anaconda3\lib\site- 
packages\scipy\optimize\_differentiable_functions.py in 
fun_wrapped(x)
128         def fun_wrapped(x):
129             self.nfev += 1
--> 130             return fun(x, *args)
131 
132         def update_fun():

TypeError: newfunc() missing 1 required positional argument: 'H'

There is a number of questions with your code (and how you posted it):您的代码(以及您如何发布它)存在许多问题:

  • there are several unused imports;有几个未使用的进口;
  • there is a bunch of commented out code that apparently has no bearing on the problem, but there's also some code that doesn't do anything (like the assignments to xdat1 and ydat1 , which are repeated a few lines down;有一堆注释掉的代码显然与问题无关,但也有一些代码不做任何事情(比如对xdat1ydat1的赋值,它们重复了几行;
  • func has a parameter that's not used, tspan ; func有一个未使用的参数tspan
  • newfunc has parameter ki , k0 and H , but doesn't use them, instead it uses the global k0 , k1 and H0 ; newfunc有参数kik0H ,但不使用它们,而是使用全局k0k1H0 it also has a completely unused x ;它还有一个完全未使用的x

All of this indicates a very careless approach to coding which, even if it results in code that runs, rarely results in code that runs correctly.所有这些都表明了一种非常粗心的编码方法,即使它导致代码运行,也很少导致代码正确运行。 Try taking one step at a time.尝试一次迈出一步。 Only add code you know will work, or if you just try something and you think it works, try to find out why it works, so you don't inadvertently break it later.仅添加您知道会起作用的代码,或者如果您只是尝试某些东西并且您认为它起作用,请尝试找出它起作用的原因,这样您以后就不会无意中破坏它。

Also, with regard to the question:另外,关于这个问题:

  • indentation is completely gone, so that has to be guessed at;压痕完全消失了,所以必须猜测;
  • your code reads a.csv, but you didn't provide a sample of the data (like the header and a few lines of data, so people can try your code)您的代码读取 a.csv,但您没有提供数据样本(如 header 和几行数据,因此人们可以尝试您的代码)

This is your code with the superfluous lines removed and some arbitrary test data, which reproduces the error (some of the errors left in, since it's unclear what the impact is without further analysis):这是您删除了多余行和一些任意测试数据的代码,它重现了错误(留下了一些错误,因为在没有进一步分析的情况下不清楚影响是什么):

import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import minimize
import matplotlib.pylab as plt
import pandas as pd

df = pd.DataFrame([{'t3_1': 1., 'CMB3_1': 2.}, {'t3_1': 3., 'CMB3_1': 4.}])

xdat1 = np.asarray(df['t3_1'], dtype='float')
ydat1 = np.asarray(df['CMB3_1'], dtype='float')

plt.plot(xdat1, ydat1, 'ob', markersize=2)
plt.xscale('log')
plt.show()


def func(tspan, ko, ki, phi, H):
    dphidt = ko * (1 - phi) * H
    dHdt = -ki * phi * H
    return [dphidt, dHdt]


H0 = [0.04818]
k0 = 0.0125
k1 = 0.00051
k = [k0, k1]
tspan = [0, max(xdat1)]


def newfunc(ko, ki, x, y, H):
    tspan = [0, max(xdat1)]
    y0 = [0, 0.04818]
    result = solve_ivp(func, tspan, y0, method='RK45', args=(k0, k1, H0), dense_output=True)
    resultnew = result.sol(tspan).T
    ephi = y - resultnew[:, 0]
    sumephi = np.sum((ephi ** 2))
    return sumephi


wguess = (k0, k1)
arguments = (xdat1, ydat1, H0)
res = minimize(newfunc, np.array(wguess), args=arguments, method='bfgs')

One problem is clear: newfunc is supposed to be minimized, but you provide the tuple (k0, k1) as a guess, while minimize expects an ndarray - a cast fixes that.一个问题很清楚: newfunc应该被最小化,但是您提供元组(k0, k1)作为猜测,而minimize需要一个ndarray - 演员表修复了这个问题。

But then the actual error you see: TypeError: newfunc() missing 1 required positional argument: 'H' .但是你看到的实际错误是: TypeError: newfunc() missing 1 required positional argument: 'H' This also makes sense, minimize will call newfunc with an array and arguments ( fun(x, *args) -> float ), as per the documentation of scipy.optimize.minimize .这也是有道理的, newfunc的文档, minimize将使用数组和arguments ( fun(x, *args) -> float ) 调用 newfunc However, 1 array + 3 arguments makes 4, while newfunc expects 5 arguments.但是,1 个数组 + 3 个 arguments 为 4,而newfunc预计为 5 个 arguments。 Perhaps you expected the elements of the tuple to be passed separately (it seems that way, from the naming), but changing newfunc to accommodate that causes new problems;也许您希望元组的元素单独传递(从命名来看似乎是这样),但是更改newfunc以适应这会导致新问题; here's the latter part of your code with the superfluous variables removed, and the passed variables used:这是代码的后半部分,删除了多余的变量,并使用了传递的变量:

def newfunc(a, y, H):
    ko, ki = a
    tspan = [0, max(xdat1)]
    y0 = [0, 0.04818]
    result = solve_ivp(func, tspan, y0, method='RK45', args=(ko, ki, H), dense_output=True)
    resultnew = result.sol(tspan).T
    ephi = y - resultnew[:, 0]
    sumephi = np.sum((ephi ** 2))
    return sumephi


wguess = (k0, k1)
arguments = (ydat1, H0)
res = minimize(newfunc, np.array(wguess), args=arguments, method='bfgs')

However, this results in a new error: TypeError: can't multiply sequence by non-int of type 'numpy.float64' .但是,这会导致一个新错误: TypeError: can't multiply sequence by non-int of type 'numpy.float64' Again, not a surprise, since your line: dHdt = -ki * phi * H takes two floats and tries to multiply them with a list ( H ).同样,这并不奇怪,因为您的行: dHdt = -ki * phi * H需要两个浮点数并尝试将它们与列表( H )相乘。

Replacing H with a single value causes further errors.用单个值替换H会导致更多错误。 Since it's not clear what your code is even supposed to do without further analysis and a deeper understanding of what your code is even for, I think you should take the approach of rewriting it - do it a small part at a time, ensuring what you write works before adding more and ensuring you know what what you write means.由于不清楚您的代码甚至应该做什么,而无需进一步分析和更深入地了解您的代码的用途,我认为您应该采用重写它的方法 - 一次只做一小部分,确保您在添加更多内容之前编写作品,并确保您知道您所写的意思。

You'll note that several people voted down your question - this likely due to them grabbing a copy of your code and trying to run it like myself (or just reading it here), and concluding that you have overlooked some very basic problems in code that has many such problems.您会注意到有几个人对您的问题投了反对票——这可能是因为他们获取了您的代码副本并尝试像我一样运行它(或者只是在这里阅读),并得出结论认为您忽略了一些非常基本的代码问题有很多这样的问题。

I think my question answers your question why you're getting that error message, but fixing your program will require some work on your part.我认为我的问题回答了您为什么会收到该错误消息的问题,但是修复程序需要您做一些工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM