TensorFlow安裝
tensorflow 在 Windows 10 只能使用 2.10.1 的版本才能啟用 GPU,所以請使用如下指令安裝套件。
#for windows 10
pip install tensorflow==2.10.1
但在 Linux 下 2.10.1 反而無法啟用 GPU,需安裝最新的版本,所以請使用如下指令安裝套件。
#for linux
./venv/bin/pip install tensorflow
TensorFlow的功能
為什麼要使用 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 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 的變數類別。
