tanh 量化#

对于定义域 \(\mathbb{R}\) 中的输入,tanh 函数将输入变换为区间 \((-1, 1)\) 上的输出。函数定义如下:

\[ \operatorname{tanh}(x) = \frac{1 - \exp(-2x)}{1 + \exp(-2x)}. \]
%matplotlib inline
from matplotlib import pyplot as plt
import torch
from torch_book.visual.mp_plot import plot

x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = torch.tanh(x)
plot(x.detach(), y.detach(), 'x', 'tanh(x)', figsize=(5, 2.5))
../../_images/f6c81aa4de9d31a4899bdfae5178f5d3dfcc7b729185e5e70307680e06a81bff.svg

tanh 函数特性:

\[ \operatorname{tanh}(x) + \operatorname{tanh}(-x) = 0 \]

tanh 函数的导数为下面的公式:

\[ \frac{\operatorname{d}}{\operatorname{d} x} \operatorname{tanh}(x) = 1 - \operatorname{tanh}^2(x). \]

可视化导函数:

y.backward(torch.ones_like(x),retain_graph=True)
plot(x.detach(), x.grad, 'x', 'tanh 导函数', figsize=(5, 2.5))
../../_images/981872b7a7da992cb36b3ad191070e5fd0833f5980c22845666fae4603ed151e.svg

tanh 函数的泰勒展示式:

\[ \operatorname{tanh}(x) = \sum_{k=-\infty}^{\infty} \frac{x^k}{k!} \]