1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonで数式を書く_02(tanh)

Last updated at Posted at 2021-02-20

数式

以下がtanh関数(hyperbolic tangent function)です。
※tanhはハイパボリックタンジェントやタンエイチと読みます。日本語では双曲線正接関数と呼びます。

y\ = \frac{e^{x}-e^{-x}}{e^{x}+e^{-x}}

Pythonで記述

import numpy as np

# tanh関数
y = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))

上の記述方法の他に次のような方法もあります。

import numpy as np

# tanh関数
y = np.tanh(x)

一番最初の記載方法だと長いので、
以降は np.tanh(x) の方で記載していきます。

import numpy as np

x = -1
y = np.tanh(x)
print(y)
x=-1の出力結果
-0.7615941559557649

コードを省略しますが、x = 0 と x = 1 のときは以下のように出力されます。

x=0の出力結果
0.0
x=1の出力結果
0.7615941559557649

tanh関数を視覚化

先ほどの入力と出力を表にまとめると次のようになります。

x = -1 x = 0 x = 1
出力結果 y -0.76 0.0 0.76

表だけだとわかりにくいですが、
グラフにするとtanhの出力は -1 ~ 1 の間になることがわかります。
tanh.jpeg

ちなみに、上のグラフは以下のコードで描くことができます。

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5, 5, 0.1)
y = np.tanh(x)

plt.plot(x, y)
plt.title("tanh")
plt.xlabel("x")
plt.ylabel("y")
plt.show()

シグモイド関数と同様にtanhもニューラルネットワークの活性化関数として利用されますので、
その方面に興味のある方はこちらも覚えておいてもよいかもしれません。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?