Can't set the attribute “trainable_weights”, likely because it conflicts with an existing read-only

假如想象 提交于 2021-01-29 06:10:42

问题


My code was running perfectly in colab. But today it's not running. It says Can't set the attribute "trainable_weights", likely because it conflicts with an existing read-only @property of the object. Please choose a different name.

I am using LSTM with the attention layer.

class Attention(Layer):

def __init__(self, **kwargs):
    self.init = initializers.get('normal')
    #self.input_spec = [InputSpec(ndim=3)]
    super(Attention, self).__init__(**kwargs)

def build(self, input_shape):
    assert len(input_shape)==3
    #self.W = self.init((input_shape[-1],1))
    self.W = self.init((input_shape[-1],))
    #self.input_spec = [InputSpec(shape=input_shape)]
    self.trainable_weights = [self.W]
    super(Attention, self).build(input_shape)  # be sure you call this somewhere!

def call(self, x, mask=None):
    eij = K.tanh(K.dot(x, self.W))
    
    ai = K.exp(eij)
    weights = ai/K.sum(ai, axis=1).dimshuffle(0,'x')

    weighted_input = x*weights.dimshuffle(0,1,'x')
    return weighted_input.sum(axis=1)

def get_output_shape_for(self, input_shape):
    return (input_shape[0], input_shape[-1])

I am not sure what happened suddenly. Anyone encounter similar problem?


回答1:


change

self.trainable_weights = [self.W]

to

self._trainable_weights = [self.W]



回答2:


This is ongoing issue with tf in colab. I could get a link with this here

Looks the issue got closed , maybe time to reopen.




回答3:


Please remove the build function and use this instead, It worked for me.

    def build(self,input_shape):
        self.W=self.add_weight(name="att_weight",shape=(input_shape[-1],1),initializer="normal", trainable = True)
        self.b=self.add_weight(name="att_bias",shape=(self.attention_dim,),initializer="normal", trainable = True)
        self.u=self.add_weight(name="u_bias",shape=(self.attention_dim,1),initializer="normal", trainable = True)        
        super(Attention, self).build(input_shape)


来源:https://stackoverflow.com/questions/63343563/cant-set-the-attribute-trainable-weights-likely-because-it-conflicts-with-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!