学习tensorflow从“tensor”开始

学习tensorflow一定要先从tensor开始,tensorflow是什么,他就是一种tensor计算框架,简单来说就是tensor+tensor_op也就是张量和在张量上的操作,如果你掌握了tensor和大部分的常用tensor op我觉得tensorflow就掌握得差不多了。然后tesor op就是张量操作这个东西其实是比较麻烦得一个事情。反正比较多,不可能一下子全部掌握。而且如果你不理解tensor是个什么东西,后面学习tensor op是很头疼的。各种错误,然后google,baidu...,下面我将从我将编程语言的角度和物理模型的角度来帮助你理解张量(tensor)是什么?

1 编程语言

我们知道python的一切都是类,所以tensor也是一个类,这个类的定义所在的目录如下:

目录:\python\Lib\site-packages\tensorflow\python\framework\ops.py
-------------------tensor类定义的主体代码------------------------

@tf_export("Tensor") 
#这个是python装饰器他的作用是使得调用这个类更加的方便
class Tensor(_TensorLike):
  """Represents one of the outputs of an `Operation`.

  def __init__(self, op, value_index, dtype):
    """Creates a new `Tensor`.

  @property
  #这个是python装饰器他的作用是把这个这个方法变成一个属性进行调用
  def op(self):
    """The `Operation` that produces this tensor as an output."""
    return self._op

  @property
  def dtype(self):
    """The `DType` of elements in this tensor."""
    return self._dtype

  @property
  def graph(self):
    """The `Graph` that contains this tensor."""
    return self._op.graph

  @property
  def name(self):
    """The string name of this tensor."""
    if not self._op.name:
      raise ValueError("Operation was not named: %s" % self._op)
    return "%s:%d" % (self._op.name, self._value_index)

  @property
  def device(self):
    """The name of the device on which this tensor will be produced, or None."""
    return self._op.device

  @property
  def shape(self):
    """Returns the `TensorShape` that represents the shape of this tensor.
  
  def eval(self, feed_dict=None, session=None):
    """Evaluates this tensor in a `Session`.

上面是tensor类的常用的几个属性和方法,当然tensor.name和tensor.shape其实是最常用的2个属性。tensor.name通常选择性保存模型参数和选择性加载模型参数的时候很有用,还有选择性冻结某一层的模型参数。通常会用到这个name,而tensor.shape在调试代码的时候会经常用来查看tensor的形状。更加详细的定义可以根据自己的需求去看源码。另外从数据结构的角度来说tensor也可以看成一个多维数组(但是它实际上不是多维数组,而是一种新的数据类型,从抽象的组成来看它就是一个多维数组)python的多维数组用ndarray来表示但是这两个不是同一个东西,主要是类定义的差别。

2 物理模型

以下图片来自:https://www.cnblogs.com/xiaoboge/p/9682352.html,如有侵权请联系删除

0维张量就是一个数,一维张量就是这个数沿着某一个轴比如x轴copy若干次形成一个一维张量,这个一维张量再沿着一个轴比如y轴copy若干次形成一个二维张量,这个二维张量沿着z轴copy若干次形成一个3维张量,这个3维张量又从x轴开始copy若干次形成一个4维张量,然后依次类推,注意这里是把张量想象成一个小的立方体,与张量的定义无关。

猜你喜欢

转载自blog.csdn.net/firesolider/article/details/103278231