我正在尝试将激活函数参数从字符串列表传递给b.layer()。
我尝试过eval('b.layer(parameters [1] = 3)')
'''
#parameters = [layers,index_activation_function,nodes]
parameters = [2,2,2]
#Activation Functions
a_functions = ['softmax','relu','tanh','sigmoid','linear']
function = a_functions[parameters[1]]
#NN
b = brain.Brain(1)
b.input_layer(1)
b.layer(linear = 2)
for i in range(layers):
eval('b.layer(function=nodes)')
b.layer(linear = 2)
'''
答案 0 :(得分:1)
下面的完整示例显示了如何使用Gekko为eval()
函数构造一个字符串。这不是Gekko独有的,可用于要作为表达式求值的任何字符串。
from gekko import brain
import numpy as np
import matplotlib.pyplot as plt
# generate training data
x = np.linspace(0.0,2*np.pi)
y = np.sin(x)
parameters = [2,2,2]
a_functions = ['softmax','relu','tanh','sigmoid','linear']
function = a_functions[parameters[1]]
s = 'b.layer('+function+'=2)'
b = brain.Brain()
b.input_layer(1)
b.layer(linear=2)
eval(s)
b.layer(linear=2)
b.output_layer(1)
# train
b.learn(x,y)
# validate
xp = np.linspace(-2*np.pi,4*np.pi,100)
yp = b.think(xp)
plt.figure()
plt.plot(x,y,'bo')
plt.plot(xp,yp[0],'r-')
plt.show()
这会通过从选项列表中选择b.layer(tanh=2)
激活函数来评估字符串tanh
。这是该脚本的结果。