當前位置: 首頁>>代碼示例>>Python>>正文


Python backend.backend方法代碼示例

本文整理匯總了Python中keras.backend.backend方法的典型用法代碼示例。如果您正苦於以下問題:Python backend.backend方法的具體用法?Python backend.backend怎麽用?Python backend.backend使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在keras.backend的用法示例。


在下文中一共展示了backend.backend方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: classifier

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def classifier(base_layers, input_rois, num_rois, nb_classes = 21, trainable=False):

    # compile times on theano tend to be very high, so we use smaller ROI pooling regions to workaround

    if K.backend() == 'tensorflow':
        pooling_regions = 14
        input_shape = (num_rois,14,14,1024)
    elif K.backend() == 'theano':
        pooling_regions = 7
        input_shape = (num_rois,1024,7,7)

    out_roi_pool = RoiPoolingConv(pooling_regions, num_rois)([base_layers, input_rois])
    out = classifier_layers(out_roi_pool, input_shape=input_shape, trainable=True)

    out = TimeDistributed(Flatten())(out)

    out_class = TimeDistributed(Dense(nb_classes, activation='softmax', kernel_initializer='zero'), name='dense_class_{}'.format(nb_classes))(out)
    # note: no regression target for bg class
    out_regr = TimeDistributed(Dense(4 * (nb_classes-1), activation='linear', kernel_initializer='zero'), name='dense_regress_{}'.format(nb_classes))(out)
    return [out_class, out_regr] 
開發者ID:akshaylamba,項目名稱:FasterRCNN_KERAS,代碼行數:22,代碼來源:resnet.py

示例2: _loadTFGraph

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def _loadTFGraph(self, sess, graph):
        """
        Loads the Keras model into memory, then uses the passed-in session to load the
        model's inference-related ops into the passed-in Tensorflow graph.

        :return: A tuple (graph, input_name, output_name) where graph is the TF graph
        corresponding to the Keras model's inference subgraph, input_name is the name of the
        Keras model's input tensor, and output_name is the name of the Keras model's output tensor.
        """
        keras_backend = K.backend()
        assert keras_backend == "tensorflow", \
            "Only tensorflow-backed Keras models are supported, tried to load Keras model " \
            "with backend %s." % (keras_backend)
        with graph.as_default():
            K.set_learning_phase(0)  # Inference phase
            model = load_model(self.getModelFile())
            out_op_name = tfx.op_name(model.output, graph)
            stripped_graph = tfx.strip_and_freeze_until([out_op_name], graph, sess,
                                                        return_graph=True)
            return stripped_graph, model.input.name, model.output.name 
開發者ID:databricks,項目名稱:spark-deep-learning,代碼行數:22,代碼來源:shared_params.py

示例3: test_save_load_all

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def test_save_load_all(self):
        for backend in self.list_backends():
            try:
                set_keras_backend(backend)
            except ModuleNotFoundError:
                continue
            K.set_learning_phase(0)  # test
            for use_attn_mask in [True, False]:
                model = self.create_small_model(use_attn_mask)
                path = '/tmp/{}.model'.format(uuid.uuid4())
                try:
                    model.save(path)
                    new_model = keras.models.load_model(path, custom_objects={'MultiHeadAttention': MultiHeadAttention,
                                                                              'LayerNormalization': LayerNormalization,
                                                                              'Gelu': Gelu})
                    TestTransformer.compare_two_models(model, new_model)
                except Exception as e:
                    raise e
                finally:
                    if os.path.exists(path):
                        os.remove(path) 
開發者ID:yyht,項目名稱:BERT,代碼行數:23,代碼來源:test_transformer.py

示例4: test_save_load_weights

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def test_save_load_weights(self):
        for backend in self.list_backends():
            try:
                set_keras_backend(backend)
            except ModuleNotFoundError:
                continue
            K.set_learning_phase(0)  # test
            for use_attn_mask in [True, False]:
                model = self.create_small_model(use_attn_mask)
                path = '/tmp/{}.model'.format(uuid.uuid4())
                try:
                    model.save_weights(path)
                    model.load_weights(path)
                except Exception as e:
                    raise e
                finally:
                    if os.path.exists(path):
                        os.remove(path) 
開發者ID:yyht,項目名稱:BERT,代碼行數:20,代碼來源:test_transformer.py

示例5: classifier

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def classifier(base_layers, input_rois, num_rois, nb_classes = 21, trainable=False):

    # compile times on theano tend to be very high, so we use smaller ROI pooling regions to workaround

    if K.backend() == 'tensorflow':
        pooling_regions = 7
        input_shape = (num_rois,7,7,512)
    elif K.backend() == 'theano':
        pooling_regions = 7
        input_shape = (num_rois,512,7,7)

    out_roi_pool = RoiPoolingConv(pooling_regions, num_rois)([base_layers, input_rois])

    out = TimeDistributed(Flatten(name='flatten'))(out_roi_pool)
    out = TimeDistributed(Dense(4096, activation='relu', name='fc1'))(out)
    out = TimeDistributed(Dropout(0.5))(out)
    out = TimeDistributed(Dense(4096, activation='relu', name='fc2'))(out)
    out = TimeDistributed(Dropout(0.5))(out)

    out_class = TimeDistributed(Dense(nb_classes, activation='softmax', kernel_initializer='zero'), name='dense_class_{}'.format(nb_classes))(out)
    # note: no regression target for bg class
    out_regr = TimeDistributed(Dense(4 * (nb_classes-1), activation='linear', kernel_initializer='zero'), name='dense_regress_{}'.format(nb_classes))(out)

    return [out_class, out_regr] 
開發者ID:kbardool,項目名稱:keras-frcnn,代碼行數:26,代碼來源:vgg.py

示例6: swish

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def swish(x,
          name="swish"):
    """
    Swish activation function from 'Searching for Activation Functions,' https://arxiv.org/abs/1710.05941.

    Parameters:
    ----------
    x : keras.backend tensor/variable/symbol
        Input tensor/variable/symbol.
    name : str, default 'swish'
        Block name.

    Returns
    -------
    keras.backend tensor/variable/symbol
        Resulted tensor/variable/symbol.
    """
    w = nn.Activation("sigmoid", name=name + "/sigmoid")(x)
    x = nn.multiply([x, w], name=name + "/mul")
    return x 
開發者ID:osmr,項目名稱:imgclsmob,代碼行數:22,代碼來源:common.py

示例7: clip_norm

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def clip_norm(g, c, n):
    if c > 0:
        if K.backend() == 'tensorflow':
            import tensorflow as tf
            import copy
            condition = n >= c
            then_expression = tf.scalar_mul(c / n, g)
            else_expression = g

            if hasattr(then_expression, 'get_shape'):
                g_shape = copy.copy(then_expression.get_shape())
            elif hasattr(then_expression, 'dense_shape'):
                g_shape = copy.copy(then_expression.dense_shape)
            if condition.dtype != tf.bool:
                condition = tf.cast(condition, 'bool')
            g = K.tensorflow_backend.control_flow_ops.cond(
                condition, lambda: then_expression, lambda: else_expression)
            if hasattr(then_expression, 'get_shape'):
                g.set_shape(g_shape)
            elif hasattr(then_expression, 'dense_shape'):
                g._dense_shape = g_shape
        else:
            g = K.switch(n >= c, g * c / n, g)
    return g 
開發者ID:danieljl,項目名稱:keras-image-captioning,代碼行數:26,代碼來源:keras_patches.py

示例8: classifier

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def classifier(base_layers, input_rois, num_rois, nb_classes=21, trainable=False):

    # compile times on theano tend to be very high, so we use smaller ROI pooling regions to workaround

    if K.backend() == 'tensorflow':
        pooling_regions = 14
        # Changed the input shape to 1088 from 1024 because of nn_base's output being 1088. Not sure if this is correct
        input_shape = (num_rois, 14, 14, 1088)
    elif K.backend() == 'theano':
        pooling_regions = 7
        input_shape = (num_rois, 1024, 7, 7)

    out_roi_pool = RoiPoolingConv(pooling_regions, num_rois)([base_layers, input_rois])
    out = classifier_layers(out_roi_pool, input_shape=input_shape, trainable=True)

    out = TimeDistributed(Flatten())(out)

    out_class = TimeDistributed(Dense(nb_classes, activation='softmax', kernel_initializer='zero'), name='dense_class_{}'.format(nb_classes))(out)
    # note: no regression target for bg class
    out_regr = TimeDistributed(Dense(4 * (nb_classes-1), activation='linear', kernel_initializer='zero'), name='dense_regress_{}'.format(nb_classes))(out)
    return [out_class, out_regr] 
開發者ID:you359,項目名稱:Keras-FasterRCNN,代碼行數:23,代碼來源:inception_resnet_v2.py

示例9: classifier

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def classifier(base_layers, input_rois, num_rois, nb_classes = 21, trainable=False):

    # compile times on theano tend to be very high, so we use smaller ROI pooling regions to workaround

    if K.backend() == 'tensorflow':
        pooling_regions = 7
        input_shape = (num_rois, 7, 7, 512)
    elif K.backend() == 'theano':
        pooling_regions = 7
        input_shape = (num_rois, 512, 7, 7)

    out_roi_pool = RoiPoolingConv(pooling_regions, num_rois)([base_layers, input_rois])

    out = TimeDistributed(Flatten(name='flatten'))(out_roi_pool)
    out = TimeDistributed(Dense(4096, activation='relu', name='fc1'))(out)
    out = TimeDistributed(Dense(4096, activation='relu', name='fc2'))(out)

    out_class = TimeDistributed(Dense(nb_classes, activation='softmax', kernel_initializer='zero'), name='dense_class_{}'.format(nb_classes))(out)
    # note: no regression target for bg class
    out_regr = TimeDistributed(Dense(4 * (nb_classes-1), activation='linear', kernel_initializer='zero'), name='dense_regress_{}'.format(nb_classes))(out)

    return [out_class, out_regr] 
開發者ID:you359,項目名稱:Keras-FasterRCNN,代碼行數:24,代碼來源:vgg.py

示例10: classifier

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def classifier(base_layers, input_rois, num_rois, nb_classes=21, trainable=False):

    # compile times on theano tend to be very high, so we use smaller ROI pooling regions to workaround

    if K.backend() == 'tensorflow':
        pooling_regions = 14
        input_shape = (num_rois, 14, 14, 1024)
    elif K.backend() == 'theano':
        pooling_regions = 7
        input_shape = (num_rois, 1024, 7, 7)

    out_roi_pool = RoiPoolingConv(pooling_regions, num_rois)([base_layers, input_rois])
    out = classifier_layers(out_roi_pool, input_shape=input_shape, trainable=True)

    out = TimeDistributed(Flatten())(out)

    out_class = TimeDistributed(Dense(nb_classes, activation='softmax', kernel_initializer='zero'), name='dense_class_{}'.format(nb_classes))(out)
    # note: no regression target for bg class
    out_regr = TimeDistributed(Dense(4 * (nb_classes-1), activation='linear', kernel_initializer='zero'), name='dense_regress_{}'.format(nb_classes))(out)
    return [out_class, out_regr] 
開發者ID:you359,項目名稱:Keras-FasterRCNN,代碼行數:22,代碼來源:resnet.py

示例11: _handle_broken_model

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def _handle_broken_model(self, model, error):
        del model

        n = self.genome_handler.n_classes
        loss = log_loss(np.concatenate(([1], np.zeros(n - 1))), np.ones(n) / n)
        accuracy = 1 / n
        gc.collect()

        if K.backend() == 'tensorflow':
            K.clear_session()
            tf.reset_default_graph()

        print('An error occurred and the model could not train:')
        print(error)
        print(('Model assigned poor score. Please ensure that your model'
               'constraints live within your computational resources.'))
        return loss, accuracy 
開發者ID:joeddav,項目名稱:devol,代碼行數:19,代碼來源:devol.py

示例12: contain_tf_gpu_mem_usage

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def contain_tf_gpu_mem_usage():
    """
    By default TensorFlow may try to reserve all available GPU memory
    making it impossible to train multiple networks at once.
    This function will disable such behaviour in TensorFlow.
    """
    from keras import backend
    if backend.backend() != 'tensorflow':
        return
    try:
        # noinspection PyPackageRequirements
        import tensorflow as tf
    except ImportError:
        pass
    else:
        from keras.backend.tensorflow_backend import set_session
        config = tf.ConfigProto()
        config.gpu_options.allow_growth = True  # dynamically grow the memory
        sess = tf.Session(config=config)
        set_session(sess) 
開發者ID:kpot,項目名稱:keras-transformer,代碼行數:22,代碼來源:utils.py

示例13: classifier

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def classifier(base_layers, input_rois, num_rois, nb_classes = 21, trainable=True):

    # compile times on theano tend to be very high, so we use smaller ROI pooling regions to workaround

    if K.backend() == 'tensorflow':
        pooling_regions = 14
        input_shape = (num_rois,14,14,1024)
    elif K.backend() == 'theano':
        raise ValueError("Theano backend not supported")

    out_roi_pool = RoiPoolingConv(pooling_regions, num_rois,trainable=trainable)([base_layers, input_rois])
    out = classifier_layers(out_roi_pool, input_shape=input_shape, trainable=True)

    out = TimeDistributed(Flatten())(out)

    out_class = TimeDistributed(Dense(nb_classes, activation='softmax', kernel_initializer='zero',trainable=trainable), name='dense_class_{}'.format(nb_classes),trainable=trainable)(out)
    # note: no regression target for bg class
    out_regr = TimeDistributed(Dense(4 * (nb_classes-1), activation='linear', kernel_initializer='zero',trainable=trainable), name='dense_regress_{}'.format(nb_classes),trainable=trainable)(out)
    return [out_class, out_regr] 
開發者ID:Abhijit-2592,項目名稱:Keras_object_detection,代碼行數:21,代碼來源:nn_arch_resnet50.py

示例14: __init__

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def __init__(self, log_dir='./logs',
                 histogram_freq=0,
                 batch_size=32,
                 write_graph=True,
                 write_grads=False,
                 write_images=False,
                 embeddings_freq=0,
                 embeddings_layer_names=None,
                 embeddings_metadata=None):
        super(TensorBoard, self).__init__()
        if K.backend() != 'tensorflow':
            raise RuntimeError('TensorBoard callback only works '
                               'with the TensorFlow backend.')
        self.log_dir = log_dir
        self.histogram_freq = histogram_freq
        self.merged = None
        self.write_graph = write_graph
        self.write_grads = write_grads
        self.write_images = write_images
        self.embeddings_freq = embeddings_freq
        self.embeddings_layer_names = embeddings_layer_names
        self.embeddings_metadata = embeddings_metadata or {}
        self.batch_size = batch_size 
開發者ID:UKPLab,項目名稱:coling2018_fake-news-challenge,代碼行數:25,代碼來源:Keras_utils.py

示例15: setup

# 需要導入模塊: from keras import backend [as 別名]
# 或者: from keras.backend import backend [as 別名]
def setup(env):
        stderr = sys.stderr
        sys.stderr = open(os.devnull, "w")
        # pylint: disable=W0612
        try:
            import keras
        except Exception as e:
            raise e
        finally:
            sys.stderr = stderr

        from keras import backend as K
        if K.backend() == 'tensorflow':
            TensorFlowLibrary.setup(env)
            K.set_session(TensorFlowLibrary.create_session(env)) 
開發者ID:mme,項目名稱:vergeml,代碼行數:17,代碼來源:libraries.py


注:本文中的keras.backend.backend方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。