基於TensorFlow的機器學習(1) -- 基礎介紹
阿新 • • 發佈:2019-01-03
關於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. ]]
上述所有程式碼親測可在Ubuntu 16.04, python 2.7 相關環境下執行通過。