人工智能深度学习入门练习之(22)TensorFlow – 会话

TensorFlow中,会话(Session)表示计算图一次执行的上下文,也被称为TensorFlow运行时。

TensorFlow应用大致可以分为2个部分:

  1. 使用计算图定义神经网络结构
  2. 创建会话运行神经网络(计算图)

我们将通过一个例子来加深理解。

示例

本例完成以下操作:

  • 创建两个张量常量
  • 创建一个操作
  • 打开一个会话
  • 打印结果
import tensorflow.compat.v1 as tf
tf.compat.v1.disable_eager_execution()
## 创建2个常量
x = tf.constant([2])
y = tf.constant([4])

## 定义一个操作
multiply = tf.multiply(x, y)

## 创建会话执行操作

# 打开一个会话,所有操作都将在会话中进行
sess = tf.Session()
# 执行定义好的操作
result_1 = sess.run(multiply)
# 打印结果
print(result_1)
# 关闭会话
sess.close()

输出

[8]

可以在会话中,打印张量的值。

## 检查之前创建的张量
sess = tf.Session()
print(sess.run(x))
print(sess.run(y))
sess.close()

输出

[2]
[4]

global_variables_initializer初始化

变量中的默认值是随机值。要使用变量,在会话中,需要调用object tf.global_variables_initializer(),根据定义变量时设置的初始化器(initializer),来初始化变量的值。

import tensorflow.compat.v1 as tf
tf.compat.v1.disable_eager_execution()
# 创建一个变量
var = tf.get_variable("var", [1, 2])

# 创建一个变量,并把变量中的元素值初始化为0
var_init_1 = tf.get_variable("var_init_1", [1, 2], dtype=tf.int32,  initializer=tf.zeros_initializer)

# 创建一个变量,并使用矩阵常量初始化变量
tensor_const = tf.constant([[10, 20],[30, 40]])
var_init_2 = tf.get_variable("var_init_2", dtype=tf.int32,  initializer=tensor_const)

sess = tf.Session()
# 初始化
sess.run(tf.global_variables_initializer())
print(sess.run(var))
print(sess.run(var_init_1))
print(sess.run(var_init_2))
sess.close()

输出

[[ 1.2669944  -0.07566607]]
[[0 0]]
[[10 20] 
 [30 40]]   

占位符与feed_dict

要为占位符传值,可以在会话中使用feed_dict参数。

import tensorflow.compat.v1 as tf
tf.compat.v1.disable_eager_execution()
# 导入numpy库
import numpy as np

# 创建一个占位符
data_placeholder_b = tf.placeholder(tf.float32, name = "data_placeholder_b")

# 声明一个操作,对占位符中的数据,作平方运算
power_a = tf.pow(data_placeholder_b, 2)

with tf.Session() as sess:
    # 创建一个随机的数据数组
    data = np.arange(0, 10, 2, np.float)
    print(data)
    # 向占位符提供数据
    result = sess.run(power_a, feed_dict={data_placeholder_b: data})
    print(result)

输出

C:\Anaconda3\python.exe "C:\Program Files\JetBrains\PyCharm 2019.1.1\helpers\pydev\pydevconsole.py" --mode=client --port=60216
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['C:\\app\\PycharmProjects', 'C:/app/PycharmProjects'])
Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help.
PyDev console: using IPython 7.12.0
Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] on win32
runfile('C:/app/PycharmProjects/ArtificialIntelligence/test.py', wdir='C:/app/PycharmProjects/ArtificialIntelligence')
2020-06-19 17:52:51.869341: I tensorflow/core/platform/cpu_feature_guard.cc:143] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2020-06-19 17:52:51.886458: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x14739bafdf0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-06-19 17:52:51.888442: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
[0. 2. 4. 6. 8.]
[ 0.  4. 16. 36. 64.]

猜你喜欢

转载自www.cnblogs.com/huanghanyu/p/13164356.html