【问题标题】:Tensorflow - What does ops constructors mean?Tensorflow - ops 构造函数是什么意思?
【发布时间】:2016-07-10 15:50:35
【问题描述】:

在这个link 在建筑物下方的图表标题中有一行写着

“Python 库中的 ops 构造函数返回的对象代表构造的 ops 的输出。您可以将这些传递给其他 ops 构造函数以用作输入。”

构造函数这个词是什么意思?是在面向对象编程的上下文中还是在组装图的上下文中?

【问题讨论】:

  • 是不是说,tf.Constant是构造函数?

标签: python c++ constructor machine-learning tensorflow


【解决方案1】:

这实际上介于两者之间。 “Ops 构造函数”是指创建 Ops 对象的新实例的函数。例如 tf.constant 构造了一个新的操作,但实际上返回了对 Tensor 的引用作为该操作的结果,即 tensorflow.python.framework.ops.Tensor 的实例,但它不是 OOP 意义上的构造函数。

特别是有实际逻辑的东西,比如tf.add会同时创建tensorflow.python.framework.ops.Operation(执行加法)和tensorflow.python.framework.ops.Tensor(存储运算结果),并且只会返回张量(这就是引用的部分文档试图解释)。

例如:

import tensorflow as tf

tensor = tf.add(tf.constant(1), tf.constant(2))

for op in tf.get_default_graph().get_operations():
  print op

print tensor

会导致

name: "Const"
op: "Const"
attr {
  key: "dtype"
  value {
    type: DT_INT32
  }
}
attr {
  key: "value"
  value {
    tensor {
      dtype: DT_INT32
      tensor_shape {
      }
      int_val: 1
    }
  }
}

name: "Const_1"
op: "Const"
attr {
  key: "dtype"
  value {
    type: DT_INT32
  }
}
attr {
  key: "value"
  value {
    tensor {
      dtype: DT_INT32
      tensor_shape {
      }
      int_val: 2
    }
  }
}

name: "Add"
op: "Add"
input: "Const"
input: "Const_1"
attr {
  key: "T"
  value {
    type: DT_INT32
  }
}


Tensor("Add:0", shape=TensorShape([]), dtype=int32)

“在后台”创建了三个操作,而您仍然在 Tensor 级别上进行操作(由 tf.add 返回)。它的名称(默认创建)表明它是由Add 操作产生的张量。

更新

一个简单的基于python的例子可能更有用,所以TF做这样的事情:

class B:

  def __init__(self):
    print 'Constructor of class B is called'
    pass

class A:

  def __init__(self):
    print 'Constructor of class A is called'
    self.b = B()

def create_something():
  print 'Function is called'
  a = A()
  b = a.b
  print 'Function is ready to return'
  return b

print create_something()

你可以看到create_something 不是构造函数,它调用一些类的构造函数并返回一些实例,但它本身不是 OOP 意义上的构造函数(也不是初始化程序)。它更像是工厂设计范式。

【讨论】:

  • 如果我说 tf.Constant 是 OOP 中的构造函数,那我错了?
  • 是的,这是错误的。这不是 OOP 意义上的构造函数。它调用了几个构造函数,但它本身并不是一个面向对象的构造函数。
  • 好的,您能否更详细地解释一下您的答案?你的部分回答超出了我的想象。
  • 我无法理解的部分是,这个构造函数与 OOP 构造函数有何不同?你的意思是,像 add 构造函数调用三个构造函数,两个常量和一个 add 构造函数?
  • 我在我的代码中创建了一个仅 python 的示例来说明,希望它有所帮助。主要区别在于它是常规函数,属于工厂设计范式,OOP 中的构造函数被分配给特定的类。这不是,它比这更符合逻辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
  • 2017-01-01
  • 2013-04-25
  • 2015-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多