【tensorflow】常量、变量、实时插入数据的定义和使用

  • tensorflow 2.0 无法兼容 1.0 版本,所以需要加上一句 tf.compat.v1.disable_eager_execution(),以保障程序的正常运行。
  • 在 tensorflow 2.0 中,变量初始化、声明会话 session 等函数均被定义在了 tensorflow.compat.v1 中,调用相关函数时,需要加上前缀,或者直接将 import tensorflow as tf 改为 import tensorflow.compat.v1 as tf 。

 

1.声明并打印常量和变量

代码:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()              # 保证sess.run()能够正常运行

data1 = tf.constant(2, dtype=tf.int32) # 声明常量 data2 = tf.Variable(10, name="var") # 声明变量 print(data1, data2) # 打印数据的描述信息
init = tf.compat.v1.global_variables_initializer() # 初始化变量 with tf.compat.v1.Session() as sess: # 使用session会话执行各种操作 sess.run(init) print(sess.run(data1), sess.run(data2))

输出结果:

 

2.实时插入数据的使用

代码:

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()                                      # 保证sess.run()能够正常运行

data1 = tf.placeholder(tf.float32)                                # 声明实时插入的数据
data2 = tf.placeholder(tf.float32)

dataAdd = tf.add(data1, data2)                                    # 定义加法

with tf.Session() as sess:
    print(sess.run(dataAdd, feed_dict={data1: 2.0, data2: 6.0}))  # feed_dict={:,:} 为固定格式

输出结果:

 

posted @ 2020-08-09 16:37  狂奔的小学生  阅读(357)  评论(0编辑  收藏  举报