关于tensorflow的相关基础概念,可以参考之前写过的介绍文章。后期由于需要进行大量的代码实践,因此将会基于源代码对Tensorflow进行系统性的学习。
首先是使用tensorflow输出Hello World:
import tensorflow as tf
# simple hello world using Tensorflow
# Create a Constant op
# The op is added as a node to the default graph
# The value returned by the constructor represents the output
# of the Constant op.
hello = tf.constant("Hello, Tensorflow!")
# Start tf session
sess = tf.Session()
# Run graph
print sess.run(hello) # => Hello, Tensorflow!
相对而言较为简单,不进行详述。
接下来看tensorflow如何采用常量的方式进行算数运算:
import tensorflow as tf
a = tf.constant(2)
b = tf.constant(3)
# Launch the default graph.
with tf.Session() as sess:
print "a: %i" % sess.run(a), "b: %i" % sess.run(b)
#print "Add: %i" % (sess.run(a) + sess.run(b))
print "Add: %i" % sess.run(a+b)
print "Mul: %i" % sess.run(a*b)
# a:2 b:3, Add: 5, Mul: 6
我们知道,tensorflow是基于图的张量流运算,而上述是直接进行的常量声明,与实际并不是很相符合,因此我们接下来进行张量流图的使用:
import tensorflow as tf
a = tf.placeholder(tf.int32)
b = tf.placeholder(tf.int32)
# Define some operations
add = tf.add(a, b)
mul = tf.multiply(a, b)
# Launch the default graph
with tf.Session() as sess:
print "Add: %i" % sess.run(add, feed_dict={a:2, b:3})
print "Mul: %i" % sess.run(mul, feed_dict={a:2, b:3})
# Add: 5 Mul: 6
上述所有都是张量,还可以使用矩阵来进行操作(机器学习中几乎所有的运算归根结底都是h矩阵运算):
import tensorflow as tf
matrix1 = tf.constant([[3.,3.]])
# print matrix1
matrix2 = tf.constant([[2.], [2.]])
# print matrix2
product = tf.matmul(matrix1, matrix2)
# print product
with tf.Session() as sess:
result = sess.run(product)
print result # => [[ 12. ]]
以上即是tensorflow基础运算的所有内容,内容编写主要的参考资料为https://github.com/aymericdamien/TensorFlow-Examples。
上述所有代码亲测可在Ubuntu 16.04, python 2.7 相关环境下运行通过。