Session_Variable


#前者为Variable的案例
#后者为Session

 

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
复制代码
state = tf.Variable(0, name='counter')

# 定义常量 one
one = tf.constant(2)

# 定义加法步骤 (注: 此步并没有直接计算)
new_value = tf.add(state, one)

# 将 State 更新成 new_value
update = tf.compat.v1.assign(state, new_value)
复制代码
复制代码
# 如果定义 Variable, 就一定要 initialize
# init = tf.compat.v1.initialize_all_variables() # tf 马上就要废弃这种写法
init = tf.compat.v1.global_variables_initializer()  # 替换成这样就好
 
# 使用 Session
with tf.compat.v1.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))
#注意:直接 print(state) 不起作用!!
#一定要把 sess 的指针指向 state 再进行 print 才能得到想要的结果!
复制代码
import tensorflow as tf
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()# 由于部分代码含有版本不同,此将v2版本禁用使用v1版本
matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],
                       [2]])
product = tf.matmul(matrix1,matrix2) #numpy 使用dot()
# method 1
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()
# [[12]]
# method 2
with tf.Session() as sess: #运行到最后自动关上
    result2 = sess.run(product)
    print(result2)
# [[12]]

 

 
posted @   是冰美式诶  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示