python带参数装饰器使用

# -*- 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)...
啊。。。求解答。。。

猜你喜欢

转载自www.cnblogs.com/goingforward/p/9970446.html
今日推荐