牛骨文教育服务平台(让学习变的简单)
博文笔记

tensorflow编程填坑笔记

创建时间:2017-04-20 投稿人: 浏览次数:3464

1. tf.mul(a,b) 和 tf.matmul(a,b)

tf.mul(a,b) 这里的矩阵a和矩阵b的shape必须相等 tf.mul()是矩阵的element-wise相乘(即Hadamard乘积)
tf.matmul(a,b) 这里的矩阵a和矩阵b的shape应是a的行数对等与b的列数,tf.matmul()是矩阵的一般相乘。

例子:
a=tf.get_variable(“a”, [2,3]) b=tf.get_variable(“b”,[2,3]) c=tf.get_variable(“c”, [3,2])
tf.mul(a,b) =>Right [2,3] tf.mul(a,c) => Wrong
tf.matmul(a,b) => Wrong tf.matmul(a,c) => Right [2, 2]

def mul(x, y, name=None):
  r"""Returns x * y element-wise.

  *NOTE*: `Mul` supports broadcasting. More about broadcasting
  [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)

  Args:
    x: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`.
    y: A `Tensor`. Must have the same type as `x`.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type as `x`.
  """

def matmul(a, b, transpose_a=False, transpose_b=False,
           adjoint_a=False, adjoint_b=False,
           a_is_sparse=False, b_is_sparse=False,  name=None):
  """Multiplies matrix `a` by matrix `b`, producing `a` * `b`.

  The inputs must be matrices (or tensors of rank > 2, representing batches of
  matrices), with matching inner dimensions, possibly after transposition."""

2.tf.cond(pred, fn1, fn2, name=None)

tensorflow中tensor变量无法进行bool判断,可以借助tf.cond做判断处理。

注:
1. tf.cond函数是直接计算并返回结果的,不是返回对应的函数地址,所以在tf.cond中不能传递形参
2. tf.cond中的fn1和fn2函数是需要有返回值的,且返回值应为tensor类型。

def cond(pred, fn1, fn2, name=None):
  """Return either fn1() or fn2() based on the boolean predicate `pred`.
 `fn1` and `fn2` both return lists of output tensors. `fn1` and `fn2` must have
  the same non-zero number and type of outputs.

3.tf.argmax(a, 1) 和 tf.multinomial(a,1) 的返回值比较

注:
tf.argmax返回矩阵a在轴1上的最大值所对应的序列号
tf.multinomial根据分布概率的大小随机返回矩阵a在轴1上的序列号。

>>> a =[[0.2,0.3,0.5],[0.1,0.8,0.1]]
>>> tf.argmax(a, 1)
array([2, 1])

>>>b = tf.multinomial(a,1)
>>> sess.run(b)
array([[1],
       [0]])
>>> np.reshape(b, -1)
array([1, 0])

4.不错的总结blog

http://blog.csdn.net/u014595019/article/details/52805444

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。