TensorFlow安裝

      在〈TensorFlow安裝〉中尚無留言

學習 TensorFlow 就像在學習 numpy 或 pandas 一樣,有自已的資料格式,也有自已的計算函數跟規則。TensorFlow 可以幫我們計算複雜的數學公式,比如矩陣相乘,微分,損失函數等等,可以將它視為一個科學計算套件。

TensorFlow 計算領域非常廣泛,所以學習之路非常漫長,不像 numpy 或 pandas 幾天就可以學會的。

TensorFlow是 Google 維護的一個機器深度學習框架。因為它已被用來尋找新的行星,幫助醫生篩檢糖尿病導致視網膜病變,以預防失明。AlphoGo及Google Cloud Vision 更建立在TensorFlow 之上。TensorFlow完全開放原始碼。

TensorFlow也是目前神經網路使用率最高的框架。而其Keras(凱拉斯)則是支援 TensorFlow 的高階函數庫,可以用很簡潔的程式碼完成神經網路模型. 下圖為網路上統計各種框架的使用率。

TensorFlow現今已到了第2版本。第1版與第2版本的使用方式完全不同,太多數的網站都是第1版本的教學。此篇以 TensorFlow2為主。

安裝 Tensorflow 套件

tensorflow 2.10.1 在 Windows 下還可支援 GPU 運算,但後面的版本就全面不再支援 GPU 。

如果想要啟動 GPU,則有二種方式

在 Windows 下安裝 Python 3.8 + Cuda 11.8 + Tensorflow 2.10.1

Windows + Python3.8 + Cuda 11.8

pip install tensorflow == 2.10.1

在 Linux 下安裝 Python 3.12.3 + Cuda 12.6 + Tensorflow 任何版本

Linux + Python 3.12.3 + Cuda 12.6

pip install tensorflow

反正 Google 已放棄 TensorFlow 在 Windows 下支援 GPU。所以不要再浪費時間 survey Windows 系統了,請轉為使用 Linux。

Linux 偵測硬体設備

底下可以印出機器的硬体設備。set_visible_devices()的參數 devices=gpus[0],是使用第0塊顯示卡。若要多塊顯示卡一起用,可以下達 devices=gpus[0:2](使用 0,1二塊顯卡,不包含2)。

底下代碼中 device_type=’GPU’ ,參數名 “device_type” 可以不用打,直接輸入 ‘GPU’即可。因為list_pyhsical_devices(device_type=None) 只有接收一個參數而以,預設值為None。

gpus = tf.config.list_physical_devices(device_type='GPU')
cpus = tf.config.list_physical_devices('CPU') #device_type可以不用打
print(gpus, cpus)
#限定使用GPU
tf.config.set_visible_devices(devices=gpus[0], device_type='GPU')
結果 :
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')] [PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU')]

限定使用CPU或GPU

tf.config.set_visible_devices()可以限定只使用CPU,或使用GPU。若沒調用此方法,預設會啟動 GPU。

cpus = tf.config.list_physical_devices (device_type='CPU')
tf.config.set_visible_devices (gpus[0], device_type='GPU') #只使用GPU
tf.config.set_visible_devices (devices=cpus[0]) #只使用 CPU, device_type預設是'CPU'

常數測試

import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
tf.print(msg)

矩陣相乘

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
a = tf.constant([[1, 2], [3, 4]])
b = tf.constant([[5, 6], [7, 8]])
c = tf.matmul(a, b)
print(c.numpy())
結果 :
[[19 22]
[43 50]]

參考:

1. https://medium.com/arthur-chien/python-tensorflow2%E7%AD%86%E8%A8%98-f3a97f571b8e
2. https://tf.wiki/zh_hant/  <==中文書

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *