拟合算法不接受我的数据

0 投票
2 回答
3599 浏览
提问于 2025-04-15 13:06

我正在使用这里描述的算法,把高斯钟形曲线拟合到我的数据上。

如果我用下面的方式生成我的数据数组:

x=linspace(1.,100.,100)
data= 17*exp(-((x-10)/3)**2)

一切都运行得很好。

但是如果我用下面的方式从文本文件中读取数据:

file = open("d:\\test7.txt")
arr=[]
data=[]


def column(matrix,i):
    return [row[i] for row in matrix]

for line in file.readlines():
    numbers=map(float, line.split())
    arr.append(numbers)
    
data = column(arr,300)
x=linspace(1.,115.,115)

我就会收到错误信息:

Traceback (most recent call last):
File "readmatrix.py", line 60, in <module>    fit(f, [mu, sigma, height], data)
File "readmatrix.py", line 42, in fit    if x is None: x = arange(y.shape[0])
AttributeError: 'list' object has no attribute 'shape'

就我所见,数据中的数值是正确的,它看起来像这样:

[0.108032, 0.86181600000000003, 1.386169, 3.2790530000000002, ... ]

有没有人知道我哪里出错了?

谢谢!

2 个回答

4

balpha的解决方案不对;正确的做法是通过numpy.array把我的列表转换成一个numpy数组。

谢谢你给我提示!

4

这个fit函数需要的数据格式是numpy数组(这种格式有一个叫做shape的属性),而不是列表(列表没有这个属性),所以才会出现AttributeError错误。

你需要把你的数据转换成numpy数组:

def column(matrix,i):
    return numpy.asarray([row[i] for row in matrix])

撰写回答