### Defining a network Layer ###
# n_output_nodes: number of output nodes
# input_shape: shape of the input
# x: input to the layer
class OurDenseLayer(tf.keras.layers.Layer):
def __init__(self, n_output_nodes):
super(OurDenseLayer, self).__init__()
self.n_output_nodes = n_output_nodes
def build(self, input_shape):
d = int(input_shape[-1])
# Define and initialize parameters: a weight matrix W and bias b
# Note that parameter initialization is random!
**self.W = self.add_weight("weight", shape=[d, self.n_output_nodes]) # note the dimensionality**
self.b = self.add_weight("bias", shape=[1, self.n_output_nodes]) # note the dimensionality
def call(self, x):
'''TODO: define the operation for z (hint: use tf.matmul)'''
z = tf.add(tf.matmul(x,W,),b)
'''TODO: define the operation for out (hint: use tf.sigmoid)'''
y = tf.sigmoid(z)
return y
# Since layer parameters are initialized randomly, we will set a random seed for reproducibility
tf.random.set_seed(1)
layer = OurDenseLayer(3)
layer.build((1,2))
x_input = tf.constant([[1,2.]], shape=(1,2))
y = layer.call(x_input)
print(y.numpy())
mdl.lab1.test_custom_dense_layer_output(y)
我已经为单个感知器编写了代码。 我已经声明了 W 但仍然收到此错误 我收到 NameError: name 'W' is not Defined 错误
最佳答案
访问实例成员时,请在前面添加 self.
:
def call(self, x):
'''TODO: define the operation for z (hint: use tf.matmul)'''
z = tf.add(tf.matmul(x, self.W,), self.b)
'''TODO: define the operation for out (hint: use tf.sigmoid)'''
y = tf.sigmoid(z)
return y
您获得的唯一 W
属于您的类实例 - 因此 self.W
- 没有声明“本地”W
。
关于python - 声明的变量出现名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61780225/