tensorflow从变量-loss-optimizer

tensorflow 提供很多api,最低级的api tensorflow Core给你提供完整的编程控制,这时我们应该关注的。高层的api是建立在tensorflow core之上。A high-level API like tf.contrib.learn helps you manage data sets, estimators, training and inference. 
下面的代码将使用低级和高级的api完成。

tensor:
[1.,2.,3.]  # 三维的tensor shape[3]
[[1.,2.,3.,],[4.,5.,6.,]]  #2x3 tensor
[[[1.,2.,3.,]],[[1.,2.,3.,]]]	#2x1x3

导入申明:
import tensorflow as tf

计算图:
是通过计算节点组织而来。每个节点输入0个或者读个tensor,输出一个tensor
其中的一种节点是constant,如下所示:
node1 = tf.constant(3.0, dtype=tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
print(node1, node2)		#>>>Tensor("Const:0", shape=(), dtype=float32) Tensor("Const_1:0", shape=(), dtype=float32)

在这里的print输出就和普通python不同,其说明了这是一个tensor。
如果想要print节点的值必须是用session调用graph. Sesstion 封装了控制和tensorflow的状态。

下面就是创建一个Session并且调用run方法来评估node1和node2.
sess=tf.Session()
print(sess.run([node1,node2]))	#>>>[3.0,4.0]

同样我们也可以对node进行操作:
node3 = tf.add(node1,node2) 
print(node3)  # >>>   7.0

placeholder:
a=tf.placeholder(tf.float32)
b= tf.placeholder(tf.float32)

add_res =a+b
sess = tf.Session()

print(sess.run(add_res,feed_dict={a:1.0,b:2.0}))        #>>>3.0
print(sess.run(add_res,feed_dict={a:[1,2,3],b:[1,2,3]}))    #>>>[2.,3.,4.]

placeholder相当于预留了输入的位置,并且该预留的位置,不仅可以放置单一的值,而且可以放置tensor。这也就可以满足对数据的操作。
其中通过feed_dict参数指定多个输入,为这些占位符提供数值。
首先将数据读取为tensor,然后通过placeholder构建图,最后sess调用图,在调用的时候逐步将数据集读取到placeholder中,最后完成图的计算。

变量初始化:
constant变量在声明的时候就已经初始化,并且其值不能改变。但是variables变量需要特定的操作初始化:
init = tf.global_variables_initializer()
sess.run(init)

example: 一个线性的模型
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeholder(tf.float32)
y_actual = tf.placeholder(tf.float32)
linear_model = W * x + b

loss = tf.reduce_mean(linear_model-y_actual)
#reduce_mean 详细参考  http://blog.csdn.net/qq_32166627/article/details/52734387
init = tf.global_variables_initializer()

#手动调整参数
fixW = tf.assign(W,[-.1]) #通过-1,更新
fixb = tf.assign(b,[-1])
print(sess.run([fixW,fixb]))
print(sess.run(loss,{x:[1.,2.,3.,4.],y_actual:[2.,3.,4.,5.]}))

很明显这次的参数调整并不理想,因为调整的参数是随机的,所以并没有保证loss的下降

引入train:
tensorflow 提供了optimizers调整参数,来减小loss。
最简单就是梯度下降,根据loss梯度的大小调整每个变量。使用tf.gradients()自动生成梯度。

optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
sess.run(init)
x_train = [1.,2.,3.,4.,5.]
y_train = [2.,4.,6.,8.,10.]

for i in range(1000):
    #print(i)
    sess.run(train,{x:x_train,y_actual:y_train})

print(sess.run([W,b]))  #>>>[array([ 1.99999976], dtype=float32), array([  6.98187705e-07], dtype=float32)]

#测试
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x:x_train, y_actual:y_train})
print(curr_W,curr_b,curr_loss)      #>>>[ 1.99999976] [  6.98187705e-07] 6.82121e-13





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值