Session
Session
是 Tensorflow 为了控制,和输出文件的执行的语句. 运行 session.run()
可以获得你要得知的运算结果, 或者是你所要运算的部分.
01-graph_session.py
# -*- coding: UTF-8 -*- # 引入tensorflow import tensorflow as tf # 创建两个常量 Tensor const1 = tf.constant([[2, 2]]) const2 = tf.constant([[4], [4]]) multiple = tf.matmul(const1, const2) # 尝试用print输出multiple的值 print(multiple) # 创建了 Session(会话)对象 sess = tf.Session() # 用Session的run方法来实际运行multiple这个矩阵乘法操作 # 并把操作执行的结果赋值给 result result = sess.run(multiple) # 用print打印矩阵乘法的结果 print(result) if const1.graph is tf.get_default_graph(): print("const1所在的图(Graph)是当前上下文默认的图") # 关闭已用完的Session(会话) sess.close()
执行结果:
Tensor("MatMul:0", shape=TensorShape([Dimension(1), Dimension(1)]), dtype=int32) const1所在的图(Graph)是当前上下文默认的图
可视化工具tensorboard
构造图Demo
# -*- coding: UTF-8 -*- # 引入tensorflow import tensorflow as tf # 构造图(Graph)的结构 # 用一个线性方程的例子 y = W * x + b W = tf.Variable(2.0, dtype=tf.float32, name="Weight") # 权重 b = tf.Variable(1.0, dtype=tf.float32, name="Bias") # 偏差 x = tf.placeholder(dtype=tf.float32, name="Input") # 输入 with tf.name_scope("Output"): # 输出的命名空间 y = W * x + b # 输出 #const = tf.constant(2.0) # 不需要初始化 # 定义保存日志的路径 path = "./log" # 创建用于初始化所有变量(Variable)的操作 init = tf.global_variables_initializer() # 创建Session(会话) with tf.Session() as sess: sess.run(init) # 初始化变量 writer = tf.summary.FileWriter(path, sess.graph) result = sess.run(y, {x: 3.0}) print("y = %s" % result) # 打印 y = W * x + b 的值,就是 7
Matplotlib中的画图
import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter # useful for `logit` scale # Fixing random state for reproducibility np.random.seed(19680801) # make up some data in the interval ]0, 1[ y = np.random.normal(loc=0.5, scale=0.4, size=1000) y = y[(y > 0) & (y < 1)] y.sort() x = np.arange(len(y)) # plot with various axes scales plt.figure(1) # linear plt.subplot(221) plt.plot(x, y) plt.yscale('linear') plt.title('linear') plt.grid(True) # log plt.subplot(222) plt.plot(x, y) plt.yscale('log') plt.title('log') plt.grid(True) # symmetric log plt.subplot(223) plt.plot(x, y - y.mean()) plt.yscale('symlog', linthreshy=0.01) plt.title('symlog') plt.grid(True) # logit plt.subplot(224) plt.plot(x, y) plt.yscale('logit') plt.title('logit') plt.grid(True) # Format the minor tick labels of the y-axis into empty strings with # `NullFormatter`, to avoid cumbering the axis with too many labels. plt.gca().yaxis.set_minor_formatter(NullFormatter()) # Adjust the subplot layout, because the logit one may take more space # than usual, due to y-tick labels like "1 - 10^{-3}" plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25, wspace=0.35) plt.show()
梯度下降与线性回归