3-Tensorflow-demo_1-Graph和Session

本文介绍TensorFlow中图(Graph)的创建与使用,包括tf.constant、tf.add及tf.Session的应用。演示如何构建计算图,执行基本算术运算,并通过会话(Session)获取计算结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import tensorflow as tf
import numpy as np

"""
本节内容:
    1、Graph图的创建。
    2、使用tf.constant 和 tf.add()的使用
    3、使用会话,tf.Session()  以及  sess.run()的参数
"""

def create_graph():
    print('当前模型图为:{}'.format(tf.get_default_graph()))
    # 1、构建2个常量对象
    a = tf.constant(value=5.0, dtype=tf.float32, shape=None, name='a')
    b = tf.constant(value=8.0)

    # 2、使用操作符tf.add 对2个常数分别加一个随机数。
    v1 = tf.add(x=a, y=np.random.random_sample(), name='v1')
    v2 = tf.add(b, tf.random_normal(shape=[], dtype=tf.float32, seed=42))

    # 3、对上述2者进行相乘
    rezult = tf.multiply(x=v1, y=v2)
    print(v1, v2, rezult)



def create_graph1():
    print('当前模型图为:{}'.format(tf.get_default_graph()))
    # 1、构建2个常量对象
    a = tf.constant(value=5.0, dtype=tf.float32, shape=None, name='a')
    b = tf.constant(value=8.0)

    # 2、使用操作符tf.add 对2个常数分别加一个随机数。
    v1 = tf.add(x=a, y=np.random.random_sample(), name='v1')
    v2 = b + tf.random_normal(shape=[], dtype=tf.float32, seed=42)

    # 3、对上述2者进行相乘
    rezult = v1*v2
    print(v1, v2, rezult)


def create_graph2():
    """
    2个矩阵相乘
    :return:
    """
    # 1、构建2个常量的矩阵
    a = tf.constant(value=[1,2,3,4,5,6,7,3,2,4,3,4],
                    dtype=tf.float32, shape=[3, 5])
    b = tf.constant(value=[2,3,4,3,5,5,43,3,2,1,3,4],
                    dtype=tf.float32, shape=[5, 3])
    # 2、2个常量tensor分别加一个随机数
    v1 = a + np.random.random_sample()
    v2 = b + tf.random_normal(shape=[], dtype=tf.float32)

    # 3、矩阵相乘
    rezult = tf.matmul(v1, v2)
    print(v1, v2, rezult)


def create_graph3():
    """
    不能跨图操作,否则会报错。
    :return:
    """
    print('当前的默认图为:{}'.format(tf.get_default_graph()))
    # 1、构建2个常量的矩阵
    a = tf.constant(value=[1,2,3,4,5,6,7,3,2,4,3,4],
                    dtype=tf.float32, shape=[3, 5])

    with tf.Graph().as_default():
        print('当前的默认图为:{}'.format(tf.get_default_graph()))
        b = tf.constant(value=[2,3,4,3,5,5,43,3,2,1,3,4],
                        dtype=tf.float32, shape=[5, 3])
    # 2、2个常量tensor分别加一个随机数
    v1 = a + np.random.random_sample()
    v2 = b + tf.random_normal(shape=[], dtype=tf.float32)

    # 3、矩阵相乘
    rezult = tf.matmul(v1, v2)
    print(v1, v2, rezult)


def create_graph_do_session():
    # 1、构建2个常量的矩阵
    a = tf.constant(value=[1,2,3,4,5,6,7,3,2,4,3,4],
                    dtype=tf.float32, shape=[3, 5])
    b = tf.constant(value=[2,3,4,3,5,5,43,3,2,1,3,4],
                    dtype=tf.float32, shape=[5, 3])
    # 2、2个常量tensor分别加一个随机数
    v1 = a + np.random.random_sample()
    v2 = b + tf.random_normal(shape=[], dtype=tf.float32)

    # 3、矩阵相乘
    rezult = tf.matmul(v1, v2)
    print(v1, v2, rezult)
    # 二、构建会话
    sess = tf.Session()
    """
    tf.Session().run(self, 
            fetches,         # 给定具体要获取哪些tensor的值,可以是一个,也可以是多个。(给定多个,只运行模型图1次。)
            feed_dict=None,  # 如果模型图中定义了传入的数据(通过占位符定义),那么通过这个参数给定。
            options=None, run_metadata=None)
    """
    # print(sess.run(v1))
    print(sess.run(v2))
    # print(sess.run(rezult))
    print(sess.run(fetches=[v1, v2, rezult, v2]))
    sess.close()
    # fixme RuntimeError: Attempted to use a closed Session.
    print(sess.run(v2))


def create_graph_do_session1():
    """
    第二种执行跑会话的方法。 eval()方法。
    :return:
    """
    # 1、构建2个常量的矩阵
    a = tf.constant(value=[1,2,3,4,5,6,7,3,2,4,3,4],
                    dtype=tf.float32, shape=[3, 5])
    b = tf.constant(value=[2,3,4,3,5,5,43,3,2,1,3,4],
                    dtype=tf.float32, shape=[5, 3])
    # 2、2个常量tensor分别加一个随机数
    v1 = a + np.random.random_sample()
    v2 = b + tf.random_normal(shape=[], dtype=tf.float32)

    # 3、矩阵相乘
    rezult = tf.matmul(v1, v2)
    print(v1, v2, rezult)
    # 二、构建会话
    # sess = tf.Session()
    # print(v2.eval(session=sess))
    # print(rezult.eval(session=sess))
    # sess.close()
    with tf.Session() as sess:
        print(v2.eval())
        print(rezult.eval())


def create_graph_do_session2():
    """
    第二种构建会话的方式。 tf.InteractiveSession() 交互式会话
    :return:
    """
    # 1、构建2个常量的矩阵
    a = tf.constant(value=[1,2,3,4,5,6,7,3,2,4,3,4],
                    dtype=tf.float32, shape=[3, 5])
    b = tf.constant(value=[2,3,4,3,5,5,43,3,2,1,3,4],
                    dtype=tf.float32, shape=[5, 3])
    # 2、2个常量tensor分别加一个随机数
    v1 = a + np.random.random_sample()
    v2 = b + tf.random_normal(shape=[], dtype=tf.float32)

    # 3、矩阵相乘
    rezult = tf.matmul(v1, v2)
    print(v1, v2, rezult)
    # 二、构建会话
    sess = tf.InteractiveSession()
    print(tf.get_default_session())
    print(v2.eval())
    print(rezult.eval())

# 总结。使用tf构建模型图,一般的逻辑结构为:
# with tf.Graph().as_default():
#     # 一、基于业务逻辑构建模型图
#     pass
#     # 二、构建会话
#     with tf.Session() as sess:
#         # 1、变量初始化
#         # 2、加载数据。
#         # 3、执行模型训练
#         # 4、模型效果查看(打印 训练 和验证数据的 损失和 准确率)
#         # 5、模型持久化
#         pass


if __name__ == '__main__':
    # create_graph3()
    create_graph_do_session2()
D:\Anaconda\python.exe D:/AI20/HJZ/04-深度学习/2-TensorFlow基础/tf_基础代码/01_01Graph和Session.py
Tensor("add:0", shape=(3, 5), dtype=float32) Tensor("add_1:0", shape=(5, 3), dtype=float32) Tensor("MatMul:0", shape=(3, 3), dtype=float32)
2019-11-30 21:36:01.954243: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
<tensorflow.python.client.session.InteractiveSession object at 0x000001D8CB982D30>
[[ 1.7119892  2.7119892  3.7119892]
 [ 2.7119892  4.7119894  4.7119894]
 [42.71199    2.7119892  1.7119892]
 [ 0.7119892  2.7119892  3.7119892]
 [ 3.7119892  3.7119892  3.7119892]]
[[223.5455   97.34502  99.8936 ]
 [255.7504  140.5499  146.09848]
 [280.09116 119.89066 123.43925]]

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值