Python 如何在Pytorch中进行三次样条插值和积分

Python 如何在Pytorch中进行三次样条插值和积分,python,pytorch,interpolation,numeric,Python,Pytorch,Interpolation,Numeric,在Pytorch中,是否有类似的三次样条插值?给定1D输入张量x和y,我想通过这些点进行插值,并在xs处对它们求值,以获得ys。另外,我需要一个积分函数,它可以找到Ys,样条曲线插值从x[0]到xs的积分。在Pytorch中,我使用autograd支持高效地实现了这一点 为了方便起见,我还将把代码放在这里 将matplotlib.pylab作为P导入 进口火炬 def h_poly_助手(tt): A=T张量([ [1, 0, -3, 2], [0, 1, -2, 1], [0, 0, 3, -

在Pytorch中,是否有类似的三次样条插值?给定1D输入张量
x
y
,我想通过这些点进行插值,并在
xs
处对它们求值,以获得
ys
。另外,我需要一个积分函数,它可以找到
Ys
,样条曲线插值从
x[0]
xs

的积分。在Pytorch中,我使用autograd支持高效地实现了这一点

为了方便起见,我还将把代码放在这里

将matplotlib.pylab作为P导入
进口火炬
def h_poly_助手(tt):
A=T张量([
[1, 0, -3, 2],
[0, 1, -2, 1],
[0, 0, 3, -2],
[0, 0, -1, 1]
],dtype=tt[-1].dtype)
返回[
总和(范围(4)内j的A[i,j]*tt[j]
对于范围(4)内的i)
def h_poly(t):
tt=[范围(4)内的uu无]
tt[0]=1
对于范围(1,4)内的i:
tt[i]=tt[i-1]*t
返回h_poly_helper(tt)
def H_poly(t):
tt=[范围(4)内的uu无]
tt[0]=t
对于范围(1,4)内的i:
tt[i]=tt[i-1]*t*i/(i+1)
返回h_poly_helper(tt)
def界面(x、y、xs):
m=(y[1:]-y[:-1])/(x[1:]-x[:-1])
m=T.cat([m[[0]],(m[1:][m[:-1])/2,m[-1]]))
I=P.searchsorted(x[1:],xs)
dx=(x[I+1]-x[I])
hh=h_poly((xs-x[I])/dx)
返回hh[0]*y[I]+hh[1]*m[I]*dx+hh[2]*y[I+1]+hh[3]*m[I+1]*dx
定义整数(x,y,xs):
m=(y[1:]-y[:-1])/(x[1:]-x[:-1])
m=T.cat([m[[0]],(m[1:][m[:-1])/2,m[-1]]))
I=P.searchsorted(x[1:],xs)
Y=T.zeros_like(Y)
Y[1::=(x[1:]-x[:-1])*(
(y[:-1]+y[1:])/2+(m[:-1]-m[1:])*(x[1:]-x[:-1])/12
)
Y=Y.cumsum(0)
dx=(x[I+1]-x[I])
hh=H_poly((xs-x[I])/dx)
返回Y[I]+dx*(
hh[0]*y[I]+hh[1]*m[I]*dx+hh[2]*y[I+1]+hh[3]*m[I+1]*dx
)
#范例
如果名称=“\uuuuu main\uuuuuuuu”:
x=T.linspace(0,6,7)
y=x.sin()
xs=T.linspace(0,6101)
ys=interp(x,y,xs)
Ys=整数(x,y,xs)
P.散射(x,y,标签='样本',颜色='紫色')
P.绘图(xs,ys,label='Interpolated curve')
P.plot(xs,xs.sin(),'--',label='True Curve')
P.plot(xs,Ys,label='Spline Integral')
P.plot(xs,1-xs.cos(),'--',label='True Integral')
P.图例()
P.show()

这是对@chausies答案的评论,但太长,无法发布

我只是想发布他的答案的一个稍微缩小的版本,主要是为了我自己将来的参考:

import torch

def h_poly(t):
    tt = t[None, :]**torch.arange(4, device=t.device)[:, None]
    A = torch.tensor([
        [1, 0, -3, 2],
        [0, 1, -2, 1],
        [0, 0, 3, -2],
        [0, 0, -1, 1]
    ], dtype=t.dtype, device=t.device)
    return A @ tt


def interp(x, y, xs):
    m = (y[1:] - y[:-1]) / (x[1:] - x[:-1])
    m = torch.cat([m[[0]], (m[1:] + m[:-1]) / 2, m[[-1]]])
    idxs = torch.searchsorted(x[1:], xs)
    dx = (x[idxs + 1] - x[idxs])
    hh = h_poly((xs - x[idxs]) / dx)
    return hh[0] * y[idxs] + hh[1] * m[idxs] * dx + hh[2] * y[idxs + 1] + hh[3] * m[idxs + 1] * dx

不知道为什么这会被否决?这和这个关于Pytorch中trapz函数的问题是一样的,它没有被否决。Stackoverflow支持以问答形式分享您的知识。Nice也将使用此功能。