TensorFlow学习总结(一)思想构架

                                                  整体思想框架

1.工作机制:

       (1)构建阶段:首先定义计算图中所有的计算,即创建一个个节点,这些节点构成以图的结构相互作用;

       (2)执行阶段:建立好的“图”就像一个空壳,你需要启动会话(Session)才能运行这些节点,这就像往这个空壳里边注入血液,让它们循环活动起来。

2.基础概念:

(1)基本概念

(2)Graph调用

(3)Tensor 张量

tensor("add:0", shape=(2,), dtype=float32)
#名字(来自add节点的第1个输出) 维度(一维数组长度为2) 类型

 功能

常量constant

a = tf.constant([1.0, 2.0], neme="a")

变量variable

w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
#产生2×3矩阵矩阵元素均值0,标准差为1的随机数。
#seed设置了随机种子,保证每次运行结果是一样的。

定义1

定义2:用常量定义 

 定义3:其他变量定义

示例程序
import tensorflow as tf

#变量定义
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))

#常量定义
x = tf.constant([[0.7, 0.9]])

#op:相乘。前向传播算法获得神经网络输出
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

#执行阶段:初始化在运行
with tf.Session() as sess:
    sess.run(w1.initializer)
    sess.run(w2.initializer)
    print(sess.run(y))

Note:一个变量的值在被使用之前,这个变量的初始化过程需要明确被调用

# 初始化单个变量
init_op=variable.initializer()

# 初始化所有变量
init_op=tf.initialize_all_variables()

# 更新操作
update_op=tf.assign(variable to be updated, new_value)

#如
one = tf.constant(1)
new_value = tf.add(state,one)
update = tf.assign(state,new_value)


#执行
sess.run(init_op)

(4)Session会话

#执行阶段:最简写法
with tf.Session() as sess:
    print(sess.run(y))

功能 

用法示例

# 创建会话
sess = tf.Session()
# 赋值操作
sess.run([output], feed_dict={input1:value1, input2:value1})
# 用创建的会话执行操作
sess.run(op)
# 取值操作
# 关闭会话
sess.close()

(5)Feed_dict为变量赋值

       我们可以通过TensorFlow对象的placeholder()为变量创建指定数据类型占位符,在执行run(op)时通过feed_dict来为变量赋值.

import tensorflow as  tf

#占位符placeholder
input_1 = tf.placeholder(tf.float32)
input_2 = tf.placeholder(tf.float32)
output = tf.add(input_1, input_2)

with tf.Session() as sess:
    # 通过feed_dict来输入,outpu表示输出
    print(sess.run([output],feed_dict={input_1:[7.],input_2:[2.]}))

(6)placeholder 占位符 

  TensorFlow提供一种占位符操作,避免产生过多节点,在执行时需要为其提供数据,提高运行效率.你可以理解为预编译. 

input_value = tf.placeholder(tf.float32,shape=(1024,1024))

 (7)模型保存与恢复

用法 

#保存模型
import tensorflow as tf

def save_model():
    v1 = tf.Variable(tf.random_normal([1, 2]), name="v1")
    v2 = tf.Variable(tf.random_normal([2, 3]), name="v2")
    init_op = tf.global_variables_initializer()
    saver = tf.train.Saver()
    with tf.Session() as sess:
        sess.run(init_op)
        saver_path = saver.save(sess, "./model.ckpt")
        print("model saved in file: ", saver_path)

#恢复模型
import tensorflow as tf

def load_model():
    v1 = tf.Variable(tf.random_normal([1, 2]), name="v1")
    v2 = tf.Variable(tf.random_normal([2, 3]), name="v2")
    saver = tf.train.Saver()
    with tf.Session() as sess:
        saver.restore(sess,"./model.ckpt")
        print("mode restored")

猜你喜欢

转载自blog.csdn.net/Raoodududu/article/details/82118897