TensowFlow 2 基本語法

      在〈TensowFlow 2 基本語法〉中留言功能已關閉

TensorFlow的作用-切換到 GPU 執行

為什麼要使用 TensorFlow,它的目的是什麼? 簡易的說,就是要把四則運算交由 GPU 執行。
為什麼要交由 GPU 執行? 因為 GPU 有上千台計算機(核心)可以同時幫忙計算,但 CPU 只有一台計算機。

x= 3.1415926 * (10**2) 這個指令是計算半徑為 10 的圓面積,此指令是由 CPU 的浮點運算器進行運算。

那如何交由 GPU 執行? 這時就要使用 Tensorflow 。所以 Tensorflow 的任務就是負責把運算切換到 GPU 執行。

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
#底下是由 CPU 執行
pi=3.1415926
r=10
print(pi*r*r)

#底下是由 GPU 執行
pi=tf.constant(3.1415926)
r=tf.Variable(10, dtype=tf.float32)
print(pi*r*r)

Hellow World

使用 tf.constant 定義一個常數 str,其內容值為 “hello, World”
如果直接把str印出,則會印出內容,維度,及型態
若只要印出內容,則必需加上str.numpy()

import tensorflow as tf
str = tf.constant("hello, World")
print("Tensor:", str)
print("Value :", str.numpy())

結果:
2021-01-24 21:50:03.414182: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cudart64_110.dll
....................
2021-01-24 21:50:05.116465: I tensorflow/compiler/jit/xla_gpu_device.cc:99] Not creating XLA devices, tf_xla_enable_xla_devices not set
Tensor: tf.Tensor(b'hello, World', shape=(), dtype=string)
Value : b'hello, World'

輸出日誌

上面的程式碼執行後,有看到灰白色那一大段莫名奇妙五四三的訊息嗎! 真正重要的結果只有藍色那二行而以。那如何去除那些五四三的訊息呢。

TensorFlow 的訊息輸出機制,分為 4 個等級
0: INFO(通知)
1: WARNING(警告)
2: ERROR(錯誤)
3: FATAL(穩死的)

通知跟警告,其實都是廢話,所以只要顯示等級 2 及以上就好。如下代碼即可滿足我們的需求
 os.environ[‘TF_CPP_MIN_LOG_LEVEL’]=’2′

請注意,一定要在import tensorflow as tf  之前設定,才會生效!!!!  如果把 “import tensorflow as tf”  放在前面,就完全無效

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
str = tf.constant("hello, World")
print("Tensor:", str)
print("Value :", str.numpy())

結果:
Tensor: tf.Tensor(b'hello, World', shape=(), dtype=string)
Value : b'hello, World'

常數 tf.Tensor 類別

tensorflow 是一台功能很強大的計算機,但這台計算機沒有 int, float 這種原生基本資料型態,全部都是物件格式,這跟 Python 的特性一樣。

tf2 的基本常數類別為 tf.Tensor,中文翻譯為張量,不過翻成中文沒什麼意義,因為 “張量” 這名詞愈翻譯愈看不懂,所以只要記得 tf.Tensor 是 tensorflow 的常數類別就好

tf.Tensor 物件裏面的值一經指定後就無法變更的,裏面有很多的計算函數,且大部份的函數用法跟 numpy 類似。Tensor 物件裏面可以放入字串、數字或矩陣。

要建立 tf.Tensor 常數類別,並不是使用如下的方法

 x=tf.Tensor(.....)

建立 Tensor 物件必需使用 tf.constant() 這個方法,這個方法會產生 operation, value_index, dtype 等資料,然後再傳回 tf.Tensor 物件。

x=tf.constant(10, dtype=tf.int32) #產生 Tensor 物件

Tensor 屬性

Tensor 類別裏面有許多的屬性 (Property) 及方法 (method),比如 shape 維度,dtype 型態, numpy() 轉成Python 資料格式。

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
a=tf.constant(5)
b=tf.constant([[1,2,3], [4,5,6]])
print(a.shape, a.dtype, a.numpy())
print(b.shape, b.dtype, b.numpy())
結果 :
() <dtype: 'int32'> 5
(2, 3) <dtype: 'int32'> [[1 2 3]
[4 5 6]]

tf.constant方法

請注意 tf.constant 只是一個方法,其目的在建立一個 tf.Tensor 常數物件。因為是方法,所以constant 的 “c” 是小寫。而其傳回值為 tf.Tensor物件,所以底下代碼列印 a 這個接收變數時,型態為 tf.Tensor

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
a=tf.constant(5)
print(a)
結果:
tf.Tensor(1.0, shape=(), dtype=float32)

變數 tf.Variable 類別

tf.Variable 為 tf2 的變數類別

請注意這不是物件導向中的 類別變數 喔,類別變數是物件導向的 static variable,是存在類別中的變數。

tf.Variable 裏面的值可以改變,列印出來的結果直接顯示為 tf.Variable。首先要用 x = tf.Variable(值) 初始化變數值。若要更改其值,需使用 x.assign(值) 。

為什麼改變值不能直接使用 x = 100 呢? 因為這時 x 又變回了 Python 的 int32型態了。

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
x=tf.Variable(10)
print(x)

#底下的 x 還是 Tensor型態
x.assign(100)
print(x)

#底下的 x 變成了 Python的 int 型態 
x=100
print(x)

結果 :
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=10>
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=100>
10

資料型態

不論是常數 (tf.Tensor) 或變數 (tf.Variable),都可以使用 dtype 指定型態。常用的型態有

整數 : tf.int8, tf.int16, tf.int32, tf.int64,預設為 tf.int32。另外還有 uint8, uint16, uint32, uint64(unsigned)無號數型態。
小數 : tf.float16, tf.float32, tf.float64, 預設為 tf.float32
字串 : tf.string

a=tf.Variable(10)
b=tf.Variable(10.)
c=tf.Variable("Hello") print(a) print(b)
print(c) 結果: <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=10> <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=10.0> <tf.Variable 'Variable:0' shape=() dtype=string, numpy=b'abcd'>

四則運算

TensorFlow 這個強大的計算機,當然可以進行四則運算。請注意無論常數或變數,型態如果不一樣,就不能進行計算的。比如 x=tf.constant(10.),y=tf.constant(3),x 是 tf.float32,y是tf.int32,所以 x 跟 y 就不能進行四則運算。

常用的四則運算有 + – * /。 “/” 為除號,二數若為整數(tf.int32),運算的結果會變成tf.float64,這跟 Python的特性是一樣的。

如果要求取商數,則要使用 “//”。

另外 “%” 為求取餘數。但請注意,小數為能求餘數,否則會出現例外錯誤。

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
x = tf.constant(10)
y = tf.constant(3)
a=x+y
b=x-y
c=x*y
d=x/y
e=x//y #求商數
f=x%y #求餘數
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
結果:
tf.Tensor(13, shape=(), dtype=int32)
tf.Tensor(7, shape=(), dtype=int32)
tf.Tensor(30, shape=(), dtype=int32)
tf.Tensor(3.3333333333333335, shape=(), dtype=float64)
tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)

指定運算子 “= “

使用指定運算子 “=”,比如 a = x + y,不論 x, y 是 tf.Tensor 或 tf.Variable,最後的 a 值一定是 tf.Tensor

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
x=tf.Variable(10)
y=tf.constant(3)
a = x / y
print(a)
結果 :
tf.Tensor(3.3333333333333335, shape=(), dtype=float64)

商數

求商數的運算子為 “//”。二者若為tf.int32,結果也是 tf.int32。但若有一方是 tf.float32/64,結果會是 tf.float,這也跟 Python 的特性一模一樣。

import tensorflow as tf
a=tf.Variable(5)
b=tf.Variable(5.)
print(a.numpy()//2)
print(b.numpy()//2)
結果:
2
2.0

型態轉換

不同型態的常數或變數無法進行四則運算,所以型態轉換變成了必要的手段。

tf.cast(變數, 型態) 就是型態轉換的函數

import tensorflow as tf
a = tf.constant(10.)
b = tf.cast(a, tf.int32)
print("a=", a)
print("b=", b)
結果:
a= tf.Tensor(10.0, shape=(), dtype=float32)
b= tf.Tensor(10, shape=(), dtype=int32)