Advertisement
VladSmirN

model1

Jul 20th, 2021
387
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.99 KB | None | 0 0
  1. from tensorflow import keras
  2. from tensorflow.keras.models import Sequential
  3. from tensorflow.keras import backend as K
  4. from tensorflow.keras.layers import AveragePooling2D, Conv2D, Input, Dense, Dropout,MaxPooling2D , \
  5.     Flatten, PReLU, BatchNormalization, Layer, Lambda, LeakyReLU, SpatialDropout2D, SeparableConv2D,GlobalAveragePooling2D
  6. from tensorflow.keras.models import Model
  7. import tensorflow as tf
  8. input_shape = (img_width,img_height,3)
  9. feature_dim = 100
  10. #num_classes = 10
  11.  
  12. class CenterLossLayer(Layer):
  13.  
  14.     def __init__(self, class_num, feature_dim, alpha=0.5, **kwargs):
  15.         super().__init__(**kwargs)
  16.         self.class_num = class_num
  17.         self.feature_dim = feature_dim
  18.         self.alpha = alpha
  19.  
  20.     def build(self, input_shape):
  21.         self.centers = self.add_weight(name='centers',
  22.                                        shape=(self.class_num, self.feature_dim),
  23.                                        initializer='uniform',
  24.                                        trainable=False)
  25.         super().build(input_shape)
  26.  
  27.     def call(self, x, mask=None):
  28.         delta_centers = K.dot(K.transpose(x[1]), (K.dot(x[1], self.centers) - x[0]))  # 10x2
  29.         center_counts = K.sum(K.transpose(x[1]), axis=1, keepdims=True) + 1  # 10x1
  30.         delta_centers /= center_counts
  31.         new_centers = self.centers - self.alpha * delta_centers
  32.         self.centers.assign(new_centers)  # Chieko: something's wrong with add_update()
  33.         self.result = x[0] - K.dot(x[1], self.centers)  # Chieko: recalculate the distance from center to each point
  34.         self.result = K.sum(self.result ** 2, axis=1, keepdims=True)  # / K.dot(x[1], center_counts)
  35.         # Chieko: N(x**2 + y**2)
  36.         return self.result  # Nx1
  37.  
  38.     def compute_output_shape(self, input_shape):
  39.         return K.int_shape(self.result)
  40.  
  41.     def get_config(self):
  42.         config = super().get_config().copy()
  43.         config.update({
  44.             'centers': self.centers,
  45.         })
  46.         return config
  47.  
  48.  
  49. ### custom loss
  50.  
  51. def zero_loss(y_true, y_pred):
  52.     return 0.5 * K.sum(y_pred, axis=0)
  53. class ResnetIdentityBlock(tf.keras.Model):
  54.  
  55.   def __init__(self, filters):
  56.     super(ResnetIdentityBlock, self).__init__(name='')
  57.     self.filters = filters
  58.  
  59.    
  60.    
  61.  
  62.  
  63.   def call(self, input_tensor, training=False):
  64.  
  65.     x_box = Conv2D(self.filters, (3,3) , padding='same', kernel_initializer='he_normal' )(input_tensor)  
  66.     x_box = BatchNormalization()(x_box)
  67.     x_box = LeakyReLU(0.1)(x_box)
  68.    
  69.      
  70.     x_box = Conv2D(64, (3,3) , padding='same', kernel_initializer='he_normal' )(x_box)  
  71.     x_box = SpatialDropout2D(0.3)(x_box)
  72.     x = LeakyReLU(0.1)(x_box)
  73.    
  74.    
  75.     x += input_tensor
  76.     return x
  77.  
  78. def resnet18(input_shape: tuple, num_classes: int, feature_dim) -> (Model, Model):
  79.     x_box = inputs = Input(input_shape, name="inpnode")
  80.     labels = Input((num_classes,), name='labels')
  81.  
  82.     x_box = Lambda(lambda x: x / 255)(x_box)
  83.  
  84.  
  85.    
  86.    
  87.      
  88.     x_box = Conv2D(32, (3,3) , padding='same', kernel_initializer='he_normal' )(x_box)  
  89.     x_box = BatchNormalization()(x_box)
  90.     x_box = LeakyReLU(0.1)(x_box)
  91.  
  92.  
  93.     for i in range(1):
  94.  
  95.       x = tf.identity(x_box)
  96.  
  97.       x_box = Conv2D(128, (3,3) , padding='same', kernel_initializer='he_normal' )(x_box)  
  98.       x_box = SpatialDropout2D(0.1)(x_box)
  99.       x_box = LeakyReLU(0.1)(x_box)
  100.  
  101.       x_box = Conv2D(32, (3,3) , padding='same', kernel_initializer='he_normal' )(x_box)  
  102.       x_box = BatchNormalization()(x_box)
  103.       x_box = LeakyReLU(0.1)(x_box) + x
  104.  
  105.       x_box = AveragePooling2D(2)(x_box)
  106.      
  107.     x_box = Conv2D(64, (3,3) , padding='same', kernel_initializer='he_normal' )(x_box)  
  108.     x_box = BatchNormalization()(x_box)
  109.     x_box = LeakyReLU(0.1)(x_box)
  110.    
  111.     for i in range(1):
  112.       x = tf.identity(x_box)
  113.  
  114.       x_box = Conv2D(128, (3,3) , padding='same', kernel_initializer='he_normal' )(x_box)  
  115.       x_box = SpatialDropout2D(0.1)(x_box)
  116.       x_box = LeakyReLU(0.1)(x_box)
  117.  
  118.       x_box = Conv2D(64, (3,3) , padding='same', kernel_initializer='he_normal' )(x_box)  
  119.       x_box = BatchNormalization()(x_box)
  120.       x_box = LeakyReLU(0.1)(x_box) + x
  121.  
  122.     x_box = AveragePooling2D(2)(x_box)
  123.  
  124.     x_box = Conv2D(128, (3,3), padding='same' , kernel_initializer='he_normal' )(x_box)  
  125.     x_box = BatchNormalization()(x_box)
  126.     x_box = LeakyReLU(0.1)(x_box)
  127.    
  128.     for i in range(1):
  129.       x = tf.identity(x_box)
  130.      
  131.       x_box = Conv2D(128, (3,3) , padding='same', kernel_initializer='he_normal' )(x_box)  
  132.       x_box = SpatialDropout2D(0.1)(x_box)
  133.       x_box = LeakyReLU(0.1)(x_box)
  134.  
  135.       x_box = Conv2D(128, (3,3) , padding='same', kernel_initializer='he_normal' )(x_box)  
  136.       x_box = BatchNormalization()(x_box)
  137.       x_box = LeakyReLU(0.1)(x_box) + x
  138.  
  139.     x_box = AveragePooling2D(2)(x_box)
  140.    
  141.     x_box = Conv2D(256, (3,3) , kernel_initializer='he_normal' )(x_box)  
  142.     x_box = BatchNormalization()(x_box)
  143.     x_box = LeakyReLU(0.1)(x_box)
  144.    
  145.     x_box = AveragePooling2D(2)(x_box)
  146.  
  147.  
  148.     #x_box = AveragePooling2D(2)(x_box)
  149.  
  150.     y_box = Flatten()(x_box)
  151.  
  152.  
  153.     y_box = Dropout(0.2)(y_box)
  154.     y_box =  Dense( 200, kernel_initializer='he_normal')(y_box)
  155.     y_box =  Dropout(0.1) (y_box)
  156.     y_box =  tf.keras.layers.PReLU() (y_box)
  157.     y_box =  Dense( 200, kernel_initializer='he_normal')(y_box)
  158.     y_box =  Dropout(0.1) (y_box)
  159.     y_box =  tf.keras.layers.PReLU() (y_box)
  160.     inter_dim =  Dense(feature_dim,  kernel_initializer='he_normal') (y_box)
  161.      
  162.      
  163.  
  164.  
  165.     loss = CenterLossLayer(num_classes, feature_dim, name='center_loss')([inter_dim, labels])
  166.    
  167.     logits = Dense(num_classes, kernel_initializer='lecun_normal',
  168.                    activation='softmax', name='logits')(inter_dim)
  169.  
  170.     model = Model(inputs=[inputs, labels], outputs=[logits, loss])
  171.     infer_model = Model(inputs=inputs, outputs=inter_dim)
  172.     return model, infer_model
  173.  
  174. train_model, infer_model = resnet18(input_shape, num_classes, feature_dim)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement