小编Ain*_*heT的帖子

如何计算张量流中的阶乘?

我是tensorflow的新手,我试图找到一个计算n!的函数。我看到可以使用theano函数使用theamma函数,但不适用于tensorflow。

factorial = theano.tensor.gamma(v)
Run Code Online (Sandbox Code Playgroud)

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

这是我现在做的方式

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()
Run Code Online (Sandbox Code Playgroud)

输出是

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 …
Run Code Online (Sandbox Code Playgroud)

python factorial tensorflow

1
推荐指数
1
解决办法
1135
查看次数

标签 统计

factorial ×1

python ×1

tensorflow ×1