如何使用scipy.special.expi公司张量流中的指数积分?

2024-10-09 20:17:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我得编码scipy.special.expi公司但我不知道怎么做!!!! 拜托,有人,救命 因为在tensorflow中没有这样的直接代码,所以我被困在这里 请帮忙!!!你知道吗


Tags: 代码编码tensorflow公司scipyspecialexpi
1条回答
网友
1楼 · 发布于 2024-10-09 20:17:12

我对这个函数了解不多,但是基于SciPy中的Fortran实现,^{}中的函数EIX,我在那里的每个步骤后面都放了一个TensorFlow实现。不过,这只适用于正值,因为负值的计算包含了一个更难矢量化的循环。你知道吗

import math
import tensorflow as tf

def expi(x):
    x = tf.convert_to_tensor(x)
    # When X is zero
    m_0 = tf.equal(x, 0)
    y_0 = -math.inf + tf.zeros_like(x)
    # When X is negative
    m_neg = x < 0
    # This should be -e1xb(-x) according to ScyPy
    # (negative exponential integral -1)
    # Here it is just left as NaN
    y_neg = math.nan + tf.zeros_like(x)
    # When X is less or equal to 40 - Power series around x = 0
    m_le40 = x <= 40
    k = tf.range(1, 101, dtype=x.dtype)
    r = tf.cumprod(tf.expand_dims(x, -1) * k / tf.square(k + 1), axis=-1)
    ga = tf.constant(0.5772156649015328, dtype=x.dtype)
    y_le40 = ga + tf.log(x) + x * (1 + tf.reduce_sum(r, axis=-1))
    # Otherwise (X is greater than 40) - Asymptotic expansion (the series is not convergent)
    k = tf.range(1, 21, dtype=x.dtype)
    r = tf.cumprod(k / tf.expand_dims(x, -1), axis=-1)
    y_gt40 = tf.exp(x) / x * (1 + tf.reduce_sum(r, axis=-1))
    # Select values
    return tf.where(
        m_0, y_0, tf.where(
        m_neg, y_neg, tf.where(
        m_le40, y_le40, y_gt40)))

小测验

import tensorflow as tf
import scipy.special
import numpy as np

# Test
x = np.linspace(0, 100, 20)
y = scipy.special.expi(x)
with tf.Graph().as_default(), tf.Session() as sess:
    y_tf = sess.run(expi(x))
print(np.allclose(y, y_tf))
# True

但是请注意,这将比SciPy占用更多的内存,因为它在内存中展开近似循环,而不是一次计算一步。你知道吗

相关问题 更多 >

    热门问题