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

转载于:https://www.cnblogs.com/goingforward/p/9970446.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值