H-state 2020-07-10 10:55 采纳率: 0%
浏览 252

使用symfit进行傅立叶拟合报错,小白求助

官方doc里面的代码运行不了,报错信息看不太明白,第一次提问,求大佬们帮助

https://symfit.readthedocs.io/en/stable/examples/ex_fourier_series.html

doc里面完全一样的代码,非常简单,用3阶傅立叶函数拟合一下曲线,运行一下很快。我是使用python3运行的

from symfit import parameters, variables, sin, cos, Fit
import numpy as np
import matplotlib.pyplot as plt

def fourier_series(x, f, n=0):
    """
    Returns a symbolic fourier series of order `n`.

    :param n: Order of the fourier series.
    :param x: Independent variable
    :param f: Frequency of the fourier series
    """
    # Make the parameter objects for all the terms
    a0, *cos_a = parameters(','.join(['a{}'.format(i) for i in range(0, n + 1)]))
    sin_b = parameters(','.join(['b{}'.format(i) for i in range(1, n + 1)]))
    # Construct the series
    series = a0 + sum(ai * cos(i * f * x) + bi * sin(i * f * x)
                     for i, (ai, bi) in enumerate(zip(cos_a, sin_b), start=1))
    return series

x, y = variables('x, y')
w, = parameters('w')
model_dict = {y: fourier_series(x, f=w, n=3)}
print(model_dict)

# Make step function data
xdata = np.linspace(-np.pi, np.pi)
ydata = np.zeros_like(xdata)
ydata[xdata > 0] = 1
# Define a Fit object for this model and data
fit = Fit(model_dict, x=xdata, y=ydata)
fit_result = fit.execute()
print(fit_result)

# Plot the result
plt.plot(xdata, ydata)
plt.plot(xdata, fit.model(x=xdata, **fit_result.params).y, ls=':')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

报错信息如下:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/support.py in __get__(self, obj, objtype)
    281         try:
--> 282             return getattr(obj, self.cache_attr)
    283         except AttributeError:

AttributeError: 'Model' object has no attribute '_cached_jacobian_model'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
<ipython-input-4-cf0c44a47642> in <module>()
     29 # Define a Fit object for this model and data
     30 fit = Fit(model_dict, x=xdata, y=ydata)
---> 31 fit_result = fit.execute()
     32 print(fit_result)
     33 

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/fit.py in execute(self, **minimize_options)
    577         :return: FitResults instance
    578         """
--> 579         minimizer_ans = self.minimizer.execute(**minimize_options)
    580         minimizer_ans.covariance_matrix = self.covariance_matrix(
    581             dict(zip(self.model.params, minimizer_ans._popt))

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/support.py in wrapped_func(*args, **kwargs)
    421                     else:
    422                         bound_args.arguments[param.name] = param.default
--> 423             return func(*bound_args.args, **bound_args.kwargs)
    424         return wrapped_func
    425 

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/minimizers.py in execute(self, **minimize_options)
    408         if jacobian is None:
    409             jacobian = self.wrapped_jacobian
--> 410         return super(ScipyGradientMinimize, self).execute(jacobian=jacobian, **minimize_options)
    411 
    412     def scipy_constraints(self, constraints):

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/support.py in wrapped_func(*args, **kwargs)
    421                     else:
    422                         bound_args.arguments[param.name] = param.default
--> 423             return func(*bound_args.args, **bound_args.kwargs)
    424         return wrapped_func
    425 

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/minimizers.py in execute(self, bounds, jacobian, hessian, constraints, **minimize_options)
    353             jac=jacobian,
    354             hess=hessian,
--> 355             **minimize_options
    356         )
    357         return self._pack_output(ans)

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
    595         return _minimize_cg(fun, x0, args, jac, callback, **options)
    596     elif meth == 'bfgs':
--> 597         return _minimize_bfgs(fun, x0, args, jac, callback, **options)
    598     elif meth == 'newton-cg':
    599         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/optimize.py in _minimize_bfgs(fun, x0, args, jac, callback, gtol, norm, eps, maxiter, disp, return_all, **unknown_options)
    961     else:
    962         grad_calls, myfprime = wrap_function(fprime, args)
--> 963     gfk = myfprime(x0)
    964     k = 0
    965     N = len(x0)

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/optimize.py in function_wrapper(*wrapper_args)
    291     def function_wrapper(*wrapper_args):
    292         ncalls[0] += 1
--> 293         return function(*(wrapper_args + args))
    294 
    295     return ncalls, function_wrapper

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/minimizers.py in resized(*args, **kwargs)
    155         @wraps(func)
    156         def resized(*args, **kwargs):
--> 157             out = func(*args, **kwargs)
    158             # Make one dimensional, corresponding to a scalar function.
    159             out = np.atleast_1d(np.squeeze(out))

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/objectives.py in eval_jacobian(self, ordered_parameters, **parameters)
    337         )
    338         evaluated_jac = super(LeastSquares, self).eval_jacobian(
--> 339             ordered_parameters, **parameters
    340         )
    341 

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/objectives.py in eval_jacobian(self, ordered_parameters, **parameters)
    195         parameters.update(dict(zip(self.model.free_params, ordered_parameters)))
    196         parameters.update(self._invariant_kwargs)
--> 197         result = self.model.eval_jacobian(**key2str(parameters))._asdict()
    198         # Return only the components corresponding to the dependent data.
    199         return self._shape_of_dependent_data(

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/models.py in eval_jacobian(self, *args, **kwargs)
    851         :return: Jacobian evaluated at the specified point.
    852         """
--> 853         eval_jac_dict = self.jacobian_model(*args, **kwargs)._asdict()
    854         # Take zero for component which are not present, happens for Constraints
    855         jac = [[np.broadcast_to(eval_jac_dict.get(D(var, param), 0),

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/support.py in __get__(self, obj, objtype)
    283         except AttributeError:
    284             # Call the wrapped function with the obj instance as argument
--> 285             setattr(obj, self.cache_attr, self.fget(obj))
    286             return getattr(obj, self.cache_attr)
    287 

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/models.py in jacobian_model(self)
    825     @cached_property
    826     def jacobian_model(self):
--> 827         jac_model = jacobian_from_model(self)
    828         jac_model.params = self.params
    829         return jac_model

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/models.py in jacobian_from_model(model, as_functions)
   1252         jac.update({y: expr.subs(functions_as_vars, evaluate=False)
   1253                     for y, expr in model.items()})
-> 1254     jacobian_model = CallableModel(jac)
   1255     return jacobian_model
   1256 

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/models.py in __init__(self, model)
    122             # should be introduced to fulfill the same role.
    123             model = {Variable(): expr for expr in model}
--> 124         self._init_from_dict(model)
    125 
    126     @classmethod

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/models.py in _init_from_dict(self, model_dict)
    648 
    649     def _init_from_dict(self, model_dict):
--> 650         super(BaseCallableModel, self)._init_from_dict(model_dict)
    651         self.__signature__ = self._make_signature()
    652 

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/models.py in _init_from_dict(self, model_dict)
    303         sort_func = lambda symbol: symbol.name
    304         self.model_dict = OrderedDict(sorted(model_dict.items(),
--> 305                                              key=lambda i: sort_func(i[0])))
    306         # Everything at the bottom of the toposort is independent, at the top
    307         # dependent, and the rest interdependent.

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/models.py in <lambda>(i)
    303         sort_func = lambda symbol: symbol.name
    304         self.model_dict = OrderedDict(sorted(model_dict.items(),
--> 305                                              key=lambda i: sort_func(i[0])))
    306         # Everything at the bottom of the toposort is independent, at the top
    307         # dependent, and the rest interdependent.

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/models.py in <lambda>(symbol)
    301         :param model_dict: dict of (dependent_var, expression) pairs.
    302         """
--> 303         sort_func = lambda symbol: symbol.name
    304         self.model_dict = OrderedDict(sorted(model_dict.items(),
    305                                              key=lambda i: sort_func(i[0])))

~/software/ciao/ciao-4.11/ots/lib/python3.5/site-packages/symfit/core/support.py in name(self)
    436     """
    437     base_str = 'd{}{}_'.format(self.derivative_count if
--> 438                                self.derivative_count > 1 else '', self.expr)
    439     for var, count in self.variable_count:
    440         base_str += 'd{}{}'.format(var,  count if count > 1 else '')

AttributeError: 'Derivative' object has no attribute 'derivative_count'

谢谢大家的时间

  • 写回答

2条回答 默认 最新

  • zqbnqsdsmd 2020-08-01 22:12
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码