When using numpy I can use np.vectorize to vectorize a function that contains if statements in order for the function to accept array arguments. How can I do the same with torch in order for a function to accept tensor arguments?
For example, the final print statement in the code below will fail. How can I make this work?
import numpy as np
import torch as tc
def numpy_func(x):
return x if x > 0. else 0.
numpy_func = np.vectorize(numpy_func)
print('numpy function (scalar):', numpy_func(-1.))
print('numpy function (array):', numpy_func(np.array([-1., 0., 1.])))
def torch_func(x):
return x if x > 0. else 0.
print('torch function (scalar):', torch_func(-1.))
print('torch function (tensor):', torch_func(tc.tensor([-1., 0., 1.])))
return x.where(x > 0, 0)pytorchhasfunctorch.vmapbut doesn't yet supportifstatements and would requiretensorinputs.functorch.vmapdoesn't supportifyet...for i in x.size: x[i] = f(x[i]). You should be a mindful programmer and think about efficiency before you start implementing theifspaghetti for tensor manipulation