5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

tensorflow.kerasにおけるtf.function-decorated function tried to create variables on non-first call.のエラー

Posted at

たまに詰まりがちなので備忘録で

#エラー部分

class ResNet50(Model):
    def __init__(self, stride: int = 1, *args, **kwargs):
        super(ResNet50, self).__init__(*args, **kwargs)
        self.stride = stride
        self.avgpool = AveragePooling2D()
        self.maxpool = MaxPool2D(padding='same')
        self.ResBlocks: List[Layers] = [] 
        
        self.softmax = Softmax()
        self.dense = Dense(1, activation='sigmoid')

    def call(self, inputs):
        conv_1 = self.conv(inputs)
        maxpooled = self.maxpool(conv_1)
        layers_num = [3, 4, 6, 3]
        for i in range(len(layers_num)):
            for _ in range(layers_num[i]):
                if i==0 and u==0:
                   self.ResBlocks.append(Residual_Block(filters_num=4 * 2 ** (i))(maxpooled))
                else:
                self.ResBlocks.append(Residual_Block(filters_num=4 * 2 ** (i))(self.ResBlocks[-1])))
        
        avgpooled = self.avgpool(maxpooled)
        value = self.dense(avgpooled)
        return avgpooled, value

的なことをしてtf.function-decorated function tried to create variables on non-first callが出ていました。
調べるとtensorflowの宣言ずみvariableが新しく宣言されてしまうため、ということですが

#解決後

class ResNet50(Model):
    def __init__(self, stride: int = 1, *args, **kwargs):
        super(ResNet50, self).__init__(*args, **kwargs)
        self.stride = stride
        self.avgpool = AveragePooling2D()
        self.maxpool = MaxPool2D(padding='same')
        self.ResBlocks: List[Layers] = [] 
        layers_num = [3, 4, 6, 3]
        for i in range(len(layers_num)):
            for _ in range(layers_num[i]):
                self.ResBlocks.append(Residual_Block(filters_num=4 * 2 ** (i)))
        self.conv = Conv2D(filters=16, kernel_size=7, strides=self.stride, padding='same')
        self.softmax = Softmax()
        self.dense = Dense(1, activation='sigmoid')
    def call(self, inputs):
        conv_1 = self.conv(inputs)
        maxpooled = self.maxpool(conv_1)
        for layer in self.ResBlocks:
            maxpooled = layer(maxpooled)
        avgpooled = self.avgpool(maxpooled)
        value = self.dense(avgpooled)
        return avgpooled, value

とすれば直りました。原因としては、tensorflow.kerasのModelの仕様でLayerを宣言する時にはinitの部分にしなければいけないということでした。
完全に忘れてました。そこらへんと変数の宣言が関係しているのでしょうか。今度時間がある時にでも調べてみたいです。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?