【问题标题】:Sigmoid Function in NumpyNumpy 中的 Sigmoid 函数
【发布时间】:2020-06-29 23:29:08
【问题描述】:

为了快速计算,我必须在 Numpy 中实现我的 sigmoid 函数,这是下面的代码

   def sigmoid(Z):
    """
    Implements the sigmoid activation in bumpy

    Arguments:
    Z -- numpy array of any shape

    Returns:
    A -- output of sigmoid(z), same shape as Z
    cache -- returns Z, useful during backpropagation
    """

    cache=Z

    print(type(Z))
    print(Z)
    A=1/(1+(np.exp((-Z))))

    return A, cache

还有一些相关信息:

  Z=(np.matmul(W,A)+b)

Z的类型是:

  <class 'numpy.ndarray'>

遗憾的是,我得到了一个:“一元操作数类型错误 -: 'tuple'” 我试图在没有任何运气的情况下解决这个问题。我感谢任何建议。 最好的

【问题讨论】:

  • Z 显然是一个元组,而不是一个 numpy 数组或其他类似数组的对象。
  • 你能提供更多的代码来表明输入到函数中的内容吗?

标签: numpy sigmoid


【解决方案1】:

虽然实现 sigmoid 函数很容易,但有时函数中传递的参数可能会导致错误。

代码sn-p

def sigmoid_function(z):
""" this function implements the sigmoid function, and 
expects a numpy array as argument """
    
    if isinstance(z, numpy.ndarray):
        continue
    
    sigmoid = 1.0/(1.0 + np.exp(-z))
    return sigmoid 

需要牢记的几个要点:-

  • 在 sigmoid 的值中使用 1.0 将导致浮点型输出
  • 在执行计算之前检查参数的类型 它们是一种很好的编程习惯。它可以帮助避免以后的混淆

  • 为什么sigmoid函数这么常用?
    Sigmoid 函数用于将值的范围压缩到范围 (0, 1) 中。有多个其他函数可以做到这一点,但提高其受欢迎程度的一个非常重要的一点是它可以多么简单地表达它的导数,这在反向传播中很方便

    实现 sigmoid 的导数

    def sigmoid_derivative(z):
        """ this function implements the derivative of a sigmoid function """
        
        return sigmoid_function(z) * (1.0 - sigmoid_function(z))
    

    sigmoid的导数可以用sigmoid表示!!

    【讨论】:

      【解决方案2】:

      这对我有用。我认为不需要使用缓存,因为你已经初始化了它。试试下面的代码。

      import matplotlib.pyplot as plt 
      import numpy as np 
      
      z = np.linspace(-10, 10, 100) 
      def sigmoid(z):
          return 1/(1 + np.exp(-z))
      
      a = sigmoid(z)
      plt.plot(z, a) 
      plt.xlabel("z") 
      plt.ylabel("sigmoid(z)")
      

      【讨论】:

        猜你喜欢
        • 2017-10-08
        • 2017-11-12
        • 2013-07-14
        • 1970-01-01
        • 2019-03-15
        • 2016-12-05
        • 2021-04-25
        • 1970-01-01
        • 2018-01-20
        相关资源
        最近更新 更多