【深度学习笔记】TensorFlow 常用函数

TensorFlow 提供了一些机器学习中常用的数学函数,并封装在 Module 中,例如 tf.nn Module 提供了神经网络常用的基本运算,tf.math Module 则提供了机器学习中常用的数学函数。本文主要介绍 TensorFlow 深度学习中几个常用函数的定义与用法,并给出相应用法示例。

目录

1 tf.nn.sigmoid

2 tf.nn.relu

3 tf.nn.softmax

4 tf.math.reduce_sum

5 tf.math.reduce_mean


TensorFlow 提供了一些机器学习中常用的数学函数,包括:

  • 基本的算术运算与三角函数
  • 复数运算(例如 tf.math.imag, tf.math,angle 等)
  • Reduce 运算(例如 tf.math.reduce_mean, tf.math.cumsum 等)
  • 切片函数(例如 tf.math.segment_sum)

扫描二维码关注公众号,回复: 16140392 查看本文章

以下介绍几个 TensorFlow 中常用函数的用法。

1 tf.nn.sigmoid

        tf.nn.sigmoid 用于计算函数

f(x) = 1/(1+e^{-x}))

的值,用法为

tf.nn.sigmoid(x, name=None)

其中 x 是一个 tf.Tensor 对象。

x = tf.constant([-128., 0., 128.])
tf.nn.sigmoid(x).numpy()

输出:array([0. , 0.5, 1. ], dtype=float32)

2 tf.nn.relu

        tf.nn.relu 用于计算线性修正函数

Relu(x) = max(x, 0)

的值, 用法为

tf.nn.relu(input_tensor, name=None)

relu = tf.nn.relu([-2., 0., 3.])
relu.numpy()

输出:array([0., 0., 3.], dtype=float32)

3 tf.nn.softmax

        tf.nn.softmax 用于计算 softmax 函数值,

softmax(x) = e^{x_{i}}/\sum_{i}^{n}e^{x_{i}}

用法为

tf.nn.softmax(input_tesnor, axis=None, name=None)

其中 input_tesnor 是一个非空的 tf.Tensor 对象。

softmax = tf.nn.softmax([-1., 0., 1.])
softmax.numpy()

输出:array([0.09003057, 0.24472848, 0.66524094], dtype=float32)

sum(softmax).numpy()

输出:1.0

4 tf.math.reduce_mean

        tf.math.reduce_mean 等同于 tf.reduce_mean, 用法为

tf.math.reduce_mean(input_tensor, axis=None, keepdims=False, name=None)

        如果 axis 值为 None,则所有维度都被 reduced,返回只包含 1 个元素的 tf.Tensor 对象。

x = tf.constant([[1., 1.], [2., 2.]])
tf.reduce_mean(x).numpy()

输出:1.5

tf.reduce_mean(x, 0).numpy()

输出:array([1.5, 1.5], dtype=float32)

tf.reduce_mean(x, 1).numpy()

输出:array([1., 2.], dtype=float32)

5 tf.math.reduce_sum

        tf.math.reduce_sum 等同于 tf.reduce_sum, 用法为

tf.math.reduce_sum(input_tensor, axis=None, keepdims=False, name=None)
x = tf.constant([[1, 1, 1], [1, 1, 1]])
tf.reduce_sum(x).numpy()

输出:6

tf.reduce_sum(x, 0).numpy()

输出:array([2, 2, 2])

tf.reduce_sum(x, 1).numpy()

输出:array([3, 3])

猜你喜欢

转载自blog.csdn.net/sxyang2018/article/details/132218059