logo

Python绘制三种常见的激活函数

作者:半吊子全栈工匠2024.01.17 22:14浏览量:20

简介:本文将介绍如何使用Python绘制三种常见的激活函数:sigmoid函数、ReLU函数和tanh函数。我们将使用matplotlib库进行绘图,并通过代码示例展示如何绘制这些函数。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # 定义sigmoid函数
  4. def sigmoid(x):
  5. return 1 / (1 + np.exp(-x))
  6. # 定义ReLU函数
  7. def relu(x):
  8. return np.maximum(0, x)
  9. # 定义tanh函数
  10. def tanh(x):
  11. return np.tanh(x)
  12. # 生成x轴数据
  13. x = np.linspace(-10, 10, 1000)
  14. # 绘制sigmoid函数
  15. y_sigmoid = sigmoid(x)
  16. plt.plot(x, y_sigmoid, label='sigmoid')
  17. # 绘制ReLU函数
  18. y_relu = relu(x)
  19. plt.plot(x, y_relu, label='ReLU')
  20. # 绘制tanh函数
  21. y_tanh = tanh(x)
  22. plt.plot(x, y_tanh, label='tanh')
  23. # 添加图例和标题
  24. plt.legend()
  25. plt.title('Three Common Activation Functions')
  26. plt.xlabel('x')
  27. plt.ylabel('y')
  28. plt.grid(True)
  29. plt.show()

相关文章推荐

发表评论