如何控制拆解嵌套参数的深度并将其作为单独的参数传递给Python函数?

如何解决如何控制拆解嵌套参数的深度并将其作为单独的参数传递给Python函数?

假设我们有一个NxM阵列。由此,我想将N行解压缩为1xM数组,并将它们作为单独的参数传递给Python函数。

一个示例场景是SciPy软件包optimize.curve_fit,它具有相当高的生产率,要求N个自变量必须作为numpy.ravelnumpy.vstack ed NxM数组传递(它们称为xdata),并且fit函数还需要采用单个NxM数组作为参数。显而易见的问题是,几乎所有N维模型函数都被规范地定义为f(x1,...,xN,params) not f(xdata,params)。实际上,optimize.curve_fit甚至要求先对fit函数进行numpy.ravel,即,它希望numpy.ravel(f(xdata,params))而不只是f(x1,params)。谁想到这个...

因此,无论如何,如果不想浪费时间来处理每个曲线拟合的数据结构,则需要一个可以插入optimize.curve_fit前面的小函数来处理这种拆包和重新打包操作( optimize.curve_fit确实应该首先完成这一项工作),以便可以以规范的,数学上干净的方式定义模型函数。拟合数据也是如此,它显然是作为数据点列自然生成的,例如CSV文件中(世界上没有任何测量设备可以生成NxM阵列)。

我已经完成了将长度为M的N个数据列重新打包到这些NxM数组中的工作(如上所述,可以使用numpy.ravelnumpy.vstack)。问题是,如何接口我的健身功能f(x1,params)

如果我这样做

def unpack(f,*args):
    return f(args)

然后Python不会停止将NxM数组拆分为长度为M的N个数组,而是将数组“分解”为一个长度为1的M个数组的N个数组。有没有办法限制拆解嵌套参数的级别?

或者,如果加星标的表达式不起作用,怎么办呢?

def unpack(f,xdata):
    import numpy as np
    N_rows = xdata.shape[0]
    args = [???]    # <=== How to do this,i.e. from N rows generate N arguments?
    return f(args)

更新:在Jake Levi's answer之后,我正在尝试以下方法:

def repack_for_curve_fit(f,xdata):
    '''
    This function unpacks the NxM-array with independent data for N predictors into N separate 1xM-arrays,passes them to the fit function as the first N arguments,and returns the flattened fit function for
    further processing with the scipy.optimize.curve_fit package.
    
    Parameters
    ----------
    f : callable
        N-dimensional fit function,f(x1,*params),must take N independent variables as first N
        arguments and the fit parameters as remaining arguments
    xdata : array_like
        NxM-array with independent data for N predictors
    '''
    import numpy as np
    return np.ravel( f(*(x.reshape(1,-1) for x in xdata)) )

但是,我遇到一个错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-39-51aaf66438c3> in <module>()
     26     # Do nonlinear curve fit using scipy.optimize.curve_fit,write fit results to TXT file
     27     params_init = (-7,-7,7)    # Specify initial guesses for fit parameters (default is 0)
---> 28     params_opt,params_cov = curve_fit(repack_for_curve_fit(fit_function,xyGrid),xyGrid,imgArrayFlattened,params_init)    # Run the fit,return optimized parameters and covariance matrix
     29     params_err = np.sqrt(np.diag(params_cov))    # Standard deviation of optimized parameters
     30     print(params_opt)

/home/davidra/Desktop/repack_for_curve_fit.py in repack_for_curve_fit(f,xdata)
     14     '''
     15     import numpy as np
---> 16     return np.ravel( f(*(x.reshape(1,-1) for x in xdata)) )

TypeError: fit_function() missing 4 required positional arguments: 'x0','y0','Imax',and 'FWHM'

这是拟合函数:

def fit_function(x,y,x0,y0,Imax,FWHM):
    '''
    Parameters
    ----------
    x,y : float
        X and Y coordinates
    x0 : float
        X offset
    y0 : float
        Y offset
    Imax : float
        Peak intensity
    FWHM : float
        Full width at half maximum
    '''
    import numpy as np
    
    return Imax * np.e * 4 * np.log(2) * ((x+x0)**2 + (y+y0)**2) / FWHM**2 * np.exp(-4 * np.log(2) * ((x+x0)**2 + (y+y0)**2) / FWHM**2)

fit_function被证明可以正常工作。问题出在哪里?

此外,我真的需要使用reshape吗?列表/元组理解本身是否已经将xdata数组中的行切出了?

解决方法

您是否正在寻找这种东西,IE将NxM数组中的N行解压缩为1xM数组,并将它们作为单独的参数传递给Python函数,如以下代码片段的底行所示?它使用的是未打包的生成器表达式(但您也可以通过用方括号替换*之后的括号来将其替换为未打包的列表推导)。

import numpy as np

def useful_function(*args):
    """
    This useful function takes N arguments,each of which should be a 1*M array,and prints each argument to the console,along with its shape. N and M are
    both variable.
    """
    for i,a in enumerate(args):
        print("Argument {} is {},with shape {}".format(i,a,a.shape))


n,m = 5,4
n_x_m_array = np.arange(n*m).reshape(n,m)

print("Input NxM array:")
print(n_x_m_array)

useful_function(*(row.reshape(1,-1) for row in n_x_m_array))

输出:

Input NxM array:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]]
Argument 0 is [[0 1 2 3]],with shape (1,4)
Argument 1 is [[4 5 6 7]],4)
Argument 2 is [[ 8  9 10 11]],4)
Argument 3 is [[12 13 14 15]],4)
Argument 4 is [[16 17 18 19]],4)

您是否对SciPy界面不满意,也许打开一个问题here来讨论这个问题更合适吗?还值得注意的是,如果将序列分解,列表推导,生成器表达式和/或lambda表达式正确组合起来,通常可以很容易地解决许多将输入参数重新格式化为API函数的格式的情况。这些,知道正确的窍门。

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

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 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 -&gt; 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(&quot;/hires&quot;) 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&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-