Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

r - How to use the lambda argument of smooth.spline in RPy WITHOUT Python interprating it as lambda

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)

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...