简体   繁体   English

如何使用 Python 和 Matplotlib 绘制数值函数?

[英]How can I graph a numerical function using Python and Matplotlib?

I'm trying to graph the Sigmoid Function used in machine learning by using the Matplotlib library.我正在尝试使用 Matplotlib 库绘制机器学习中使用的 Sigmoid 函数。 My problem is that I haven't visualized a mathematical function before so I'm humbly asking for your guidance.我的问题是我之前没有想象过一个数学函数,所以我虚心地寻求你的指导。

I've tried to directly plot the following function:我试图直接绘制以下函数:

def Sigmoid(x):
  a=[]
  for i in x:
    a.append(1/(1+math.exp(-i)))
  return a

using the command plt.plot(Sigmoid) .使用命令plt.plot(Sigmoid) But that gave me the error:但这给了我错误:

TypeError: float() argument must be a string or a number, not 'function'类型错误:float() 参数必须是字符串或数字,而不是“函数”

The final result should look something like this:最终结果应该是这样的:

1

Sigmoid is a function, Matplotlib expects numerical values, ie, the results of a function evaluation, eg Sigmoid是一个函数,Matplotlib 需要数值,即函数求值的结果,例如

x = [i/50 - 1 for i in range(101)]
plt.plot(x, Sigmoid(x))

That said, you probably want to familiarize with the Numpy library也就是说,您可能想熟悉Numpy

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1, 1, 101)
plt.plot(x, 1/(1+np.exp(-x))
import numpy as np
import matplotlib.pyplot as plt

def sigmoid(arr, scale=1):
    arr = np.asarray(arr)
    result = 1/(1 + np.exp(-arr*scale))
    return result

x = np.linspace(-5, 5)
y = sigmoid(x)

fig, ax = plt.subplots()
ax.plot(x, y)

Result:结果:

在此处输入图片说明

The ax.plot method takes a pair of 1-D array-likes that are of the same length to create the lines. ax.plot方法采用一对长度相同的一维数组来创建线条。 Matplotlib is not like Mathematica in which you can give an analytic function and a domain of its arguments. Matplotlib 不像 Mathematica,在其中你可以给出一个解析函数和它的参数域。 You have to give (in this case) xy pairs (or rather, lists/arrays that can be turned into xy pairs) And in this case, order matters.您必须提供(在这种情况下)xy 对(或者更确切地说,可以转换为 xy 对的列表/数组)在这种情况下,顺序很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM