【问题标题】:Python - Using a lambda function stored in a list of functions inside a classPython - 使用存储在类内函数列表中的 lambda 函数
【发布时间】:2022-11-14 07:00:07
【问题描述】:

我正在尝试设置一个 Functions 类来处理我的 NN 项目的函数。 我发现我希望函数列表有点灵活(轻松添加或删除使用的函数)。

我创建了一个函数列表,定义了一堆 lambda 函数, 添加了一个方法,将主体中的所有函数添加到列表中。 当我尝试检查列表的长度时,它显示了正确的数字,但是当我尝试将函数检索到变量中并将其传递给参数时,我得到一个信息,即 lambda 需要 1 个参数,我给了它 2。我没有不明白第二个参数是什么。


import numpy as np

class Functions():
    f0 = identity = lambda x: x
    f1 = linear_step = lambda x: 1 if x > 0 else 0
    f2 = sigmoid = lambda x: 1/(1+np.exp(-x))
    f3 = tanh = lambda x: np.tanh(x)
    f4 = swish = lambda x: x/(1+np.exp(-x))
    f5 = absolute = lambda x: abs(x)
    f6 = cubic = lambda x: x**3
    f7 = square = lambda x: x**2
    f8 = sinusoid = lambda x: np.sin(x)
    f9 = square_root = lambda x: np.sqrt(x)
    f10 = cubic_root = lambda x: np.cbrt(x)
    f11 = opposite = lambda x: -x
    f12 = inverse = lambda x: 1/x
    f13 = exponential = lambda x: np.exp(x)
    
    def __init__(self): #constructor
        self._functions = []
        self.add_functions(self.f0, self.f1, self.f2, self.f3, self.f4, self.f5, self.f6, self.f7, self.f8, self.f9, self.f10, self.f11, self.f12, self.f13)

    #add a fyunction to the list, if it is not already there
    def _add_function(self, function):
        if function not in self._functions:
            self._functions.append(function)
            #print(f"Added function: {function.__name__}")
            return True
        else:
            #print(f"Function: {function.__name__} already exists at index: {functions.index(function)}")
            return False
        
    #add multiple functions to the list
    def add_functions(self, *args):
        for function in args:
            self._add_function(function)
            
    #get the number of functions in the list
    def number_of_functions(self):
        return len(self._functions)


    #return the function at the given index
    def get_function(self, index):
        try:
            return self._functions[index]
        except IndexError:
            print("Index out of range");
            return None
    
    def get_all_functions(self):
        return self._functions
        
        

functs = Functions()

print(f"number of functions {functs.number_of_functions()}")

iden = functs.get_function(0)
print(f"identity of one is {iden(1)}")

是什么导致了这个问题?或者,拥有一个可枚举的数据结构来存储和加载激活函数的更好方法是什么?

【问题讨论】:

  • 你忘记了self
  • 我应该在哪个地方添加self
  • 问题是什么?这与add_functions()方法有关吗?
  • 您可以发布一个片段作为答案吗?这可能是最好的答案。
  • @quamrana 我认为那里没有问题。

标签: python


【解决方案1】:

所有这些函数的行为与add_function__init__number_of_functions 相同。他们正在秘密通过self。我在下面展示了两个修复:

class Functions:
    f0 = identity = lambda self, x: x
    f1 = linear_step = lambda self, x: 1 if x > 0 else 0
    f2 = sigmoid = lambda self, x: 1 / (1 + np.exp(-x))
    f3 = tanh = lambda self, x: np.tanh(x)
    # ...

class Functions:
    f0 = identity = staticmethod(lambda x: x)
    f1 = linear_step = staticmethod(lambda x: 1 if x > 0 else 0)
    f2 = sigmoid = staticmethod(lambda x: 1 / (1 + np.exp(-x)))
    f3 = tanh = staticmethod(lambda x: np.tanh(x))
    # ...

【讨论】:

    【解决方案2】:

    当你执行self.f1 时,你创建了一个绑定方法,它比f1 少了一个参数。这就是 Python 中方法的工作方式,因此您不必一直使用self.foo(self, ...)。这个通常合理的决定会给您带来不幸的后果。

    有几种方法可以解决此问题。最简单的可能是重写__init__ 如下。

        def __init__(self): #constructor
            self._functions = []
            cls = type(self)
            self.add_functions(cls.f0, cls.f1, cls.f2, cls.f3, cls.f4, cls.f5, cls.f6, cls.f7, cls.f8, cls.f9, cls.f10, cls.f11, cls.f12, cls.f13)
    
    

    但是,真的,我怀疑这是存储函数的正确方法。我将它们放入一个列表中,并在实例化时将其传递给类。或者只是放弃课程并使用字典。

    【讨论】:

      猜你喜欢
      • 2021-08-06
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 2015-07-16
      • 2021-12-04
      相关资源
      最近更新 更多