اذهب إلى المحتوى
  • 0

كيف يمكن ان تستبدل او تضيف طبقة في keras

Moatasm Elshahry

السؤال

انا احاول ان اقوم بعمل تبديل لطبقة  Con2D باخري ممثالة لكن بدون bias. كذلك احاول اضافة  BatchNormalization قبل اول طبقة activation.

def keras_simple_model():
    from keras.models import Model
    from keras.layers import Input, Dense,  GlobalAveragePooling2D
    from keras.layers import Conv2D, MaxPooling2D, Activation

    inputs1 = Input((28, 28, 1))
    x = Conv2D(4, (3, 3), activation=None, padding='same', name='conv1')(inputs1)
    x = Activation('relu')(x)
    x = Conv2D(4, (3, 3), activation=None, padding='same', name='conv2')(x)
    x = Activation('relu')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='pool1')(x)

    x = Conv2D(8, (3, 3), activation=None, padding='same', name='conv3')(x)
    x = Activation('relu')(x)
    x = Conv2D(8, (3, 3), activation=None, padding='same', name='conv4')(x)
    x = Activation('relu')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='pool2')(x)

    x = GlobalAveragePooling2D()(x)
    x = Dense(10, activation=None)(x)
    x = Activation('softmax')(x)

    model = Model(inputs=inputs1, outputs=x)
    return model


if __name__ == '__main__':
    model = keras_simple_model()
    print(model.summary())

كيف استطيع ان اقوم بهذا؟

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

الكود التالي يوضح كيف تضيف طبقة او تعدل طبقة والتي يطابق اسمها اسم معين regular expression:

import re
from keras.models import Model

def insert_layer_nonseq(model, layer_regex, insert_layer_factory,
                        insert_layer_name=None, position='after'):

    # توضيح الرسم الخاص بالنموذج
    network_dict = {'input_layers_of': {}, 'new_output_tensor_of': {}}

    # تعيينالدخل لكل طبقة
    for layer in model.layers:
        for node in layer._outbound_nodes:
            layer_name = node.outbound_layer.name
            if layer_name not in network_dict['input_layers_of']:
                network_dict['input_layers_of'].update(
                        {layer_name: [layer.name]})
            else:
                network_dict['input_layers_of'][layer_name].append(layer.name)

    # تعيين الخرج لكل دخل
    network_dict['new_output_tensor_of'].update(
            {model.layers[0].name: model.input})

    # نمر على كل الطقات بعد تعيين الدخل
    model_outputs = []
    for layer in model.layers[1:]:

        # نوضح ال tensor 
        layer_input = [network_dict['new_output_tensor_of'][layer_aux] 
                for layer_aux in network_dict['input_layers_of'][layer.name]]
        if len(layer_input) == 1:
            layer_input = layer_input[0]

        # نقوم باضافة طبقة اذا وافق اسمها اسم معين
        if re.match(layer_regex, layer.name):
            if position == 'replace':
                x = layer_input
            elif position == 'after':
                x = layer(layer_input)
            elif position == 'before':
                pass
            else:
                raise ValueError('position must be: before, after or replace')

            new_layer = insert_layer_factory()
            if insert_layer_name:
                new_layer.name = insert_layer_name
            else:
                new_layer.name = '{}_{}'.format(layer.name, 
                                                new_layer.name)
            x = new_layer(x)
            print('New layer: {} Old layer: {} Type: {}'.format(new_layer.name,
                                                            layer.name, position))
            if position == 'before':
                x = layer(x)
        else:
            x = layer(layer_input)

 
        network_dict['new_output_tensor_of'].update({layer.name: x})

        # نقوم بحفظ الخرج 
        if layer_name in model.output_names:
            model_outputs.append(x)

    return Model(inputs=model.inputs, outputs=model_outputs)
رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0

لحذف ال bias من ال conv2D يمكنك اضافة المتغير use_bias = False للطبقة التي لا تريد استعمال bias فيها.

x = Conv2D(4, (3, 3), activation=None, padding='same', name='conv1', use_bias = False)(inputs1)

بالنسبة لل BatchNormalization, لاضافة طبقة من هذا النوع ستحتاج اولا لاستدعائها

from keras.layers import BatchNormalization

بعدها يمكنك استعمالها كما تستعمل اي طبقة أخرى في keras في المكان الذي تريده

inputs1 = Input((28, 28, 1))
x = Conv2D(4, (3, 3), activation=None, padding='same', name='conv1')(inputs1)
x = BatchNormalization()(x)
x = Activation('relu')(x)

 

تم التعديل في بواسطة Walid K
رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...