Skip to main content
 首页 » 编程设计

python之如何计算 tensorflow 中的阶乘

2025年05月04日23mq0036

我是 tensorflow 的新手,我正在尝试找到一个计算 n! 的函数。 我看到可以使用 gamma 函数,这对于 theano 是可行的,但不适用于 tensorflow。

factorial = theano.tensor.gamma(v) 

我正在使用 for 循环将数字从 n 乘以 1,但我认为有更简单快捷的方法。我看到了与 Gamma 分布相关的函数,但无法弄清楚如何计算阶乘。如果有人能指出一些文档,我将不胜感激。

这是我现在的做法

import tensorflow as tf 
 
factorial = tf.Variable(1, "factorial") 
recursion = tf.Variable(1, "recursion") 
 
# calculate factorial 
mult = tf.multiply(recursion, factorial) 
assign_fact = tf.assign(factorial, mult) 
 
init = tf.global_variables_initializer() 
 
with tf.Session() as sess: 
    sess.run(init)  
    for i in range(2,10): 
        counter = tf.assign(recursion, tf.constant(i)) 
        sess.run(counter) 
        sess.run(assign_fact) 
 
        print(i,"factorial is", sess.run(factorial)) 
 
    sess.close() 

输出是

2 factorial is 2 
3 factorial is 6 
4 factorial is 24 
5 factorial is 120 
6 factorial is 720 
7 factorial is 5040 
8 factorial is 40320 
9 factorial is 362880 

请您参考如下方法:

试试这个:tf.exp(tf.lgamma(x + 1))。

tf.lgamma按元素计算 Gamma(x) 绝对值的对数,因此指数将为您提供原始 Gamma(x) 值:

>>> sess.run(tf.exp(tf.lgamma(5.0))) 
24.0