Erf and erfinv functions in PyTorch
I have a torch.FloatTensor say A of size u,v,x,y. I have to calculate its erf and erfinv. Is there any way to do this in PyTorch. Please help me.
Soniya
What is Erf (and what is it’s inverse)? Is this an abbreviation?
smth
Soniya
I’m actually interested by this as well, could you give us some updates if you find a solution?
hadware
<SCODE>import torch
from scipy import special
## reference - https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.special.erf.html

u = 1
v = 2
x = 3
y = 4

A = torch.randn(u,v,x,y)

special.erf( A.numpy() )
special.erfinv( A.numpy())
<ECODE>
AjayTalati
Soniya
Nope, it does not work, because I also need the error function but as an autograd function; I mean, I would like to insert this function in the computation graph and pytorch to automatically differentiate it ! If the function is not supported for now in pytorch, may I define my own custom autograd function ?
cerisara
AjayTalati
<SCODE>import torch
a_for_erf = 8.0/(3.0*numpy.pi)*(numpy.pi-3.0)/(4.0-numpy.pi)
def erf_approx(x):
    return torch.sign(x)*torch.sqrt(1-torch.exp(-x*x*(4/numpy.pi+a_for_erf*x*x)/(1+a_for_erf*x*x)))
def erfinv_approx(x):
    b = -2/(numpy.pi*a_for_erf)-torch.log(1-x*x)/2
    return torch.sign(x)*torch.sqrt(b+torch.sqrt(b*b-torch.log(1-x*x)/a_for_erf))<ECODE> To get an impression of how they look, you could plot it against the scipy.special functions like <SCODE>from matplotlib import pyplot
%matplotlib inline
import scipy.special
x = numpy.linspace(-2,2,100)
pyplot.subplot(1,2,1)
pyplot.title('erf')
pyplot.plot(x,erf_approx(torch.from_numpy(x)).numpy(), label="approx")
pyplot.plot(x,scipy.special.erf(x),'--', label="scipy")
pyplot.legend()
pyplot.subplot(1,2,2)
y = scipy.special.erf(x)
pyplot.title('erfinv')
pyplot.plot(y,erfinv_approx(torch.from_numpy(y)).numpy(), label="approx")
pyplot.plot(y,scipy.special.erfinv(y),'--', label="scipy")
pyplot.legend()<ECODE> (the %matplotlib is for jupyter). Best regards Thomas
tom
nice work !!! I found a very simple implementation of the sinkhorn-knopp matrix normalisation, we were looking at a while ago. It’s in MATLAB, but it’s very understandable, All the best, Aj
AjayTalati
Great ! Thank you, very useful !
cerisara
One use case that I needed was to sample from a Gaussian VAE and do interpolation in uniform distributed variables. That is because u = erfinv(v) follows normal distribution if v follows uniform distribution via a technique called inverse sampling.
zhangxiangxiao
ira
Awesome, thank you! Best regards Thomas
tom
MAsad