python - Tensorflow - ops 构造函数是什么意思?

标签 python c++ constructor machine-learning tensorflow

在此link在建筑物的图表标题下,有一行内容是

"The ops constructors in the Python library return objects that stand for the output of the constructed ops. You can pass these to other ops constructors to use as inputs."

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

最佳答案

这实际上介于两者之间。 “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 意义上的构造函数(也不是初始化程序)。它更像是工厂设计范例。

关于python - Tensorflow - ops 构造函数是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38293688/

相关文章:

python - 将 PANDAS 中的索引转换为最新日期

python - 图像生成器缺少 unet keras 的位置参数

python - conda 中不提供 Pip 包

c++ - 制作目标和依赖名称格式

python - 适用于 Python 3 的 Jupyter Notebook 中出现 ModuleNotFoundError,但不适用于 Python 2 (Mac OSX)

c++ - 将 std::unique_ptr 插入 boost:ptr_map

android - 将 Sprite 矩形旋转 90 度不符合 iOS 中的纵横比

c# - 部分类构造器

c++ - 接受字符串引用的构造函数。馊主意?

c++ - 无法从 switch case 语句传递构造函数的参数