TensorFlow入门教程(2)占位符、变量、损失函数

接上文“TensorFlow入门教程(1)安装、基础、Tensorboard
占位符(placeholders)
官网教程称之前的例子不够interesting,因为只产生固定的结果。一个计算图应该被参数化来接受输入,这就是占位符,占位符告诉程序,它占的这个位置,之后会有输入进来,用tf.placeholder()实现。
码一下代码,学习一下流程:

import tensorflow as tf

sess=tf.Session()
a=tf.placeholder(tf.float32)
b=tf.placeholder(tf.float32)
adder_node=a+b
print(sess.run(adder_node,{a:30,b:4.5}))
print(sess.run(adder_node,{a:[1,2],b:[2,4.5]}))

writer = tf.summary.FileWriter('D:/ten', tf.get_default_graph())
writer.close()

“+”等同于tf.add
结果如下:

34.5
[ 3.   6.5]

占位符示例
我们可以通过加入其它操作来充实计算图。

add_and_triple=adder_node*6.5
print(sess.run(add_and_triple,{a:30,b:4.5}))

结果为:

224.25

乘

变量(Variable)
为了让模型可以训练,我们需要让模型能在相同输入时给出不同输出,我们可以通过使用Variables给计算图加入可训练的参数。跟着官网教程走一遍,用tf.Variable()创建变量。

import tensorflow as tf

sess = tf.Session()

W = tf.Variable([.3],dtype=tf.float32)
b = tf.Variable([-.3],dtype=tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W*x+b

init=tf.global_variables_initializer()
sess.run(init)

print(sess.run(linear_model,{x:[1,2,3,4]}))

结果为:

[ 0.          0.30000001  0.60000002  0.90000004]

官网对tf.global_variables_initializer()的解释是当用tf.Variable()时没有初始化变量,所以需要它来初始化变量,我尝试了将这两句去掉,结果如下:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable
         [[Node: Variable/read = Identity[T=DT_FLOAT, _class=["loc:@Variable"], _device="/job:localhost/replica:0/task:0/device:CPU:0"](Variable)]]

提示使用未初始化的变量值。

损失函数(loss function)
现在虽然我们已经创建了一个模型,但是我们不知道模型好不好。为了用数据集评估模型,我们需要一个占位符来规定需要的值还需要一个损失函数(loss function)。

import tensorflow as tf

sess = tf.Session()
W = tf.Variable([.3],dtype=tf.float32)
b = tf.Variable([-.3],dtype=tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W*x+b
init=tf.global_variables_initializer()
sess.run(init)

y = tf.placeholder(tf.float32) #占位符,用于输入想要得到的数据集
squared_deltas = tf.square(linear_model-y) #正确结果与模型结果差的平方
loss = tf.reduce_sum(squared_deltas) #所有差平方的和
print(sess.run(loss,{x:[1,2,3,4],y:[0,-1,-2,-3]})) #打印损失函数的值

writer = tf.summary.FileWriter('D:/ten', tf.get_default_graph())
writer.close()

变量再赋值
我们可以通过给W、b再分配值来改进模型。一个变量的初始值由tf.Variable提供,但可以用tf.assign来改变:

fixW = tf.assign(W,[-1.])
fixb = tf.assign(b,[1.])
sess.run([fixW,fixb])
print(sess.run(loss,{x:[1,2,3,4],y:[0,-1,-2,-3]}))

最终计算图如下:
计算图
输出为:

0.0

我们手动找到了让损失函数最小的参数,但是机器学习的要点是自动得出最佳的参数,这些将在之后学习。
还有TensorFlow入门教程(3)

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值