Tensorflow2疑難問題---2、tensorflow2.3的GPU版本安裝


Tensorflow2疑難問題---2、tensorflow2.3的GPU版本安裝

一、總結

一句話總結:

安裝tensorflow的gpu的版本的時候,要特別注意CUDA、cuDNN、tensorflow版本的一致性,在tensorflow官網可以查看對應版本關系

 

 

二、tensorflow2.3的GPU版本安裝

博客對應課程的視頻位置:

2、tensorflow2.3的GPU版本安裝(一)-范仁義-讀書編程筆記

https://www.fanrenyi.com/video/37/336

2、tensorflow2.3的GPU版本安裝(二)-范仁義-讀書編程筆記

https://www.fanrenyi.com/video/37/337

 

一、准備資料

需要顯卡,還需要安裝CUDA和cuDNN

1、顯卡

比如我這台機器,顯卡就是 NVIDIA GTX 1060,顯存6GB

2、CUDA(Compute Unified Device Architecture):統一計算架構

是顯卡廠商NVIDIA推出的運算平台。
CUDA是一種由NVIDIA推出的通用並行計算架構,該架構使GPU能夠解決復雜的計算問題。

3、CUDNN:NVIDIA cuDNN是用於深度神經網絡的GPU加速庫。

The NVIDIA CUDA® Deep Neural Network library (cuDNN) is a GPU-accelerated library of primitives for deep neural networks.

4、CUDA和CUDNN的關系

CUDA看作是一個工作台,上面配有很多工具,如錘子、螺絲刀等。
cuDNN是基於CUDA的深度學習GPU加速庫,有了它才能在GPU上完成深度學習的計算。

二、安裝CUDA和cuDNN

特別注意:

當配置CUDA、cuDNN、tensorflow時,要確保這三者之間的版本對應一致

在tensorflow官網可以查看這些軟件版本對應信息

https://tensorflow.google.cn/install/source_windows

1、安裝cuda

各個版本位置

https://developer.nvidia.com/cuda-toolkit-archive

2、安裝cuDNN

cuDNN各個版本的下載網址:

https://developer.nvidia.com/rdp/cudnn-archive#a-collapse51b

這個下載要注冊,太太太麻煩,

所以我們可以直接復制鏈接地址,迅雷下載即可,不要點進去,點進去要注冊麻煩

3、配置系統變量

 

 

4、驗證是否安裝成功

 

 

配置完成后,我們可以驗證是否配置成功,主要使用CUDA內置的deviceQuery.exe 和 bandwithTest.exe:

首先win+R啟動cmd,cd到安裝目錄下的 ...\extras\demo_suite,然后分別執行bandwidthTest.exe和deviceQuery.exe,

 

 

 

 

如果以上兩步都返回了Result=PASS,那么就算成功啦。

三、安裝tensorflow

如果安裝了tensorflow-cpu版本,可以先把cpu版本先卸了

pip uninstall tensorflow-cpu

然后再安裝gpu版本

pip install tensorflow-gpu

四、驗證tensorflow是否成功用gpu加速

In [2]:
import tensorflow as tf print("GPU:",tf.test.is_gpu_available()) 
WARNING:tensorflow:From <ipython-input-2-ae62284c8fe5>:2: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
GPU: True
In [3]:
tf.config.list_physical_devices('GPU') 
Out[3]:
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

五、卷積神經網絡中GUP和CPU性能對比

In [5]:
import  os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import tensorflow as tf from tensorflow.keras import layers, optimizers, datasets, Sequential # 按需分配GPU # from tensorflow.compat.v1 import ConfigProto # from tensorflow.compat.v1 import InteractiveSession # config = ConfigProto() # config.gpu_options.allow_growth = True # session = InteractiveSession(config=config) tf.random.set_seed(2345) # 卷積層 conv_layers = [ # 5 units of conv + max pooling # 5個單元 # unit 1 layers.Conv2D(64, kernel_size=[3, 3], padding="same", activation=tf.nn.relu), layers.Conv2D(64, kernel_size=[3, 3], padding="same", activation=tf.nn.relu), layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'), # unit 2 layers.Conv2D(128, kernel_size=[3, 3], padding="same", activation=tf.nn.relu), layers.Conv2D(128, kernel_size=[3, 3], padding="same", activation=tf.nn.relu), layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'), # unit 3 layers.Conv2D(256, kernel_size=[3, 3], padding="same", activation=tf.nn.relu), layers.Conv2D(256, kernel_size=[3, 3], padding="same", activation=tf.nn.relu), layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'), # unit 4 layers.Conv2D(512, kernel_size=[3, 3], padding="same", activation=tf.nn.relu), layers.Conv2D(512, kernel_size=[3, 3], padding="same", activation=tf.nn.relu), layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'), # unit 5 layers.Conv2D(512, kernel_size=[3, 3], padding="same", activation=tf.nn.relu), layers.Conv2D(512, kernel_size=[3, 3], padding="same", activation=tf.nn.relu), layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same') ] # 歸一化處理 def preprocess(x, y): # [0~1] x = tf.cast(x, dtype=tf.float32) / 255. y = tf.cast(y, dtype=tf.int32) return x,y # 加載數據 (x,y), (x_test, y_test) = datasets.cifar100.load_data() # 擠壓 y = tf.squeeze(y, axis=1) y_test = tf.squeeze(y_test, axis=1) print(x.shape, y.shape, x_test.shape, y_test.shape) # 訓練數據 train_db = tf.data.Dataset.from_tensor_slices((x,y)) train_db = train_db.shuffle(1000).map(preprocess).batch(128) # 測試數據 test_db = tf.data.Dataset.from_tensor_slices((x_test,y_test)) test_db = test_db.map(preprocess).batch(64) # 數據樣例 sample = next(iter(train_db)) print('sample:', sample[0].shape, sample[1].shape, tf.reduce_min(sample[0]), tf.reduce_max(sample[0])) def main(): # 卷積層 # [b, 32, 32, 3] => [b, 1, 1, 512] conv_net = Sequential(conv_layers) # 全連接層 fc_net = Sequential([ layers.Dense(256, activation=tf.nn.relu), layers.Dense(128, activation=tf.nn.relu), # 100個分類,輸出 layers.Dense(100, activation=None), ]) # 卷積層網絡構建 conv_net.build(input_shape=[None, 32, 32, 3]) # 全連接網絡構建 fc_net.build(input_shape=[None, 512]) # 優化函數 optimizer = optimizers.Adam(lr=1e-4) # [1, 2] + [3, 4] => [1, 2, 3, 4] # 所有的參數就是 卷積層的參數 和 全連接層的參數 variables = conv_net.trainable_variables + fc_net.trainable_variables for epoch in range(50): for step, (x,y) in enumerate(train_db): with tf.GradientTape() as tape: # 卷積層 # [b, 32, 32, 3] => [b, 1, 1, 512] out = conv_net(x) # reshape方便全連接層用 # flatten, => [b, 512] out = tf.reshape(out, [-1, 512]) # 全連接層 # [b, 512] => [b, 100] logits = fc_net(out) # [b] => [b, 100] y_onehot = tf.one_hot(y, depth=100) # compute loss:crossentropy loss = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True) loss = tf.reduce_mean(loss) grads = tape.gradient(loss, variables) optimizer.apply_gradients(zip(grads, variables)) if step %100 == 0: print(epoch, step, 'loss:', float(loss)) total_num = 0 total_correct = 0 for x,y in test_db: out = conv_net(x) out = tf.reshape(out, [-1, 512]) logits = fc_net(out) prob = tf.nn.softmax(logits, axis=1) pred = tf.argmax(prob, axis=1) pred = tf.cast(pred, dtype=tf.int32) correct = tf.cast(tf.equal(pred, y), dtype=tf.int32) correct = tf.reduce_sum(correct) total_num += x.shape[0] total_correct += int(correct) acc = total_correct / total_num print(epoch, 'acc:', acc) if __name__ == '__main__': with tf.device("/cpu:0"): main() 
(50000, 32, 32, 3) (50000,) (10000, 32, 32, 3) (10000,)
sample: (128, 32, 32, 3) (128,) tf.Tensor(0.0, shape=(), dtype=float32) tf.Tensor(1.0, shape=(), dtype=float32)
0 0 loss: 4.605703353881836

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM