欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

tensorflow指定CPU與GPU運算的方法實現(xiàn)

 更新時間:2020年04月21日 15:44:28   作者:Baby-Lily  
這篇文章主要介紹了tensorflow指定CPU與GPU運算的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1.指定GPU運算

如果安裝的是GPU版本,在運行的過程中TensorFlow能夠自動檢測。如果檢測到GPU,TensorFlow會盡可能的利用找到的第一個GPU來執(zhí)行操作。

如果機器上有超過一個可用的GPU,除了第一個之外的其他的GPU默認(rèn)是不參與計算的。為了讓TensorFlow使用這些GPU,必須將OP明確指派給他們執(zhí)行。with......device語句能夠用來指派特定的CPU或者GPU執(zhí)行操作:

import tensorflow as tf
import numpy as np

with tf.Session() as sess:
  with tf.device('/cpu:0'):
    a = tf.placeholder(tf.int32)
    b = tf.placeholder(tf.int32)
    add = tf.add(a, b)
    sum = sess.run(add, feed_dict={a: 3, b: 4})
    print(sum)

設(shè)備的字符串標(biāo)識,當(dāng)前支持的設(shè)備包括以下的幾種:

cpu:0 機器的第一個cpu。

gpu:0 機器的第一個gpu,如果有的話

gpu:1 機器的第二個gpu,依次類推

類似的還有tf.ConfigProto來構(gòu)建一個config,在config中指定相關(guān)的GPU,并且在session中傳入?yún)?shù)config=“自己創(chuàng)建的config”來指定gpu操作

其中,tf.ConfigProto函數(shù)的參數(shù)如下:

log_device_placement=True: 是否打印設(shè)備分配日志

allow_soft_placement=True: 如果指定的設(shè)備不存在,允許TF自動分配設(shè)備

import tensorflow as tf
import numpy as np

config = tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)

with tf.Session(config=config) as sess:
  a = tf.placeholder(tf.int32)
  b = tf.placeholder(tf.int32)
  add = tf.add(a, b)
  sum = sess.run(add, feed_dict={a: 3, b: 4})
  print(sum)

2.設(shè)置GPU使用資源

上文的tf.ConfigProto函數(shù)生成的config之后,還可以設(shè)置其屬性來分配GPU的運算資源,如下代碼就是按需分配

import tensorflow as tf
import numpy as np

config = tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)
config.gpu_options.allow_growth = True

with tf.Session(config=config) as sess:
  a = tf.placeholder(tf.int32)
  b = tf.placeholder(tf.int32)
  add = tf.add(a, b)
  sum = sess.run(add, feed_dict={a: 3, b: 4})
  print(sum)

使用allow_growth option,剛開始會分配少量的GPU容量,然后按需要慢慢的增加,有與不會釋放內(nèi)存,隨意會導(dǎo)致內(nèi)存碎片。

同樣,上述的代碼也可以在config創(chuàng)建時指定,

import tensorflow as tf
import numpy as np

gpu_options = tf.GPUOptions(allow_growth=True)
config = tf.ConfigProto(gpu_options=gpu_options)


with tf.Session(config=config) as sess:
  a = tf.placeholder(tf.int32)
  b = tf.placeholder(tf.int32)
  add = tf.add(a, b)
  sum = sess.run(add, feed_dict={a: 3, b: 4})
  print(sum)

我們還可以給gpu分配固定大小的計算資源。

gpu_options = tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction=0.5)

上述代碼的含義是分配給tensorflow的GPU顯存大小為:GPU的實際顯存*0.5

到此這篇關(guān)于tensorflow指定CPU與GPU運算的方法實現(xiàn)的文章就介紹到這了,更多相關(guān)tensorflow指定CPU與GPU運算內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論