《TensorFlow实战Google深度学习框架(第2版)》3.tensorflow入门

TensorFlow计算模型------计算图

计算图的概念

Tensor就是张量。在TensorFlow 中,张量可以被简单地理解为多维数组,如果说TensorFlow 的第一个词Tensor表明了它的数据结构,那么Flow 则体现了它的计算模型。Flow翻译成中文就是“流”,它直观地表达了张量之间通过计算相互转化的过程。

Tensor Board是TensorFlow的可视化工具。

# 样例
import tensorflow as tf  # 载入TensorFlow
a = tf.constant([1.0, 2.0], name="a")
b = tf.constant([2.0, 3.0], name="b")
result = a + b

# tf.get_default_graph 函数获取当前默认的计算图
# a.graph 可以查看a张量所属的计算图
print(a.graph is tf.get_default_graph())

sess = tf.Session()
print(sess.run(result))
True
[3. 5.]

不同计算图上定义和使用变量;产生两个计算图

import tensorflow as tf

# tf.Graph函数来生成新的计算图
g1 = tf.Graph()
with g1.as_default():
# 在计算图g1中定义变量"v",并设置初始值为0。
    v = tf.get_variable("v", initializer=tf.zeros_initializer()(shape=[1])) # 需要加一个()
                                                                               
g2 = tf.Graph()
with g2.as_default():
# 在计算图g2中定义变量"v",并设置初始值为1。
    v = tf.get_variable("v", initializer=tf.ones_initializer()(shape=[1]))

with tf.Session(graph=g1) as sess:
    tf.global_variables_initializer().run()
    with tf.variable_scope("", reuse=True):
        print(sess.run(tf.get_variable("v")))
        
with tf.Session(graph=g2) as sess:
    tf.global_variables_initializer().run()
    with tf.variable_scope("", reuse=True):
        print(sess.run(tf.get_variable("v")))
WARNING:tensorflow:From C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
[0.]
[1.]
g = tf.Graph()
# 指定计算运行的设备。
with g.device('/gpu:0'):
    result = a + b

TensorFlow数据模型------张量

在TensorFlow中所有数据都通过张量的形式来表示。
在功能的角度,张量可以被简单的理解为多维数组;
它只是对运算结果的引用。

import tensorflow as tf
a = tf.constant([1.0, 2.0], name="a")
b = tf.constant([2.0, 3.0], name="b")
result = tf.add(a, b, name="add")
print(result)
Tensor("add_2:0", shape=(2,), dtype=float32)

Tensor(“add_2:0”, shape=(2,), dtype=float32)
三个属性
名字:这样张量的命名就可以通过“node:src_output”的形式来给出。其中node 为节点的名称,src_output表示当前张量来自节点的第几个输出。比如上面代码打出来的“add:0”就说明了result这个张量是计算节点“add”输出的第一个结果(编号从O 开始)。
张量的维度(shape):
类型(type):实数(tf.float32 、tf.float64 )、整数(tf.int8 、tf.intl6 、tf.int32 、tf.int64 、tf.uint8),布尔型(tf.bool) 和复数(tf.complex64 、tf.complex128 )。

张量的使用

1.对中间计算结果的引用
2.当计算图构造完成之后,张量可以用来获得计算结果,也就是得到真实的数字。

TensorFlow运行模型------会话(session)

会话拥有并管理TensorFlow程序运行时的所有资源。所有计算完成之后需要关闭会话来帮助系统回收资源,否则就可能出现资源泄漏的问题。
TensorFlow中使用会话的模式一般有两种,第一种模式需要明确调用会话生成函数和关闭会话函数;
第二种通过使用上下文管理器来使用会话。

import tensorflow as tf
a = tf.constant([1.0, 2.0], name="a")
b = tf.constant([2.0, 3.0], name="b")
result = tf.add(a, b, name="add")
#创建一个会话,并通过Python中的上下文管理器来管理这个会话。
with tf.Session() as sess:
#使用创建好的会话来计算关心的结果。
    print(sess.run(result))
#不需要再调用“Session.close()”函数来关闭会话,当上下文退出时会话关闭和资源释放也自动完成了。

[3. 5.]

TensorFlow实现神经网络

前向传播神经网络实现
# 前向传播神经网络实现
import tensorflow as tf

# 声明w1,w2两个变量,这里还通过seed参数设定了随机种子,这样可以保证每次运行得到的结果是一样的。
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]])

a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

sess = tf.Session()
# 初始化运行,虽然在变量定义时给出了变量初始化的方法,但这个方法并没有被真正运行
# sess.run(w1.initializer)
# sess.run(w2.initializer)
# 全部初始化
init_op = tf.global_variables_initializer()
sess.run(init_op)
print(sess.run(y))
sess.close()

[[3.957578]]
# placeholder占位符
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]])
# 定义placeholder作为存放输入数据的地方
x = tf.placeholder(tf.float32, shape=(1,2), name="input")

a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

sess = tf.Session()
init_op = tf.global_variables_initializer()
sess.run(init_op)

# feed_dict是一个字典(map)在字典中需要给出每个用到的placeholder的取值
print(sess.run(y, feed_dict={x: [[0.7,0.9]]}))
sess.close()

[[3.957578]]
完整神经网络

1.定义神经网络的结构和前向传播的输出结果。
2.定义损失函数以及选择反向传播优化的算法。
3.生成会话(tf.Session)并且在训练、数据上反复运行反向传播优化算法。

# 完整神经网络
import tensorflow as tf
from numpy.random import RandomState

batch_size = 8 # 定义batch的大小
# 权重参数
w1 = tf.Variable(tf.random_normal((2, 3), stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal((3, 1), stddev=1, seed=1))
# placeholder占位符
x = tf.placeholder(tf.float32, shape=(None, 2), name="x-input")
y_ = tf.placeholder(tf.float32, shape=(None, 1), name="y-input")
# 定义前向传播过程
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

# 定义损失函数和反向传播算法
y = tf.sigmoid(y) # sigmoid函数将y转换为0~1之间的数值
cross_entropy = -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0)) \
                                + (1-y_) * tf.log(tf.clip_by_value(1-y, 1e-10, 1.0)))
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)

# 通过随机数生成一个模拟数据集
rdm = RandomState(1)
dataset_size = 128
X = rdm.rand(dataset_size, 2)
Y = [[int(x1+x2 < 1)] for (x1, x2) in X]

# 会话
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    
    print(sess.run(w1))
    print(sess.run(w2))
    
    STEPS = 5000 # 训练轮数
    for i in range(STEPS):
        # 每次选取batch_size=8个样本进行训练。
        start = (i * batch_size) % dataset_size
        end = min(start + batch_size, dataset_size)
        
        # 通过选取的样本训练神经网络并更新参数
        sess.run(train_step, feed_dict={x: X[start:end], y_: Y[start:end]})
        if i % 1000 == 0:
            total_cross_entropy = sess.run(cross_entropy, feed_dict={x: X, y_:Y})
            print('After %d training step(s), cross entropy on all data is %g' % (i, total_cross_entropy))
    print(sess.run(w1))
    print(sess.run(w2))
    

[[-0.8113182   1.4845988   0.06532937]
 [-2.4427042   0.0992484   0.5912243 ]]
[[-0.8113182 ]
 [ 1.4845988 ]
 [ 0.06532937]]
After 0 training step(s), cross entropy on all data is 1.89805
After 1000 training step(s), cross entropy on all data is 0.655075
After 2000 training step(s), cross entropy on all data is 0.626172
After 3000 training step(s), cross entropy on all data is 0.615096
After 4000 training step(s), cross entropy on all data is 0.610309
[[ 0.02476973  0.56948674  1.6921943 ]
 [-2.1977348  -0.23668918  1.1143894 ]]
[[-0.4554469 ]
 [ 0.49110925]
 [-0.9811033 ]]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值