亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

1.指定GPU運(yùn)算

如果安裝的是GPU版本,在運(yùn)行的過(guò)程中TensorFlow能夠自動(dòng)檢測(cè)。如果檢測(cè)到GPU,TensorFlow會(huì)盡可能的利用找到的第一個(gè)GPU來(lái)執(zhí)行操作。

如果機(jī)器上有超過(guò)一個(gè)可用的GPU,除了第一個(gè)之外的其他的GPU默認(rèn)是不參與計(jì)算的。為了讓TensorFlow使用這些GPU,必須將OP明確指派給他們執(zhí)行。with......device語(yǔ)句能夠用來(lái)指派特定的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)識(shí),當(dāng)前支持的設(shè)備包括以下的幾種:

cpu:0 機(jī)器的第一個(gè)cpu。

gpu:0 機(jī)器的第一個(gè)gpu,如果有的話(huà)

gpu:1 機(jī)器的第二個(gè)gpu,依次類(lèi)推

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

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

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

allow_soft_placement=True: 如果指定的設(shè)備不存在,允許TF自動(dòng)分配設(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è)置其屬性來(lái)分配GPU的運(yùn)算資源,如下代碼就是按需分配

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,剛開(kāi)始會(huì)分配少量的GPU容量,然后按需要慢慢的增加,有與不會(huì)釋放內(nèi)存,隨意會(huì)導(dǎo)致內(nèi)存碎片。

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

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分配固定大小的計(jì)算資源。

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

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

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

相關(guān)文章

最新評(píng)論