如何在拟合期间向曲线而不是数据点添加权重?我使用什么导入/函数?

如何解决如何在拟合期间向曲线而不是数据点添加权重?我使用什么导入/函数?

我试过 scipy.optimize import curve_fit 但它似乎只改变了数据点。我想在从我的数据点残差(带权重的最小平方)拟合 Ycurve 期间添加 1/Y^2 权重。我不确定如何定位 yfit 而不是 ydata 或者我是否应该使用其他东西?任何帮助将不胜感激。

xdata = np.array([0.10,0.10,1.12,2.89,6.19,23.30,108.98,255.33,1188.62,1188.62],dtype=float)

ydata = np.array([0.264352,0.412386,0.231238,0.483558,0.613206,0.728528,-1.15391,-1.46504,-0.942926,-2.12808,-2.90962,-1.51093,-3.09798,-5.08591,-4.75703,-4.91317,-5.1966,-4.04019,-13.8455,-16.9911,-11.0881,-10.6453,-15.1288,-52.4669,-68.2344,-74.7673,-70.2025,-65.8181,-55.7344,-271.286,-329.521,-436.097,-654.034,-396.45,-826.195,-1084.43,-984.344,-1124.8,-1076.27,-1072.03,-3968.22,-3114.46,-3771.61,-2805.4,-4078.05],dtype=float)

def fourPL(x,A,B,C,D):
    return ((A-D)/(1.0+((x/C)**B))) + D

params,params_covariance = spo.curve_fit(fourPL,xdata,ydata)
params_list = params
roundy = [round(num,4) for num in params_list]
print(roundy)

popt2,pcov2 = spo.curve_fit(fourPL,ydata,sigma=1/ydata**2,absolute_sigma=True)
yfit2 = fourPL(xdata,*popt2)
params_list2 = popt2
roundy2 = [round(num,4) for num in params_list2]
print(roundy2)

x_min,x_max = np.amin(xdata),np.amax(xdata)
xs = np.linspace(x_min,x_max,1000)
plt.scatter(xdata,ydata)
plt.plot(xs,fourPL(xs,*params),'m--',label='No Weight')
plt.plot(xs,*popt2),'b--',label='Weights')
plt.legend(loc='upper center',bbox_to_anchor=(0.5,1.05,0.1,0.1),ncol=3,fancybox=True,shadow=True)
plt.xlabel('µg/mL)')
plt.ylabel('kHz/s')
#plt.xscale('log')
plt.show()
```

解决方法

这将是我使用手动 least_squares 拟合的版本。我将它与使用简单的 curve_fit 获得的解决方案进行了比较。实际上差异不是很大,curve_fit 的结果对我来说看起来不错。

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import least_squares
from scipy.optimize import curve_fit

np.set_printoptions( linewidth=250,precision=2 )  ## avoids OPs "roundy"

xdata = np.array(
    [
        0.10,0.10,1.12,2.89,6.19,23.30,108.98,255.33,1188.62,1188.62
    ],dtype=float
)

ydata = np.array(
    [
        0.264352,0.412386,0.231238,0.483558,0.613206,0.728528,-1.15391,-1.46504,-0.942926,-2.12808,-2.90962,-1.51093,-3.09798,-5.08591,-4.75703,-4.91317,-5.1966,-4.04019,-13.8455,-16.9911,-11.0881,-10.6453,-15.1288,-52.4669,-68.2344,-74.7673,-70.2025,-65.8181,-55.7344,-271.286,-329.521,-436.097,-654.034,-396.45,-826.195,-1084.43,-984.344,-1124.8,-1076.27,-1072.03,-3968.22,-3114.46,-3771.61,-2805.4,-4078.05
    ],dtype=float
)

def fourPL( x,a,b,c,d ):
    out = ( a - d ) / ( 1 + ( x / c )**b ) + d
    return out

def residuals( params,xlist,ylist ):
    # ~a,d = params
    yth = np.fromiter( (fourPL( x,*params ) for x in xlist ),np.float )
    diff = np.subtract( yth,ylist )
    weights = 1 / np.abs( yth )**1
    ## not sure if this makes sense,but we weigth with function value
    ## here I put it inverse linear as it gets squared in the chi-square
    ## but other weighting may be required
    return diff * weights

### for initial guess
xl = np.linspace( .1,1200,150 )
yl0 = np.fromiter( (fourPL( x,1,1000,-6000) for x in xl ),np.float )

### standard curve_fit
cfsol,_ = curve_fit( fourPL,xdata,ydata,p0=( 1,-6000 ) )
print( cfsol )
yl1 = np.fromiter( (fourPL( x,*cfsol ) for x in xl ),np.float )

### least square with manual residual function including "unusual" weighting
lssol = least_squares( residuals,x0=( 1,-6000 ),args=( xdata,ydata ) )
print( lssol.x )
yl2 = np.fromiter( (fourPL( x,*( lssol.x ) ) for x in xl ),np.float )

### plotting
fig = plt.figure()
ax = fig.add_subplot( 1,1 )
ax.scatter( xdata,ydata )
ax.plot( xl,yl1 )
ax.plot( xl,yl2 )

plt.show()

two fit variants

查看协方差矩阵,不仅显示出相当大的误差,而且参数的相关性也相当高。这当然是由模型的性质决定的,但应谨慎处理,尤其是在数据解释方面。

当我们只考虑小 x 的数据时,问题变得更加明显。无论如何,大 x 的数据分散很多。对于小x或大c,泰勒展开式是(a - d ) (1 - b x / c ) + d,即a - (a - d ) b / c x,基本上是a + e x。所以 bcd 基本上都是一样的。

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

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res