Tensorflow变量赋值输出1+2+3+4+5+6+7+8+...

1. Tensorflow之变量赋值输出1+2+3+4+5+6+…+10

import tensorflow.compat.v1 as tf
tf.reset_default_graph()
value = tf.Variable(0,name='value')
res = tf.Variable(0,name='res')
one = tf.constant(1)
new_value = tf.add(value,one)
update_value = tf.assign(value,new_value)
temp_value = tf.add(res,value)
update_res_value = tf.assign(res,temp_value)
log_dir = 'log/'
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for _ in range(10):
        sess.run(update_value)
        sess.run(update_res_value)
    print(sess.run(res))

writer = tf.summary.FileWriter(log_dir,sess.graph)

tensorboard可视化
Tensorflow变量赋值输出1+2+3+4+5+6+7+8+..._第1张图片

2.通过变量赋值输出1+2+3+4+5+6+7+8+9+…+n

import tensorflow.compat.v1 as tf
value = tf.Variable(0,name="value")
sum = tf.Variable(0,name="sum")
one = tf.constant(1)
tf.disable_v2_behavior()
n = tf.placeholder(tf.int32,name='n') 

new_value = tf.add(value,one)
update_value = tf.assign(value,new_value)
new_sum = tf.add(sum,value)
update_sum = tf.assign(sum,new_sum)
    
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    number = int(input("请输入数字: "))
    for i in range(number):
        sess.run(update_value)
        sess.run(update_sum)
    result = sess.run(sum,feed_dict={n:number})
    print(result)

你可能感兴趣的:(深度学习)