To receive notifications about scheduled maintenance, please subscribe to the mailing-list gitlab-operations@sympa.ethz.ch. You can subscribe to the mailing-list at https://sympa.ethz.ch

mhcnn.py 4.99 KB
Newer Older
matthmey's avatar
matthmey committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
"""
Script for the paper "Systematic Identification of External Influences in Multi-Year Micro-Seismic Recordings Using Convolutional Neural Networks"

Implementation of a mountaineer image classifier based on MobileNet

Copyright (c) 2018, Swiss Federal Institute of Technology (ETH Zurich)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""


from __future__ import print_function
    
from keras.preprocessing import image
from keras.layers import Dense, GlobalAveragePooling2D,Reshape, Convolution2D, Dropout, Activation, Flatten, Input, TimeDistributed, LSTM
from keras.models import Model, Sequential
import numpy as np
from keras.applications.resnet50 import ResNet50
from keras.applications.mobilenet import preprocess_input, decode_predictions
# from aednn.models.modmobilenet import MobileNet
from keras.applications.mobilenet import MobileNet

def get_params():
    return []

def get_model(dataset,input_shape=None,num_labels=None,weights=None,copy_layer=True, **kwargs):

    if num_labels is None:
        num_labels = dataset.num_labels
    if input_shape is None:
        input_shape = dataset.shape[1:]
    model_name = 'notresnet'
    # input_tensor = Input(shape=(dataset.Nx,dataset.Ny,dataset.Nd))
    input_tensor = Input(shape=input_shape)

    alpha = 1



    if model_name == 'resnet':
        model = ResNet50(weights='imagenet',include_top=True,classes=num_labels)
    else:
        # model = MobileNet(weights=weights,include_top=False,input_tensor=input_tensor,input_shape=input_shape[1:],alpha=alpha)
        model = MobileNet(weights=None,include_top=False,input_tensor=input_tensor,input_shape=input_shape,alpha=alpha)
        # model = MobileNet(weights=None,include_top=False,input_tensor=input_tensor)


    if copy_layer:
        pretrained_net = MobileNet(weights='imagenet',input_shape=(224,224,3),include_top=False,alpha=alpha)

        for idx in range(len(model.layers)):
            model.layers[idx].set_weights(pretrained_net.layers[idx].get_weights())
            model.layers[idx].trainable = True

    # model.summary()

    print(len(model.layers))
    # for layer in model.layers:
        # layer.trainable = False

        # if 'res5c' in layer.name or 'bn5c' in layer.name:
        #     layer.trainable = True

        # if 'w_13' in layer.name:
        #     layer.trainable=True
        
    print(model.layers[-1].name)
    print(model.layers[0].name)




    if model_name == 'resnet':
        model.layers.pop()
        x = Dense(num_labels,activation='sigmoid')(model.layers[-1].output)
    else:
        dropout=1e-3
        shape = (1, 1, int(1024 * alpha))
        x = GlobalAveragePooling2D()(model.layers[-1].output)
        x = Reshape(shape, name='reshape_1')(x)
        x = Dropout(dropout, name='dropout')(x)
        x = Convolution2D(num_labels, (1, 1), padding='same', name='conv_preds')(x)
        x = Activation('sigmoid', name='act_sigmoid')(x)
        # x = Activation('softmax', name='act_softmax')(x)
        x = Reshape((num_labels,), name='reshape_2')(x)


    model = Model(model.layers[0].output,x)


    return [model]

def preprocessing(X,y=None,train_data=False):
    # print('Preprocessing',np.max(X),np.min(X))
    X = preprocess_input(X)     
    # X /= 255  
    if y is not None:
        # if y.ndim == 1 or y.shape[1] == 1:
        #     y = to_categorical(y.astype(np.int), num_classes=dataset.num_labels)
        return X,y
    else:
        return X
        


def gen_image(in_data):
    """
        insert one data sample and returns a suitable graphical representation
        generates one image with (width,height,depth)
    """
    print('data shape',in_data.shape)
    img = in_data
    return img