• tensorflow 里面的占位符 placeholder


    占位符比变量更基本。它只是我们在未来时间分配数据的变量。占位符是在执行时才输入值的节点。如果我们的网络输入依赖于一些外部数据,并且我们不希望我们的图在定义开发时依赖于任何实际值,那么占位符就是我们需要的数据类型。事实上,我们可以在没有任何数据的情况下构建图。因此,占位符不需要任何初始值;只有一个数据类型(例如 float32)和一个张量形状,因此即使它还没有任何存储值,图形仍然知道要计算什么。

    创建占位符的一些示例如下:

    1. a = tf.placeholder(tf.float32, shape=[5])
    2. b = tf.placeholder(dtype=tf.float32, shape=None, name=None)
    3. X = tf.placeholder(tf.float32, shape=[None, 784], name='input')
    4. Y = tf.placeholder(tf.float32, shape=[None, 10], name='label')
    1. # importing packages
    2. import tensorflow.compat.v1 as tf
    3. # disabling eager mode
    4. tf.compat.v1.disable_eager_execution()
    5. # creating a placeholder
    6. a = tf.placeholder(tf.float32, None)
    7. # creating an operation
    8. b = a + 10
    9. # creating a session
    10. with tf.Session() as session:
    11. # feeding data in the placeholder
    12. operation_res = session.run(b, feed_dict={a: [10, 20, 30, 40]})
    13. print("after executing the operation: " + str(operation_res))
    after executing the operation: [20. 30. 40. 50.]

    Explanation:

    • Eager mode is disabled in case there are any errors. 
    • A placeholder is created using tf.placeholder() method which has a dtype ‘tf.float32’, None says we didn’t specify any size. 
    • Operation is created before feeding in data. 
    • The operation adds 10 to the tensor. 
    • A session is created and started using tf.Session(). 
    • Session.run takes the operation we created and data to be fed as parameters and it returns the result.

     

    1. # importing packages
    2. import tensorflow.compat.v1 as tf
    3. # disabling eager mode
    4. tf.compat.v1.disable_eager_execution()
    5. # creating a tensorflow graph
    6. graph = tf.Graph()
    7. with graph.as_default():
    8. # creating a placeholder
    9. a = tf.placeholder(tf.float64, shape=(3, 3), name='tensor1')
    10. # creating an operation
    11. b = a ** 2
    12. # array1 will be fed into 'a'
    13. array1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    14. # Creating a session, and running the graph
    15. with tf.Session(graph=graph) as session:
    16. # run the session until it reaches node b,
    17. # then input an array of values into a
    18. operation_res = session.run(b, feed_dict={a: array1})
    19. print("after executing the operation: ")
    20. print(operation_res)

     

    after executing the operation: 
    [[ 1.  4.  9.]
     [16. 25. 36.]
     [49. 64. 81.]]
  • 相关阅读:
    【图论——第十讲】匈牙利算法实现二分图的最大匹配
    了解LLVM、Clang编译过程
    Element实现行合并
    Java项目:SSM医药信息管理系统
    Cesium中自定义材质material
    Java项目:小说阅读管理系统(java+JSP+bootstrap+Servlet+Mysql)
    常用激活函数:Sigmoid/Softmax/ELU/ReLU/LeakyReLU/Tanh...(Pytorch)
    最全HTTP/HTTPS面试题整理(三)
    时延抖动和通信的本质
    vue新手入门之使用vue框架搭建用户登录注册案例,手动搭建webpack+Vue项目(附源码,图文详解,亲测有效)
  • 原文地址:https://blog.csdn.net/u010087338/article/details/126978258