如何在RPy中使用smooth.spline的lambda参数而不用Python将其插入为lambda [英] How to use the lambda argument of smooth.spline in RPy WITHOUT Python interprating it as lambda

查看:121
本文介绍了如何在RPy中使用smooth.spline的lambda参数而不用Python将其插入为lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Python中使用R中的自然三次平滑样条线smooth.spline(就像许多其他人一样想要(是否有一个Python等效于R中的smooth.spline函数 https://morioh.com/p/eb4151821dc4 中所述,但我想直接设置lambda而不是spar:

I want to use the natural cubic smoothing splines smooth.spline from R in Python (like som many others want as well (Python natural smoothing splines, Is there a Python equivalent to the smooth.spline function in R, Python SciPy UnivariateSpline vs R smooth.spline, ...)) Therefore I am using rpy2 like described in https://morioh.com/p/eb4151821dc4, but I want to set directly lambda instead of spar:

import rpy2.robjects as robjects
r_y = robjects.FloatVector(y_train)
r_x = robjects.FloatVector(x_train)

r_smooth_spline = robjects.r['smooth.spline'] #extract R function# run smoothing function
spline1 = r_smooth_spline(x=r_x, y=r_y, lambda=42)
#alternative: spline1 = r_smooth_spline(x=r_x, y=r_y, spar=0.7) would work fine, but I would like to control lambda dirctly
ySpline=np.array(robjects.r['predict'](spline1,robjects.FloatVector(x_smooth)).rx2('y'))
plt.plot(x_smooth,ySpline)

当我这样做时,spline1 = r_smooth_spline(x=r_x, y=r_y, lambda=42)行不起作用,因为Python已经对lambda进行了预定义(您可以从lambda的蓝色代码突出显示中看到): 我希望将lambda解释为平滑惩罚参数lambda.

When I do this the line spline1 = r_smooth_spline(x=r_x, y=r_y, lambda=42) doesn't work because Python has already a predefined interpretation of lambda (you can see this from the blue code-highlighting of lambda) :( I want lambda to be interpreted as the smoothing penalty parameter lambda.

如果用spar替换lambda,我会得到自然的三次样条,但是我想直接控制lambda.

If I replace lambda by spar I would get a natural cubic spline, but I want to control lambda directly.

推荐答案

通过允许您在字符串中写入"lambda",此小技巧将解决您遇到的特定问题.

This little trick will work around the specific problem you're having, by allowing you to write "lambda" in a string.

kwargs = {"x": r_x, "y": r_y, "lambda":  42}
spline1 = r_smooth_spline(**kwargs)

通常,您可以使用元组和字典轻松传递参数容器.

In the general case, you can pass around argument containers easily with tuples and dicts.

# as normal
f = function("foo", "bar", my_kwarg="my_value")

# the same call using argument containers
args = ("foo", "bar")
kwargs = {"my_kwarg": "my_value"}
f = function(*args, **kwargs)

这篇关于如何在RPy中使用smooth.spline的lambda参数而不用Python将其插入为lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆