问题是你最初的猜测与实际的解决方案相差甚远。如果你在里面添加一条打印语句chisqfunc()
like print (a,b)
,然后重新运行你的代码,你会得到类似的结果:
(0, 0)
(1.4901161193847656e-08, 0.0)
(0.0, 1.4901161193847656e-08)
这意味着minimize
仅在这些点评估函数。
如果你现在尝试评估chisqfunc()
在这 3 对值中,您会发现它们完全匹配,例如
print chisqfunc((0,0))==chisqfunc((1.4901161193847656e-08,0))
True
发生这种情况是因为对浮点运算进行舍入。换句话说,在评估时stress - model
, 变量stress
比大了太多数量级model
,并且结果被截断。
然后,人们可以尝试暴力破解它,提高浮点精度,并编写data=data.astype(np.float128)
加载数据后loadtxt
. minimize
失败,与result.success=False
,但有一条有用的消息
由于精度损失,不一定能实现所需的误差。
一种可能性是提供更好的初始猜测,以便在减法中stress - model
the model
一部分具有相同的数量级,另一部分重新调整数据,使解决方案更接近您最初的猜测(0,0)
.
It is MUCH如果您只是重新缩放数据,例如相对于特定应力值(例如这种材料的屈服/开裂),则变得无量纲会更好
这是一个拟合示例,使用最大测量应力作为应力标度。您的代码几乎没有变化:
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)
Your linear model is quite good, i.e. your material has a very linear behaviour for this range of deformation (what material is it anyway?):