當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。