【发布时间】: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