本例子主要是按照 tensorflow的中文文档来学习 tensorflow 的基本用法。按照文档说明,主要存在的一些问题:
- 1.就是 Session() 和 InteractiveSession() 的用法。后者用 Tensor.eval() 和 Operation.run() 来替代了 Session.run(). 其中更多的是用 Tensor.eval(),所有的表达式都可以看作是 Tensor.
- 2.另外,tf的表达式中所有的变量或者是常量都应该是 tf 的类型。
- 3.只要是声明了变量,就得用 sess.run(tf.global_variables_initializer()) 或者 x.initializer.run() 方法来初始化才能用。
例一:平面拟合 通过本例可以看到机器学习的一个通用过程:1.准备数据 -> 2.构造模型(设置求解目标函数) -> 3.求解模型 import tensorflow as tf
import numpy as np
x_data = np.float32(np.random.rand(2, 100))
y_data = np.dot([0.100, 0.200], x_data) + 0.300
b = tf.Variable(tf.zeros([1]))
W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))
y = tf.matmul(W, x_data) + b
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
sess.run(init)
for step in xrange(0, 201):
sess.run(train)
if step % 20 == 0:
print step, sess.run(W), sess.run(b)
0 [[ 0.27467242 0.81889796]] [-0.13746099]
20 [[ 0.1619305 0.39317462]] [ 0.18206716]
40 [[ 0.11901411 0.25831661]] [ 0.2642329]
60 [[ 0.10580806 0.21761954]] [ 0.28916073]
80 [[ 0.10176832 0.20532639]] [ 0.29671678]
100 [[ 0.10053726 0.20161074]] [ 0.29900584]
120 [[ 0.100163 0.20048723]] [ 0.29969904]
140 [[ 0.10004941 0.20014738]] [ 0.29990891]
160 [[ 0.10001497 0.20004457]] [ 0.29997244]
180 [[ 0.10000452 0.20001349]] [ 0.29999167]
200 [[ 0.10000138 0.2000041 ]] [ 0.29999748]
例二:两个数求和 input1 = tf.constant(2.0)
input2 = tf.constant(3.0)
input3 = tf.constant(5.0)
intermd = tf.add(input1, input2)
mul = tf.multiply(input2, input3)
with tf.Session() as sess:
result = sess.run([mul, intermd])
print result
print type(result)
print type(result[0]) [15.0, 5.0]
<type 'list'>
<type 'numpy.float32'>
1.变量,常量 1.1 用 tensorflow 实现计数器,主要是设计了 在循环中调用加法实现计数
state = tf.Variable(0, name="counter")
one = tf.constant(1)
new_value = tf.add(state, 1)
update = tf.assign(state, new_value)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print sess.run(state)
for _ in range(3):
sess.run(update)
print sess.run(state) 0
1
2
3
1.2 用 tf 来实现对一组数求和,再计算平均 h_sum = tf.Variable(0.0, dtype=tf.float32)
h_vec = tf.constant([1.0,2.0,3.0,4.0])
h_add = tf.placeholder(tf.float32)
h_new = tf.add(h_sum, h_add)
update = tf.assign(h_sum, h_new)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print 's_sum =', sess.run(h_sum)
print "vec = ", sess.run(h_vec)
for _ in range(4):
sess.run(update, feed_dict={h_add: sess.run(h_vec[_])})
print 'h_sum =', sess.run(h_sum)
print 'the mean is ', sess.run(sess.run(h_sum) / tf.constant(4.0)) s_sum = 0.0
vec = [ 1. 2. 3. 4.]
h_sum = 1.0
h_sum = 3.0
h_sum = 6.0
h_sum = 10.0
the mean is 2.5
1.3 只用一个变量来实现计数器 上面的计数器是 TensorFlow 官方文档的例子,但是让人觉得好臃肿,所以下面我写了个更加简单的,只需要定义一个变量和一个加1的操作(op)。通过for循环就能够实现了。
state = tf.Variable(0.0, tf.float32)
add_op = tf.assign(state, state+1)
sess.run(tf.global_variables_initializer())
print 'init state ', sess.run(state)
for _ in xrange(3):
sess.run(add_op)
print sess.run(state) init state 0.0
1.0
2.0
3.0
这样子和我们平时实现计数器的方法基本上就 一致了。我们要重点理解的是, TensorFlow 中通过 tf.assign(ref, value) 的方式来把 value 值赋给 ref 变量。这样子,每一次循环的时候,ref 变量才不会再做定义时候的初始化操作。 2. InteractiveSession() 的用法 InteractiveSession() 主要是避免 Session(会话)被一个变量持有 a = tf.constant(1.0)
b = tf.constant(2.0)
c = a + b
with tf.Session():
print c.eval()
sess = tf.InteractiveSession()
print c.eval()
sess.close() 3.0
3.0
a = tf.constant(1.0)
b = tf.constant(2.0)
c = tf.Variable(3.0)
d = a + b
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
print a.eval()
print d.eval()
x = tf.Variable(1.2)
x.initializer.run()
print x.eval()
sess.close() 1.0
3.0
1.2
2.1 怎样使用 tf.InteractiveSession() 来完成上面 1.2 中 求和 、平均 的操作呢? h_sum = tf.Variable(0.0, dtype=tf.float32)
h_vec = tf.constant([1.0,2.0,3.0,4.0])
h_add = tf.placeholder(tf.float32)
h_new = tf.add(h_sum, h_add)
update = tf.assign(h_sum, h_new)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
print 's_sum =', h_sum.eval()
print "vec = ", h_vec.eval()
print "vec = ", h_vec[0].eval()
for _ in range(4):
update.eval(feed_dict={h_add: h_vec[_].eval()})
print 'h_sum =', h_sum.eval()
sess.close() s_sum = 0.0
vec = [ 1. 2. 3. 4.]
vec = 1.0
h_sum = 1.0
h_sum = 3.0
h_sum = 6.0
h_sum = 10.0
3.使用feed来对变量赋值 这些需要用到feed来赋值的操作可以通过tf.placeholder()说明,以创建占位符。 下面的例子中可以看出 session.run([output], …) 和 session.run(output, …) 的区别。前者输出了 output 的类型等详细信息,后者只输出简单结果。 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.0], input2:[2.0]}) [array([ 14.], dtype=float32)]
with tf.Session() as sess:
result = sess.run(output, feed_dict={input1:[7.0], input2:[2.0]})
print type(result)
print result <type 'numpy.ndarray'>
[ 14.]
with tf.Session() as sess:
result = sess.run(output, feed_dict={input1:7.0, input2:2.0})
print type(result)
print result <type 'numpy.float32'>
14.0
with tf.Session() as sess:
print sess.run([output], feed_dict={input1:[7.0, 3.0], input2:[2.0, 1.0]}) [array([ 14., 3.], dtype=float32)]
with tf.Session() as sess:
print sess.run(output, feed_dict={input1:[7.0, 3.0], input2:[2.0, 1.0]}) [ 14. 3.]
作者:Jerr__y 发表于2017/2/25 16:37:06
原文链接
|