抱歉,我对深度学习和keras是新手.我正在try 自己定义一个层.

我查看了keras文件,https://keras.io/api/layers/base_layer/#layer-class

class SimpleDense(Layer):

  def __init__(self, units=32):
      super(SimpleDense, self).__init__()
      self.units = units

  def build(self, input_shape):  # Create the state of the layer (weights)
    w_init = tf.random_normal_initializer()
    self.w = tf.Variable(
        initial_value=w_init(shape=(input_shape[-1], self.units),
                             dtype='float32'),
        trainable=True)
    b_init = tf.zeros_initializer()
    self.b = tf.Variable(
        initial_value=b_init(shape=(self.units,), dtype='float32'),
        trainable=True)

  def call(self, inputs):  # Defines the computation from inputs to outputs
      return tf.matmul(inputs, self.w) + self.b

# Instantiates the layer.
linear_layer = SimpleDense(4)

我知道当我创建linear_layer时,会调用__init__方法,当我将输入放入linear_layer时,会调用call方法.但我不知道何时调用build方法,更具体地说,input_shape in build方法是如何指定的?这里的input_shape是多少?我不知道何时调用build方法,所以我不知道哪些参数作为input_shape参数放入.

此外,我想指定一个固定大小的参数,在我的例子中是(1768).所以在这种情况下,我是否仍应使用input_shape in-build方法?

推荐答案

要了解这SimpleDense层并回答您的问题,我们需要解释weightbias.SimpleDense中的权重首先得到随机数,bias得到zero个数字,在模型的训练中,这个权重和偏差会发生变化,以使损失最小化.The answer to First Question:构建方法仅一次性调用,在第一次使用层时,此方法正在调用,权重和偏差设置为随机数和零数,但每个训练批中的调用方法正在调用.The answer to the Second Question:是的,在调用方法中,我们可以访问一批数据,第一个维度显示该批数据.我编写了一个示例,在buildcall方法调用时打印,并打印输入和输出数据的形状,以澄清上述解释.

在以下示例中:

  1. 我使用batch_size = 525 sample data,在每个时代,我们可以在call method中看到5 sample data.
  2. one-time层创建和构建以及one-time 101 is calling5 epoch5-time 103 is calling.
  3. Units = 4shape data = (100, 2) [sample, features],然后total params = 12<-&燃气轮机;4*2 (weights*features) + 4 (bias)
  4. 添加末端,附加一张显示matmul如何工作以及为什么输出形状为(5,4)的图像,以及计算intput*weight+bias.的公式
import tensorflow as tf

class SimpleDense(tf.keras.layers.Layer):
  def __init__(self, units=32):
      super(SimpleDense, self).__init__()
      self.units = units

  def build(self, input_shape):  # Create the state of the layer (weights)
    tf.print('calling build method')
    w_init = tf.random_normal_initializer()
    self.w = tf.Variable(
        initial_value=w_init(shape=(input_shape[-1], self.units),
                             dtype='float32'),trainable=True)
    b_init = tf.zeros_initializer()
    self.b = tf.Variable(initial_value=b_init(shape=(self.units,), 
                                              dtype='float32'),trainable=True)

  def call(self, inputs):  # Defines the computation from inputs to outputs
      tf.print('\ncalling call method')
      tf.print(f'input shape : {inputs.shape}')
      out = tf.matmul(inputs, self.w) + self.b
      tf.print(f'output shape : {out.shape}')
      return out

model = tf.keras.Sequential()
model.add(SimpleDense(units = 4))
model.compile(optimizer = 'adam',loss = 'mse',)
model.fit(tf.random.uniform((25, 2)), tf.ones((25, 1)), batch_size = 5)
model.summary()

输出:

calling build method

calling call method
input shape : (5, 2)
output shape : (5, 4)
1/5 [=====>........................] - ETA: 1s - loss: 0.9794
calling call method
input shape : (5, 2)
output shape : (5, 4)

calling call method
input shape : (5, 2)
output shape : (5, 4)

calling call method
input shape : (5, 2)
output shape : (5, 4)

calling call method
input shape : (5, 2)
output shape : (5, 4)
5/5 [==============================] - 0s 15ms/step - loss: 0.9770
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 simple_dense (SimpleDense)  (5, 4)                    12        
                                                                 
=================================================================
Total params: 12
Trainable params: 12
Non-trainable params: 0
_________________________________________________________________

enter image description here

Python相关问答推荐

Pandas 修改原始excel

错误:找不到TensorFlow / Cygwin的匹配分布

两极:滚动组,起始指数由不同列设置

在Python中使用一行try

为什么dict(id=1,**{id:2})有时会引发KeyMessage:id而不是TypMessage?

如何终止带有队列的Python进程?+ 队列大小的错误?

用gekko解决的ADE方程系统突然不再工作,错误消息异常:@错误:模型文件未找到.& &

如何比较numPy数组中的两个图像以获取它们不同的像素

Python json.转储包含一些UTF-8字符的二元组,要么失败,要么转换它们.我希望编码字符按原样保留

'discord.ext. commanders.cog没有属性监听器'

如何在Python中将returns.context. DeliverresContext与Deliverc函数一起使用?

有症状地 destruct 了Python中的regex?

按列分区,按另一列排序

如果值不存在,列表理解返回列表

在ubuntu上安装dlib时出错

如何在turtle中不使用write()来绘制填充字母(例如OEG)

解决调用嵌入式函数的XSLT中表达式的语法移位/归约冲突

将scipy. sparse矩阵直接保存为常规txt文件

如何使regex代码只适用于空的目标单元格

Python Pandas—时间序列—时间戳缺失时间精确在00:00