如何以 OOP 风格使用 TensorFlow? [英] How to use TensorFlow in OOP style?

查看:26
本文介绍了如何以 OOP 风格使用 TensorFlow?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具体来说,当使用 TensorFlow 以 OOP 风格构建我的模型时,我应该在哪里构建图形?我应该在哪里开始会话来运行图表?这种情况下的最佳做法是什么?

Specifically, when using TensorFlow to build my model in OOP style, where should I build the graph? Where should I start a session to run the graph? What's the best practice for this case?

TensorFlow Mechanics 101 中,MNIST 示例只是简单地定义了 mnist.py 模块中的 inference、losstraining 函数,并在 fully_connected_feed.py 中构建图代码>.但在我看来,图实际上是模型的一部分,应该在模型内部构建,也许在它的 __init__ 方法中.

In TensorFlow Mechanics 101, the MNIST example just simply define the inference, loss and training function in the module mnist.py and build the graph in fully_connected_feed.py. But in my opinion, the graph is actually part of the model and should be built inside the model, maybe in its __init__ method.

我在 model zoo 中看到了许多其他使用 TensorFlow 的模型,并且每个模型都有自己的实践,所以我在这里有点困惑.使用 TensorFlow 时是否有最佳实践或任何推荐的编程范式?

I have seen many other models using TensorFlow in its model zoo and each have their own practice, so I am a little confused here. Is there a best practice or any recommended programming paradigms when using TensorFlow?

推荐答案

另请查看有关此主题的精彩文章:

Also check out a nice article about this topic:

https://danijar.com/structuring-your-tensorflow-models/

在本文中,Danijar Hafner 介绍了惰性属性:

In this article, Danijar Hafner introduces lazy property:

class Model:

    def __init__(self, data, target):
        self.data = data
        self.target = target
        self.prediction
        self.optimize
        self.error

    @lazy_property
    def prediction(self):
        data_size = int(self.data.get_shape()[1])
        target_size = int(self.target.get_shape()[1])
        weight = tf.Variable(tf.truncated_normal([data_size, target_size]))
        bias = tf.Variable(tf.constant(0.1, shape=[target_size]))
        incoming = tf.matmul(self.data, weight) + bias
        return tf.nn.softmax(incoming)

    @lazy_property
    def optimize(self):
        cross_entropy = -tf.reduce_sum(self.target, tf.log(self.prediction))
        optimizer = tf.train.RMSPropOptimizer(0.03)
        return optimizer.minimize(cross_entropy)

    @lazy_property
    def error(self):
        mistakes = tf.not_equal(
            tf.argmax(self.target, 1), tf.argmax(self.prediction, 1))
        return tf.reduce_mean(tf.cast(mistakes, tf.float32))

在文章中查看更多.

这篇关于如何以 OOP 风格使用 TensorFlow?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆