笔记链接:黑马程序员3天带你玩转Python深度学习TensorFlow框架学习笔记_wisdom_zhe的博客-CSDN博客
视频链接:
调试大半天终于弄好,
进入环境,tensorboard --logdir=F:\pythonProject\tf_demo\temp\summary --port=6007
import tensorflow._api.v2.compat.v1 as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.compat.v1.disable_eager_execution()
def tensorflow_demo1():
# python版本
a = 2
b = 3
c = a + b
print('python版本的加法操作:\n', c)
# tensorflow实现加法操作
a_t = tf.constant(2) # 定义常量
b_t = tf.constant(3)
c_t = a_t + b_t
print('tensorflow版本的加法操作:\n', c_t)
# 开启会话
with tf.Session() as sess:
c_t_value = sess.run(c_t)
print('开启会话的结果\n', c_t_value)
if __name__ == '__main__':
tensorflow_demo1()
'''
python版本的加法操作:
5
tensorflow版本的加法操作:
Tensor("add:0", shape=(), dtype=int32)
开启会话的结果
5
'''
def graph_demo():
# tensorflow实现加法操作
a_t = tf.constant(2) # 定义常量
b_t = tf.constant(3)
c_t = a_t + b_t
#查看默认图
#方法1:调用方法
defalut_g=tf.get_default_graph()
print('默认图:',defalut_g)
#方法2:调用属性
print('a_t的图属性: ',a_t.graph)
print('c_t的图属性: ',c_t.graph)
# 开启会话
with tf.Session() as sess:
c_t_value = sess.run(c_t)
print('sess的图属性:',sess.graph)
if __name__ == '__main__':
graph_demo()
'''
默认图: <tensorflow.python.framework.ops.Graph object at 0x0000026249C36E48>
a_t的图属性: <tensorflow.python.framework.ops.Graph object at 0x0000026249C36E48>
c_t的图属性: <tensorflow.python.framework.ops.Graph object at 0x0000026249C36E48>
sess的图属性: <tensorflow.python.framework.ops.Graph object at 0x0000026249C36E48>
'''
def create_graph():
# 自定义图
new_graph=tf.Graph()
# 图上下文管理器定义数据和操作
with new_graph.as_default():
a_new = tf.constant(20)
b_new = tf.constant(30)
c_new = a_new + b_new
print("c_new:", c_new)
print("a_new的图属性:", a_new.graph)
print("c_new的图属性:", c_new.graph)
#开启会话,执行图,注意这里需要传入自定义图对象graph
with tf.Session(graph = new_graph) as sess:
c_new_value=sess.run(c_new)
print('自定义图的运算结果:',c_new_value)
print('sess的图属性:',sess.graph)
if __name__ == '__main__':
create_graph()
'''
c_new: Tensor("add:0", shape=(), dtype=int32)
a_new的图属性: <tensorflow.python.framework.ops.Graph object at 0x000001D3439BF278>
c_new的图属性: <tensorflow.python.framework.ops.Graph object at 0x000001D3439BF278>
自定义图的运算结果: 50
sess的图属性: <tensorflow.python.framework.ops.Graph object at 0x000001D3439BF278>
'''
def graph_demo():
# tensorflow实现加法操作
a_t = tf.constant(2) # 定义常量
b_t = tf.constant(3)
c_t = a_t + b_t
# 开启会话
with tf.Session() as sess:
c_t_value = sess.run(c_t)
print('sess的图属性:', sess.graph)
# sess图序列化为summary对象
# 参数一:输出sumary对象的路径,参数二:需要进行序列化的图
tf.summary.FileWriter('./temp/summary', graph=sess.graph)
if __name__ == '__main__':
graph_demo()