zoukankan      html  css  js  c++  java
  • 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:
    " + str(a))

    遇到一个在TensorFlow里使用GPU的需求,看了下官网的使用介绍(https://www.tensorflow.org/guide/using_gpu?hl=zh-cn)然后就敲了楼上的那些代码。。。突然陷入沉思,真的是这么用的吗?_?,好像还不如直接在程序里代码块上加

    tf.device(device)...
    啊。。。求解答。。。
  • 相关阅读:
    密码框组件
    文本框组件
    列表框组件
    复选框组件
    单选按钮组件
    nginx for windows
    Mesa 3D
    下载服务器文件到本地
    消息服务
    Redis查看已注册的提供者消费者信息
  • 原文地址:https://www.cnblogs.com/goingforward/p/9970446.html
Copyright © 2011-2022 走看看