如何按名称应用python函数?

时间:2019-07-03 06:24:13

标签: python

我有一个列表,其中包含要应用于NN的每个隐藏层的激活函数名称。

我想要修改以下命令,以便该命令代替relu调用activation[i]

#activation = ['relu','softplus','softsign']
for i in range (1,hidden_layers+1):
    W_dmd[i] = tf.Variable(tf.initializers.GlorotUniform()(shape=[input_shape,code_length]))
    b_encoder_dmd[i] = tf.Variable(tf.initializers.Zeros()(shape=[code_length]))
    x_dmd[i] = tf.compat.v1.nn.relu(tf.compat.v1.nn.xw_plus_b(x_dmd[i-1], W_dmd[i], b_encoder_dmd[i])) #Instead of relu, same command but with the name in activation[i]

命令应为:

x_dmd[1] = tf.compat.v1.nn.relu(tf.compat.v1.nn.xw_plus_b(x_dmd[0], W_dmd[1], b_encoder_dmd[1])) 
x_dmd[1] = tf.compat.v1.nn.softplus(tf.compat.v1.nn.xw_plus_b(x_dmd[1], W_dmd[2], b_encoder_dmd[2]))
x_dmd[3] = tf.compat.v1.nn.softsign(tf.compat.v1.nn.xw_plus_b(x_dmd[2], W_dmd[3], b_encoder_dmd[3]))

从这个post,我可以提出:

x_dmd[i] = getattr(tf.compat.v1.nn, activation[i])(tf.compat.v1.nn.xw_plus_b(x_dmd[i-1], W_dmd[i], b_encoder_dmd[i]))

这是正确的吗?谢谢!

0 个答案:

没有答案
相关问题