gpt4 book ai didi

Python - 最小化卡方

转载 作者:太空宇宙 更新时间:2023-11-03 10:47:27 24 4
gpt4 key购买 nike

我一直在尝试通过最小化卡方来将线性模型拟合到一组应力/应变数据。不幸的是,使用下面的代码并没有正确地最小化 chisqfunc 函数。它正在寻找初始条件下的最小值 x0,这是不正确的。我查看了 scipy.optimize 文档并测试了最小化其他正常工作的功能。您能否建议如何修复下面的代码或建议我可以使用的另一种方法,通过最小化卡方来将线性模型拟合到数据?

import numpy
import scipy.optimize as opt

filename = 'data.csv'

data = numpy.loadtxt(open(filename,"r"),delimiter=",")

stress = data[:,0]
strain = data[:,1]
err_stress = data[:,2]

def chisqfunc((a, b)):
model = a + b*strain
chisq = numpy.sum(((stress - model)/err_stress)**2)
return chisq

x0 = numpy.array([0,0])

result = opt.minimize(chisqfunc, x0)
print result

感谢您阅读我的问题,我们将不胜感激。

干杯,威尔

编辑:我目前使用的数据集:Link to data

最佳答案

问题在于您最初的猜测与实际解决方案相差甚远。如果您在 chisqfunc() 中添加打印语句,例如 print (a,b),然后重新运行您的代码,您将得到如下结果:

(0, 0)
(1.4901161193847656e-08, 0.0)
(0.0, 1.4901161193847656e-08)

这意味着 minimize 仅在这些点计算函数。

如果您现在尝试在这 3 对值上评估 chisqfunc(),您会看到它们完全匹配,例如

print chisqfunc((0,0))==chisqfunc((1.4901161193847656e-08,0))
True

发生这种情况是因为舍入浮点运算。换句话说,在评估 stress - model 时,var stressmodel 大了太多数量级,结果被截断了。

然后可以尝试暴力破解它,提高浮点精度,在使用 loadtxt 加载数据后写入 data=data.astype(np.float128)minimize 失败,返回 result.success=False,但有一条有用的消息

Desired error not necessarily achieved due to precision loss.

然后,一种可能性是提供更好的初始猜测,以便在减法 stress - model 中,model 部分具有相同的数量级,另一种可能是重新缩放数据,以便解决方案更接近您的初始猜测 (0,0)

MUCH 如果您只是重新缩放数据,则更好,例如,相对于某个应力值(例如这种 Material 的屈服/开裂)进行无量纲化

这是一个拟合示例,使用最大测量应力作为应力标度。您的代码几乎没有变化:

import numpy
import scipy.optimize as opt

filename = 'data.csv'

data = numpy.loadtxt(open(filename,"r"),delimiter=",")

stress = data[:,0]
strain = data[:,1]
err_stress = data[:,2]


smax = stress.max()
stress = stress/smax
#I am assuming the errors err_stress are in the same units of stress.
err_stress = err_stress/smax

def chisqfunc((a, b)):
model = a + b*strain
chisq = numpy.sum(((stress - model)/err_stress)**2)
return chisq

x0 = numpy.array([0,0])

result = opt.minimize(chisqfunc, x0)
print result
assert result.success==True
a,b=result.x*smax
plot(strain,stress*smax)
plot(strain,a+b*strain)

您的线性模型非常好,即您的 Material 在此变形范围内具有非常线性的行为(它到底是什么 Material ?): enter image description here

关于Python - 最小化卡方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22177576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com