Tensorflow中tf.ConfigProto()的用法詳解
參考Tensorflow Machine Leanrning Cookbook
tf.ConfigProto()主要的作用是配置tf.Session的運算方式,比如gpu運算或者cpu運算
具體代碼如下:
import tensorflow as tf session_config = tf.ConfigProto( log_device_placement=True, inter_op_parallelism_threads=0, intra_op_parallelism_threads=0, allow_soft_placement=True) sess = tf.Session(config=session_config) a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2,3], name='b') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3,2], name='b') c = tf.matmul(a,b) print(sess.run(c))
具體解釋
log_device_placement=True
設(shè)置為True時,會打印出TensorFlow使用了那種操作
inter_op_parallelism_threads=0
設(shè)置線程一個操作內(nèi)部并行運算的線程數(shù),比如矩陣乘法,如果設(shè)置為0,則表示以最優(yōu)的線程數(shù)處理
intra_op_parallelism_threads=0
設(shè)置多個操作并行運算的線程數(shù),比如 c = a + b,d = e + f . 可以并行運算
allow_soft_placement=True
有時候,不同的設(shè)備,它的cpu和gpu是不同的,如果將這個選項設(shè)置成True,那么當(dāng)運行設(shè)備不滿足要求時,會自動分配GPU或者CPU。
其他選項
當(dāng)使用GPU時候,Tensorflow運行自動慢慢達到最大GPU的內(nèi)存
session_config.gpu_options.allow_growth = True
當(dāng)使用GPU時,設(shè)置GPU內(nèi)存使用最大比例
session_config.gpu_options.per_process_gpu_memory_fraction = 0.4
是否能夠使用GPU進行運算
tf.test.is_built_with_cuda()
另外的處理方法
import tensorflow as tf
sess = tf.Session()
with tf.device('/cpu:0'):
a = tf.constant([1.0, 3.0, 5.0], shape=[1, 3])
b = tf.constant([2.0, 4.0, 6.0], shape=[3, 1])
with tf.device('/gpu:0'):
c = tf.matmul(a, b)
c = tf.reshape(c, [-1])
with tf.device('/gpu:0'):
d = tf.matmul(b, a)
flat_d = tf.reshape(d, [-1])
combined = tf.multiply(c, flat_d)
print(sess.run(combined))
以上這篇Tensorflow中tf.ConfigProto()的用法詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
cv2.imread?和?cv2.imdecode?用法及區(qū)別
對于路徑中含有中文的圖像,直接用cv2.imread讀取會報錯,上次看到有大佬使用cv2.imdecode就可以正常讀取,有點好奇,所以今天來記錄下二者用法和區(qū)別,感興趣的朋友跟隨小編一起看看吧2023-02-02
Python 中的 import 機制之實現(xiàn)遠程導(dǎo)入模塊
模塊導(dǎo)入( import ),是指在一個模塊中使用另一個模塊的代碼的操作,它有利于代碼的復(fù)用。這篇文章主要介紹了Python 的 import 機制:實現(xiàn)遠程導(dǎo)入模塊,需要的朋友可以參考下2019-10-10

