当 x 和 y 形状相同时,为什么我会得到“x 和 y 必须具有相同的第一维,但形状为 (1,) 和 (319,)”?

问题描述

我正在使用 lmfit 包来拟合我的数据的双指数函数。我首先从 CSV 文件获取 x 和 y 坐标值并绘制它们。它工作正常。其次,我正在定义一个 double_exponential 函数,并使用 lmfit 包,根据我的数据绘制 double_exponential 函数。 我已经打印出我的 x 和 y 值的长度(长度 = 319)以及它的形状,看看它们是否匹配(319,)。他们是这样!。但我仍然得到一个 'x 和 y 必须具有相同的第一维,但有形状 (1,) 和 (319,) ' 错误。我附上了下面的代码。任何解决此问题的建议都会有所帮助。

xData=[]
yData=[]
for file in files:
        basename = os.path.basename(file)
        file_name = os.path.splitext(basename)[0]
        # print(file_name)
        #File_List.append(file_name)

        with open(file,"r") as f_in:
            reader = csv.reader(f_in)
            next(reader)
            next(reader)
            for line in reader:
                try:
                    float_1,float_2 = float(line[0]),float(line[1])
                    xData=np.append(xData,float_1)
                    yData=np.append(yData,float_2)                  
                except ValueError:
                    continue
        xData = np.array(xData)
        yData = np.array(yData)
        plt.plot(xData,yData)
        plt.show()
        def double_exp(a,t,T):
            return a*np.exp(-t/T)
        print(xData.shape)
        print(yData.shape)        
        mod = Model(double_exp)
        result = mod.fit(yData,x=xData,a=1,t=1,T=1)
        result.plot()            
        xData=[]
        yData=[] 

我的回溯错误是:

(319,)
(319,)

C:\ANACONDA\lib\site-packages\lmfit\model.py:968: UserWarning: The keyword argument x does not match any arguments of the model function. It will be ignored.
  warnings.warn("The keyword argument %s does not " % name +
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-29-085a1a8ec72a> in <module>
     35         mod = Model(double_exp)
     36         result = mod.fit(yData,T=1)
---> 37         result.plot()
     38 
     39 

C:\ANACONDA\lib\site-packages\lmfit\model.py in wrapper(*args,**kws)
     48         @wraps(function)
     49         def wrapper(*args,**kws):
---> 50             return function(*args,**kws)
     51         return wrapper
     52 

C:\ANACONDA\lib\site-packages\lmfit\model.py in plot(self,datafmt,fitfmt,initfmt,xlabel,ylabel,yerr,numpoints,fig,data_kws,fit_kws,init_kws,ax_res_kws,ax_fit_kws,fig_kws,show_init,parse_complex)
   2115         ax_fit = fig.add_subplot(gs[1],sharex=ax_res,**ax_fit_kws)
   2116 
-> 2117         self.plot_fit(ax=ax_fit,datafmt=datafmt,fitfmt=fitfmt,yerr=yerr,2118                       initfmt=initfmt,xlabel=xlabel,ylabel=ylabel,2119                       numpoints=numpoints,data_kws=data_kws,C:\ANACONDA\lib\site-packages\lmfit\model.py in wrapper(*args,**kws)
     51         return wrapper
     52 

C:\ANACONDA\lib\site-packages\lmfit\model.py in plot_fit(self,ax,ax_kws,parse_complex)
   1890                         fmt=datafmt,label='data',**data_kws)
   1891         else:
-> 1892             ax.plot(x_array,reduce_complex(self.data),1893                     datafmt,**data_kws)
   1894 

C:\ANACONDA\lib\site-packages\matplotlib\axes\_axes.py in plot(self,scalex,scaley,data,*args,**kwargs)
   1741         """
   1742         kwargs = cbook.normalize_kwargs(kwargs,mlines.Line2D)
-> 1743         lines = [*self._get_lines(*args,data=data,**kwargs)]
   1744         for line in lines:
   1745             self.add_line(line)

C:\ANACONDA\lib\site-packages\matplotlib\axes\_base.py in __call__(self,**kwargs)
    271                 this += args[0],272                 args = args[1:]
--> 273             yield from self._plot_args(this,kwargs)
    274 
    275     def get_next_color(self):

C:\ANACONDA\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self,tup,kwargs)
    397 
    398         if x.shape[0] != y.shape[0]:
--> 399             raise ValueError(f"x and y must have same first dimension,but "
    400                              f"have shapes {x.shape} and {y.shape}")
    401         if x.ndim > 2 or y.ndim > 2:

ValueError: x and y must have same first dimension,but have shapes (1,) and (319,)

解决方法

错误消息会准确地告诉您问题所在:

UserWarning: The keyword argument x does not match any arguments of the model function. It will be ignored.

您为 x=xData 方法提供了 fit 的值,但您的函数 doubl_exp 不包含此变量。在这里,正如您针对 lmfit 提出的各种其他问题一样,最好的建议是:阅读文档并查看网站上提供的示例。它们可能会覆盖超过 95% 的用例,然后阅读 Python 给您的错误消息总是有帮助的 ;)