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]]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)