I am trying to convert Densenet from functional API to Model subclassing API. But I am getting error. My model is as follows:
inputs = tf.keras.layers.Input( shape=input_shape )
x = tf.keras.layers.Conv2D( num_filters , kernel_size=(3,3) , use_bias=False, kernel_initializer='he_normal' , kernel_regularizer=tf.keras.regularizers.l2( 1e-4 ) )( inputs )
for i in range( num_blocks ):
x, num_filters = dense_block( x, num_layers_per_block , num_filters, growth_rate , dropout_rate )
x = transition(x, num_filters , compress_factor , dropout_rate )
x = tf.keras.layers.GlobalAveragePooling2D()( x )
x = tf.keras.layers.Dense( 37 )( x ) # Num Classes for CIFAR-10
outputs = tf.keras.layers.Activation( 'softmax' )( x )
I converted it to something like this
class CNN(keras.Model):
def __init__(self,nfilters,sfilters):
super(CNN,self).__init__()
#tf.random.set_seed(0)
self.conv1 = keras.layers.Conv2D(nfilters[0] , kernel_size=(sfilters[0],sfilters[0]) , use_bias=False, kernel_initializer='he_normal', kernel_regularizer=tf.keras.regularizers.l2( 1e-4 ) )
#self.dense_block = dense_block(self, sfilters[0] , num_filters, growth_rate , dropout_rate )
#self.transition = transition(self,num_filters , compress_factor , dropout_rate )
self.globalaverage = keras.layers.GlobalAveragePooling2D()
self.dense = keras.layers.Dense(37) # Num Classes for CIFAR-10
self.activation = keras.layers.Activation( 'softmax' )
def call(self, input_tensor, training=False):
global num_filters
x = self.conv1(input_tensor)
for i in range( num_blocks ):
x, num_filters = dense_block( x, num_layers_per_block , num_filters, growth_rate , dropout_rate )
x = transition(x, num_filters , compress_factor , dropout_rate )
x = self.globalaverage( x )
x = self.dense( x ) # Num Classes for CIFAR-10
return self.activation( x )
But when I run the code my model didn't build properly and i get error as follows:
ValueError: tf.function only supports singleton tf.Variables created on the first call. Make sure the tf.Variable is only created once or created outside tf.function. See https://www.tensorflow.org/guide/function#creating_tfvariables for more information.
Call arguments received:
• input_tensor=tf.Tensor(shape=(16, 32, 32, 3), dtype=float32)
• training=True
Kindly help me how to convert Functional API CNN to Model Subclass API CNN