python - 声明的变量出现名称错误

标签 python tensorflow keras deep-learning neural-network

### 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/

相关文章:

tensorflow - Tensorflow 上的全卷积网络(FCN)

opencv - 深度 CNN 不会学习,准确率只是保持在相同值

python - 从 Keras model.predict_generator 计算准确性

python - 如何使用外部 fixture 跳过 pytest?

python - 在数据帧中复制行 x 次 - 提高性能

python - 如何将单个小部件的值传递给面板/ Bokeh 中一个对象的多个实例

python - 游戏代码中存在缩进问题

tensorflow - 没有传递到第一层的 `input_shape` 的顺序模型无法重新加载优化器状态

python - 带有参数的 Tensorflow serving_input_receiver_fn

python - 自定义 keras 损失函数