python调用gpu进行运算_tensorflow指定CPU与GPU运算的方法实现
1.指定GPU運算
如果安裝的是GPU版本,在運行的過程中TensorFlow能夠自動檢測。如果檢測到GPU,TensorFlow會盡可能的利用找到的第一個GPU來執(zhí)行操作。
如果機器上有超過一個可用的GPU,除了第一個之外的其他的GPU默認是不參與計算的。為了讓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è)備的字符串標識,當前支持的設(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)存,隨意會導致內(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)文章希望大家以后多多支持我們!
本文標題: tensorflow指定CPU與GPU運算的方法實現(xiàn)
本文地址: http://www.cppcns.com/jiaoben/python/309046.html
總結(jié)
以上是生活随笔為你收集整理的python调用gpu进行运算_tensorflow指定CPU与GPU运算的方法实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 字符串比较txt,PHP读到tx
- 下一篇: python画矩形函数drawrecta