我有下面的代码,我想将其翻译成 pytorch。在这种情况下,我正在寻找一种将 np.vectorize 转换为任何 pytorch 方式的方法

I have the code below which I want to translate into pytorch. I'm looking for a way to translate np.vectorize to any pytorch way in this case

我需要将这段代码翻译成pytorch。下面给出的代码使用 np.vectorize。我正在为此寻找等效的 pytorch。

class SimplexPotentialProjection(object):
    def __init__(self, potential, inversePotential, strong_convexity_const, precision = 1e-10):
        self.inversePotential = inversePotential
        self.gradPsi = np.vectorize(potential)
        self.gradPsiInverse = np.vectorize(inversePotential)
        self.precision = precision
        self.strong_convexity_const = strong_convexity_const

numpy.vectorize 的文档明确指出:

The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.

因此,为了转换您的 code to ,您只需要在张量参数的循环中应用 potentialinversePotential。 但是,这可能非常低效。您最好 re-implement 您的函数以矢量化方式“本地”作用于张量。