TensorFlow学习笔记之基本框架

TensorFlow是Google开源的深度学习框架,使用数据流图(data flow graphs)来进行数值计算。
参考文章:(http://www.jeyzhang.com/tensorflow-learning-notes.html)

基本概念

  • 使用图 (graph) 来表示计算任务。
  • 在会话 (Session) 的上下文 (context) 中执行图。
  • 使用 tensor 表示数据。
  • 通过变量 (Variable) 维护状态。
  • 使用 feed 和 fetch 可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据。

TensorFlow采用的是符号式编程(python/C++等采用的是命令式编程),将计算过程抽象为计算图,计算流图可以方便的描述计算过程。计算图中的节点称为ops (operation的简称),代表数值运算,节点节点之间的边,代表多维数据(tensors)之间的某种联系。优点是运行速度快,节省内存空间。

导包

import tensorflow as tf

创建常量(constant)

matrix1 = tf.constant([[3., 3.]]) #1x2的二维矩阵常量
matrix2 = tf.constant([[2.], [2.]]) #2x1的二维矩阵常量
product = tf.matmul(matrix1, matrix2) #矩阵乘法运算

创建Session

上一步只是创建了图中的运算节点,真正的运行发生在Session中。

sess = tf.Session() #创建一个Session
result = sess.run(product) #运行上面定义的矩阵乘法运算
print(result)
sess.close() #Session使用完毕后需要关闭

Sessions最后需要关闭,以释放相关的资源,可以使用下面的方法自动关闭,有点类似于对文件的读写操作。

with tf.Session() as sess:
    result = sess.run([product])
    print(result)

创建变量(Variables)

state = tf.Variable(0, name='counter') #创建变量,初始值为0

one = tf.constant(1) #创建值为1的常量
new_value = tf.add(state, one) #加法运算
update = tf.assign(state, new_value) #赋值运算,将new_value赋值给state

init_op = tf.global_variables_initializer() #对变量初始化

with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(update))
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))
# 1
# 2
# 3
# 4

抓取(Fetches)

TensorFlow 中 ops 的输出,需要先执行 session 的 run 函数,然后打印结果。

input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.add(input2, input3)
mul = tf.multiply(input1, intermed) #乘法运算

with tf.Session() as sess:
    result = sess.run([mul, intermed]) #运行上面定义的两个运算
    print(result)
# [21.0, 7.0]
value = tf.Variable(5)
sess = tf.Session()
init_op = tf.global_variables_initializer()
sess.run(init_op)
print(sess.run(value))
sess.close()
# 5

填充(Feeds)

先创建特定数据类型的占位符 (placeholder),之后再进行数据的填充。

input1 = tf.placeholder(tf.float32) #占位符
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2) 
with tf.Session() as sess:
    print(sess.run([output], feed_dict={input1:[7.], input2:[2.]})) #feed_dict对input1和input2传值
#[array([14.], dtype=float32)]

注:placeholder的使用必须进行传值

例子:曲线拟合

import tensorflow as tf
import numpy as np

#生成100对数据对
x_data = np.random.rand(100).astype('float32')
y_data = x_data * 0.1 + 0.3 # y=0.1*x+0.3

#w和b变量的取值范围
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) #生成-1到1均匀分布的数据
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b

#最小化均方误差
loss = tf.reduce_mean(tf.square(y-y_data)) #定义损失函数
optimizer = tf.train.GradientDescentOptimizer(0.5) #优化方法,这里为随机梯度下降算法
train = optimizer.minimize(loss) #目标位最小化损失函数

#初始化TensorFlow参数
init = tf.global_variables_initializer()

#运行数据流图(开始执行计算过程)
sess = tf.Session()
sess.run(init)

#多次迭代观察w和b的拟合值
for step in range(201):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(W), sess.run(b))
sess.close()

#经过多轮迭代运算,W和b的值逐渐逼近0.1和0.3
0 [-0.14997652] [0.6842848]
20 [0.01789117] [0.3489156]
40 [0.08092632] [0.31136298]
60 [0.09556921] [0.3026396]
80 [0.09897073] [0.3006132]
100 [0.09976091] [0.30014244]
120 [0.09994447] [0.3000331]
140 [0.09998711] [0.3000077]
160 [0.09999702] [0.3000018]
180 [0.0999993] [0.30000043]
200 [0.09999985] [0.3000001]
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值