对于以下代码,我可以对n使用占位符,并通过进给来传递n吗? 我是tensorflow的新手。
n = int(input("Enter an integer: "))
one=tf.constant(1)
#increase
increasing_value=tf.Variable(0,name="increasing_value")
increasing_op=tf.assign_add(increasing_value,one)
#sum
sumvalue=tf.Variable(0,name="sumvalue")
sum_op=tf.assign_add(sumvalue,increasing_value)
init=tf.global_variables_initializer()
with tf.Session() as session:
session.run(init)
for _ in range (n):
session.run(increasing_op)
session.run(sum_op)
print(session.run(sumvalue))
答案 0 :(得分:0)
你可以试试吗?
n = tf.placeholder(tf.int32, name='n')
fedvalue = session.run( n , feed_dict = { n : 10 })
for _ in range ( fedvalue ):
session.run(increasing_op)
session.run(sum_op)
答案 1 :(得分:0)
您可以使用tf.while_loop
在TensorFlow中复制代码。
import tensorflow as tf
n = tf.placeholder(tf.int32, [])
increasing_value = tf.constant(0, dtype=tf.int32)
sum_value = tf.constant(0, dtype=tf.int32)
def loop_body(i, increasing_value, sum_value):
increased_value = increasing_value + 1
return i + 1, increased_value, sum_value + increased_value
i = tf.constant(0, dtype=tf.int32)
_, increasing_value, sum_value = tf.while_loop(
lambda i, _, __: i < n,
loop_body,
[i, increasing_value, sum_value])
with tf.Session() as session:
for x in range(10):
print(session.run(sum_value, feed_dict={n: x}))
输出:
0
1
3
6
10
15
21
28
36
45
但是,TensorFlow循环通常很慢,您应该尝试找到进行计算的矢量方式(也就是说,将其表示为对值和归约数组的操作)。在您的特定情况下,您的代码仅在计算1 + 2 + 3 + 4 + ⋯,这就是(n * (n + 1)) / 2
:
import tensorflow as tf
n = tf.placeholder(tf.int32, [])
sum_value = (n * n + n) // 2
with tf.Session() as session:
for x in range(10):
print(session.run(sum_value, feed_dict={n: x}))
输出:
0
1
3
6
10
15
21
28
36
45