python 最大值最小化,Python-最小化卡方

问题是你最初的猜测与实际的解决方案相去甚远。如果在chisqfunc()中添加一个print语句,比如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时,varstress的数量级太多,大于model,结果被截断。

然后可以尝试对其进行粗处理,增加浮点精度,在用loadtxt加载数据之后写入data=data.astype(np.float128)。minimize失败,有result.success=False,但有一条有用的消息Desired error not necessarily achieved due to precision loss.

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

如果你只是重新缩放数据,例如使某个应力值无量纲(比如这种材料的嘶嘶声/破裂声),会好得多

这是拟合的一个例子,使用最大测量应力作为应力标度。代码中很少有更改: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)

你的线性模型很好,也就是说,你的材料在这个变形范围内有一个非常线性的行为(它到底是什么材料?):

hny8S.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Python中的`scipy.stats`库来进行卡方检验,并使用`matplotlib`库来可视化结果。下面是一个简单的示例代码: ```python import numpy as np from scipy import stats import matplotlib.pyplot as plt # 创建两个分类变量的观察值 observed = np.array([[10, 15, 25], [30, 40, 15]]) # 执行卡方检验 chi2, p, dof, expected = stats.chi2_contingency(observed) # 可视化卡方检验结果 labels = ['Category 1', 'Category 2', 'Category 3'] x = np.arange(len(labels)) width = 0.35 fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, observed[0], width, label='Observed 1') rects2 = ax.bar(x + width/2, observed[1], width, label='Observed 2') ax.set_ylabel('Frequency') ax.set_title('Observed Frequencies by Category') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() fig.tight_layout() plt.show() ``` 这段代码中,我们首先创建了一个包含两个分类变量的观察值的数组`observed`。然后,我们使用`scipy.stats`库中的`chi2_contingency()`函数执行卡方检验,得到卡方值`chi2`、p值`p`、自由度`dof`和期望频率`expected`。 接下来,我们使用`matplotlib.pyplot`库绘制了一个柱状图,分别展示了两个分类变量的观察频率。横轴表示不同的分类,纵轴表示观察频率。其中,`rects1`表示第一个分类变量的观察频率,`rects2`表示第二个分类变量的观察频率。 最后,我们通过调用`plt.show()`函数显示出可视化结果。 希望这个示例对你有所帮助!如果有任何疑问,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值