微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

TypeError:输入错误:N = 3不能超过M = 1,不确定我的尺寸有什么问题吗?

如何解决TypeError:输入错误:N = 3不能超过M = 1,不确定我的尺寸有什么问题吗?

我正在尝试将洛仑兹峰拟合到数据集中的一个峰。

我们得到了适合高斯的拟合,除了实际的拟合方程外,代码非常相似,因此我不确定我要去哪里。我没有看到为什么在使用curve_fit时尺寸出现问题。

以下是我的代码中的相关部分,可以更好地了解我在说什么。

读取CSV文件并对其进行修剪

import csv
import numpy as np 
import matplotlib.pyplot as plt 
from scipy.optimize import curve_fit
from matplotlib.ticker import StrMethodFormatter

#reading in the csv file 

with open("Data-Oscilloscope.csv") as csv_file: 

    csv_reader = csv.reader(csv_file,delimiter=",")
    time =[]
    voltage_raw = [] 

    for row in csv_reader:
        time.append(float(row[3]))
        voltage_raw.append(float(row[4]))
        print("voltage:",row[4])

#trimming the data 

trim_lower_index = 980
trim_upper_index = 1170

time_trim = time[trim_lower_index:trim_upper_index]
voltage_trim = voltage_raw[trim_lower_index:trim_upper_index]

给出的高斯拟合

#fitting the gaussian function 

def gauss_function(x,a,x0,sigma):
    return a*np.exp(-(x-x0)**2/(2*sigma**2))


popt,pcov = curve_fit(gauss_function,time_trim,voltage_trim,p0=[1,.4,0.1])
perr = np.sqrt(np.diag(pcov))

#plot of the gaussian fit 

plt.figure(2)
plt.plot(time_trim,gauss_function(time_trim,*popt),label = "fit")
plt.plot(time_trim,"-b")
plt.show()

我尝试的洛伦兹式拟合

#x is just the x values,a is the amplitude,x0 is the central value,and f is the full width at half max

def lorentz_function(x,f):
    w = f/2 #half width at half max
    return a*w/ [(x-x0)**2+w**2]

popt,pcov = curve_fit(lorentz_function,0.1])

运行此程序时出现错误提示

in至少sq引发TypeError(“输入错误:N =%s不能超过M =%s'%(n,m)) TypeError:输入错误:N = 3不能超过M = 1

我可能会丢失一些非常明显的东西,但看不到它。

提前谢谢! 编辑:我看了其他类似的问题并进行了解释,但看不到它们与我的代码如何匹配,因为输入的参数数量和维数应该很好,因为它们适用于高斯拟合。

解决方法

您没有显示完整的追溯/错误,所以我只能猜测它的发生位置。它可能正在查看lorentz_function返回的结果,并发现尺寸错误。因此,尽管错误是由您的函数产生的,但测试仍在其调用者中(在这种情况下为一两个级别)。

def optimize.curve_fit(
    f,xdata,ydata,p0=None,...    # p0=[1,.4,0.1]
    ...  
    res = leastsq(func,p0,...

curve_fit将任务传递给leastsq,任务开始于:

def optimize.leastsq(
    func,x0,args=(),...

    x0 = asarray(x0).flatten()
    n = len(x0)
    if not isinstance(args,tuple):
        args = (args,)
    shape,dtype = _check_func('leastsq','func',func,args,n)
    m = shape[0]

    if n > m:
        raise TypeError('Improper input: N=%s must not exceed M=%s' % (n,m))

我猜_check_func确实

 res = func(x0,*args)     # call your func with initial values

并返回res的形状。该错误表明,根据x0的形状所期望的结果与您的func的结果之间存在不匹配。

我猜想带有3个元素的p0就是在抱怨您的函数返回了1个元素的结果(由于[])。

lorentz是您的职责。您无需测试输出形状,以免出现此错误。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。