当前位置: 首页>>代码示例>>Python>>正文


Python keras.Sequential方法代码示例

本文整理汇总了Python中keras.Sequential方法的典型用法代码示例。如果您正苦于以下问题:Python keras.Sequential方法的具体用法?Python keras.Sequential怎么用?Python keras.Sequential使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在keras的用法示例。


在下文中一共展示了keras.Sequential方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def __init__(self, input_shape, num_classes, **params):
        """
        Constructor to initialize the deep neural network model. Takes the input
        shape and number of classes and other parameters required for the
        abstract class `Model` as parameters.

        Args:
            input_shape (tuple): shape of the input
            num_classes (int): number of different classes ( labels ) in the data.
            **params: Additional parameters required by the underlying abstract
                class `Model`.

        """
        super(DNN, self).__init__(**params)
        self.input_shape = input_shape
        self.model = Sequential()
        self.make_default_model()
        self.model.add(Dense(num_classes, activation='softmax'))
        self.model.compile(loss='binary_crossentropy', optimizer='adam',
                           metrics=['accuracy'])
        print(self.model.summary(), file=sys.stderr)
        self.save_path = self.save_path or self.name + '_best_model.h5' 
开发者ID:harry-7,项目名称:speech-emotion-recognition,代码行数:24,代码来源:dnn.py

示例2: __build_model

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def __build_model(self):
        model = Sequential()

        embedding_layer = Embedding(input_dim=len(self.vocab) + 1,
                                    output_dim=self.embedding_dim,
                                    weights=[self.embedding_mat],
                                    trainable=False)
        model.add(embedding_layer)

        bilstm_layer = Bidirectional(LSTM(units=256, return_sequences=True))
        model.add(bilstm_layer)

        model.add(TimeDistributed(Dense(256, activation="relu")))

        crf_layer = CRF(units=len(self.tags), sparse_target=True)
        model.add(crf_layer)

        model.compile(optimizer="adam", loss=crf_loss, metrics=[crf_viterbi_accuracy])
        model.summary()

        return model 
开发者ID:fordai,项目名称:CCKS2019-Chinese-Clinical-NER,代码行数:23,代码来源:model.py

示例3: _make_char_embedding_layer

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def _make_char_embedding_layer(self) -> keras.layers.Layer:
        """
        Apply embedding, conv and maxpooling operation over time dimension
        for each token to obtain a vector.

        :return: Wrapper Keras 'Layer' as character embedding feature
            extractor.
        """

        return keras.layers.TimeDistributed(keras.Sequential([
            keras.layers.Embedding(
                input_dim=self._params['char_embedding_input_dim'],
                output_dim=self._params['char_embedding_output_dim'],
                input_length=self._params['input_shapes'][2][-1]),
            keras.layers.Conv1D(
                filters=self._params['char_conv_filters'],
                kernel_size=self._params['char_conv_kernel_size']),
            keras.layers.GlobalMaxPooling1D()])) 
开发者ID:NTMC-Community,项目名称:MatchZoo,代码行数:20,代码来源:diin.py

示例4: __init__

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def __init__(self, females_files_path, males_files_path, females_model_path, males_model_path):
        self.females_training_path = females_files_path
        self.males_training_path   = males_files_path
        self.error                 = 0
        self.total_sample          = 0
        self.features_extractor    = FeaturesExtractor()
        # load models
        self.females_gmm = pickle.load(open(females_model_path, 'rb'))
        self.males_gmm   = pickle.load(open(males_model_path, 'rb'))
        
        # svm
        self.X_train = np.vstack((self.females_gmm, self.males_gmm))
        self.y_train = np.hstack(( 0 * np.ones(self.females_gmm.shape[0]), np.ones(self.males_gmm.shape[0])))
        print(self.X_train.shape, self.y_train.shape)
        # define the keras model
        self.model = keras.Sequential()
        self.model.add(keras.layers.Dense(39, input_dim=39, activation='relu'))
        self.model.add(keras.layers.Dense(13, activation='relu'))
        self.model.add(keras.layers.Dense( 2, activation='sigmoid'))
        
        self.model.compile(optimizer = 'adam',
                           loss      = 'binary_crossentropy',
                           metrics   = ['accuracy'])
        self.model.fit(self.X_train, keras.utils.to_categorical(self.y_train), epochs = 5) 
开发者ID:SuperKogito,项目名称:Voice-based-gender-recognition,代码行数:26,代码来源:GenderIdentifier.py

示例5: build_generator

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def build_generator():
    gen_model = Sequential()

    gen_model.add(Dense(input_dim=100, output_dim=2048))
    gen_model.add(ReLU())

    gen_model.add(Dense(256 * 8 * 8))
    gen_model.add(BatchNormalization())
    gen_model.add(ReLU())
    gen_model.add(Reshape((8, 8, 256), input_shape=(256 * 8 * 8,)))
    gen_model.add(UpSampling2D(size=(2, 2)))

    gen_model.add(Conv2D(128, (5, 5), padding='same'))
    gen_model.add(ReLU())

    gen_model.add(UpSampling2D(size=(2, 2)))

    gen_model.add(Conv2D(64, (5, 5), padding='same'))
    gen_model.add(ReLU())

    gen_model.add(UpSampling2D(size=(2, 2)))

    gen_model.add(Conv2D(3, (5, 5), padding='same'))
    gen_model.add(Activation('tanh'))
    return gen_model 
开发者ID:PacktPublishing,项目名称:Generative-Adversarial-Networks-Projects,代码行数:27,代码来源:run.py

示例6: eval_batch

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def eval_batch(o, ims, allow_input_layer = False):
  layer_functions, has_input_layer = (
    get_layer_functions (o) if isinstance (o, (keras.Sequential, keras.Model))
    # TODO: Check it's sequential? --------------------------------------^
    else o)
  having_input_layer = allow_input_layer and has_input_layer
  activations = []
  for l, func in enumerate(layer_functions):
    if not having_input_layer:
      if l==0:
        activations.append(func([ims])[0])
      else:
        activations.append(func([activations[l-1]])[0])
    else:
      if l==0:
        activations.append([]) #activations.append(func([ims])[0])
      elif l==1:
        activations.append(func([ims])[0])
      else:
        activations.append(func([activations[l-1]])[0])
  return activations 
开发者ID:TrustAI,项目名称:DeepConcolic,代码行数:23,代码来源:utils.py

示例7: initiate_agent

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def initiate_agent(self, nb_actions):
        """initiate a deep Q agent"""

        self.model = Sequential()
        self.model.add(Dense(512, activation='relu', input_shape=env.observation_space))  # pylint: disable=no-member
        self.model.add(Dropout(0.2))
        self.model.add(Dense(512, activation='relu'))
        self.model.add(Dropout(0.2))
        self.model.add(Dense(512, activation='relu'))
        self.model.add(Dropout(0.2))
        self.model.add(Dense(nb_actions, activation='linear'))

        # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and
        # even the metrics!
        memory = SequentialMemory(limit=memory_limit, window_length=window_length)  # pylint: disable=unused-variable
        policy = TrumpPolicy()  # pylint: disable=unused-variable 
开发者ID:dickreuter,项目名称:neuron_poker,代码行数:18,代码来源:agent_custom_q1.py

示例8: main

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def main():
    x_train, x_test, y_train, y_test = get_train_test()
    x_train = x_train.reshape(-1, 220)
    x_test = x_test.reshape(-1, 220)
    y_train_hot = to_categorical(y_train)
    y_test_hot = to_categorical(y_test)
    model = Sequential()
    model.add(Dense(64, activation='relu', input_shape=(220,)))
    model.add(Dense(64, activation='relu'))
    model.add(Dense(64, activation='relu'))
    model.add(Dense(6, activation='softmax'))

    model.compile(loss=keras.losses.categorical_crossentropy,
                  optimizer=keras.optimizers.RMSprop(),
                  metrics=['accuracy'])
    history = model.fit(x_train, y_train_hot, batch_size=100, epochs=20, verbose=1,
                        validation_data=(x_test, y_test_hot))
    plot_history(history) 
开发者ID:xflywind,项目名称:Python-Application,代码行数:20,代码来源:weixin_audio.py

示例9: test_keras_callback

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def test_keras_callback(self):
        expected_score = f1_score(self.y_true, self.y_pred)
        tokenizer = Tokenizer(lower=False)
        tokenizer.fit_on_texts(self.y_true)
        maxlen = max((len(row) for row in self.y_true))

        def prepare(y, padding):
            indexes = tokenizer.texts_to_sequences(y)
            padded = pad_sequences(indexes, maxlen=maxlen, padding=padding, truncating=padding)
            categorical = to_categorical(padded)
            return categorical

        for padding in ('pre', 'post'):
            callback = F1Metrics(id2label=tokenizer.index_word)
            y_true_cat = prepare(self.y_true, padding)
            y_pred_cat = prepare(self.y_pred, padding)

            input_shape = (1,)
            layer = Lambda(lambda _: constant(y_pred_cat), input_shape=input_shape)
            fake_model = Sequential(layers=[layer])
            callback.set_model(fake_model)

            X = numpy.zeros((y_true_cat.shape[0], 1))

            # Verify that the callback translates sequences correctly by itself
            y_true_cb, y_pred_cb = callback.predict(X, y_true_cat)
            self.assertEqual(y_pred_cb, self.y_pred)
            self.assertEqual(y_true_cb, self.y_true)

            # Verify that the callback stores the correct number in logs
            fake_model.compile(optimizer='adam', loss='categorical_crossentropy')
            history = fake_model.fit(x=X, batch_size=y_true_cat.shape[0], y=y_true_cat,
                                     validation_data=(X, y_true_cat),
                                     callbacks=[callback])
            actual_score = history.history['f1'][0]
            self.assertAlmostEqual(actual_score, expected_score) 
开发者ID:chakki-works,项目名称:seqeval,代码行数:38,代码来源:test_metrics.py

示例10: test_preprocess_weights_for_loading_gru_incompatible

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def test_preprocess_weights_for_loading_gru_incompatible():
    """
    Loading weights between incompatible layers should fail fast with an exception.
    """
    def gru(cudnn=False, **kwargs):
        layer_class = keras.layers.CuDNNGRU if cudnn else keras.layers.GRU
        return layer_class(2, input_shape=[3, 5], **kwargs)

    def initialize_weights(layer):
        # A model is needed to initialize weights.
        _ = keras.models.Sequential([layer])
        return layer

    def assert_not_compatible(src, dest, message):
        with pytest.raises(ValueError) as ex:
            keras.engine.topology.preprocess_weights_for_loading(
                dest, initialize_weights(src).get_weights())
        assert message in ex.value.message

    assert_not_compatible(gru(), gru(cudnn=True),
                          'GRU(reset_after=False) is not compatible with CuDNNGRU')
    assert_not_compatible(gru(cudnn=True), gru(),
                          'CuDNNGRU is not compatible with GRU(reset_after=False)')
    assert_not_compatible(gru(), gru(reset_after=True),
                          'GRU(reset_after=False) is not compatible with GRU(reset_after=True)')
    assert_not_compatible(gru(reset_after=True), gru(),
                          'GRU(reset_after=True) is not compatible with GRU(reset_after=False)') 
开发者ID:hello-sea,项目名称:DeepLearning_Wavelet-LSTM,代码行数:29,代码来源:cudnn_recurrent_test.py

示例11: create_model

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def create_model():
    model = Sequential()
    model.add(Dense(12, input_dim=5, kernel_initializer='uniform', activation='relu'))
    model.add(Dense(8, kernel_initializer='uniform', activation='relu'))
    model.add(Dense(1, kernel_initializer='uniform', activation='sigmoid'))

    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

    return model 
开发者ID:devAmoghS,项目名称:Machine-Learning-with-Python,代码行数:11,代码来源:hparams_grid_search_keras_nn.py

示例12: build_discriminator

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def build_discriminator():
    dis_model = Sequential()
    dis_model.add(
        Conv2D(128, (5, 5),
               padding='same',
               input_shape=(64, 64, 3))
    )
    dis_model.add(LeakyReLU(alpha=0.2))
    dis_model.add(MaxPooling2D(pool_size=(2, 2)))

    dis_model.add(Conv2D(256, (3, 3)))
    dis_model.add(LeakyReLU(alpha=0.2))
    dis_model.add(MaxPooling2D(pool_size=(2, 2)))

    dis_model.add(Conv2D(512, (3, 3)))
    dis_model.add(LeakyReLU(alpha=0.2))
    dis_model.add(MaxPooling2D(pool_size=(2, 2)))

    dis_model.add(Flatten())
    dis_model.add(Dense(1024))
    dis_model.add(LeakyReLU(alpha=0.2))

    dis_model.add(Dense(1))
    dis_model.add(Activation('sigmoid'))

    return dis_model 
开发者ID:PacktPublishing,项目名称:Generative-Adversarial-Networks-Projects,代码行数:28,代码来源:run.py

示例13: build_adversarial_model

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def build_adversarial_model(gen_model, dis_model):
    model = Sequential()
    model.add(gen_model)
    dis_model.trainable = False
    model.add(dis_model)
    return model 
开发者ID:PacktPublishing,项目名称:Generative-Adversarial-Networks-Projects,代码行数:8,代码来源:run.py

示例14: build_model

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def build_model(self):
        '''构建模型'''
        model = keras.Sequential()
        model.add(Embedding(len(self.num2word) + 2, 300, input_length=self.config.max_len))
        model.add(Bidirectional(GRU(128, return_sequences=True)))
        model.add(Dropout(0.6))
        model.add(Flatten())
        model.add(Dense(len(self.words), activation='softmax'))
        # 设置优化器
        optimizer = Adam(lr=self.config.learning_rate)
        model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
        self.model = model 
开发者ID:apachecn,项目名称:AiLearning,代码行数:14,代码来源:text_PoetryModel.py

示例15: create_model

# 需要导入模块: import keras [as 别名]
# 或者: from keras import Sequential [as 别名]
def create_model(self, input_shape, nb_classes):
        model = Sequential()
        model.add(Conv2D(filters=32, input_shape=input_shape, padding='same', kernel_size=(3, 3)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Conv2D(filters=32, padding='same', kernel_size=(3, 3)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Dropout(rate=0.25))

        model.add(Conv2D(filters=64, kernel_size=(3, 3), padding='same'))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Conv2D(filters=64, padding='same', kernel_size=(3, 3)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Dropout(rate=0.25))

        model.add(Flatten())
        model.add(Dense(units=512))
        model.add(Activation('relu'))
        model.add(Dropout(rate=0.5))
        model.add(Dense(units=nb_classes))
        model.add(Activation('softmax'))

        model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

        return model 
开发者ID:chen0040,项目名称:keras-video-classifier,代码行数:34,代码来源:convolutional.py


注:本文中的keras.Sequential方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。