3-Tensorflow-demo_02-变量_占位符_feeddict使用

本文通过实例讲解了TensorFlow中图(Graph)和会话(Session)的基本使用方法,包括如何构建图中的操作节点、变量和占位符,以及如何在会话中运行这些操作。还介绍了如何使用TensorBoard进行模型可视化。
部署运行你感兴趣的模型镜像


import tensorflow as tf
import numpy as np
"""
以线性回归为例
y = x*w +b
x = [[1,2,3,],
     [2,3,4],
     [3,4,5],
     [34,23,2]]
变量:
w = [[-1.5],
     [2.9],
     [3.0]]
b= [3]
"""

def f1():
    """
    用tf.constant来构建。
    :return:
    """
    with tf.Graph().as_default():
        # 1、构建输入x
        x = tf.constant(value=[[1,2,3,],
                             [2,3,4],
                             [3,4,5],
                             [34,23,2]],
                        dtype=tf.float32, shape=[4, 3], name='x')
        # 2、构建变量
        w = tf.constant(value=[[-1.5],
                                 [2.9],
                                 [3.0]],
                        dtype=tf.float32, shape=[3, 1], name='w')
        b = tf.constant(value=[3], dtype=tf.float32, shape=[1], name='b')

        # 3、执行正向传播,获得预测值。
        y_pred = tf.matmul(x, w) + b
        # 二、构建会话
        with tf.Session() as sess:
            y_pred_ = sess.run(y_pred)
            print(y_pred_)


def f2():
    """
    用tf.Variable来构建变量。
    :return:
    """
    with tf.Graph().as_default():
        # 1、构建输入x
        x = tf.constant(value=[[1,2,3,],
                             [2,3,4],
                             [3,4,5],
                             [34,23,2]],
                        dtype=tf.float32, shape=[4, 3], name='x')

        # 2、构建变量
        """
        tf.Variable((self,
               initial_value=None,    # 给定该变量的初始值,可以是python基本数据类型或者tf.tensor对象
               trainable=True,        # 给定该变量是否参数模型训练。(就是是否可以使用梯度值进行更新)
               collections=None,
               validate_shape=True,   # 在更新变量的前后 验证该变量的形状。
               caching_device=None,
               name=None,             # 给定tensor底层的名字
               variable_def=None,
               dtype=None,            # 数据类型
               expected_shape=None,
               import_scope=None,
               constraint=None)
        """
        w = tf.Variable(initial_value=[[-1.5],
                                         [2.9],
                                         [3.0]],
                        dtype=tf.float32, name='w')
        b1 = tf.constant(value=[3], dtype=tf.float32, shape=[1], name='b1')
        b = tf.Variable(initial_value=b1, dtype=tf.float32, name='b')

        # 3、执行正向传播,获得预测值。
        y_pred = tf.matmul(x, w) + b
        # 二、构建会话
        with tf.Session() as sess:
            # fixme 变量初始化。
            sess.run(tf.global_variables_initializer())
            y_pred_ = sess.run(y_pred)
            print(y_pred_)


def f3():
    """
    用1、tf.placeholder()
      2、tf.placeholder_with_default()   来构建输入的占位符(代替 input_x 和 input_y 来构建模型图)。
    :return:
    """

    with tf.Graph().as_default():
        # 1、构建输入占位符
        # None 这里代表有这根轴,但是具体的数字不知道,等到传入的时候,自己解析。
        input_x = tf.placeholder(
            dtype=tf.float32, shape=[None, 3], name='input_x'
        )
        c = tf.placeholder_with_default(input=1.0, shape=[], name='c')

        # 2、构建变量
        w = tf.Variable(initial_value=[[-1.5],
                                         [2.9],
                                         [3.0]],
                        dtype=tf.float32, name='w')
        b1 = tf.constant(value=[3], dtype=tf.float32, shape=[1], name='b1')
        b = tf.Variable(initial_value=b1, dtype=tf.float32, name='b')

        # 3、执行正向传播,获得预测值。
        y_pred = tf.matmul(input_x, w) + b
        y1 = y_pred + c
        print(input_x, y_pred, y1)
        # 二、构建会话
        with tf.Session() as sess:
            # fixme 变量初始化。
            sess.run(tf.global_variables_initializer())
            batch_x1 = [[1,2,3,],
                      [2,3,4],
                      [3,4,5],
                      [34,23,2]]
            y_pred_, y1_ = sess.run([y_pred, y1],
                                    feed_dict={input_x: batch_x1, c: 2.0})
            print(y_pred_, y1_)

            batch_x2 = [[1, 2, 3],
                       [2, 3, 4],
                       [3, 4, 5]]
            y_pred_, y1_ = sess.run([y_pred, y1],
                                    feed_dict={input_x: batch_x2})
            print(y_pred_, y1_)


def tensorboard():
    """
    tensorboard的调用。
    :return:
    """

    with tf.Graph().as_default():
        # 1、构建输入占位符
        # None 这里代表有这根轴,但是具体的数字不知道,等到传入的时候,自己解析。
        input_x = tf.placeholder(
            dtype=tf.float32, shape=[None, 3], name='input_x'
        )
        c = tf.placeholder_with_default(input=1.0, shape=[], name='c')

        # 2、构建变量
        w = tf.Variable(initial_value=[[-1.5],
                                         [2.9],
                                         [3.0]],
                        dtype=tf.float32, name='w')
        b1 = tf.constant(value=[3], dtype=tf.float32, shape=[1], name='b1')
        b = tf.Variable(initial_value=b1, dtype=tf.float32, name='b')

        # 3、执行正向传播,获得预测值。
        y_pred = tf.matmul(input_x, w) + b
        y1 = y_pred + c
        print(input_x, y_pred, y1)
        # 二、构建会话
        with tf.Session() as sess:
            # fixme 变量初始化。
            sess.run(tf.global_variables_initializer())

            # fixme 加入一段可视化代码
            writer = tf.summary.FileWriter(
                logdir='./models/ai20', graph=sess.graph
            )
            batch_x1 = [[1,2,3,],
                      [2,3,4],
                      [3,4,5],
                      [34,23,2]]
            y_pred_, y1_ = sess.run([y_pred, y1],
                                    feed_dict={input_x: batch_x1, c: 2.0})
            print(y_pred_, y1_)

            batch_x2 = [[1, 2, 3],
                       [2, 3, 4],
                       [3, 4, 5]]
            y_pred_, y1_ = sess.run([y_pred, y1],
                                    feed_dict={input_x: batch_x2})
            print(y_pred_, y1_)


if __name__ == '__main__':
    # f1()
    # f3()
    tensorboard()
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:41:45.163586: 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 0x0000015446943C50>
[[ 3.0295024  4.0295024  5.0295024]
 [ 4.0295024  6.0295024  6.0295024]
 [44.029503   4.0295024  3.0295024]
 [ 2.0295024  4.0295024  5.0295024]
 [ 5.0295024  5.0295024  5.0295024]]
[[169.57771   47.04595   49.489716]
 [182.50339   70.971634  76.4154  ]
 [215.10666   58.574913  62.01868 ]]

Process finished with exit code 0

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值