Esempio n. 1
0
def load_old_model(model_file, backend='keras'):
    """ Loading an old keras model file. A thing wrapper around load_model
        that uses DeepNeuro's custom cost functions.
    
        TODO: Investigate application in Tensorflow.

        Parameters
        ----------
        model_file : str
            At present, a filepath to a ".h5" keras file.
        implementation : str, optional
            Specify 'keras' or 'tensorflow' implementation.
        
        Returns
        -------
        Keras model
            A Keras model object stored in the given filepath.
        
    """

    if backend == 'keras':
        custom_objects = cost_function_dict()

        return KerasModel(
            model=load_model(model_file, custom_objects=custom_objects))

    if backend == 'tf':
        sess = tf.Session()
        # First let's load meta graph and restore weights
        saver = tf.train.import_meta_graph(model_file)
        saver.restore(sess, tf.train.latest_checkpoint('./'))
        return sess
Esempio n. 2
0
def load_old_model(model_file, backend='keras', **kwargs):
    """ Loading an old keras model file. A thing wrapper around load_model
        that uses DeepNeuro's custom cost functions.
    
        TODO: Investigate application in Tensorflow.

        Parameters
        ----------
        model_file : str
            At present, a filepath to a ".h5" keras file.
        implementation : str, optional
            Specify 'keras' or 'tensorflow' implementation.
        
        Returns
        -------
        Keras model
            A Keras model object stored in the given filepath.
        
    """

    if backend == 'keras':

        from keras.models import load_model, model_from_json
        from deepneuro.models.keras_model import KerasModel

        custom_objects = cost_function_dict(**kwargs)

        model_file_extension = nifti_splitext(model_file)[1]

        if model_file_extension == '.json':
            model = KerasModel(initial_build=False, **kwargs)
            with open(model_file, 'r') as json_file:
                loaded_model_json = json_file.read()
                model.model = model_from_json(loaded_model_json,
                                              custom_objects=custom_objects)
            model.build_model(compute_output=False)
        else:
            model = KerasModel(
                model=load_model(model_file, custom_objects=custom_objects))

        # Necessary?
        model.build_model(compute_output=False)

        return model

    if backend == 'tf':

        import tensorflow as tf

        sess = tf.Session()
        # First let's load meta graph and restore weights
        saver = tf.train.import_meta_graph(model_file)
        saver.restore(sess, tf.train.latest_checkpoint('./'))
        return sess
Esempio n. 3
0
def load_old_model(model_file, backend='keras'):
    """ Loading an old keras model file. A thing wrapper around load_model
        that uses DeepNeuro's custom cost functions.
    
        TODO: Investigate application in Tensorflow.

        Parameters
        ----------
        model_file : str
            At present, a filepath to a ".h5" keras file.
        implementation : str, optional
            Specify 'keras' or 'tensorflow' implementation.
        
        Returns
        -------
        Keras model
            A Keras model object stored in the given filepath.
        
    """

    if backend == 'keras':
        custom_objects = cost_function_dict()

        return DeepNeuroModel(
            model=load_model(model_file, custom_objects=custom_objects))

    if backend == 'tf':
        sess = tf.Session()
        # First let's load meta graph and restore weights
        saver = tf.train.import_meta_graph(model_file)
        saver.restore(sess, tf.train.latest_checkpoint('./'))
        return sess


# def MinimalModel(DeepNeuroModel):

#     def load(self, kwargs):

#         if 'dummy_parameter' in kwargs:
#             self.depth = kwargs.get('depth')
#         else:
#             self.depth = False

#     def build_model(self):

#         """ A basic implementation of the U-Net proposed in https://arxiv.org/abs/1505.04597

#             TODO: specify optimizer

#             Returns
#             -------
#             Keras model or tensor
#                 If input_tensor is provided, this will return a tensor. Otherwise,
#                 this will return a Keras model.
#         """

#         print self.inputs.get_shape()

#         left_outputs = []

#         for level in xrange(self.depth):

#             filter_num = int(self.max_filter / (2 ** (self.depth - level)) / self.downsize_filters_factor)

#             if level == 0:
#                 left_outputs += [Conv3D(filter_num, self.filter_shape, activation=self.activation, padding=self.padding)(self.inputs)]
#                 left_outputs[level] = Conv3D(2 * filter_num, self.filter_shape, activation=self.activation, padding=self.padding)(left_outputs[level])
#             else:
#                 left_outputs += [MaxPooling3D(pool_size=self.pool_size)(left_outputs[level - 1])]
#                 left_outputs[level] = Conv3D(filter_num, self.filter_shape, activation=self.activation, padding=self.padding)(left_outputs[level])
#                 left_outputs[level] = Conv3D(2 * filter_num, self.filter_shape, activation=self.activation, padding=self.padding)(left_outputs[level])

#             if self.dropout is not None and self.dropout != 0:
#                 left_outputs[level] = Dropout(self.dropout)(left_outputs[level])

#             if self.batch_norm:
#                 left_outputs[level] = BatchNormalization()(left_outputs[level])

#         right_outputs = [left_outputs[self.depth - 1]]

#         for level in xrange(self.depth):

#             filter_num = int(self.max_filter / (2 ** (level)) / self.downsize_filters_factor)

#             if level > 0:
#                 right_outputs += [UpConvolution(pool_size=self.pool_size)(right_outputs[level - 1])]
#                 right_outputs[level] = concatenate([right_outputs[level], left_outputs[self.depth - level - 1]], axis=4)
#                 right_outputs[level] = Conv3D(filter_num, self.filter_shape, activation=self.activation, padding=self.padding)(right_outputs[level])
#                 right_outputs[level] = Conv3D(int(filter_num / 2), self.filter_shape, activation=self.activation, padding=self.padding)(right_outputs[level])
#             else:
#                 continue

#             if self.dropout is not None and self.dropout != 0:
#                 right_outputs[level] = Dropout(self.dropout)(right_outputs[level])

#             if self.batch_norm:
#                 right_outputs[level] = BatchNormalization()(right_outputs[level])

#         output_layer = Conv3D(int(self.num_outputs), (1, 1, 1))(right_outputs[-1])

#         # TODO: Brainstorm better way to specify outputs
#         if self.input_tensor is not None:
#             return output_layer

#         if self.output_type == 'regression':
#             self.model = Model(inputs=self.inputs, outputs=output_layer)
#             self.model.compile(optimizer=Nadam(lr=self.initial_learning_rate), loss='mean_squared_error', metrics=['mean_squared_error'])

#         if self.output_type == 'binary_label':
#             act = Activation('sigmoid')(output_layer)
#             self.model = Model(inputs=self.inputs, outputs=act)
#             self.model.compile(optimizer=Nadam(lr=self.initial_learning_rate), loss=dice_coef_loss, metrics=[dice_coef])

#         if self.output_type == 'categorical_label':
#             act = Activation('softmax')(output_layer)
#             self.model = Model(inputs=self.inputs, outputs=act)
#             self.model.compile(optimizer=Nadam(lr=self.initial_learning_rate), loss='categorical_crossentropy',
#                           metrics=['categorical_accuracy'])

#         return self.model