Python -使用存储在类内函数列表中的lambda函数



我试图建立一个函数类,将处理函数为我的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.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)

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

所有这些函数的行为与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))
# ...

最新更新