TensorFlow学习系列(二):入门起步

1.常量

a = tf.constant(10)

2.变量

x = tf.Variable(tf.ones([3,3]))
y = tf.Variable(tf.zeros([3,3]))

变量定义完,必须显式的执行一下初始化操作:

init = tf.initialize_all_variables()

3.占位符

变量在定义时要初始化,但是如果有些变量刚开始我们并不知道它们的值,无法初始化,那怎么办呢?

那就用占位符来占个位置,如:

x = tf.placeholder(tf.float32,[None,784])

指定这个变量的类型和shape,以后再用feed的方式来输入值。

4.图(graph)

如果把下面的python语句改在tf语句,该怎么写呢:

x = 3
y = 2
z = x + y
print(z)

如果在tf中直接像上面这样写,那就错了。x,y,z分别是三个tensor对象,对象间的运算称之为操作(op), tf不会去一条条地执行各个操作,而是把所有的操作都放入到一个图(graph)中,图中的每一个结点就是一个操作。然后行将整个graph 的计算过程交给一个 TensorFlow 的Session, 此 Session 可以运行整个计算过程,比起操作(operations)一条一条的执行效率高的多。

执行代码如下:

import tensorflow as tf

x = tf.Variable(3)
y = tf.Variable(5)
z = x + y
init = tf.initialize_all_variables()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(z))

其中sess.run()即是执行,注意要先执行变量初始化操作,再执行运算操作。

Session需要先创建,使用完后还需要释放。因此我们使用with...as..语句,让系统自动释放。

例子1:hello world

import tensorflow as tf
s = tf.constant('hello world')
with tf.Session() as sess:
    print(sess.run(s))

例子2:加法和乘法

import tensorflow as tf
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)
add = tf.add(a,b)
mul = tf.mul(a,b)

with tf.Session() as sess:
    print('a+b=',sess.run(add,feed_dict={a:2,b:3}))
    print('a*b=',sess.run(mul,feed_dict={a:2,b:3}))

此处使用feed_dict以字典的方式对多个变量输入值。

例子3:矩阵乘法

import tensorflow as tf
a = tf.Variable(tf.ones([3,2]))
b = tf.Variable(tf.ones([2,3]))
product = tf.matmul(5*a,4*b)
init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(product))

其中

product=tf.matmul(5*a,4*b)

也可以改成

product=tf.matmul(tf.mul(5.0,a),tf.mul(4.0,b))

定义变量时,没有指定数据类型,则默认为float32,因此是5.0而不是5

posted @ 2017-02-24 10:32  zhoulixue  阅读(402)  评论(0编辑  收藏  举报