Python keras.__version__() Examples

The following are code examples for showing how to use keras.__version__(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: deploy-ml   Author: deploy-ml   File: base.py    MIT License 6 votes vote down vote up
def __init__(self, file_path):
        if file_path[-3:] == "sav":
            package = pickle.load(open(file_path, "rb"))
        else:
            print("error wrong format no 'sav' found")
            package = None

        self.model = package["model"]
        self.convolutional = package["convolutional"]
        if self.convolutional:
            self.dims_one, self.dims_two = package["image dims"]
        self.scaling_tool = package["scaler"]
        if self.scaling_tool:
            self.scaled_inputs = True
        else:
            self.scaled_inputs = False
        if package["system version"] != str(sys.version):
            print("warning! model was trained in {}. You're running {}".format(package["system version"],
                                                                               str(sys.version)))
        if package["Keras Version"] != str(keras.__version__):
            print("warning! model was trained on {}. You're running {}".format(package["Keras Version"],
                                                                               str(keras.__version__))) 
Example 2
Project: aetros-cli   Author: aetros   File: backend.py    MIT License 6 votes vote down vote up
def collect_environment(self, overwrite_variables=None):
        import socket
        import os
        import pip
        import platform

        env = {}

        if not overwrite_variables:
            overwrite_variables = {}

        import aetros
        env['aetros_version'] = aetros.__version__
        env['python_version'] = platform.python_version()
        env['python_executable'] = sys.executable

        env['hostname'] = socket.gethostname()
        env['variables'] = dict(os.environ)
        env['variables'].update(overwrite_variables)

        if 'AETROS_SSH_KEY' in env['variables']: del env['variables']['AETROS_SSH_KEY']
        if 'AETROS_SSH_KEY_BASE64' in env['variables']: del env['variables']['AETROS_SSH_KEY_BASE64']

        env['pip_packages'] = sorted([[i.key, i.version] for i in pip.get_installed_distributions()])
        self.set_system_info('environment', env) 
Example 3
Project: dts   Author: albertogaspar   File: Seq2Seq.py    MIT License 6 votes vote down vote up
def _get_decoder_initial_states(self):
        """
        Return decoder states as Input layers
        """
        decoder_states_inputs = []
        for units in self.encoder_layers:
            decoder_state_input_h = Input(shape=(units,))
            input_states = [decoder_state_input_h]
            if self.cell == LSTMCell:
                decoder_state_input_c = Input(shape=(units,))
                input_states = [decoder_state_input_h, decoder_state_input_c]
            decoder_states_inputs.extend(input_states)
        if keras.__version__ < '2.2':
            return list(reversed(decoder_states_inputs))
        else:
            return decoder_states_inputs 
Example 4
Project: mljar-supervised   Author: mljar   File: learner_nn.py    MIT License 6 votes vote down vote up
def __init__(self, params):
        super(NeuralNetworkLearner, self).__init__(params)

        self.library_version = keras.__version__
        self.model_file = self.uid + ".nn.model"
        self.model_file_path = os.path.join(storage_path, self.model_file)

        self.rounds = additional.get("one_step", 10)
        self.max_iters = additional.get("max_steps", 1)
        self.learner_params = {
            "dense_layers": params.get("dense_layers"),
            "dense_1_size": params.get("dense_1_size"),
            "dense_2_size": params.get("dense_2_size"),
            "dense_3_size": params.get("dense_3_size"),
            "dropout": params.get("dropout"),
            "learning_rate": params.get("learning_rate"),
            "momentum": params.get("momentum"),
            "decay": params.get("decay"),
        }
        self.model = None  # we need input data shape to construct model
        log.debug("NeuralNetworkLearner __init__") 
Example 5
Project: mead-baseline   Author: dpressel   File: run.py    Apache License 2.0 6 votes vote down vote up
def run_model(si, config_params, logs, settings, datasets, embeddings, task_name, dir_, gpu):
    """Run a model and collect system information."""
    os.chdir(dir_)
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
    config_params['reporting'] = {}
    with suppress_output():
        task = mead.Task.get_task_specific(task_name, logs, settings)
        task.read_config(config_params, datasets)
        task.initialize(embeddings)
        task.train()

        si['framework_version'] = get_framework_version(config_params['backend'])
        si['cuda'], si['cudnn'] = get_cuda_version(config_params['backend'])
        si['gpu_name'], si['gpu_mem'] = get_gpu_info(gpu)
        si['cpu_name'], si['cpu_mem'], si['cpu_cores'] = get_cpu_info()
        si['python'] = get_python_version()
        si['baseline'] = version_str_to_tuple(baseline.__version__) 
Example 6
Project: deeprace   Author: psteinb   File: care_denoise2d_details.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def can_train():
    import warnings
    warnings.simplefilter(action='ignore', category=FutureWarning)

    keras_found = importlib.util.find_spec('keras')

    available_backends = []

    if keras_found:
        from keras import __version__ as kv
        max_version = "2.2.4"
        min_version = "2.1.0"

        if versiontuple(kv, 3) >= versiontuple(min_version, 3) and versiontuple(kv, 3) <= versiontuple(max_version, 3):
            available_backends.append("keras")
        else:
            logging.debug("your keras version %s is not supported (%s - %s)", str(kv), min_version, max_version)

    return available_backends 
Example 7
Project: deeprace   Author: psteinb   File: resnet_details.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def can_train():
    import warnings
    warnings.simplefilter(action='ignore', category=FutureWarning)

    keras_found = importlib.util.find_spec('keras')

    available_backends = []

    if keras_found:
        from keras import __version__ as kv
        max_version = "2.2.4"
        min_version = "2.1.0"

        if versiontuple(kv, 3) >= versiontuple(min_version, 3) and versiontuple(kv, 3) <= versiontuple(max_version, 3):
            available_backends.append("keras")
        else:
            logging.debug("your keras version %s is not supported (%s - %s)", str(kv), min_version, max_version)

    return available_backends 
Example 8
Project: neural-fingerprinting   Author: StephanZheng   File: utils_keras.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def conv_2d(filters, kernel_shape, strides, padding, input_shape=None):
    """
    Defines the right convolutional layer according to the
    version of Keras that is installed.
    :param filters: (required integer) the dimensionality of the output
                    space (i.e. the number output of filters in the
                    convolution)
    :param kernel_shape: (required tuple or list of 2 integers) specifies
                         the strides of the convolution along the width and
                         height.
    :param padding: (required string) can be either 'valid' (no padding around
                    input or feature map) or 'same' (pad to ensure that the
                    output feature map size is identical to the layer input)
    :param input_shape: (optional) give input shape if this is the first
                        layer of the model
    :return: the Keras layer
    """
    if LooseVersion(keras.__version__) >= LooseVersion('2.0.0'):
        if input_shape is not None:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding,
                          input_shape=input_shape)
        else:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding)
    else:
        if input_shape is not None:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding,
                                 input_shape=input_shape)
        else:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding) 
Example 9
Project: gandlf   Author: codekansas   File: models.py    MIT License 5 votes vote down vote up
def save_model(model, filepath, overwrite=True):

    def get_json_type(obj):
        if hasattr(obj, 'get_config'):
            return {'class_name': obj.__class__.__name__,
                    'config': obj.get_config()}

        if type(obj).__module__ == np.__name__:
            return obj.item()

        if callable(obj) or type(obj).__name__ == type.__name__:
            return obj.__name__

        raise TypeError('Not JSON Serializable:', obj)

    import h5py
    from keras import __version__ as keras_version

    if not overwrite and os.path.isfile(filepath):
        proceed = keras.models.ask_to_proceed_with_overwrite(filepath)
        if not proceed:
            return

    f = h5py.File(filepath, 'w')
    f.attrs['keras_version'] = str(keras_version).encode('utf8')
    f.attrs['generator_config'] = json.dumps({
        'class_name': model.discriminator.__class__.__name__,
        'config': model.generator.get_config(),
    }, default=get_json_type).encode('utf8')
    f.attrs['discriminator_config'] = json.dumps({
        'class_name': model.discriminator.__class__.__name__,
        'config': model.discriminator.get_config(),
    }, default=get_json_type).encode('utf8')

    generator_weights_group = f.create_group('generator_weights')
    discriminator_weights_group = f.create_group('discriminator_weights')
    model.generator.save_weights_to_hdf5_group(generator_weights_group)
    model.discriminator.save_weights_to_hdf5_group(discriminator_weights_group)

    f.flush()
    f.close() 
Example 10
Project: deploy-ml   Author: deploy-ml   File: base.py    MIT License 5 votes vote down vote up
def deploy_model(self, description, author, organisation, file_name, contact="no contact information provided"):
        """
        Run before deploying the package
        :param description: short description of what the model does
        :param author: short string of the person deploying the model
        :param organisation: short string of organisation
        :param file_name: string, name of file to be saved
        :param contact: short string of where to find you, can be left
        :return: populates the package dictionary with the model, scaler if used,
                 inputs, versions the model was trained in, datetime, and inputs
                 so it is suitable for deployment
        """
        self.package["model title"] = self.model_title
        self.package["model"] = self.model
        self.package["description"] = description
        self.package["author"] = author
        self.package["organisation"] = organisation
        self.package["contact"] = contact
        self.package["date"] = str(datetime.now())
        self.package["metrics"] = self.general_report
        self.package["convolutional"] = self.convolutional
        if self.scaled_inputs:
            self.package["scaler"] = self.scaling_tool
            self.package["scaling used"] = self.scaling_title
        else:
            self.package["scaler"] = None
            self.package["scaling used"] = "Data was not scaled for training"
        self.package["system version"] = str(sys.version)
        self.package["Keras Version"] = str(keras.__version__)
        self.package["package version"] = "1"
        if self.convolutional:
            self.package["image dims"] = (self.dims_one, self.dims_two)
        else:
            self.package["input order"] = list(self.X.columns.values)
            self.package["prediction target"] = self.outcome_pointer
        self.package["package type"] = "pickle"
        pickle.dump(self.package, open(file_name, 'wb')) 
Example 11
Project: deploy-ml   Author: deploy-ml   File: base.py    MIT License 5 votes vote down vote up
def deploy_keras_model(self, description, author, organisation, file_name, contact="no contact information provided"):
        """
        Run before deploying the package
        :param description: short description of what the model does
        :param author: short string of the person deploying the model
        :param organisation: short string of organisation
        :param file_name: string, name of file to be saved
        :param contact: short string of where to find you, can be left
        :return: populates the package dictionary with the model, scaler if used,
                 inputs, versions the model was trained in, datetime, and inputs
                 so it is suitable for deployment
        """
        import keras
        self.package["model title"] = self.model_title
        # self.package["model"] = self.model
        self.package["description"] = description
        self.package["author"] = author
        self.package["organisation"] = organisation
        self.package["contact"] = contact
        self.package["date"] = str(datetime.now())
        self.package["metrics"] = self.general_report
        self.package["input order"] = list(self.X.columns.values)
        self.package["prediction target"] = self.outcome_pointer
        if self.scaled_inputs:
            self.package["scaler"] = self.scaling_tool
            self.package["scaling used"] = self.scaling_title
        else:
            self.package["scaler"] = "Data was not scaled for training"
        self.package["system version"] = str(sys.version)
        self.package["Keras Version"] = keras.__version__
        model_json = self.model.to_json()
        with open("model.json", "w") as json_file:
            json_file.write(model_json)
        # serialize weights to HDF5
        self.model.save_weights("model.h5")
        print("Saved model to disk") 
Example 12
Project: deploy-ml   Author: deploy-ml   File: base.py    MIT License 5 votes vote down vote up
def deploy_model(self, description, author, organisation, file_name, contact="no contact information provided"):
        """
        Run before deploying the package
        :param description: short description of what the model does
        :param author: short string of the person deploying the model
        :param organisation: short string of organisation
        :param file_name: string, name of file to be saved
        :param contact: short string of where to find you, can be left
        :return: populates the package dictionary with the model, scaler if used,
                 inputs, versions the model was trained in, datetime, and inputs
                 so it is suitable for deployment
        """
        self.package["model title"] = self.model_title
        self.package["model"] = self.model
        self.package["description"] = description
        self.package["author"] = author
        self.package["organisation"] = organisation
        self.package["contact"] = contact
        self.package["date"] = str(datetime.now())
        self.package["metrics"] = self.general_report
        self.package["input order"] = list(self.X.columns.values)
        self.package["prediction target"] = self.outcome_pointer
        if self.scaled_inputs:
            self.package["scaler"] = self.scaling_tool
            self.package["scaling used"] = self.scaling_title
        else:
            self.package["scaler"] = "Data was not scaled for training"
        self.package["system version"] = str(sys.version)
        self.package["sklearn version"] = sklearn.__version__
        self.package["package version"] = "1"
        self.package["package type"] = "pickle"
        pickle.dump(self.package, open(file_name, 'wb')) 
Example 13
Project: deploy-ml   Author: deploy-ml   File: base.py    MIT License 5 votes vote down vote up
def deploy_keras_model(self, description, author, organisation, file_name, contact="no contact information provided"):
        """
        Run before deploying the package
        :param description: short description of what the model does
        :param author: short string of the person deploying the model
        :param organisation: short string of organisation
        :param file_name: string, name of file to be saved
        :param contact: short string of where to find you, can be left
        :return: populates the package dictionary with the model, scaler if used,
                 inputs, versions the model was trained in, datetime, and inputs
                 so it is suitable for deployment
        """
        import keras
        self.package["model title"] = self.model_title
        # self.package["model"] = self.model
        self.package["description"] = description
        self.package["author"] = author
        self.package["organisation"] = organisation
        self.package["contact"] = contact
        self.package["date"] = str(datetime.now())
        self.package["metrics"] = self.general_report
        self.package["input order"] = list(self.X.columns.values)
        self.package["prediction target"] = self.outcome_pointer
        if self.scaled_inputs:
            self.package["scaler"] = self.scaling_tool
            self.package["scaling used"] = self.scaling_title
        else:
            self.package["scaler"] = "Data was not scaled for training"
        self.package["system version"] = str(sys.version)
        self.package["Keras Version"] = keras.__version__
        model_json = self.model.to_json()
        with open("model.json", "w") as json_file:
            json_file.write(model_json)
        # serialize weights to HDF5
        self.model.save_weights("model.h5")
        print("Saved model to disk") 
Example 14
Project: gumpy-deeplearning   Author: gumpy-bci   File: utils.py    MIT License 5 votes vote down vote up
def print_version_info():
    now = datetime.now()

    print('%s/%s/%s' % (now.year, now.month, now.day))
    print('Keras version: {}'.format(keras.__version__))
    if keras.backend._BACKEND == 'tensorflow':
        import tensorflow
        print('Keras backend: {}: {}'.format(keras.backend._backend, tensorflow.__version__))
    else:
        import theano
        print('Keras backend: {}: {}'.format(keras.backend._backend, theano.__version__))
    print('Keras image dim ordering: {}'.format(keras.backend.image_dim_ordering()))
    print('Kapre version: {}'.format(kapre.__version__)) 
Example 15
Project: gumpy-deeplearning   Author: gumpy-bci   File: utils.py    MIT License 5 votes vote down vote up
def print_version_info():
    now = datetime.now()
    print('%s/%s/%s' % (now.year, now.month, now.day))
    print('Keras version: {}'.format(keras.__version__))
    if keras.backend._BACKEND == 'tensorflow':
        import tensorflow
        print('Keras backend: {}: {}'.format(keras.backend._backend, tensorflow.__version__))
    else:
        import theano
        print('Keras backend: {}: {}'.format(keras.backend._backend, theano.__version__))
    print('Keras image dim ordering: {}'.format(keras.backend.image_dim_ordering()))
    print('Kapre version: {}'.format(kapre.__version__)) 
Example 16
Project: DisplaceNet   Author: GKalliatakis   File: keras_version.py    MIT License 5 votes vote down vote up
def keras_version():
    """ Get the Keras version.

    Returns
        tuple of (major, minor, patch).
    """
    return tuple(map(int, keras.__version__.split('.'))) 
Example 17
Project: DisplaceNet   Author: GKalliatakis   File: keras_version.py    MIT License 5 votes vote down vote up
def assert_keras_version():
    """ Assert that the Keras version is up to date.
    """
    detected = keras.__version__
    required = '.'.join(map(str, minimum_keras_version))
    assert(keras_version() >= minimum_keras_version), 'You are using keras version {}. The minimum required version is {}.'.format(detected, required) 
Example 18
Project: dialectal_arabic_segmenter   Author: qcri   File: topology.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _updated_config(self):
        """Shared between different serialization methods."""
        from keras import __version__ as keras_version

        config = self.get_config()
        model_config = {
            'class_name': self.__class__.__name__,
            'config': config,
            'keras_version': keras_version
        }
        return model_config 
Example 19
Project: aetros-cli   Author: aetros   File: backend.py    MIT License 5 votes vote down vote up
def upload_keras_graph(self, model):
        from aetros.keras import model_to_graph
        import keras

        if keras.__version__[0] == '2':
            graph = model_to_graph(model)
            self.set_graph(graph) 
Example 20
Project: aetros-cli   Author: aetros   File: Trainer.py    MIT License 5 votes vote down vote up
def set_generator_validation_nb(self, number):
        """
        sets self.nb_val_samples which is used in model.fit if input is a generator
        :param number:
        :return:
        """

        self.nb_val_samples = number
        diff_to_batch = number % self.get_batch_size()
        if diff_to_batch > 0:
            self.nb_val_samples += self.get_batch_size() - diff_to_batch

        import keras
        if '1' != keras.__version__[0]:
            self.nb_val_samples = self.nb_val_samples // self.get_batch_size() 
Example 21
Project: robust_physical_perturbations   Author: evtimovi   File: utils_keras.py    MIT License 5 votes vote down vote up
def conv_2d(filters, kernel_shape, strides, padding, input_shape=None):
    """
    Defines the right convolutional layer according to the
    version of Keras that is installed.
    :param filters: (required integer) the dimensionality of the output
                    space (i.e. the number output of filters in the
                    convolution)
    :param kernel_shape: (required tuple or list of 2 integers) specifies
                         the strides of the convolution along the width and
                         height.
    :param padding: (required string) can be either 'valid' (no padding around
                    input or feature map) or 'same' (pad to ensure that the
                    output feature map size is identical to the layer input)
    :param input_shape: (optional) give input shape if this is the first
                        layer of the model
    :return: the Keras layer
    """
    if LooseVersion(keras.__version__) >= LooseVersion('2.0.0'):
        print "Using Keras version", keras.__version__
        if input_shape is not None:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding,
                          input_shape=input_shape)
        else:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding)
    else:
        print "Using *old* keras version", keras.__version__
        if input_shape is not None:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding,
                                 input_shape=input_shape)
        else:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding) 
Example 22
Project: robust_physical_perturbations   Author: evtimovi   File: utils_keras.py    MIT License 5 votes vote down vote up
def conv_2d(filters, kernel_shape, strides, padding, input_shape=None):
    """
    Defines the right convolutional layer according to the
    version of Keras that is installed.
    :param filters: (required integer) the dimensionality of the output
                    space (i.e. the number output of filters in the
                    convolution)
    :param kernel_shape: (required tuple or list of 2 integers) specifies
                         the strides of the convolution along the width and
                         height.
    :param padding: (required string) can be either 'valid' (no padding around
                    input or feature map) or 'same' (pad to ensure that the
                    output feature map size is identical to the layer input)
    :param input_shape: (optional) give input shape if this is the first
                        layer of the model
    :return: the Keras layer
    """
    if LooseVersion(keras.__version__) >= LooseVersion('2.0.0'):
        print "Using Keras version", keras.__version__
        if input_shape is not None:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding,
                          input_shape=input_shape)
        else:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding)
    else:
        print "Using *old* keras version", keras.__version__
        if input_shape is not None:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding,
                                 input_shape=input_shape)
        else:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding) 
Example 23
Project: poker   Author: surgebiswas   File: topology.py    MIT License 5 votes vote down vote up
def _updated_config(self):
        """Shared between different serialization methods."""
        from keras import __version__ as keras_version

        config = self.get_config()
        model_config = {
            'class_name': self.__class__.__name__,
            'config': config,
            'keras_version': keras_version
        }
        return model_config 
Example 24
Project: Res3DUNET   Author: tgwboers   File: UnetBuilder.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,config):
        print('Tensorflow version: ',tf.__version__)
        print('Keras version:', k_version)

        self.input_shape = eval(config.get('DATA', 'grid_size'))
        self.pool_size = eval(config.get('MODEL', 'pool_size'))
        self.initial_learning_rate = config.getfloat('TRAINING', 'initial_learning_rate')

        self.n_labels = config.getint('DATA', 'n_labels')
        self.wt_fac = eval(config.get('TRAINING', 'loss_weight_factors'))
        self.wt_fac = self.wt_fac[:self.n_labels+1] 
Example 25
Project: ImageAI   Author: OlafenwaMoses   File: keras_version.py    MIT License 5 votes vote down vote up
def keras_version():
    return tuple(map(int, keras.__version__.split('.'))) 
Example 26
Project: ImageAI   Author: OlafenwaMoses   File: keras_version.py    MIT License 5 votes vote down vote up
def assert_keras_version():
    detected = keras.__version__
    required = '.'.join(map(str, minimum_keras_version))
    assert(keras_version() >= minimum_keras_version), 'You are using keras version {}. The minimum required version is {}.'.format(detected, required) 
Example 27
Project: vergeml   Author: vergeml   File: libraries.py    MIT License 5 votes vote down vote up
def version():
        import tensorflow # pylint: disable=E0401
        tensorflow.logging.set_verbosity(tensorflow.logging.ERROR)
        return tensorflow.__version__ #pylint: disable=E1101 
Example 28
Project: RPGOne   Author: RTHMaK   File: checks.py    Apache License 2.0 5 votes vote down vote up
def log_keras_version_info():
    import keras
    logger.info("Keras version: " + keras.__version__)
    from keras import backend as K
    try:
        backend = K.backend()
    except AttributeError:
        backend = K._BACKEND  # pylint: disable=protected-access
    if backend == 'theano':
        import theano
        logger.info("Theano version: " + theano.__version__)
    elif backend == 'tensorflow':
        import tensorflow
        logger.info("Tensorflow version: " + tensorflow.__version__)  # pylint: disable=no-member 
Example 29
Project: DeepBayes   Author: deepgenerativeclassifier   File: utils_keras.py    MIT License 5 votes vote down vote up
def conv_2d(filters, kernel_shape, strides, padding, input_shape=None):
    """
    Defines the right convolutional layer according to the
    version of Keras that is installed.
    :param filters: (required integer) the dimensionality of the output
                    space (i.e. the number output of filters in the
                    convolution)
    :param kernel_shape: (required tuple or list of 2 integers) specifies
                         the strides of the convolution along the width and
                         height.
    :param padding: (required string) can be either 'valid' (no padding around
                    input or feature map) or 'same' (pad to ensure that the
                    output feature map size is identical to the layer input)
    :param input_shape: (optional) give input shape if this is the first
                        layer of the model
    :return: the Keras layer
    """
    if LooseVersion(keras.__version__) >= LooseVersion('2.0.0'):
        if input_shape is not None:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding,
                          input_shape=input_shape)
        else:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding)
    else:
        if input_shape is not None:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding,
                                 input_shape=input_shape)
        else:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding) 
Example 30
Project: script-languages   Author: exasol   File: tensorflow.py    MIT License 5 votes vote down vote up
def test_import_keras(self):
        self.query(udf.fixindent('''
                CREATE OR REPLACE python3 scalar SCRIPT tfbasic.import_keras()
                returns varchar(1000) as
                import keras
                import tensorflow
                import tensorflow_hub
                
                def run(ctx):
                    return str(keras.__version__)
                /
                '''))

        row = self.query("select tfbasic.import_keras()")[0] 
Example 31
Project: dts   Author: albertogaspar   File: Seq2Seq.py    MIT License 5 votes vote down vote up
def _format_encoder_states(self, encoder_states, use_first=True):
        """
        Format the encoder states in such a way that only the last state from the first layer of the encoder
        is used to init the first layer of the decoder.
        If the cell type used is LSTM then both c and h are kept.
        :param encoder_states: Keras.tensor
            (last) hidden state of the decoder
        :param use_first: bool
            if True use only the last hidden state from first layer of the encoder, while the other are init to zero.
            if False use last hidden state for all layers
        :return:
            masked encoder states
        """
        if use_first:
            # Keras version 2.1.4 has encoder states reversed w.r.t later versions
            if keras.__version__ < '2.2':
                if self.cell == 'lstm':
                    encoder_states = [Lambda(lambda x: K.zeros_like(x))(s) for s in encoder_states[:-2]] + [
                        encoder_states[-2]]
                else:
                    encoder_states = [Lambda(lambda x: K.zeros_like(x))(s) for s in encoder_states[:-1]] + [
                        encoder_states[-1]]
            else:
                if self.cell == 'lstm':
                    encoder_states = encoder_states[:2] + [Lambda(lambda x: K.zeros_like(x))(s) for s in
                                                                encoder_states[2:]]
                else:
                    encoder_states = encoder_states[:1] + [Lambda(lambda x: K.zeros_like(x))(s) for s in
                                                                encoder_states[1:]]
        return encoder_states 
Example 32
Project: certifiable-distributional-robustness   Author: duchi-lab   File: utils.py    Apache License 2.0 5 votes vote down vote up
def conv_2d(filters, kernel_shape, strides, padding, input_shape=None):
    """
    Defines the right convolutional layer according to the
    version of Keras that is installed.
    :param filters: (required integer) the dimensionality of the output
                    space (i.e. the number output of filters in the
                    convolution)
    :param kernel_shape: (required tuple or list of 2 integers) specifies
                         the strides of the convolution along the width and
                         height.
    :param padding: (required string) can be either 'valid' (no padding around
                    input or feature map) or 'same' (pad to ensure that the
                    output feature map size is identical to the layer input)
    :param input_shape: (optional) give input shape if this is the first
                        layer of the model
    :return: the Keras layer
    """
    if LooseVersion(keras.__version__) >= LooseVersion('2.0.0'):
        if input_shape is not None:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding,
                          input_shape=input_shape)
        else:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding)
    else:
        if input_shape is not None:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding,
                                 input_shape=input_shape)
        else:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding) 
Example 33
Project: kaggle-rsna18   Author: i-pan   File: keras_version.py    MIT License 5 votes vote down vote up
def keras_version():
    """ Get the Keras version.

    Returns
        tuple of (major, minor, patch).
    """
    return tuple(map(int, keras.__version__.split('.'))) 
Example 34
Project: kaggle-rsna18   Author: i-pan   File: keras_version.py    MIT License 5 votes vote down vote up
def assert_keras_version():
    """ Assert that the Keras version is up to date.
    """
    detected = keras.__version__
    required = '.'.join(map(str, minimum_keras_version))
    assert(keras_version() >= minimum_keras_version), 'You are using keras version {}. The minimum required version is {}.'.format(detected, required) 
Example 35
Project: cleverhans-models   Author: tiendzung-le   File: utils_keras.py    MIT License 5 votes vote down vote up
def conv_2d(filters, kernel_shape, strides, padding, input_shape=None):
    """
    Defines the right convolutional layer according to the
    version of Keras that is installed.
    :param filters: (required integer) the dimensionality of the output
                    space (i.e. the number output of filters in the
                    convolution)
    :param kernel_shape: (required tuple or list of 2 integers) specifies
                         the strides of the convolution along the width and
                         height.
    :param padding: (required string) can be either 'valid' (no padding around
                    input or feature map) or 'same' (pad to ensure that the
                    output feature map size is identical to the layer input)
    :param input_shape: (optional) give input shape if this is the first
                        layer of the model
    :return: the Keras layer
    """
    if LooseVersion(keras.__version__) >= LooseVersion('2.0.0'):
        if input_shape is not None:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding,
                          input_shape=input_shape)
        else:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding)
    else:
        if input_shape is not None:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding,
                                 input_shape=input_shape)
        else:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding) 
Example 36
Project: mead-baseline   Author: dpressel   File: run.py    Apache License 2.0 5 votes vote down vote up
def get_framework_version(framework):
    """Get the version of a framework without importing them all at the same time."""
    if framework == "tensorflow":
        import tensorflow
        version = tensorflow.__version__
    elif framework == "pytorch":
        import torch
        version = torch.__version__
    elif framework == "dynet":
        import dynet
        version = dynet.__version__
    elif framework == "keras":
        import keras
        version = keras.__version__
    return version_str_to_tuple(version) 
Example 37
Project: mead-baseline   Author: dpressel   File: run.py    Apache License 2.0 5 votes vote down vote up
def add(args):
    conn = create_db(args.db)
    config = read_config_file(args.config)
    speeds = parse_logs(args.log)
    if not speeds:
        return
    si = {}
    si['framework_version'] = get_framework_version(config['backend'])
    si['cuda'], si['cudnn'] = get_cuda_version(config['backend'])
    si['gpu_name'], si['gpu_mem'] = get_gpu_info(args.gpu)
    si['cpu_name'], si['cpu_mem'], si['cpu_cores'] = get_cpu_info()
    si['python'] = get_python_version()
    si['baseline'] = version_str_to_tuple(baseline.__version__)

    save_data(conn, speeds, config, si) 
Example 38
Project: MAMMO_Retinanet   Author: hwejin23   File: keras_version.py    Apache License 2.0 5 votes vote down vote up
def keras_version():
    return tuple(map(int, keras.__version__.split('.'))) 
Example 39
Project: MAMMO_Retinanet   Author: hwejin23   File: keras_version.py    Apache License 2.0 5 votes vote down vote up
def assert_keras_version():
    detected = keras.__version__
    required = '.'.join(map(str, minimum_keras_version))
    assert(keras_version() >= minimum_keras_version), 'You are using keras version {}. The minimum required version is {}.'.format(detected, required) 
Example 40
Project: MAMMO_Retinanet   Author: hwejin23   File: keras_version.py    Apache License 2.0 5 votes vote down vote up
def keras_version():
    return tuple(map(int, keras.__version__.split('.'))) 
Example 41
Project: MAMMO_Retinanet   Author: hwejin23   File: keras_version.py    Apache License 2.0 5 votes vote down vote up
def assert_keras_version():
    detected = keras.__version__
    required = '.'.join(map(str, minimum_keras_version))
    assert(keras_version() >= minimum_keras_version), 'You are using keras version {}. The minimum required version is {}.'.format(detected, required) 
Example 42
Project: Ground-Plane-Polling   Author: arangesh   File: keras_version.py    MIT License 5 votes vote down vote up
def keras_version():
    """ Get the Keras version.

    Returns
        tuple of (major, minor, patch).
    """
    return tuple(map(int, keras.__version__.split('.'))) 
Example 43
Project: Ground-Plane-Polling   Author: arangesh   File: keras_version.py    MIT License 5 votes vote down vote up
def assert_keras_version():
    """ Assert that the Keras version is up to date.
    """
    detected = keras.__version__
    required = '.'.join(map(str, minimum_keras_version))
    assert(keras_version() >= minimum_keras_version), 'You are using keras version {}. The minimum required version is {}.'.format(detected, required) 
Example 44
Project: keras-retinanet   Author: ghada-soliman   File: keras_version.py    Apache License 2.0 5 votes vote down vote up
def keras_version():
    """ Get the Keras version.

    Returns
        tuple of (major, minor, patch).
    """
    return tuple(map(int, keras.__version__.split('.'))) 
Example 45
Project: keras-retinanet   Author: ghada-soliman   File: keras_version.py    Apache License 2.0 5 votes vote down vote up
def assert_keras_version():
    """ Assert that the Keras version is up to date.
    """
    detected = keras.__version__
    required = '.'.join(map(str, minimum_keras_version))
    assert(keras_version() >= minimum_keras_version), 'You are using keras version {}. The minimum required version is {}.'.format(detected, required) 
Example 46
Project: OrgaQuant   Author: TKassis   File: keras_version.py    MIT License 5 votes vote down vote up
def keras_version():
    """ Get the Keras version.

    Returns
        tuple of (major, minor, patch).
    """
    return tuple(map(int, keras.__version__.split('.'))) 
Example 47
Project: OrgaQuant   Author: TKassis   File: keras_version.py    MIT License 5 votes vote down vote up
def assert_keras_version():
    """ Assert that the Keras version is up to date.
    """
    detected = keras.__version__
    required = '.'.join(map(str, minimum_keras_version))
    assert(keras_version() >= minimum_keras_version), 'You are using keras version {}. The minimum required version is {}.'.format(detected, required) 
Example 48
Project: Neural-Headline-Generator-CN   Author: QuantumLiu   File: wechat_utils.py    GNU General Public License v3.0 5 votes vote down vote up
def prog(self):#Show progress
        nb_batches_total=(self.params['epochs'] if kv-1 else self.params['nb_epoch'])*(self.params['samples'] if kv-1 else self.params['nb_sample'])/self.params['batch_size']
        nb_batches_epoch=(self.params['samples'] if kv-1 else self.params['nb_sample'])/self.params['batch_size']
        prog_total=(self.t_batches/nb_batches_total if nb_batches_total else 0)+0.01
        prog_epoch=(self.c_batches/nb_batches_epoch if nb_batches_epoch else 0)+0.01
        if self.t_epochs:
            now=time.time()
            t_mean=float(sum(self.t_epochs)) / len(self.t_epochs)
            eta_t=(now-self.train_start)*((1/prog_total)-1)
            eta_e=t_mean*(1-prog_epoch)
            t_end=time.asctime(time.localtime(now+eta_t))
            e_end=time.asctime(time.localtime(now+eta_e))
            m='\nTotal:\nProg:'+str(prog_total*100.)[:5]+'%\nEpoch:'+str(self.epoch[-1])+'/'+str(self.stopped_epoch)+'\nETA:'+str(eta_t)[:8]+'sec\nTrain will be finished at '+t_end+'\nCurrent epoch:\nPROG:'+str(prog_epoch*100.)[:5]+'%\nETA:'+str(eta_e)[:8]+'sec\nCurrent epoch will be finished at '+e_end
            self.t_send(msg=m)
            print(m)
        else:
            now=time.time()
            eta_t=(now-self.train_start)*((1/prog_total)-1)
            eta_e=(now-self.train_start)*((1/prog_epoch)-1)
            t_end=time.asctime(time.localtime(now+eta_t))
            e_end=time.asctime(time.localtime(now+eta_e))
            m='\nTotal:\nProg:'+str(prog_total*100.)[:5]+'%\nEpoch:'+str(len(self.epoch))+'/'+str(self.stopped_epoch)+'\nETA:'+str(eta_t)[:8]+'sec\nTrain will be finished at '+t_end+'\nCurrent epoch:\nPROG:'+str(prog_epoch*100.)[:5]+'%\nETA:'+str(eta_e)[:8]+'sec\nCurrent epoch will be finished at '+e_end
            self.t_send(msg=m)
            print(m)
            
#==============================================================================
# 
#============================================================================== 
Example 49
Project: cleverhans-attacking-bnns   Author: AngusG   File: utils_keras.py    MIT License 5 votes vote down vote up
def conv_2d(filters, kernel_shape, strides, padding, input_shape=None):
    """
    Defines the right convolutional layer according to the
    version of Keras that is installed.
    :param filters: (required integer) the dimensionality of the output
                    space (i.e. the number output of filters in the
                    convolution)
    :param kernel_shape: (required tuple or list of 2 integers) specifies
                         the strides of the convolution along the width and
                         height.
    :param padding: (required string) can be either 'valid' (no padding around
                    input or feature map) or 'same' (pad to ensure that the
                    output feature map size is identical to the layer input)
    :param input_shape: (optional) give input shape if this is the first
                        layer of the model
    :return: the Keras layer
    """
    if LooseVersion(keras.__version__) >= LooseVersion('2.0.0'):
        if input_shape is not None:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding,
                          input_shape=input_shape)
        else:
            return Conv2D(filters=filters, kernel_size=kernel_shape,
                          strides=strides, padding=padding)
    else:
        if input_shape is not None:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding,
                                 input_shape=input_shape)
        else:
            return Convolution2D(filters, kernel_shape[0], kernel_shape[1],
                                 subsample=strides, border_mode=padding) 
Example 50
Project: lacmus-web-api   Author: lacmus-foundation   File: keras_version.py    GNU General Public License v3.0 5 votes vote down vote up
def keras_version():
    """ Get the Keras version.

    Returns
        tuple of (major, minor, patch).
    """
    return tuple(map(int, keras.__version__.split('.'))) 
Example 51
Project: lacmus-web-api   Author: lacmus-foundation   File: keras_version.py    GNU General Public License v3.0 5 votes vote down vote up
def assert_keras_version():
    """ Assert that the Keras version is up to date.
    """
    detected = keras.__version__
    required = '.'.join(map(str, minimum_keras_version))
    assert(keras_version() >= minimum_keras_version), 'You are using keras version {}. The minimum required version is {}.'.format(detected, required) 
Example 52
Project: keras-rl   Author: keras-rl   File: callbacks.py    MIT License 5 votes vote down vote up
def on_step_end(self, step, logs):
        """ Update progression bar at the end of each step """
        if self.info_names is None:
            self.info_names = logs['info'].keys()
        values = [('reward', logs['reward'])]
        if KERAS_VERSION > '2.1.3':
            self.progbar.update((self.step % self.interval) + 1, values=values)
        else:
            self.progbar.update((self.step % self.interval) +
                                1, values=values, force=True)
        self.step += 1
        self.metrics.append(logs['metrics'])
        if len(self.info_names) > 0:
            self.infos.append([logs['info'][k] for k in self.info_names]) 
Example 53
Project: deeprace   Author: psteinb   File: care_denoise.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def versions(self):

        value = ""

        if self.backend.lower().startswith("keras"):

            import keras
            from keras import backend as K

            value = "keras:{kver},backend:{bname}".format(kver=keras.__version__, bname=K.backend())

            if K.tf:
                value += ":" + K.tf.__version__
            else:
                # the following is untested!
                try:
                    if K.th:
                        value += ":" + K.th.__version__
                    else:
                        if K.cntk:
                            value += ":" + K.cntk.__version__
                except BaseException:
                    value += ":???"

        else:

            if self.backend.lower() == "tensorflow" or self.backend.lower() == "tf":
                import tensorflow as tf
                value = "tensorflow:{ver}".format(ver=tf.__version__)
            elif self.backend.lower() == "tensorflow.keras" or self.backend.lower() == "tf.keras":
                import tensorflow as tf
                value = "tensorflow:{ver},tf.keras:{kver}".format(ver=tf.__version__, kver=tf.keras.__version__)
            else:
                value = "unknown:0.0"

        return value 
Example 54
Project: deeprace   Author: psteinb   File: resnet.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def versions(self):

        value = ""

        if self.backend.lower().startswith("keras"):

            import keras
            from keras import backend as K

            value = "keras:{kver},backend:{bname}".format(kver=keras.__version__, bname=K.backend())

            if K.tf:
                value += ":" + K.tf.__version__
            else:
                # the following is untested!
                try:
                    if K.th:
                        value += ":" + K.th.__version__
                    else:
                        if K.cntk:
                            value += ":" + K.cntk.__version__
                except BaseException:
                    value += ":???"

        else:

            if self.backend.lower() == "tensorflow" or self.backend.lower() == "tf":
                import tensorflow as tf
                value = "tensorflow:{ver}".format(ver=tf.__version__)
            elif self.backend.lower() == "tensorflow.keras" or self.backend.lower() == "tf.keras":
                import tensorflow as tf
                value = "tensorflow:{ver},tf.keras:{kver}".format(ver=tf.__version__, kver=tf.keras.__version__)
            else:
                value = "unknown:0.0"

        return value 
Example 55
Project: keras-retinanet   Author: fizyr   File: keras_version.py    Apache License 2.0 5 votes vote down vote up
def keras_version():
    """ Get the Keras version.

    Returns
        tuple of (major, minor, patch).
    """
    return tuple(map(int, keras.__version__.split('.'))) 
Example 56
Project: keras-retinanet   Author: fizyr   File: keras_version.py    Apache License 2.0 5 votes vote down vote up
def assert_keras_version():
    """ Assert that the Keras version is up to date.
    """
    detected = keras.__version__
    required = '.'.join(map(str, minimum_keras_version))
    assert(keras_version() >= minimum_keras_version), 'You are using keras version {}. The minimum required version is {}.'.format(detected, required) 
Example 57
Project: deep_qa   Author: allenai   File: checks.py    Apache License 2.0 5 votes vote down vote up
def log_keras_version_info():
    import keras
    logger.info("Keras version: " + keras.__version__)
    from keras import backend as K
    try:
        backend = K.backend()
    except AttributeError:
        backend = K._BACKEND  # pylint: disable=protected-access
    if backend == 'theano':
        import theano
        logger.info("Theano version: " + theano.__version__)
        logger.warning("Using Keras' theano backend is not supported! Expect to crash...")
    elif backend == 'tensorflow':
        import tensorflow
        logger.info("Tensorflow version: " + tensorflow.__version__)  # pylint: disable=no-member 
Example 58
Project: MODS_ConvNet   Author: santiagolopezg   File: little_foo3.py    MIT License 4 votes vote down vote up
def foo():

    # Determine proper input shape
	if keras.__version__ > '1.0.3':
		K.set_image_dim_ordering('th')
	input_shape = (1, 224, 224)

	#img_input = Input(shape=input_shape)

	model = Sequential()

	model.add(Convolution2D(32, 8, 8,
			        input_shape=input_shape,init=weight_init, name='conv1_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(32, 6, 6,init=weight_init, name='conv1_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(32, 4, 4,init=weight_init, name='conv1_3'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(32, 2, 2,init=weight_init, name='conv1_4'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2))) # in 208, out 104
	model.add(Dropout(dropout))

	model.add(Convolution2D(64, 8, 8,init=weight_init, name='conv2_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(64, 6, 6,init=weight_init, name='conv2_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(64, 4, 4,init=weight_init, name='conv2_3'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(64, 2, 2,init=weight_init, name='conv2_4'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2))) # in is 88, out is 44 
	model.add(Dropout(dropout))

	model.add(Flatten())
	model.add(Dense(220, init=weight_init))
	model.add(Activation('relu'))
	model.add(Dropout(dropout))

	model.add(Dense(2))
	model.add(Activation('sigmoid'))

	return model 
Example 59
Project: MODS_ConvNet   Author: santiagolopezg   File: foo_three.py    MIT License 4 votes vote down vote up
def foo():

    # Determine proper input shape
	if keras.__version__ > '1.0.3':
		K.set_image_dim_ordering('th')
	input_shape = (1, 224, 224)

	#img_input = Input(shape=input_shape)

	model = Sequential()

	model.add(Convolution2D(32, 3, 3,
			        input_shape=input_shape,init=weight_init, name='conv1_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(32, 3, 3,init=weight_init, name='conv1_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))
	model.add(Dropout(dropout))

	model.add(Convolution2D(64, 3, 3,init=weight_init, name='conv2_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(64, 3, 3,init=weight_init, name='conv2_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(64, 3, 3,init=weight_init, name='conv2_3'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))  
	model.add(Dropout(dropout))

	model.add(Convolution2D(128, 3, 3,init=weight_init, name='conv3_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(128, 3, 3,init=weight_init, name='conv3_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))  
	model.add(Dropout(dropout))

	model.add(Convolution2D(512, 3,3,init=weight_init, border_mode='same', name='conv4_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(512, 3,3,init=weight_init, border_mode='same', name='conv4_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))  
	model.add(Dropout(dropout))

	model.add(Flatten())
	model.add(Dense(120, init=weight_init))
	model.add(Activation('relu'))
	model.add(Dropout(dropout))

	model.add(Dropout(dropout))
	model.add(Dense(2))
	model.add(Activation('sigmoid'))

	return model 
Example 60
Project: MODS_ConvNet   Author: santiagolopezg   File: little_foo.py    MIT License 4 votes vote down vote up
def foo():

    # Determine proper input shape
	if keras.__version__ > '1.0.3':
		K.set_image_dim_ordering('th')
	input_shape = (1, 224, 224)

	#img_input = Input(shape=input_shape)

	model = Sequential()

	model.add(Convolution2D(32, 5, 5,
			        input_shape=input_shape,init=weight_init, name='conv1_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(32, 3, 3,init=weight_init, name='conv1_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(32, 3, 3,init=weight_init, name='conv1_3'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2))) # in 116, out 58
	model.add(Dropout(dropout))

	model.add(Convolution2D(64, 3, 3,init=weight_init, name='conv2_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(64, 3, 3,init=weight_init, name='conv2_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(64, 3, 3,init=weight_init, name='conv2_3'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2))) # in is 52, out is 26 
	model.add(Dropout(dropout))

	model.add(Convolution2D(128, 3, 3,init=weight_init, name='conv3_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(128, 3, 3,init=weight_init, name='conv3_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(128, 3, 3,init=weight_init, name='conv3_3'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))  # in is 20, out is 10 
	model.add(Dropout(dropout))

	model.add(Flatten())
	model.add(Dense(10, init=weight_init))
	model.add(Activation('relu'))
	model.add(Dropout(dropout))

	model.add(Dense(2))
	model.add(Activation('sigmoid'))

	return model 
Example 61
Project: MODS_ConvNet   Author: santiagolopezg   File: foo_two.py    MIT License 4 votes vote down vote up
def foo():

    # Determine proper input shape
	if keras.__version__ > '1.0.3':
		K.set_image_dim_ordering('th')
	input_shape = (1, 224, 224)

	#img_input = Input(shape=input_shape)

	model = Sequential()

	model.add(Convolution2D(16, 3, 3,
			        input_shape=input_shape,init=weight_init, name='conv1_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(16, 3, 3,init=weight_init, name='conv1_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))
	model.add(Dropout(dropout))

	model.add(Convolution2D(32, 3, 3,init=weight_init, name='conv2_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(32, 3, 3,init=weight_init, name='conv2_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(32, 3, 3,init=weight_init, name='conv2_3'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))  
	model.add(Dropout(dropout))

	model.add(Convolution2D(64, 3, 3,init=weight_init, name='conv3_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(64, 3, 3,init=weight_init, name='conv3_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))  
	model.add(Dropout(dropout))

	model.add(Convolution2D(128, 3,3,init=weight_init, border_mode='same', name='conv4_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(128, 3,3,init=weight_init, border_mode='same', name='conv4_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))  
	model.add(Dropout(dropout))

	model.add(Flatten())
	model.add(Dense(120, init=weight_init))
	model.add(Activation('relu'))
	model.add(Dropout(dropout))

	model.add(Dropout(dropout))
	model.add(Dense(2))
	model.add(Activation('sigmoid'))

	return model 
Example 62
Project: MODS_ConvNet   Author: santiagolopezg   File: foo_three.py    MIT License 4 votes vote down vote up
def foo():

    # Determine proper input shape
	if keras.__version__ > '1.0.3':
		K.set_image_dim_ordering('th')
	input_shape = (1, 224, 224)

	#img_input = Input(shape=input_shape)

	model = Sequential()

	model.add(Convolution2D(32, 3, 3,
			        input_shape=input_shape,init=weight_init, name='conv1_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(32, 3, 3,init=weight_init, name='conv1_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))
	model.add(Dropout(dropout))

	model.add(Convolution2D(64, 3, 3,init=weight_init, name='conv2_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(64, 3, 3,init=weight_init, name='conv2_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(64, 3, 3,init=weight_init, name='conv2_3'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))  
	model.add(Dropout(dropout))

	model.add(Convolution2D(128, 3, 3,init=weight_init, name='conv3_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(128, 3, 3,init=weight_init, name='conv3_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))  
	model.add(Dropout(dropout))

	model.add(Convolution2D(512, 3,3,init=weight_init, border_mode='same', name='conv4_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(512, 3,3,init=weight_init, border_mode='same', name='conv4_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))  
	model.add(Dropout(dropout))

	model.add(Flatten())
	model.add(Dense(120, init=weight_init))
	model.add(Activation('relu'))
	model.add(Dropout(dropout))

	model.add(Dropout(dropout))
	model.add(Dense(2))
	model.add(Activation('sigmoid'))

	return model