標籤:

TensorFlow 的簡單例子

在本文中,我們將看一些 TensorFlow 的例子,並從中感受到在定義張量(tensor)和使用張量做數學計算方面有多麼容易,我還會舉些別的機器學習相關的例子。

TensorFlow 是什麼?

TensorFlow 是 Google 為了解決複雜的數學計算耗時過久的問題而開發的一個庫。

事實上,TensorFlow 能幹許多事。比如:

  • 求解複雜數學表達式
  • 機器學習技術。你往其中輸入一組數據樣本用以訓練,接著給出另一組數據樣本基於訓練的數據而預測結果。這就是人工智慧了!
  • 支持 GPU 。你可以使用 GPU(圖像處理單元)替代 CPU 以更快的運算。TensorFlow 有兩個版本: CPU 版本和 GPU 版本。

開始寫例子前,需要了解一些基本知識。

什麼是張量?

張量tensor是 TensorFlow 使用的主要的數據塊,它類似於變數,TensorFlow 使用它來處理數據。張量擁有維度和類型的屬性。

維度指張量的行和列數,讀到後面你就知道了,我們可以定義一維張量、二維張量和三維張量。

類型指張量元素的數據類型。

定義一維張量

可以這樣來定義一個張量:創建一個 NumPy 數組(LCTT 譯註:NumPy 系統是 Python 的一種開源數字擴展,包含一個強大的 N 維數組對象 Array,用來存儲和處理大型矩陣 )或者一個 Python 列表 ,然後使用 tf_convert_to_tensor 函數將其轉化成張量。

可以像下面這樣,使用 NumPy 創建一個數組:

import numpy as np arr = np.array([1, 5.5, 3, 15, 20])arr = np.array([1, 5.5, 3, 15, 20])

運行結果顯示了這個數組的維度和形狀。

import numpy as nparr = np.array([1, 5.5, 3, 15, 20])print(arr)print(arr.ndim)print(arr.shape)print(arr.dtype)

它和 Python 列表很像,但是在這裡,元素之間沒有逗號。

現在使用 tf_convert_to_tensor 函數把這個數組轉化為張量。

import numpy as npimport tensorflow as tfarr = np.array([1, 5.5, 3, 15, 20])tensor = tf.convert_to_tensor(arr,tf.float64)print(tensor)

這次的運行結果顯示了張量具體的含義,但是不會展示出張量元素。

要想看到張量元素,需要像下面這樣,運行一個會話:

import numpy as npimport tensorflow as tfarr = np.array([1, 5.5, 3, 15, 20])tensor = tf.convert_to_tensor(arr,tf.float64)sess = tf.Session()print(sess.run(tensor))print(sess.run(tensor[1]))

定義二維張量

定義二維張量,其方法和定義一維張量是一樣的,但要這樣來定義數組:

arr = np.array([(1, 5.5, 3, 15, 20),(10, 20, 30, 40, 50), (60, 70, 80, 90, 100)])

接著轉化為張量:

import numpy as npimport tensorflow as tfarr = np.array([(1, 5.5, 3, 15, 20),(10, 20, 30, 40, 50), (60, 70, 80, 90, 100)])tensor = tf.convert_to_tensor(arr)sess = tf.Session()print(sess.run(tensor))

現在你應該知道怎麼定義張量了,那麼,怎麼在張量之間跑數學運算呢?

在張量上進行數學運算

假設我們有以下兩個數組:

arr1 = np.array([(1,2,3),(4,5,6)])arr2 = np.array([(7,8,9),(10,11,12)])

利用 TenserFlow ,你能做許多數學運算。現在我們需要對這兩個數組求和。

使用加法函數來求和:

import numpy as npimport tensorflow as tfarr1 = np.array([(1,2,3),(4,5,6)])arr2 = np.array([(7,8,9),(10,11,12)])arr3 = tf.add(arr1,arr2)sess = tf.Session()tensor = sess.run(arr3)print(tensor)

也可以把數組相乘:

import numpy as npimport tensorflow as tfarr1 = np.array([(1,2,3),(4,5,6)])arr2 = np.array([(7,8,9),(10,11,12)])arr3 = tf.multiply(arr1,arr2)sess = tf.Session()tensor = sess.run(arr3)print(tensor)

現在你知道了吧。

三維張量


我們已經知道了怎麼使用一維張量和二維張量,現在,來看一下三維張量吧,不過這次我們不用數字了,而是用一張 RGB 圖片。在這張圖片上,每一塊像素都由 x、y、z 組合表示。

這些組合形成了圖片的寬度、高度以及顏色深度。

首先使用 matplotlib 庫導入一張圖片。如果你的系統中沒有 matplotlib ,可以 使用 pip來安裝它。

將圖片放在 Python 文件的同一目錄下,接著使用 matplotlib 導入圖片:

import matplotlib.image as imgmyfile = "likegeeks.png"myimage = img.imread(myfile)print(myimage.ndim)print(myimage.shape)

從運行結果中,你應該能看到,這張三維圖片的寬為 150 、高為 150 、顏色深度為 3 。

你還可以查看這張圖片:

import matplotlib.image as imgimport matplotlib.pyplot as plotmyfile = "likegeeks.png"myimage = img.imread(myfile)plot.imshow(myimage)plot.show()

真酷!

那怎麼使用 TensorFlow 處理圖片呢?超級容易。

使用 TensorFlow 生成或裁剪圖片

首先,向一個佔位符賦值:

myimage = tf.placeholder("int32",[None,None,3])

使用裁剪操作來裁剪圖像:

cropped = tf.slice(myimage,[10,0,0],[16,-1,-1])

最後,運行這個會話:

result = sess.run(cropped, feed\_dict={slice: myimage})

然後,你就能看到使用 matplotlib 處理過的圖像了。

這是整段代碼:

import tensorflow as tfimport matplotlib.image as imgimport matplotlib.pyplot as plotmyfile = "likegeeks.png"myimage = img.imread(myfile)slice = tf.placeholder("int32",[None,None,3])cropped = tf.slice(myimage,[10,0,0],[16,-1,-1])sess = tf.Session()result = sess.run(cropped, feed_dict={slice: myimage})plot.imshow(result)plot.show()

是不是很神奇?

使用 TensorFlow 改變圖像

在本例中,我們會使用 TensorFlow 做一下簡單的轉換。

首先,指定待處理的圖像,並初始化 TensorFlow 變數值:

myfile = "likegeeks.png"myimage = img.imread(myfile)image = tf.Variable(myimage,name=image)vars = tf.global_variables_initializer()

然後調用 transpose 函數轉換,這個函數用來翻轉輸入網格的 0 軸和 1 軸。

sess = tf.Session()flipped = tf.transpose(image, perm=[1,0,2])sess.run(vars)result=sess.run(flipped)

接著你就能看到使用 matplotlib 處理過的圖像了。

import tensorflow as tfimport matplotlib.image as imgimport matplotlib.pyplot as plotmyfile = "likegeeks.png"myimage = img.imread(myfile)image = tf.Variable(myimage,name=image)vars = tf.global_variables_initializer()sess = tf.Session()flipped = tf.transpose(image, perm=[1,0,2])sess.run(vars)result=sess.run(flipped)plot.imshow(result)plot.show()

以上例子都向你表明了使用 TensorFlow 有多麼容易。


via: codementor.io/likegeeks

作者:LikeGeeks 譯者:ghsgz 校對:wxy

本文由 LCTT 原創編譯,Linux中國 榮譽推出

推薦閱讀:

學習筆記TF040:多GPU並行
TensorFlow 到底慢在哪裡?
Berkeley CS294-112 深度增強學習 筆記 (4) 策略梯度法
用tf.placeholder構建features, labels容器
TensorFlow筆記

TAG:TensorFlow |