AttributeError:“PositionEncoding”对象没有属性“position”

2024-10-01 00:18:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法理解为什么会出现此错误。代码在不保存模型的情况下工作正常,但当我运行model.save()时,它会引发异常。 错误为

AttributeError:Traceback (most recent call last) in () 1 model.summary() 2 model.save('/content/Data/chatbot_model',include_optimizer=False)

in get_config(self)

  9         config = super(PositionalEncoding, self).get_config()
 10         config.update({'position': self.position,
 12             'd_model': self.d_model,
 13 

AttributeError: 'PositionalEncoding' object has no attribute 'position'

这是位置编码类的类代码


 def __init__(self, position, d_model):
   super(PositionalEncoding, self).__init__()
   self.pos_encoding = self.positional_encoding(position, d_model)
 
 def get_config(self):

       config = super(PositionalEncoding, self).get_config()
       config.update({
           'position': self.position,
           'd_model': self.d_model,
           
       })
       return config

 def get_angles(self, position, i, d_model):
   angles = 1 / tf.pow(10000, (2 * (i // 2)) / tf.cast(d_model, tf.float32))
   return position * angles

 def positional_encoding(self, position, d_model):
   angle_rads = self.get_angles(
       position=tf.range(position, dtype=tf.float32)[:, tf.newaxis],
       i=tf.range(d_model, dtype=tf.float32)[tf.newaxis, :],
       d_model=d_model)
   # apply sin to even index in the array
   sines = tf.math.sin(angle_rads[:, 0::2])
   # apply cos to odd index in the array
   cosines = tf.math.cos(angle_rads[:, 1::2])

   pos_encoding = tf.concat([sines, cosines], axis=-1)
   pos_encoding = pos_encoding[tf.newaxis, ...]
   return tf.cast(pos_encoding, tf.float32)

 def call(self, inputs):
   return inputs + self.pos_encoding[:, :tf.shape(inputs)[1], :]```

Tags: inposselfconfiggetmodelreturntf