python帶引數裝飾器使用
阿新 • • 發佈:2018-11-16
# -*- coding: utf-8 -* """TensorFlow指定使用GPU工具類 author: Jill usage: 方法上加@tf_with_device(device) 具體見本檔案demo """ from functools import wraps import tensorflow as tf def tf_with_device(device): """ Using the special device. args: device : gpu或者cpu名""" def decorate(func): @wraps(func) def wrapper(*args, **kwargs): with tf.device(device): result = func(*args, **kwargs) return result return wrapper return decorate # demo @tf_with_device('/cpu:0') def calculate(): c= [] a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3]) b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2]) c.append(tf.matmul(a, b)) # Creates a session with log_device_placement set to True. sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))# Runs the op. result = sess.run(tf.add_n(c)) print(result) return result a = calculate() print("result:\n" + str(a))
遇到一個在TensorFlow裡使用GPU的需求,看了下官網的使用介紹(https://www.tensorflow.org/guide/using_gpu?hl=zh-cn)然後就敲了樓上的那些程式碼。。。突然陷入沉思,真的是這麼用的嗎?_?,好像還不如直接在程式裡程式碼塊上加
tf.device(device)...
啊。。。求解答。。。